C Programming - Strings - Discussion

Discussion Forum : Strings - Find Output of Program (Q.No. 1)
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;
}
Hello
World
Hello World
WorldHello
Answer: Option
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".

Discussion:
6 comments Page 1 of 1.

Raghudeep said:   7 years ago
If we change str2 size=8 and it will print same how?

Jeffiry said:   9 years ago
@Vaibhav.

Because str2 is " world",not "world",there is a space before 'w'.

Vaibhav said:   1 decade ago
@Rucha.

But %s is used to outputs a strings without spaces.

Rucha said:   1 decade ago
Because there is a space before world in the input itself "world".

Devanshi said:   1 decade ago
Why there is space b/w hello world?

Dilini said:   1 decade ago
Why can't it be answer D. How can there be a space between the two words?

Post your comments here:

Your comments will be displayed after verification.