Programming is a powerful skill that allows us to solve problems and create solutions efficiently. One fundamental exercise that helps beginners understand control structures and conditional statements is identifying numbers divisible by specific values. In this blog post, we'll explore a simple C program that prints numbers between 1 and 50 divisible by 3 and 5.
Problem Statement
We need to write a C program that:
- Iterates through numbers from 1 to 50.
- Check each number to see if it's divisible by 3 and 5.
- Prints each qualifying number.
- Counts the total number of qualifying numbers and prints this count.
Step-by-Step Solution
Let's break down our approach:
- Set Up the Loop: We'll use a
for
loop to iterate through numbers from 1 to 50. - Check Divisibility: Within the loop, we'll use an
if
statement to check if the number is divisible by both 3 and 5 using the modulus operator (%
). - Print and Count: If the number meets the condition, we'll print it and increment our counter.
The Code
Here's the complete C program to solve this problem:
Detailed Explanation
- Include Libraries: We include
stdio.h
for standard input and output functions andstdlib.h
for thesystem
function. - Main Function: The program starts executing from the
main
function. - Clearing the Screen:
system("cls")
clears the console screen for a clean output view (optional and may not work on all systems). - Loop Initialization: We declare an integer
i
for our loop counter andcount
to keep track of numbers that meet our condition. - Loop and Condition: The
for
loop runs from 1 to 50. Inside the loop, we use anif
statement to check ifi
is divisible by both 3 and 5 (i % 3 == 0 && i % 5 == 0
). - Print and Count: If the condition is true, we print the number and increment the
count
variable. - Final Output: After the loop completes, we print the total count of divisible numbers by both 3 and 5.
Sample Output
When you run the program, you'll see the following output:
Conclusion
This simple exercise helps you understand how to use loops and conditional statements in C. By experimenting with this code, you can gain a deeper understanding of these fundamental programming concepts. Try modifying the range or the divisibility conditions to see how the output changes.
0 Comments