Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

GATE | GATE-CS-2017 (Set 2) | Question 47

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Consider the following snippet of a C program. Assume that swap(&x, &y) exchanges the contents of x and y.

int main()
{
    int array[] = {3, 5, 1, 4, 6, 2};
    int done = 0;
    int i;

    while (done == 0)
    {
        done  = 1;
        for (i = 0; i <= 4; i++)
        {
            if (array[i] = 1; i--)
        {
            if (array[i] > array[i-1])
            {
                swap(&array[i], &array[i-1]);
                done = 0;
            }
        }
    }

    printf("%d", array[3]);
}

The output of the program is _____.
Note: This question appeared as Numerical Answer Type.
(A) 1
(B) 2
(C) 3
(D) 4


Answer: (C)

Explanation: After the execution of the for loop, the content of array:

First time: 5 3 4 6 2 1
Second time: 6 5 4 3 2 1
Third time: 6 5 4 3 2 1
Now, when while loop execute again, done = 1 and first and second for loop if condition will not be satisfied .
Therefore, At the end, value of arr[3] = 3, Option C is correct.

See this to understand more:




#include <stdio.h>
void swap(int *t, int *x)
{
    int m;
    m = *t;
    *t = *x;
    *x = m;
}
  
int main()
{
    int array[] = {3, 5, 1, 4, 6, 2};
    int done = 0;
    int i;
  
    while (done == 0)
    {
        done  = 1;
        for( i = 0; i <= 4; i++)
        {
            if(array[i] < array[i+1])
            {
                swap(&array[i], &array[i+1]);
                done = 0;
            }
        }
        for (i = 5; i >= 1; i--)
        {
            if( array[i] > array[i-1])
            {
                swap(&array[i], &array[i-1]);
                done = 0;
            }
        }
    }
  
    printf("%d", array[3]);
}


Quiz of this Question


My Personal Notes arrow_drop_up
Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads