C Programming - Pointers - Discussion

Discussion Forum : Pointers - Find Output of Program (Q.No. 22)
22.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    int i, a[] = {2, 4, 6, 8, 10};
    change(a, 5);
    for(i=0; i<=4; i++)
        printf("%d, ", a[i]);
    return 0;
}
void change(int *b, int n)
{
    int i;
    for(i=0; i<n; i++)
        *(b+1) = *(b+i)+5;
}
7, 9, 11, 13, 15
2, 15, 6, 8, 10
2 4 6 8 10
3, 1, -1, -3, -5
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
52 comments Page 2 of 6.

Jyoti Nagpal said:   1 decade ago
Only a[1] value is changed. Reaming arrays value are same,

*(b+1) = *(b+i)+5;

b is base address +1 means assign the value to b[1];

Every time, each row is increment by 5 and assign to b[1].

At last value increment with five and finally overwrite value 10+5=15.

Agnivesh said:   1 decade ago
*(b+i) tell the location of array
each time it increment the position
and then update the value
so for i=0,*(b+i) become *b i.e the first location
hence *(b)+5 increase the value by 5 so first loc element is 7
similarly for next location

Shreya said:   1 decade ago
But won't the pointer will be moving along with the increment?
i.e., during first for loop execution the pointer will move ahead to 4.

So during second for loop, the pointer will be at 4 then how come *(b+1) is 4 for every loop ?

Pankaj Singh said:   1 decade ago
*[b+1] = *[b+i]+5;
*[a+1] = *[b+0]+5;
a[1] = b[0]+5;
a[1] = 2+5;
a[1] = 7;

Now it will continuous till the b[i] = 10.
So a[1] = 15;

For other it will remain same.
2 15 6 8 10.
a[0] a[1] a[2] a[3] a[4].

Mothi said:   8 years ago
Change (a, 5); run and then the control is given back to the main function not stored. (i. E) it cannot update any value. So it prints the value of local variable.

Hence the output is 2, 4, 6, 8, 10.

Shilpa said:   2 decades ago
When the function is called..during the first pass through the loop..
*(a+1)=*(a+0)+5..this becomes 7..we then repalce 4 by 7..similar;y through all the passes.

We ultimately get 2 15 6 8 10

Prithviraj said:   1 decade ago
Answer is [B]. 2, 15, 6, 8, 10.

Because in the above code there are few mistakes.

1) There is no link between main program and function. i.e there is no prototype.

2) Return type is void.

Sarada said:   1 decade ago
Each time when I valuse increases in the change function it will update in * (b+1) i.e. , first it will be 7 then it changes to 9 then it changes again to 11, then 13, 15 finally.

Sujju said:   1 decade ago
#include<stdio.h>
int main(){
int a=5,b=10,c=15;
int *arr[]={&a,&b,&c};
printf("%d",*arr[1]);
return 0;

What is the o/p of above program?

Devendar said:   8 years ago
Guys, actually the function is void and it not returning any values.

Then why you are changing the array values?

The answer is same as array: 2 4 6 8 10.


Post your comments here:

Your comments will be displayed after verification.