Output of C++ programs | Set 23

Question 1 What will be the output?




#include <iostream>
using namespace std;
  
int main()
{
    int x = 0;
    for (int i = 0; i < 10; i++)
    {
        x = x++ + ++x;
        if (x > 100)
            break;
    }
  
    cout << x;
    return 1;
}


Answer: Compiler dependent. The subexpression x++ causes a side effect, it modifies x’s value, which leads to undefined behavior since i is also referenced elsewhere in the same expression. Please refer Sequence Points in C | Set 1 for details.

Question 2 How many times does the cout executes?




#include <iostream>
using namespace std;
  
int main()
{
    int n = 10;
    for (int i = 0; i < n; i++ )
    {
        n++;
        continue;
        cout<< n;
    }
  
    return 1;
}


Answer:

No Output

The continue statement will never let the cout statement get executed and thus never executed.

Question 3 What will be the output?




#include <iostream>
using namespace std;
  
int main()
{
    int n = 10, i;
  
    for (i=0; i<n; i++)
    {
        n++;
        cout<< n << endl;
        goto x;
    }
  
x:
    do
    {
        cout << "label x"<< endl;
        break;
    }
    while( 0 ) ;
  
    return 1;
}


Answer:

11
label x

Description:
This program is executed normally by entering for loop and in the first iteration, the control jumps to label x. We need to be careful while using goto statement because it may turn the program to infinite repetitions. For example, in the above program if we keep the for loop after the label then it will turn into infinite iterations.

Question 4 What will be the output?




#include <iostream>
using namespace std;
  
int main()
{
    int choice = 1 ;
  
    switch(choice)
    {
        cout << "\nFirst Statement";
    case 1 :
        cout << "\nInside Switch case 1";
    case 2 :
        cout << "\nInside Switch case 2";
        break;
    case 3 :
        cout << "\nInside Switch case 3";
        break;
    default:
        cout << "bye bye";
    }
    return(0);
}


Answer:

Inside Switch case 1
Inside Switch case 2


Contact Us