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 1 of 2.
Patrudu said:
1 decade ago
Want more explanation about this question.
Awasthi said:
1 decade ago
Name of array represent the base address. So in if statement we are passing base address. That is not same for both string thats why if return false.
Mani said:
1 decade ago
How can you compare two strings using == ?
Shouldn't we use strcmp ?
Shouldn't we use strcmp ?
Rohini said:
1 decade ago
@Mani.
Use strcmp(str1,str2).
Use strcmp(str1,str2).
Ganeshsablejtc said:
1 decade ago
We have use strcmp(s1,s2) function to compare strings.
strcmp print 0 that same print 0 so condition fail print unequal.
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.
strcmp print 0 that same print 0 so condition fail print unequal.
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.
Kanak vashistha said:
1 decade ago
But base address of strings were same = hello.
Shourya said:
8 years ago
<string.h> is not included.
It should produce error.
It should produce error.
Mihai said:
8 years ago
#include<stdio.h>
int main()
{
char str1[] = "Hello";
char str2[] = "Hello";
if(str1[6] == str2[6])
printf("Equal\n");
else
printf("Unequal\n");
return 0;
}
If as above result will be Equal.
int main()
{
char str1[] = "Hello";
char str2[] = "Hello";
if(str1[6] == str2[6])
printf("Equal\n");
else
printf("Unequal\n");
return 0;
}
If as above result will be Equal.
Shweta said:
7 years ago
How we should compare the address of string?
Please explain me.
Please explain me.
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.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers