C Programming - Strings - Discussion

Discussion Forum : Strings - Find Output of Program (Q.No. 25)
What will be the output of the program ?

int main()
    char sentence[80];
    int i;
    printf("Enter a line of text\n");
    for(i=strlen(sentence)-1; i >=0; i--)
    return 0;
The sentence will get printed in same order as it entered
The sentence will get printed in reverse order
Half of the sentence will get printed
None of above
Answer: Option
No answer description is available. Let's discuss.
10 comments Page 1 of 1.

Neeraj said:   6 years ago

The output of this program is False
This happens because if(str1==str2) compares the address of str1 and srt2 which is not the same.

Hence it swiches to else part and gives False as output.
You can instead use strcmp(str1,str2) or declare them as char *str1, *str2;

Gourav said:   6 years ago
int main()
char str1[]="Hello";
char str2[]="Hello";
if ( str1==str2 )

What is the output? and please explain.

Ashish said:   7 years ago
Nice explation @kavyashree

Priya said:   7 years ago
Clear Explanation @Nandita thank you.

Thenu said:   7 years ago

Nice explanation, thank you.

Nandita said:   8 years ago

Enter a line of text. This is a sentence


for(i=strlen(sentence)-1; i >=0; i--)

=>for(i=strlen(This is a sentence)-1; i >=0; i--)
=>for(i=18-1; i >=0; i--)
=>for(i=17; i >=0; i--)


=> putchar(sentence[i]);
=> putchar(sentence[17]);
=> e


=>for(i=16; i >=0; i--)
=> putchar(sentence[i]);
=> putchar(sentence[16]);
=> c

i-- => sentence[i]=>sentence[15]=>n.
i-- => sentence[i]=>sentence[14]=>e.
i-- => sentence[i]=>sentence[13]=>t.
i-- => sentence[i]=>sentence[12]=>n.
i-- => sentence[i]=>sentence[11]=>e.
i-- => sentence[i]=>sentence[10]=>s.
i-- => sentence[i]=>sentence[9]=>
i-- => sentence[i]=>sentence[8]=>a.
i-- => sentence[i]=>sentence[7]=>
i-- => sentence[i]=>sentence[6]=>s.
i-- => sentence[i]=>sentence[5]=>i.
i-- => sentence[i]=>sentence[4]=>
i-- => sentence[i]=>sentence[3]=>s.
i-- => sentence[i]=>sentence[2]=>i.
i-- => sentence[i]=>sentence[1]=>h.
i-- => sentence[i]=>sentence[0]=>T.

So,The sentence will get printed in reverse order.

Reetika said:   1 decade ago
strlen function will give the length of input string including null character and strlen(sentence)-1 will point to last character.

Sankari said:   1 decade ago
But strlen (hello) means it prints only 5 not 6. How I points to the last element of the string. Please anyone explain?

Sweety said:   1 decade ago
Thanks kavyashree.

Nice explanation.

Kavyashree said:   1 decade ago
In for loop we initializing i with 1 less the length of the string, so i points to the last element of the string, and we printing each character and decrementing i by 1 which willl print the characters in revers order.

Post your comments here:

Your comments will be displayed after verification.