📜  门| GATE-CS-2006 |第 56 题(1)

📅  最后修改于: 2023-12-03 15:28:42.760000             🧑  作者: Mango

GATE-CS-2006 Question 56

The following program fragment is written in a programming language that allows variables and does not allow nested loops.

  for ( i=0; i<5; i++ )
    for ( j=0; j<5; j++ )
      if ( i > 2 ) j = 5;

(a) What is the output of the program?

(b) Explain your answer by indicating what gets printed and/or how the program executes.


Answer

(a) The program does not generate any output.

(b) The program fragment contains two loops that iterate from 0 to 4. The inner loop has a conditional statement that breaks out of the loop when i is greater than 2. This effectively sets j to 5, which means the inner loop will never execute again. However, the program does not generate any output, so there is nothing to print.

One way to verify this behavior is to add a print statement inside the inner loop like so:

  for ( i=0; i<5; i++ )
    for ( j=0; j<5; j++ )
      if ( i > 2 ) {
        j = 5;
        printf("i=%d, j=%d\n", i, j);
      }

With this modification, the program would output the following:

i=3, j=5
i=4, j=5

This shows that the inner loop was terminated early when i became greater than 2. The values of i and j at that point were 3 and 5, respectively, followed by 4 and 5.