Write the output which is generated from each of the followi

Write the output which is generated from each of the following program segments. #include using namespace std; int main() {int result(0), i = 1; do {switch (i) {case 2: result -= 2; case 3: result *= 3; default: result += 1; break;} cout

Solution

Initially, result=0 and i=1

as i=1 it will enter in the do-while loop and there is no case statement for i=1, so it default case will be executed.

now i=1 and result=0+1=1. so in screen it will print i=1 and result=1.

note that while loop condition is using post increment operator.it means i will be compared first with old value and it will get incremented value next time. that is after first iteration comparison will be 1<3 like that and i will be incrmented to 2 .

for next iteration i=2 :

matched with case 2: so result=result-2=1-2=-1

as there is no break statement all of the cases below case 2 will be executed till it gets break statement.so case 3 and default case will be executed.

after case 3 executed : result=result*3=(-1)*3 = -3

after default case executed: result=result+1 = -3 +1 =-2

now i=2 and result=-2 will be printed for cout statement.

next condition check for while loop will be like this 2<3 and i will be incremented to 3.

for next iteration i=3:

this time case 3 and default case will be executed .

after case 3 executed : result=result*3=(-2)*3 = -6

after default case executed: result=result+1 = -6 +1 =-5

so i=3 and result=-5 will be printed.

after this condition check will be failed as 3< 3 this fails.It will come out of the loop.

 Write the output which is generated from each of the following program segments. #include using namespace std; int main() {int result(0), i = 1; do {switch (i)

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site