Introduction:
The FizzBuzz problem is a simple programming task often used in coding interviews and programming exercises to test basic logic and control structures. The objective is to print the numbers from 1 to 100, but for multiples of 3, print “Fizz” instead of the number, for multiples of 5, print “Buzz”, and for multiples of both 3 and 5, print “FizzBuzz”. This is a classic example of using conditional statements and loops in programming.
Objective:
The goal of this task is to demonstrate the use of loops and conditionals in C to solve a well-known problem. Specifically, we will implement a program that iterates over the numbers from 1 to 100, checks the divisibility conditions, and outputs the corresponding result based on these conditions.
FizzBuzz Code in C:
#include int main() { // Loop through numbers from 1 to 100 for (int i = 1; i <= 100; i++) { // Check if the number is divisible by both 3 and 5 if (i % 3 == 0 && i % 5 == 0) { printf("FizzBuzz\n"); } // Check if the number is divisible by 3 else if (i % 3 == 0) { printf("Fizz\n"); } // Check if the number is divisible by 5 else if (i % 5 == 0) { printf("Buzz\n"); } // If none of the conditions are met, print the number else { printf("%d\n", i); } } return 0; }
Explanation of the Program Structure:
The program follows a straightforward structure:
- Initialization: The program starts by including the necessary header file
#include <stdio.h>
which is required for input/output operations. - Loop: The program uses a
for
loop to iterate through numbers from 1 to 100. The loop starts withi = 1
and continues untili = 100
. - Conditional Statements: Within the loop, the program checks three conditions:
- If the current number is divisible by both 3 and 5, it prints “FizzBuzz”.
- If the number is only divisible by 3, it prints “Fizz”.
- If the number is only divisible by 5, it prints “Buzz”.
- If none of the above conditions are met, it simply prints the number itself.
- Output: The program prints the result of each iteration to the console using the
printf
function.
How to Run the Program:
Follow these steps to compile and run the FizzBuzz program in C:
-
- Write the C code into a text file, for example
fizzbuzz.c
. - Open a terminal or command prompt and navigate to the directory where your
fizzbuzz.c
file is located. - Compile the program using the following command (assuming you have GCC installed):
- Write the C code into a text file, for example
gcc fizzbuzz.c -o fizzbuzz
-
- Once compiled, you can run the program with the following command:
./fizzbuzz
- The output will display the numbers from 1 to 100, with “Fizz”, “Buzz”, or “FizzBuzz” replacing the numbers as per the conditions outlined earlier.
Conclusion:
The FizzBuzz problem is an excellent exercise to practice loops, conditionals, and modular arithmetic in C. By solving this problem, you can improve your understanding of control flow structures and logic in programming.