C Programming - Strings - Discussion

Discussion Forum : Strings - Find Output of Program (Q.No. 30)
30.
What will be the output of the program ?
#include<stdio.h>
#include<string.h>

int main()
{
    char str1[5], str2[5];
    int i;
    gets(str1);
    gets(str2);
    i = strcmp(str1, str2);
    printf("%d\n", i);
    return 0;
}
Unpredictable integer value
0
-1
Error
Answer: Option
Explanation:

gets() gets collects a string of characters terminated by a new line from the standard input stream stdin.

The gets(str1) read the input string from user and store in variable str1.

The gets(str2) read the input string from user and store in variable str2.

The code i = strcmp(str1, str2); The strcmp not only returns -1, 0 and +1, but also other negative or positive values. So the value of i is "unpredictable integer value".

printf("%d\n", i); It prints the value of variable i.

Discussion:
4 comments Page 1 of 1.

R@hit said:   1 decade ago
You are wrong because str1 and str2 both are declared but not initialized at the time of declaration
in the line.....
char str1[5],str2[5]; //this is the declaration it will say's
to compiler that make a character array of size 5 whose names are str1 and str2.
in the third and fourth line.....
gets(str1);
gets(str2); //gets is the function of stdio.h library function
this function works like scanf() but it will accept a string from input stream.
when you will pass the strings from input stream (like keyboard)
then these character arrays are initialized.
in the next line............
i = strcmp(str1, str2); //here the strcmp()is the function of
string.h library function it will compare both strings if these strings are identical then it will print 0 otherwise another unpredictable value.

Neha Dubey said:   1 decade ago
In reference to the given code, we do not know what input string the user will enter.

Then how we can say whether it will return
1
0

Or unpredictable value. The output is completely completely dependent on the users input.

Mahesh said:   1 decade ago
Here str1 and str2 are not declared....then it should give result like, these are not initialized.....plz some one give explanation....thnx...

TEJAS said:   4 years ago
But if we input two identical strings like tejas, tejas. Wouldn't it give output as 0.

So option 0 will be right.

Correct me if I'm wrong.

Post your comments here:

Your comments will be displayed after verification.