Introduction:
In this program, we will print the numbers from 1 to 100 with some variations based on certain rules. The basic rule is simple: print the numbers sequentially from 1 to 100. However, we will add additional rules where:
- If the number is divisible by 3, print “Fizz” instead of the number.
- If the number is divisible by 5, print “Buzz” instead of the number.
- If the number is divisible by both 3 and 5, print “FizzBuzz”.
The objective of this program is to demonstrate the use of loops, conditionals, and basic input/output in C.
Program Code
#include int main() { // Loop through numbers from 1 to 100 for (int i = 1; i <= 100; i++) { // Check if divisible by both 3 and 5 if (i % 3 == 0 && i % 5 == 0) { printf("FizzBuzz\n"); } // Check if divisible by 3 else if (i % 3 == 0) { printf("Fizz\n"); } // Check if divisible by 5 else if (i % 5 == 0) { printf("Buzz\n"); } // Print the number if none of the conditions match else { printf("%d\n", i); } } return 0; }
Explanation of the Program
The program starts by including the stdio.h
header file, which is necessary for input and output operations in C. The main
function is the entry point of the program.
The program uses a for
loop to iterate through all integers from 1 to 100. For each number i
, it checks the following conditions:
- If the number is divisible by both 3 and 5 (i.e.,
i % 3 == 0 && i % 5 == 0
), it prints “FizzBuzz”. - If the number is divisible by only 3 (i.e.,
i % 3 == 0
), it prints “Fizz”. - If the number is divisible by only 5 (i.e.,
i % 5 == 0
), it prints “Buzz”. - If none of the above conditions are true, it simply prints the number.
The program continues looping until all numbers from 1 to 100 have been processed. The printf
function is used to display the appropriate output to the screen.
How to Run the Program
Follow these steps to compile and run the program:
-
- Save the code in a file named fizzbuzz.c.
- Open a terminal or command prompt.
- Navigate to the directory where the fizzbuzz.c file is saved.
- Compile the code using the C compiler. For example, if you are using GCC, run the command:
gcc fizzbuzz.c -o fizzbuzz
-
- Once the code is compiled, run the program with the following command:
./fizzbuzz
- The program will print the numbers from 1 to 100, with “Fizz”, “Buzz”, or “FizzBuzz” according to the rules specified above.