Multiple choice

What is the output of C++ program given below?

#include<iostream> using namespace std; int main() { int i,j,k=5; for(i=1;i<=5;i++) { for(j=1;j<=k;j++) { cout<<j; } k=k-1; cout<<"n"; } }

  1. 12345 12345 12345 12345 12345

  2. 12345 1234 123 12 1

  3. 1 12 123 1234 12345

  4. Error in the program

  5. None of the above

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

Lets trace out i,j,k values of the given program:|k|i|j| |---|---|---| |5|1|1 2 3 4 5| |4|2|1 2 3 4| |3|3|1 2 3| |2|4|1 2| |1|5|1|

As we are displaying 'j' values, hence the output will be the similar to column 'j' as shown in the given table. In the table each row represents a single iteration of first for loop. We are decrementing value of 'k' and incrementing 'i'. More over second for loop iteration depends on value of 'k' which is decreasing through out the program hence we can see it narrows down in the output. This option is correct.