What is the output of the following code?int arr[5] = {10, 20, 30, 40, 50};int *ptr = arr;cout << *(ptr + 2);10203040
Question
What is the output of the following code?
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
cout << *(ptr + 2);
10203040
Solution
The output of the code will be 30.
Here's the step by step explanation:
-
An integer array
arrof size 5 is declared and initialized with the values 10, 20, 30, 40, 50. -
A pointer
ptris declared and it is pointed to the first element of the arrayarr. -
cout << *(ptr + 2);is used to print the value at the addressptr + 2. In pointer arithmetic,ptr + 2means the address of the third element in the array (since indexing starts from 0). -
Therefore,
*(ptr + 2)will give us the value at the third position of the arrayarr, which is 30.
So, the output of the code is 30.
Similar Questions
What is the output of the following code?int arr[] = {1, 2, 3, 4, 5};int *p = arr;p++;printf("%d\n", *p);
. Find the output of the following program.main(){ int i = (1, 2, 3); cout << i << endl;}
What will be the output of the following code? int i = 1;while(i<10){ if (i / 2 == 2) cout << i << “ ”;i++;}
What is the output of the following code snippet?int x = 5;int y = 10;int *ptr = &x;*ptr = y;printf("%d", x);510015Generates a compilation error
What will this code print? #includeusing namespace std;int x = 7;int main(){int x = 2;{int x = 3;cout << ::x << endl;}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.