The Gateway to Computer Science Excellence
+2 votes
2.4k views

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 _______

in Programming by Veteran (425k points)
edited by | 2.4k views

2 Answers

+14 votes
Best answer
$\text{sum}=0, *b = a+4  \text{ i.e.pointing to }10$

$\text{sum}= \text{sum}+ (*b-i) - *(b-i)$

$i=0$
$\text{sum}= 0+ (10-0) - (10) = 0$

$i=1$
$\text{sum}= 0 + (10-1) - (8) = 1$

$i=2$
$\text{sum}= 1 + (10-2) - (6) = 3$

$i=3$
$\text{sum}= 3 + (10-3) - (4) = 6$

$i=4$
$\text{sum}= 6 + (10-4) - (2) = 10$
by Veteran (60.5k points)
edited by
+1
For i=4,
You took sum = 7 while in i=3 sum is 6
+1 vote
#include <stdio.h>
int main()
{
    int a[] = {2, 4, 6, 8, 10};
    int i, sum=0, *b=a+4; /* Here b points to the address of a[4]=10 */
    
    /*  *b means the value of which the address b points to. */
    /*  So *b = a[4] = 10 */
    
    /*  (b-1) means &a[4-1], so *(b-1)=a[4-1]=8  */
    /*  (b-2) means &a[4-2], so *(b-2)=a[4-2]=6  */
    /*  and so on.  */
    
    for (i=0; i<5; i++)
        sum=sum+(*b-i)-*(b-i); /* sum=0+(10-0)-(10) = 0 */
                               /* sum=0+(10-1)-(8) = 1 */
                               /* sum=1+(10-2)-(6) = 3 */
                               /* sum=3+(10-3)-(4) = 6 */
                               /* sum=6+(10-4)-(2) = 10 */
        
    printf("%d\n", sum);       /* It will give the output as 10. */
    return 0;
}

 

So the correct answer is $10$.

 

by Active (3.2k points)

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,644 questions
56,503 answers
195,554 comments
101,039 users