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

Madhu said:   1 decade ago
The o/p is hhe! because ch=++i[s];

Firstly i is value is 3 from i++ then we use ++i[s]

++i is evaluated its space ascii value is incremented and it becomes !.

So the o/p is hhe!

Iranna said:   1 decade ago
s[++i]=s[1]=h here i is incremented and assigned
s[i++]=s[1]=h here i is incremented but not assigned
i++[s]<->(i++)[s]<->s[i++]=s[2]=e
++i[s]<->++(i[s])<->++(s[i])=++(s[3])=++(asci value of space)=++(32)=33 is equivalent to !

So ans is hhe!

Xyz said:   1 decade ago
Can anyone explain clearly.

Shashi said:   1 decade ago
[] has higher precedence than ++.
so i++[s] <---> (i++)[s] <---> s[i++]
++i[s] <---> ++(i[s]) <---> ++s[i]=33 whose ascii is !

FlameNfire said:   1 decade ago
int i=0;
std::cout<<i++;
//Adds 1 to i, but output i's value before adding.

int a=0;
std::cout<<++a;
//Adds 1 to a, but output a's value after adding.(Which seems more logical for us).

Preethi said:   1 decade ago
What is the actual explanation. Please explain it clearly for each line. What is ASCII value. How you are calculating it. Tell me clearly?

Ragini said:   1 decade ago
s[++i] = given i=0 ++i means 0+1 therefore s[1]=h.

s[i++] = s[1] itself because post increment therefore s[1]=h.

i++[s] = s[i+1] as now i=1 increment i => 1+1=2 s[2]=e.

++i[s] = ++(s[i]) => ++s[2] => 33(ascii value ) so !.

Ravli said:   1 decade ago
I didn't understand it clearly can anyone explain it?

Manohar Reddy said:   1 decade ago
//Remember %c for number means it will print equivalent ASCII value//.

I=0; s[++i] ==> s[1] ==> h.

I=1; s[i++] ==> s[1] ==> h /*Since it is post increment no change to inside i*/.

I=2; i++[s] ==> (i++) [s] ==> s[i++] ==> s[2] ==>e /*post increment to I */.

I=3; ++i[s] ==> ++ (i[s]) ==> ++ (s[i]) ==> ++ (s[3]) ==> ++ (32) ==> 33.

==> ASCII value of 33 !

S[3] is nothing but "space" in the given string. ASCII value for "space" is 32.

It was incremented by 1. So 32+1=33.

ASCII value of 33 will be print.

Anusha.v said:   1 decade ago
In the last statement ++i[s] is 33. I didn't understand explanation of this statement.


Post your comments here:

Your comments will be displayed after verification.