Fizz Bang

 

Modules - Structured Programming 1, Structured Programming 2

 

Teacher’s Notes:

========================================================================

This is a classic programming question for beginner programmers.  There are several different ways to write this program. I have shown two different ways in the solutions below.

If you would like to make the program harder, you could:

  1. have the program prompt the user for the two numbers with which to check divisibility.

  2. have the program prompt the user for the words to print out.

 

Assignment:

========================================================================

In this assignment, you are to write a program that will prompt the user for a starting number (s) and an ending number (e).  For each number from s to e, the program will output a phrase.  If the number is divisible by 3, the program will output the word “fizz”.  If the number is divisible by 5, the program will output the word “bang”. If the number is not divisible by 3 or 5, the program will just output a hyphen.

Sample Output:

Please enter a starting number: 10

Please enter an ending number: 15

 

bang

-

fizz

-

-

fizzbang

 

 

Solution (Python):

========================================================================

  

start = (int)(input("Please enter a starting number:"))

end = (int)(input("Please enter an ending number:"))

 

for x in range(start,end+1,1):

 if x % 3 == 0:

   print("fizz",end="")

 if x % 5 == 0:

   print ("bang",end="")

 if x % 3 != 0 and x % 5 !=0:

   print("-",end="")

 print()

 

 

 

Solution (C++):

========================================================================

#include <iostream>

using namespace std;

 

int main()

{

    int start, endNumber;

    cout << "Please enter a starting number: ";

    cin >> start;

    cout << "Please enter an ending number: ";

    cin >> endNumber;

 

    for(int x = start; x <= endNumber; x++){

        if(x % 3 == 0 && x % 5 == 0)

            cout << "fizzbang";

        else if(x % 3 == 0)

            cout << "fizz";

        else if (x % 5 == 0)

            cout << "bang";

        else

            cout << "-";

        cout << endl;

    }

    return 0;

}

 

 

Advanced Solution (Python):

========================================================================

 

start = (int)(input("Please enter a starting number:"))

end = (int)(input("Please enter an ending number:"))

div1 = (int)(input("Please enter the first divisor:"))

div2 = (int)(input("Please enter the second divisor:"))

word1 = input("Please enter the first word to use:")

word2 = input("Please enter the second word to use:")

 

for x in range(start,end+1,1):

 if x % div1 == 0:

   print(word1,end="")

 if x % div2 == 0:

   print (word2,end="")

 if x % div1 != 0 and x % div2 !=0:

   print("-",end="")

 print()