Monday 28 June 2010

Interview Questions on for loops

The following code ‘for(;;)’ represents an infinite loop. It can be terminated by.
a) break
b) exit(0)
c) abort()
d) All of the mentioned

Answer:a
The correct syntax for running two variable for loop simultaneously is.
a) for (i = 0; i < n; i++)    
   for (j = 0; j < n; j += 5)
b) for (i = 0, j = 0;i < n, j < n; i++, j += 5)
c) for (i = 0; i < n;i++){}  
   for (j = 0; j < n;j += 5){}
d) None of the mentioned

Answer:b

Which for loop has range of similar indexes of 'i' used in for (i = 0;i < n; i++)?
a) for (i = n; i>0; i–)
b) for (i = n; i >= 0; i–)
c) for (i = n-1; i>0; i–)
d) for (i = n-1; i>-1; i–)

Answer:d
Which of the following cannot be used as LHS of the expression in for (exp1;exp2; exp3) ?
a) Variable
b) Function
c) typedef
d) macros

Answer:d
What is the output of this C code?

    #include <stdio.h>
    int main()
    {
        short i;
        for (i = 1; i >= 0; i++)
            printf("%d\n", i);

    }


a) The control won’t fall into the for loop
b) Numbers will be displayed until the signed limit of short and throw a runtime error
c) Numbers will be displayed until the signed limit of short and program will successfully     terminate
d) This program will get into an infinite loop and keep printing numbers with no errors

Answer:c

What is the output of this C code?

    #include <stdio.h>
    void main()
    {
        int k = 0;
        for (k)
            printf("Hello");
    }
a) Compile time error
b) hello
c) Nothing
d) Varies

Answer:a
What is the output of this C code?

    #include <stdio.h>
    void main()
    {
        int k = 0;
        for (k < 3; k++)
        printf("Hello");
    }
a) Compile time error
b) Hello is printed thrice
c) Nothing
d) Varies

Answer:a

What is the output of this C code?
    #include <stdio.h>
    void main()
    {
        double k = 0;
        for (k = 0.0; k < 3.0; k++)
            printf("Hello");
    }
a) Run time error
b) Hello is printed thrice
c) Hello is printed twice
d) Hello is printed infinitely

Answer:b


What is the output of this C code?
    #include <stdio.h>
    int main()
    {
        int i = 0;
        for (; ; ;)
            printf("In for loop\n");
            printf("After loop\n");
    }

a) Compile time error
b) Infinite loop
c) After loop
d) Undefined behaviour

Answer:a

What is the output of this C code?
    #include <stdio.h>
    int main()
    {
        int i = 0;
        for (i++; i == 1; i = 2)
            printf("In for loop ");
            printf("After loop\n");
    }
a) In for loop after loop
b) After loop
c) Compile time error
d) Undefined behaviour

Ans: a

Back to Interview Questions on Loops
Back   Next

You may like the following posts:
Loops
Interview Questions on while loop

No comments:

Post a Comment