Monday, 28 June 2010

Interview Questions on Switch Statements

Comment on the output of this C code?
    #include <stdio.h>
    int main()
    {
        int a = 1;
        switch (a)
        case 1:
            printf("%d", a);
        case 2:
            printf("%d", a);
        case 3:
            printf("%d", a);
        default:
            printf("%d", a);
    }
a) No error, output is 1111
b) No error, output is 1
c) Compile time error, no break statements
d) Compile time error, case label outside switch statement

Answer:d

Switch statement accepts.
a) int
b) char
c) long
d) All of the mentioned

Answer:d

Comment on the output of this C code?
    #include <stdio.h>
    switch (ch)
    {
    case 'a':
    case 'A':
        printf("true");
    }
a) if (ch == ‘a’ && ch == ‘A’) printf(“true”);
b) if (ch == ‘a’)
    if (ch == ‘a’) printf(“true”);
c) if (ch == ‘a’ || ch == ‘A’) printf(“true”);
d) Both a and b

Answer:c

What is the output

    #include <stdio.h>
    void main()
    {
        double ch=1;
        switch (ch)
        {
        case 1:
            printf("1");
            break;
        case 2:
            printf("2");
            break;
        }
    }
a) Compile time error
b) 1
c) 2
d) Varies

Answer:a

What is the output

    #include <stdio.h>
    void main()
    {
        char *p;
        p=1;
        switch (p)
        {
        case "1":
            printf("1");
            break;
        case "2":
            printf("2");
            break;
        }
    }
a) 1
b) 2
c) Compile time error
d) No Compile time error

Answer:c

What is the output

    #include <stdio.h>
    void main()
    {
        int ch=1;
        switch (ch)
        {
        case 1:
            printf("1\n");
        default:
            printf("2\n");
        }
    }

a) 1
b) 2
c) 1 2
d) Run time error

Answer:c

What is the output

    #include <stdio.h>
    void main()
    {
        int ch=2;
        switch (ch)
        {
        case 1:
            printf("1\n");
            break;
            printf("Hi");
        default:
            printf("2\n");
        }
    }
a) 1
b) Hi 2
c) Run time error
d) 2

Answer:d

What is the output

    #include <stdio.h>
    void main()
    {
        int ch=1;
        switch (ch, ch + 1)
        {
        case 1:
            printf("1\n");
            break;
        case 2:
            printf("2");
            break;
        }
    }
a) 1
b) 2
c) 3
d) Run time error

Answer:b


Back   Next


You may like the following posts:
switch statement



No comments:

Post a Comment