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 4 of 4.

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)

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".

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)

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


Post your comments here:

Your comments will be displayed after verification.