What will be the output of the following code?12345678910111213141516#include<stdio.h>int main() { int arr[] = {2, 4, 6, 8, 10}; int *p = &arr[0]; for (int i = 1; i <= 4; i++) { if (i % 3 == 0) { p += 1; } } printf("%d", (*(p + 2))); return 0; }
Question
What will be the output of the following code?12345678910111213141516#include<stdio.h>int main() { int arr[] = {2, 4, 6, 8, 10}; int p = &arr[0]; for (int i = 1; i <= 4; i++) { if (i % 3 == 0) { p += 1; } } printf("%d", ((p + 2))); return 0; }
Solution
The output of the code will be 10.
Here's the step-by-step explanation:
-
An integer array
arr[]is declared and initialized with the values{2, 4, 6, 8, 10}. -
A pointer
pis declared and initialized to point to the first element of the arrayarr[]. -
A
forloop is set up to run fromi = 1toi = 4. -
Inside the
forloop, there's anifcondition that checks ifiis divisible by 3. If it is, the pointerpis incremented by 1. This happens only once wheniis 3. So, after theforloop, the pointerppoints to the third element of the arrayarr[], which is 6. -
After the
forloop, the value at the address(p + 2)is printed. Sincepis currently pointing to the third element (6),(p + 2)will point to the fifth element (10). -
Therefore, the output of the code will be 10.
Similar Questions
What will be the output of the following code?
What will be the output of the following program?1234567891011121314151617181920#include <stdio.h>void one();void two();void one() { for(int i = 0; i < 2; i++){ two(); }}void two() { printf("TWO ");}int main(){ one(); two(); return 0;}
What will be the output of the following code snippet?123456789101112131415#include <stdio.h> int main() { char direction = 'N'; if (direction == 'N') printf("North"); else if (direction == 'S') printf("South"); else if (direction == 'E') printf("East"); else if (direction == 'W') printf("West"); else printf("Unknown"); return 0; }
What will be the output of the following code?1234567891011121314151617#include <stdio.h>int main() { int a = 100; int *p = &a; int count = 0; while (count < 1) { *p += 1; ++count; } int b = *p; printf("%d, %d", a, b); return 0; }
What will be the output of the following code?1234567891011121314151617#include <stdio.h>int main() { int i = 0, product = 10;start: if (i < 4) { product *= (i + 1); i++; if (i != 2) goto start; } printf("%d", product); return 0;}
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.