if/ else if

i was reading my c++ book and i came across this problem which is a checkpoint. basically a review that was read. i compiled this code and it displays 11. now the things is i dont understand how it displays 11. i have tried to figure it out on my own for a while how this code works but i need some help..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  int funny = 7, serious = 15;
funny = serious % 2;
if (funny != 1)
{
funny = 0;
serious = 0;
}
else if (funny == 2)
{
funny = 10;
serious = 10;
}
else
{
funny = 1;
serious = 1;
}
cout << funny << "" << serious << endl;
Well, just take it in steps. First, funny is 7 and serious is 15. Then funny is the remainder of serious divided by 2 (so 1). Then, if funny isn't one, make funny 0, and make serious zero. Now, funny is equal to one, so we skip that and go to the second if, which is if funny is 2. Funny isn't, so we go to the final else, which makes funny 1 and serious 1. It then displays funny, followed by serious, which is 1 1.
Hope this helps :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
using namespace std;

int main()
 {
    int funny = 7, serious = 15; // funny = 7, serious = 15
    funny = serious % 2; // funny = 1
    if (funny != 1) // funny = 1 so not run
    {
        funny = 0;
        serious = 0;
    }
    else if (funny == 2) // funny doesnt equal 2 so not run
    {
        funny = 10;
        serious = 10;
    }
    else // else is run as other fs return false
    {
    funny = 1;
    serious = 1;
    }
cout << funny << "" << serious << endl; // outputs funny and serious, both equal one
                               // if you put a comma in the quotes you would see they are two different values of '1' not the value '11'
}
Last edited on
wow im so dumb...thank you guys. i honestly thought it outputted 11 but its actually one and one. again thanks! :)
Topic archived. No new replies allowed.