C Programming - Strings - Discussion

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

int main()
{
    static char s[25] = "The cocaine man";
    int i=0;
    char ch;
    ch = s[++i];
    printf("%c", ch);
    ch = s[i++];
    printf("%c", ch);
    ch = i++[s];
    printf("%c", ch);
    ch = ++i[s];
    printf("%c", ch);
    return 0;
}
hhe!
he c
The c
Hhec
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
34 comments Page 1 of 4.

Chetan said:   3 years ago
Thanks for the explanation @Tarlika.

Vivek said:   3 years ago
Why it didn't take s[4]=c and gave the answer hhec directly, I mean to say as it did in the first 3 cases, why not it's the same as in the last case. Why do they take ASCII value in the last?
(1)

Richa said:   7 years ago
++i is pre incrementor.

Whereas i++ is postincrementor, both of these are the binary operator and has LOW PRIORITY when compared to Assignment operator(=),so in 1st case, ++i yields s[1], and then due to priority case first " VALUE IS ASSIGNED AND THEN INCREMENTED".

Hemanth said:   8 years ago
int main()
{
static char s[25] = "The cocaine man";
int i=0;
char ch;
ch = s[++I]; //pre-increment pointer from s[0] to s[1] i.e s[1]= h
printf("%c", ch); // print s[1]=h
ch = s[i++]; //post-increment pointer from s[1] to s[2]

printf("%c", ch);// print s[1]=h because ch = s[i++]; is post increment which increment after next print

ch = i++[s]; //post-increment pointer from s[2] to s[3]
printf("%c", ch); // print s[2]=e because ch = s[i++]; is post increment which increment after next print

ch = ++i[s];// this increment s[3] which is blank space by incrementing the ascii address 20 to 21(!)
printf("%c", ch);//print (!)
return 0;
}
(6)

Vinaya said:   8 years ago
How hhe! came? Please explain me.
(2)

Koteswararao said:   8 years ago
Nice explanation. Thank you all.

Tarlika said:   9 years ago
Here for first ch=s[++i]: first i=1,then ch=s[1]='h'.
For second ch=s[i++]:first ch=s[i]=s[1]='h',then i++becomes i=2;.
For third ch=i++[s];ch=2[s]='e';then i++ becomes i=3;.
For fourth ch=++i[s];here first ch=3[s]=s[3]=' '(space), ASSCII value=32 after that ++i[s] Takes place so ch=33 which means ASSCII Value for '!' so ch='!'.
(2)

Jhon said:   9 years ago
Why s[i]=i[s]?

Matt said:   9 years ago
++i means that i is incremented first and then evaluated.

i=0;
if(++i == 1) this is evaluated as ((i+1) == 1) which is ((0+1) == 1) which is true.

i++ means that i is evaluated first and then incremented.

i=0;
if(i++ == 1) this is evaluated as (i == 1) which is (0 == 1) which is false and then i = i+1;

Darshan said:   9 years ago
Nice explanation @ Ragini.


Post your comments here:

Your comments will be displayed after verification.