Print Numbers from 1 to 100 with Different Rules in CPlusPlus

 

 

Introduction

This program is designed to print the numbers from 1 to 100 while applying different rules based on specific conditions.
The program will print:

  • “Fizz” for numbers divisible by 3
  • “Buzz” for numbers divisible by 5
  • “FizzBuzz” for numbers divisible by both 3 and 5
  • The number itself if it is divisible by neither 3 nor 5

Objective

The goal of this program is to demonstrate control flow in C++ using conditions and loops. By applying these rules,
it will help you understand how to structure your logic based on conditions and iterations.

Code Implementation

#include 
using namespace std;

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) {
            cout << "FizzBuzz" << endl;
        }
        // Check if the number is divisible by 3
        else if (i % 3 == 0) {
            cout << "Fizz" << endl;
        }
        // Check if the number is divisible by 5
        else if (i % 5 == 0) {
            cout << "Buzz" << endl;
        }
        // If the number is not divisible by 3 or 5, print the number itself
        else {
            cout << i << endl;
        }
    }
    return 0;
}

Explanation of Program Structure

The program starts by including the necessary header #include <iostream>, which provides input/output functionality.

The main() function is the entry point of the program. A for loop is used to iterate over the numbers from 1 to 100.
Inside the loop, the program checks:

  • If a number is divisible by both 3 and 5, it prints “FizzBuzz”.
  • If the number is divisible only by 3, it prints “Fizz”.
  • If the number is divisible only by 5, it prints “Buzz”.
  • If the number is divisible by neither, it simply prints the number itself.

How to Run the Program

To run this program, follow these steps:

  1. Install a C++ compiler like GCC or use an integrated development environment (IDE) such as Code::Blocks or Visual Studio.
  2. Open a new project or create a new file with a “.cpp” extension (e.g., fizzbuzz.cpp).
  3. Copy and paste the above code into your C++ file.
  4. Compile the program using the compiler or IDE of your choice.
  5. Run the compiled program, and the numbers from 1 to 100 will be displayed with the specified rules.
© 2024 Learn Programming. All rights reserved.

 

One Reply to “Print Numbers from 1 to 100 with Different Rules in CPlusPlus”

Leave a Reply to www.binance.com Registrácia Cancel reply

Your email address will not be published. Required fields are marked *