I am typing a program in c where it takes a number and does the following.
If the number is a multiple of 3 but not 5, the output is Fizz.
If the number is a multiple of 5 but not 3, the output is Buzz.
If the number is a multiple of both 5 and 3, the output is FizzBuzz.
If the number is neither a multiple of 3 or 5, it just prints out the a number.
Whenever I compile the code with 15 as the test input, instead of getting the expected output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
I instead get this
FizzBuzz
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
My code is as follows:
#include <bits/stdc .h>
#include <iostream>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
void fizzBuzz(int n) {
for(int i = 0; i <= n; i )
{
if(i % 3 == 0 && i % 5 != 0)
{
cout << "Fizz" << endl;
}
if (i % 3 != 0 && i % 5 == 0)
{
cout << "Buzz" << endl;
}
if (i % 3 != 0 && i % 5 != 0)
{
cout << i << endl;
}
if (i % 3 == 0 && i % 5 == 0)
{
cout << "FizzBuzz" << endl;
}
}
}
int main()
{
string n_temp;
getline(cin, n_temp);
int n = stoi(ltrim(rtrim(n_temp)));
fizzBuzz(n);
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
Would like to know what I'm doing wrong that's making the extra line in the output show up, any advice will be greatly appreciated!
CodePudding user response:
For loop should start from 1.
void fizzBuzz(int n) {
for(int i = 1; i <= n; i ){
if(i % 3 == 0 && i % 5 != 0) cout << "Fizz" << endl;
if (i % 3 != 0 && i % 5 == 0) cout << "Buzz" << endl;
if (i % 3 != 0 && i % 5 != 0) cout << i << endl;
if (i % 3 == 0 && i % 5 == 0) cout << "FizzBuzz" << endl;
}
}
CodePudding user response:
@JIN's answer is correct, because 0
is a multiple of both 3
and 5
. However, I'd like to further suggest you change the order with which you check the conditions.
Currently you check if it's a multiple of 3, then a multiple of 5, then a multiple of neither, and then if it's a multiple of 15. This works, but we can be more efficient without coding if we check like so:
if (i % 3 == 0 && i % 5 == 0) {
// Multiple of 15.
}
else if (i % 3 == 0) {
// If we reach this stage and we know that i is divisible by 3,
// then we *know* the only reason it failed the first condition
// is that it's *not* divisible by 5, so we don't need to check
// that.
// Multiple of 3.
}
else if (i % 5 == 0) {
// As in the previous condition, if we're here, we know that
// i is not a multiple of 3.
// Multiple of 5.
}
else {
// Must be a multiple of neither 3 nor 5.
}