C Programming - Pointers - Discussion

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

int main()
{
    char str1[] = "India";
    char str2[] = "BIX";
    char *s1 = str1, *s2=str2;
    while(*s1++ = *s2++)
        printf("%s", str1);

    printf("\n");
    return 0;
}
IndiaBIX
BndiaBIdiaBIXia
India
(null)
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
43 comments Page 4 of 5.

Bharathi said:   1 decade ago
Thanks raju.

It was good explanation.

Wikiok said:   1 decade ago
#include<stdio.h>

int main()
{

char aa[]="1stString";
char bb[]="2nd";
char *sa,*sb;
sa=&aa;sb=&bb;

while (*sa=*sb)
{
printf("Value for while condition: %c,\n",*sa=*sb);
*sa++;
*sb++;
}
}

Try this, and you will see, that "=" operator gives back other values, than true.

Avi said:   1 decade ago
Here str1 points to I of India first. str2 points B of BIX... in while loop B of bix is assigned to I of india now string value changes to Bndia since assignment statement is executed successfully Bndia is printed. now str1 points to n of Bndia and str2 points to I of BIX again n is replaced by I ... this condition is continued till '\0' is encountered where assignment statement fails and the program comes out of the loop.

Atul said:   1 decade ago
@Manoj: It is a assignment operator not a comparison. so it will be true in all cases. Point not clear to me is what will be the result at end of "BIX". it will assign '\0' to *s1++. what while loop will do that time? Rest explanation is given by Ramu.

Manoj said:   1 decade ago
while(*s1++ = *s2++)

What is condition does?

Aditi said:   1 decade ago
None of the explanations are clear. Please give some more description. Anyone?

Nitin said:   1 decade ago
@(ramu and nishu)::it works.raju has explained it well ,read his explanation once more you will get the idea.each assignment comes to TRUE and that leads to the PRINT.

Nishu said:   1 decade ago
Agree wth ramu.

Ramu kaka said:   1 decade ago
You all wrong see in while statement operator '=' is assignment operator not a equality operator, so s2 is assigned to s1.

Subbu said:   1 decade ago
Here we have to understand operator precedence.
let us understand:
ite1:*s1++=*s2++ (here s2 points to B and s1 points to I) by this end of the statement first s1 gets value of s2(B) then increment takes place India->Bndia
Ite2: now s1="Bndia" *s1 points to n
here *s2 points to I
same operation repeated this time it is BIdia ang goes on until end of the loop


Post your comments here:

Your comments will be displayed after verification.