Loop problem

Pages: 12
I tried converting the code filipe gave to while.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream.h>
int main()
{
    int n;
    int i;
    n = 1;
    i = 0;
    while(i < 11)
    {
    ++i;
    n = n + i;
    cout << n;
    if(i == 5) n = n + 10;
    if(i != 10) cout << ", ";
    }
	system ("PAUSE");
	return 0;
}


But the results are wrong: 2, 5, 9, 14, 30, 37, 45, 54, 6475
Why?
This code may help you figure it out:

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>
int main()
{
    using namespace std;
    int n;
    int i;
    n = 1;
    i = 0;
    while(i < 11)
    {
         ++i;
         cout << "\nn: " << n << "\n";
         cout << "i: " << i << "\n";
         n = n + i;
         cout << "n: " << n << "\n";
         
         if(i == 5) 
         {
             n = n + 10;
             cout << "n: " << n << "\n";
         }
    }
	
	cout << "\nPress ENTER to exit\n";
	cin.get();
	return 0;
}


It simply writes it out each step showing you what's going on.
It's kinda.. wrong. But thanks for helping anyway. :)
I took out the last if statement because it wasn't necessary. When using your direct code I got a different output then you:

2, 4, 7, 11, 16, 32, 39, 47, 56, 6677,


Regardless, if you can be a bit more specific on what you mean why the program outputs what it does, I will do my best to help.
Do you mean why should I output the following numbers?: 1,2,4,7,11,16,32,39,47,56,66
I was simply looking for more specific info you are looking for as to why it outputs what it outputs.
The exact reproduction of this loop:

1
2
3
4
5
6
7
8
int n = 1;
for(int i = 0; i < 11; ++i)
{
    n += i;
    std::cout << n;
    if(i == 5) n += 10;
    if(i != 10) std::cout << ", ";
}

as a while loop would be:

1
2
3
4
5
6
7
8
9
10
int n = 1;
int i = 0;
while(i < 11)
{
    n += i;
    std::cout << n;
    if(i == 5) n += 10;
    if(i != 10) std::cout << ", ";
    ++i;
}

You should prefer the for loop, however, as it more directly represents what you're doing (iterating using a counter variable until a condition is met).
Topic archived. No new replies allowed.
Pages: 12