Show the printout of the following code and explain how you got it ( what is goi
ID: 3756114 • Letter: S
Question
Show the printout of the following code and explain how you got it ( what is going on in the program)
a.
#include <iostream>
using namespace std;
void xFunction(int i)
{
int num = 1;
for (int j = 1; j <= i; j++) {
cout << num << " ";
num *= 3;
}
cout << endl;
}
int main()
{
int i = 1;
while (i <= 5)
{
xFunction(i);
i++;
}
return 0;
}
b.
#include <iostream>
using namespace std;
void xFunction(int i)
{
do
{
if (i % 2 != 0)
cout << i << " ";
i--;
}
while (i >= 1);
cout << endl;
}
int main()
{
int i = 1;
while (i <= 5)
{
xFunction(i);
i++;
}
cout << "i is " << i;
return 0;
}
Explanation / Answer
a)output will be
1
1 3
1 3 9
1 3 9 27
1 3 9 27 81
we got this output as
in main we have initialized i=1
then we have a while loop which is calling the function xFunction(i) incrementing i by 1 in every call, and it will loop untill i==5
i=1 xFunction(1) is called
in xFunction we have num initialized to 1
followed by a for loop which loops till the value of 1 that is 1
so it will print 1 and exit the loop
similarly now i++ is done in while loop of main so value of i becomes 2 which is less than 5
i=2 xFunction(2) is called
in xFunction we have num initialized to 1
followed by a for loop which loops till the value of i that is 2
so it will print 1 and then multiply num by 3 now num=3 prints 3 and exits
similarly it will do it for i=3,4 5 and then the output will be
1
1 3
1 3 9
1 3 9 27
1 3 9 27 81
B) the output will be
1
1
3 1
3 1
5 3 1
i is 6
as it is similar to program a where we have a while loop in main which loops from 1 to 5 and exits as soon as i is 6 calling the xFunction(i) in every iteration
and in function xFunction(i) it is basically printing the odd numbers from i to 1.
so when i=1 in main is called xFunction(1) is passed in xFunction i%2!=0 so it prints 1 does i-- which makes i=0 and since i>=1 condition becomes false it exits the function. similarly it does for every iteration of while loop in main and when the value of i becomes 6 while loops terminates, then the value of i is printed that is i is 6 and program terminates.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.