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;
}
Discussion:
52 comments Page 4 of 6.
Dev said:
1 decade ago
/*
for(i=0; i<n; i++)
*(b+1) = *(b+i)+5;
*/
This code only modifies the value @ (b+1) i.e. if address of b is 1002 then it will increment to 1006 and value @ 1006 is the second element (4) which is modified to *(b+i)+5 i.e. *(b+1)=*(1002+4)+5 => 10+5 => 15 @ the last iteration when the value of i becomes 4.
for(i=0; i<n; i++)
*(b+1) = *(b+i)+5;
*/
This code only modifies the value @ (b+1) i.e. if address of b is 1002 then it will increment to 1006 and value @ 1006 is the second element (4) which is modified to *(b+i)+5 i.e. *(b+1)=*(1002+4)+5 => 10+5 => 15 @ the last iteration when the value of i becomes 4.
Gowri said:
1 decade ago
I can t understand this prob how it work.
Some one explain for me.
Some one explain for me.
Keerthi kumar said:
1 decade ago
Thanks Atul.
Arun tomar said:
1 decade ago
Nice explanation atul.
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 ?
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 ?
Aloke said:
1 decade ago
Thanks atul.
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
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
Ashishprabhakar said:
1 decade ago
Thanks dev except you all gave wrong information.
Ashishprabhakar said:
1 decade ago
Here in 2nd last line clearly mentioned
*(b+1) = *(b+i)+5;
that means only *(b+1)will change all other will remain as it is....
*(b+1) = *(b+i)+5;
that means only *(b+1)will change all other will remain as it is....
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
*(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
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers