Generating A list of numbered sentences

Here's my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int Number()
{
    static int iii = 0;
    return iii++;
    while (iii < 200)
    {
        cout << iii << ". What's up Mister " << iii << "?\n";
    }
    
}
int main()
{
 Number();
 return 0;
}


I was expecting a list like this:
1. What's up Mister 1?
2. What's up Mister 2?
up to 200. What's up Mister 200?

This code doesn't output anything.
What's wrong with the code? I suspect the problem is that I only used Number(); in int main()
Your code returns on line 8. Therefore, the flow of control returns to main at that point and nothing else in Number is executed.

If you remove the return, you'll have an endless loop, because iii is not updated within the loop.

If you fix that, you'll have undefined behavior because Number says it returns a value, and there would be no value returned.
I changed this
1
2
3
4
5
    return iii++;
    while (iii < 200)
    {
        cout << iii << ". What's up Mister " << iii << "?\n";
    }


to this
1
2
3
4
    while (iii < 200)
    {
        cout << iii++ << ". What's up Mister " << iii << "?\n";
    }


This gives me the output I wanted:
0. What's up Mister 0?
1. What's up Mister 1?
2. What's up Mister 2?
3. What's up Mister 3?
4. What's up Mister 4?
5. What's up Mister 5?
...


note that if you put iii++ (instead of iii) after What's up Mister you would get the output:

1. What's up Mister 0?
3. What's up Mister 2?
5. What's up Mister 4?
7. What's up Mister 6?
9. What's up Mister 8?
11. What's up Mister 10?
13. What's up Mister 12?
15. What's up Mister 14?
...
Last edited on
Topic archived. No new replies allowed.