+ 1
#include<stdio.h> #include<string.h> void main() { char *str="His"; int i=0; for(i=0;i<=strlen(str);i++) printf("%s",str++); }
Please Give me output and why?
3 Answers
+ 1
Can you explain second iteration again
+ 1
The first iteration of the loop prints the str and increases the pointer offset by one. Then 'i' is incremented.
The second iteration now prints "is" because the "str" pointer was offset by one. Then str is offset again by one and now points to "s". Then 'i' is incremented.
Now the loop ends because of the condition. i = 2 and the strlen of str returns 1 because the string was offset 2 times and only points to the character "s".
+ 1
The for-loop condition i <= strlen(str) is checked each iteration.
When you type printf("%s", str++) because it's a postfix increment the old value is used before str is incremented. So the starting position is shifted one step after the string has been printed. So what's printed is "His" and after that the str is offset so it points to "is".
The for-loop checks the length of str ("is") which is now 2. And because you're on the second iteration the variable 'i' is 1.
The loop continues because 1 <= 2 is true. It prints the str "is" and increases the offset by one. Then the variable 'i' is incremented to 2.
Now the condition of the for-loop is false because strlen("s") returns 1 and i = 2.
2 <= 1 is false so the loop stops.