C Programming - Strings - Discussion
Discussion Forum : Strings - Find Output of Program (Q.No. 32)
32.
What will be the output of the program ?
#include<stdio.h>
int main()
{
char str1[] = "Hello";
char str2[] = "Hello";
if(str1 == str2)
printf("Equal\n");
else
printf("Unequal\n");
return 0;
}
Answer: Option
Explanation:
Step 1: char str1[] = "Hello"; The variable str1 is declared as an array of characters and initialized with a string "Hello".
Step 2: char str2[] = "Hello"; The variable str2 is declared as an array of characters and initialized with a string "Hello".
We have use strcmp(s1,s2) function to compare strings.
Step 3: if(str1 == str2) here the address of str1 and str2 are compared. The address of both variable is not same. Hence the if condition is failed.
Step 4: At the else part it prints "Unequal".
Discussion:
16 comments Page 2 of 2.
RS RANA said:
6 years ago
char str1[6]="hello",str2[6]="hello";
if(strcmp(str1,str2))
printf("equal");
else
printf("not equal");
Output: not equal.
Then how, Unequal? Explain it.
if(strcmp(str1,str2))
printf("equal");
else
printf("not equal");
Output: not equal.
Then how, Unequal? Explain it.
Priya said:
5 years ago
char str1[6]="hello",str2[6]="hello";
if(strcmp(str1,str2))
printf("equal");
else
printf("not equal");
Output: not equal.
Then how, Unequal? Explain it.
Here in if condition after strcmp it will return zero .if zero is there in if condition then it is false then goes to else statement and prints not equal.
if(strcmp(str1,str2))
printf("equal");
else
printf("not equal");
Output: not equal.
Then how, Unequal? Explain it.
Here in if condition after strcmp it will return zero .if zero is there in if condition then it is false then goes to else statement and prints not equal.
Malhar said:
5 years ago
How it is not equal and how are we comparing 2 strings using == operator?
Please Explain.
Please Explain.
Rutu said:
4 years ago
Address of the variables of diff string always different. Then it's never equal, right?
Vivek Ambatpure said:
3 years ago
If we want output equal here, then how will be the code written?
Swaroop dhage said:
3 years ago
For equal output use the below code.
if (strcmp (str1, str2) ==0).
printf ("Equal\n") ;.
else.
printf ("Unequal\n") ;.
if (strcmp (str1, str2) ==0).
printf ("Equal\n") ;.
else.
printf ("Unequal\n") ;.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers