A Simple C Program to Find Numbers Divisible by 3 and 5

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:

  1. Iterates through numbers from 1 to 50.
  2. Check each number to see if it's divisible by 3 and 5.
  3. Prints each qualifying number.
  4. Counts the total number of qualifying numbers and prints this count.

Step-by-Step Solution

Let's break down our approach:

  1. Set Up the Loop: We'll use a for loop to iterate through numbers from 1 to 50.
  2. 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 (%).
  3. 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 and stdlib.h for the system 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 and count 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 an if statement to check if i 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.

Post a Comment

0 Comments