C Programming - Strings

Exercise :: Strings - Find Output of Program

1. 

What will be the output of the program ?

#include<stdio.h>
#include<string.h>

int main()
{
    char str1[20] = "Hello", str2[20] = " World";
    printf("%s\n", strcpy(str2, strcat(str1, str2)));
    return 0;
}

A. Hello
B. World
C. Hello World
D. WorldHello

Answer: Option C

Explanation:

Step 1: char str1[20] = "Hello", str2[20] = " World"; The variable str1 and str2 is declared as an array of characters and initialized with value "Hello" and " World" respectively.

Step 2: printf("%s\n", strcpy(str2, strcat(str1, str2)));

=> strcat(str1, str2)) it append the string str2 to str1. The result will be stored in str1. Therefore str1 contains "Hello World".

=> strcpy(str2, "Hello World") it copies the "Hello World" to the variable str2.

Hence it prints "Hello World".


2. 

What will be the output of the program ?

#include<stdio.h>

int main()
{
    char p[] = "%d\n";
    p[1] = 'c';
    printf(p, 65);
    return 0;
}

A. A
B. a
C. c
D. 65

Answer: Option A

Explanation:

Step 1: char p[] = "%d\n"; The variable p is declared as an array of characters and initialized with string "%d".

Step 2: p[1] = 'c'; Here, we overwrite the second element of array p by 'c'. So array p becomes "%c".

Step 3: printf(p, 65); becomes printf("%c", 65);

Therefore it prints the ASCII value of 65. The output is 'A'.


3. 

What will be the output of the program ?

#include<stdio.h>
#include<string.h>

int main()
{
    printf("%d\n", strlen("123456"));
    return 0;
}

A. 6
B. 12
C. 7
D. 2

Answer: Option A

Explanation:

The function strlen returns the number of characters in the given string.

Therefore, strlen("123456") returns 6.

Hence the output of the program is "6".


4. 

What will be the output of the program ?

#include<stdio.h>

int main()
{
    printf(5+"Good Morning\n");
    return 0;
}

A. Good Morning
B. Good
C. M
D. Morning

Answer: Option D

Explanation:

printf(5+"Good Morning\n"); It skips the 5 characters and prints the given string.

Hence the output is "Morning"


5. 

What will be the output of the program ?

#include<stdio.h>
#include<string.h>

int main()
{
    char str[] = "India\0\BIX\0";
    printf("%s\n", str);
    return 0;
}

A. BIX
B. India
C. India BIX
D. India\0BIX

Answer: Option B

Explanation:

A string is a collection of characters terminated by '\0'.

Step 1: char str[] = "India\0\BIX\0"; The variable str is declared as an array of characters and initialized with value "India"

Step 2: printf("%s\n", str); It prints the value of the str.

The output of the program is "India".