Explain the output?

Can someone please explain the output of this code?
Please and thank you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
using namespace std;

void main()
{
	int a[4] = { 10, 20, 30, 40 };
	int i = 0;
	int j = 4;
	while (i++ < 4)
	{
		j = i;
		cout << a[i] << endl;
		while (j-->0)
			cout << i << " ";
	}


     system("pause");
}
That all seems quite self-explanatory. Is it the post-increment and post-decrement operators that baffle you?

Incidentally, condition on line 12 leads to out-of-range error on line 15 on the last iteration.

Line 7 is non-standard and so is line 21.
Lines 2 and 4 are unnecessary.
I'm just confused with the outputs we get on line 17
Line 17 outputs the value of i for the number of times it takes to decrement j to 0 - at which point the while loop condition is no longer true.


First it output's the number in array corresponding to the i index (which increments by 1 each iteration).
Second it outputs i as long as j-- is greater than 0, lets look at what happens.

First iteration:
j = i (i is 1 now)
output 1st element in array
is 1-- > 0? Yes

Second Iteration:
j = i (i is 2 now)
output the 2nd element in array
is 2-- > 0? Yes

Hope this helps.
Last edited on
^
see that's what i expect to happen too!
but instead in the first iteration:
i = 1
j = i
outputs a[1] which is 20
then 1-- > 0? yes... so it should output i which is 1.. but instead it only outputs 20...
that's why im confused.
On the first iteration i = 1
and a[i] = 20.
if you do not include the array i is just 1. if that's what you mean?
The 1 prints on the next line. There's an endl on line 15. Only 20 is going to print on the first line.
1
2
3
4
5
6
{
        j = i;
	cout << a[i] << endl; // endl ends the line.
	while (j-->0)
	cout << i << " "; // output 1 on the new line.
}
Last edited on
ahhhhh im such an idiot.
thank you guys
Topic archived. No new replies allowed.