What will be the output of the following code?#include <stdio.h>int main() { char str[] = "Programming"; printf("%s\n", str + 3); return 0;}
Question
What will be the output of the following code?#include <stdio.h>int main() { char str[] = "Programming"; printf("%s\n", str + 3); return 0;}
Solution
The output of the code will be "gramming".
Here's the step by step explanation:
-
The code declares a character array
str[]and initializes it with the string "Programming". -
The
printffunction is used to print a string. However, instead of printing the whole string, it prints fromstr + 3. -
In C, strings are arrays of characters. So, when you do
str + 3, it means you're moving 3 positions forward in the array. -
The string "Programming" starts at index 0. So,
str + 3will point to the 4th character of the string, which is 'g'. -
Therefore,
printf("%s\n", str + 3);will print the string starting from 'g', which is "gramming". -
The program then returns 0 and ends.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.