Consider the following C program: #include <stdio.h> int main() { int a[] =…

2019

Consider the following C program:

#include <stdio.h>
int main()
{
     int a[] = {2, 4, 6, 8, 10};
     int i, sum = 0, *b = a + 4;
     for (i = 0; i < 5; i++)
         sum = sum + (*b – i) – *(b – i);
         printf (“%d\n”, sum);
         return 0;
 }


The output of the above C program is __________.

Attempted by 35 students.

Show answer & explanation

Correct answer: 10

Answer: 10

Explanation: The pointer b is set to the last element of the array (value 10). In each loop iteration i goes from 0 to 4 and the expression computes (value pointed by b minus i) minus the value at (b - i) which is the array element a[4 - i].

  • i = 0: (10 - 0) - a[4] = 10 - 10 = 0; cumulative sum = 0

  • i = 1: (10 - 1) - a[3] = 9 - 8 = 1; cumulative sum = 1

  • i = 2: (10 - 2) - a[2] = 8 - 6 = 2; cumulative sum = 3

  • i = 3: (10 - 3) - a[1] = 7 - 4 = 3; cumulative sum = 6

  • i = 4: (10 - 4) - a[0] = 6 - 2 = 4; cumulative sum = 10

Therefore, the program prints 10.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir