Exam Question Predict the Output

closed account (4jzvC542)
In my Final Exam paper I got following question :
"give the output of following program"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#pragma GCC diagnostic ignored "-fpermissive"
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
	for(int i = 1; i <= 6; i += 2)
	{
		if(i%2 == 0)
			cout << i++ << "*\n";
		else
			cout << ++i << "#\n";
	}
	cout << i << "*\n";
	return 0;
}

now I was unable to guess its output
so after paper was over I compiled this code in my pc
i got following output

2#
4*
7*

so now can anyone tell me how exactly to predict compiler
I mean I am stuck up being total beginner to c++
can any one point me how step by step to proceed and evaluate particularly a for loop
thanks
parjanya
1st run of the loop :
1
2
3
4
5
6
// i = 1

if ( i % 2 == 0 ) // 1 % 2 == 1, therefore this is false, else is executed
    cout << i++ << "*\n";
else
    cout << ++i << "#\n"; // pre-increment i ( i becomes 2 ) 

output is 2#

2nd run of the loop
1
2
3
4
5
// i == 4  ( i += 2 )

if ( i % 2 == 0 ) // 4 % 2 == 0, therefore this is excecuted
    cout << i++ << "*\n"; // post-increment i ( return the value first, then increment it)
                           //  thus i++ expression returns 4 to operator << then increments i 

output is 4*

3rd run ( the loop is not executed since (7 <= 6) is false
output is 7*

can any one point me how step by step to proceed and evaluate particularly a for loop

practice
Last edited on
At the start of the loop i == 1. Which means it is odd so it will go to the else statement and execute cout << ++i << "#\n"; which means it increment i by 1 (i == 2) then it outputs "#\n." we now add 2 to i since the loop finished its pass and i+=2 is now called. i == 4 now and it is even so it executes cout << i++ << "*\n"; which outputs 4*\n then increments i so i == 5 then we add 2. i == 7 so we exit the for loop and execute cout << i << "*\n";
closed account (4jzvC542)
@nvrmnd hey.... hey thanks man
yep I lost the marks for this questions alright but true
ok I got it what you pointed out...
take one value ........ put it in loop .... evaluate .......... get the result.
Thanks man
thanks....... really it was quite obvious though
And yes patient is the key to everything but see marks are lost and when working in time-bound factor or so patient is not choice always... nice cheek
I think answer is lots of hard work and repeted c++ practice to reach to your level :)
closed account (4jzvC542)
@giblit
yes I got it but bit late... see I lost marks alright
but joke aside the thing is that underlaying principle is that
as in scond loop if 2% == 0;
thus odd terms will be *
Yep......... thanks for replying it helped a lot :)
Topic archived. No new replies allowed.