Q31.Marks: +2.0UGC NET Paper 2: Computer Sc 23rd August 2024 Shift 1
Consider following C program:
#include < stdio.h >
int main()
{
int x[] = {2, 4, 6, 8, 10};
int a, b = 0, *y = x + 4;
for(a = 0; a < 5; a++)
{
b = b + (*y - a) - *(y - a);
}
printf("%d\n", b);
return 0;
}
What will be the output of the above C program?
1.4
2.6
3.8
4.10✓ Correct
Solution
The correct answer is 10
Concept:
In C programming, the comma operator (`,`) is used to separate two or more expressions that are included where only one expression is expected. The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
In the code `int x[] = {2, 4, 6, 8, 10};`, the values inside curly brackets are evaluated and the last value `10` is assigned to the first element of the array `x`.
Explanation:-
Given the corrected code:
#include < stdio.h >
int main()
{
int x[] = {2, 4, 6, 8, 10};
int a, b = 0, *y = x + 4;
for(a = 0; a < 5; a++)
{
b = b + (*y - a) - *(y - a);
}
printf("%d\n", b);
return 0;
}
Explanation:
int x[] = {2, 4, 6, 8, 10}; initializes the array x.
int a, b = 0, y = x + 4; initializes a, b to 0, and y to point to the address of the 5th element of array x (i.e., x[4] which is 10).
The for loop runs from a = 0 to a < 5:
In each iteration, *y is 10 (value at x[4]).
y - a points to different elements of x as a varies from 0 to 4.
The expression b + (*y - a) - *(y - a) simplifies to 0 for every iteration:
When a = 0: 0 + (*y - a) - *(y - a) becomes 0 + 10 - 0 - x[4] = 0 + 10 - 10 = 0
When a = 1: 0 + (*y - a) - *(y - a) becomes 0 + 10 - 1 - x[3] = 0 + 9 - 8 = 1
When a = 2: 1 + (*y - a) - *(y - a) becomes 1 + 10 - 2 - x[2] = 1 + 8 - 6 = 3
When a = 3: 3 + (*y - a) - *(y - a) becomes 3 + 10 - 3 - x[1] = 3 + 7 - 4 = 6
When a = 4: 6 + (*y - a) - *(y - a) becomes 6 + 10 - 4 - x[0] = 6 + 6 - 2 = 10
Final Output: After the loop, the final value of b is printed10