-7

I'm relatively new to stack overflow (yes, i'm extremely new to coding), and i'm currently working on an altered version of the Fizz Buzz Question. Could someone help me figure out as to what i'm doing wrong? I can't seem to find the answer on Stack Overflow. Use a while loop instead of for loop to write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

n = 15,

Output:

1

2

Fizz

4

Buzz

Fizz

7

8

Fizz

Buzz

11

Fizz

13

14

FizzBuzz

My code is

   #include <iostream>
using namespace std;
int n = 0;
{
       cout << "Enter your number ";      // Prompt for input
       cin >> n;                          // Get the input.
       for (int i = 1; i <= n; i++) 
       {
               if ((i % 15) == 0)
                       cout << "FizzBuzz\n";
               else if ((i % 3) == 0)
                       cout << "Fizz\n";
               else if ((i % 5) == 0)
                       cout << "Buzz\n";
               else
                       cout << i << "\n";
       }
       return 0;
}

While I am receiving the error for line 4:

4:1: error: expected ',' or ';' before '{' token 
J Le
  • 1
  • 1
  • 2
  • The question appears to ask for a `while` loop yet you have used a `for` loop. – Obsidian Age Jan 23 '19 at 02:50
  • Please paste your actual code into the question. Your edits imply that this is one of several approximations of your code. Where is `main()`? – Drew Dormann Jan 23 '19 at 03:25
  • 1
    That was my actual code. I just replaced the main function with n = 0. i don't know why i did that. – J Le Jan 23 '19 at 03:27

8 Answers8

3

You should be able to do this equally well with either for-loop or while-loop. However, that is not why your program is failing. As mentioned earlier by @EvilTeach, your program is basically accepting input from stdin(via cin) outside the braces({}) in main() function.

A Function signature in C/C++ is defined as:-

return-type funcName(ArgType1 arg1, ... , ArgTypeN argN) 
{
    // cin goes here
    // Your loop goes here
}
Alok Garg
  • 164
  • 9
2

For starters you need to move the cin inside the braces {}. That should get your past your compilation error. It is generally a good idea to print a prompt as well when you are asking for input. As a general rule, if you ask for help, always include any compilation errors you get. That helps zero in on the issue. Welcome to stack overflow.

#include <iostream>
using namespace std;
int main ()
{
       cout << "Enter your number ";      // Prompt for input
       cin >> n;                          // Get the input.
       for (int i = 1; i <= n; i++) 
       {
               if ((i % 15) == 0)
                       cout << "FizzBuzz\n";
               else if ((i % 3) == 0)
                       cout << "Fizz\n";
               else if ((i % 5) == 0)
                       cout << "Buzz\n";
               else
                       cout << i << "\n";
       }
       return 0;
}
EvilTeach
  • 28,120
  • 21
  • 85
  • 141
1

Naive Solution

for(int i = 1; i <= n; i++)
{
    if(i % 15 == 0)
        cout << "FizzBuzz\n";
    else if(i % 3 == 0)  
        cout << "Fizz\n";
    else if(i % 5 == 0)
        cout << "Buzz\n";
    else
        cout << i << "\n";       
}

Problem with Naive solution: % 15 is equivalent to % 3 && % 5.

Hence, there is no point in checking the same condition again.

Efficient Approach

for(int i = 1; i <= n; i++)
{
    string d ="";
    if(i % 3 == 0) d += "Fizz";
    if(i % 5 == 0) d += "Buzz";
    if(d == "") cout << i << "\n";
    else cout<< d << "\n"; 
}

Problem with the above Efficient solution: '%' is a costly operator.

The complexity of '%' operator is O(n ^ 2)

More Efficient Approach

int c3 = 0;
int c5 = 0;
for(int i = 1; i <= n; i++)
{
    c3++;
    c5++;
    string d = "";
     if(c3 == 3) 
     {
         d += "Fizz"; 
         c3 = 0;
     }
     if(c5 == 5)
     {
         d += "Buzz";
         c5 = 0;
     }   
     if(d == "") cout << i << "\n";
     else cout << d << "\n";
}
0

In FizzBuzz code efficiency is important; shorter codes seem more cryptic, but larger ones tends to have a lower learning curve (less readables). I've chosen three ways of coding this and measuring their duration; it's well known that c++ similar code takes more time and memory than the ones written y C. So you should peek your way of coding depending on the final destination of binaries and the time-frame you have for doing it.

#include <iostream>
#include <chrono>
#include <cstring>

void runOne(int n, void (*fnc)(int));
void fizzbuzzAnsiC(int n);
void fizzbuzzAnsiC2(int n);
void fizzbuzzCpp(int n);

using namespace std;
using namespace std::chrono;

int main(int argc, char *argv[])
{ long iter = 100;

  if (argc > 1)
    iter = strtol(argv[1], nullptr, 10);

  runOne(int(iter), fizzbuzzAnsiC2);
  cout << endl << "==============" << endl;
  runOne(int(iter), fizzbuzzAnsiC);
  cout << endl << "==============" << endl;
  runOne(int(iter), fizzbuzzCpp);
  cout << endl << "==============" << endl;

  return 0;
}

void runOne(int n, void (*fnc)(int))
{ high_resolution_clock::time_point t1 = high_resolution_clock::now();
  fnc(n);
  high_resolution_clock::time_point t2 = high_resolution_clock::now();

  auto duration = duration_cast<microseconds>( t2 - t1 ).count();
  cerr << "Lasted: " << duration << " us" << endl;
}

static const char* cszFizz = "Fizz";
static const char* cszBuzz = "Buzz";

void fizzbuzzAnsiC(int n)
{ int     i;
  char    szPrn[11];
  char    szNum[11]; //Suppose 9 digits number max (10e8-1)
  char    uMul;

  for (i = 1; i <= n; ++i)
  { uMul = i%15 == 0;
    strcpy(szPrn, uMul | (i%3==0) ? cszFizz : (i%5==0 ? cszBuzz : itoa(i, szNum, 10)));
    if (uMul) strcat(szPrn, cszBuzz);
    strcat(szPrn, "\n");
    fwrite(szPrn, 1, strlen(szPrn), stdout);
  }
}

void fizzbuzzAnsiC2(int n)
{ int i;
  const char *messages[] = {"%i\n", "Fizz\n", "Buzz\n", "FizzBuzz\n"};

  for (i = 1; i <= n; ++i)
    printf(messages[((i % 3) == 0) + 2*((i % 5) == 0)], i); //printf takes longer then str* functions
}

void fizzbuzzCpp(int n)
{ for (int i = 1; i <= n; ++i)
  { bool uMul = i%15 == 0;
    std::cout << (uMul | (i%3==0) ? cszFizz : (i%5==0 ? cszBuzz : std::to_string(i)));
    if (uMul) std::cout << cszBuzz;
    std::cout << std::endl;
  }
}

As the number of iterations increases fizzbuzzAnsiC2 becomes less efficient. fizzbuzzAnsiC function is the most efficient always.

delverdl
  • 85
  • 10
0

simplest version.

#include <iostream>
#include <string>

using namespace std;
int main(){
    for(int i=1; i<=100; i++){
        string output = "";
        if(i%3 == 0) output += "fizz";
        if(i%5 == 0) output += "buzz";
        if(output == "") output = to_string(i);
        cout << output <<endl;
    }
}
0

What use is code that can be understood by a mere novie? It doesn't contribute towards job security, doesn't show off that you are a jerk that knows more than everybody else, and it isn' FUN. So here is my FizzBuzz, inspired by Duff. It can still be improved, there is for instance no use of exceptions as normal returns, no abuse of 2-phase lookup, and nothing significant happening at compile time, not even SFINAE, which is of course required in every modern C++ application.

#include <iostream>
#include <string>
#include <algorithm>

// FizzBuzz using Duff's device 
auto FizzBuzz( int n ){
   auto s = std::string( "" );
   switch( n % 15 ){
      while( n >= 0 ){
         case 14 : s = ", " + std::to_string( n-- ) + s;
         case 13 : s = ", " + std::to_string( n-- ) + s;
         case 12 : s = ( n--, ", Fizz" )            + s;
         case 11 : s = ", " + std::to_string( n-- ) + s;
         case 10 : s = ( n--, ", Buzz" )            + s;
         case  9 : s = ( n--, ", Fizz" )            + s;
         case  8 : s = ", " + std::to_string( n-- ) + s;
         case  7 : s = ", " + std::to_string( n-- ) + s;
         case  6 : s = ( n--, ", Fizz" )            + s;
         case  5 : s = ( n--, ", Buzz" )            + s;
         case  4 : s = ", " + std::to_string( n-- ) + s;
         case  3 : s = ( n--, ", Fizz" )            + s;
         case  2 : s = ", " + std::to_string( n-- ) + s;
         case  1 : s = ", " + std::to_string( n-- ) + s;
         case  0 : s = ( n--, ", FizzBuzz" )        + s;
      }   
   }   
   return s.substr( std::min( 12, static_cast< int >( s.size() ) ) );
} 

// test harnesses are severly overrated
#define check_equal( a, b ) check_equal_func( __FILE__, __LINE__, a, b )
template< typename A, typename B >
void check_equal_func( const char *file, int line, const A & a, const B & b ){
   if( a != b ){
       std::cout << file << ":" << line << " [" <<a << "] != [" << b << "]\n";
   }    
}

// test cases from https://catonmat.net/tools/generate-fizzbuzz-sequence
int main(int argc, char **argv){
   check_equal( FizzBuzz(   0 ), "" );
   check_equal( FizzBuzz(   1 ), "1" );
   check_equal( FizzBuzz(  10 ), "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz" );
   check_equal( FizzBuzz( 100 ), "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, FizzBuzz, 31, 32, Fizz, 34, Buzz, Fizz, 37, 38, Fizz, Buzz, 41, Fizz, 43, 44, FizzBuzz, 46, 47, Fizz, 49, Buzz, Fizz, 52, 53, Fizz, Buzz, 56, Fizz, 58, 59, FizzBuzz, 61, 62, Fizz, 64, Buzz, Fizz, 67, 68, Fizz, Buzz, 71, Fizz, 73, 74, FizzBuzz, 76, 77, Fizz, 79, Buzz, Fizz, 82, 83, Fizz, Buzz, 86, Fizz, 88, 89, FizzBuzz, 91, 92, Fizz, 94, Buzz, Fizz, 97, 98, Fizz, Buzz" );
   check_equal( "If you see no messages before this one ", "all tests were successfull." );
}
0

Can reduce line using ternary operators and also combining cout with to_string

#include <iostream>
using namespace std;
int main() {
    string str = "";
    for (int i = 1; i < 100; i++) {
        str = !(i % 3) ? "fizz" : "";
        str += !(i % 5) ? "buzz" : "";
        cout << (str == "" ? to_string(i) : str) << endl;
    }
    return 0;
 }
0

#include

using namespace std;

int main(){

int num{0};

cout<< "enter number" << "\n" ;

cin>>num;

for(int i = 1; i <= num; i++){

if(i % 3 == 0 && i % 5 == 0){

    cout<< "FizzBuzz" << "\n" ;
}

else if (i % 3 == 0 ){

    cout<< "Fizz" << "\n" ;

}

else if (i % 5 == 0){

    cout<< "Buzz" << "\n";

}

else

    cout<< i << "\n";

} }