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 3 of 6.
Mrinal said:
8 years ago
How the first element printed is 2?
PRATHYUSHA said:
8 years ago
Thank you @Pankaj Singh.
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.
Hence the output is 2, 4, 6, 8, 10.
Vaibhav said:
6 years ago
Why? Please explain.
Saif said:
5 years ago
The function isn't declared and defined after the main shouldn't be Wrong? Please explain.
Vijay said:
3 years ago
#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;
}
Here the entire sub function work is to change second value in the array .
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;
}
Here the entire sub function work is to change second value in the array .
Ramya said:
1 decade ago
Can you explain the answer in detail?
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.
Nirlep said:
1 decade ago
But in *(a+1) it is not incremented.
Atul said:
1 decade ago
*(b+1) = *(b+i)+5;
1. i = 0 => *(b+1) ie 4 is replaced by *(b+0)+5 ie 2+5
2. i = 1 => *(b+1) ie 4 is replaced by *(b+1)+5 ie 4+5
3. i = 2 => *(b+1) ie 4 is replaced by *(b+2)+5 ie 6+5
4. i = 3 => *(b+1) ie 4 is replaced by *(b+3)+5 ie 8+5
5. i = 4 => *(b+1) ie 4 is replaced by *(b+4)+5 ie 10+5
1. i = 0 => *(b+1) ie 4 is replaced by *(b+0)+5 ie 2+5
2. i = 1 => *(b+1) ie 4 is replaced by *(b+1)+5 ie 4+5
3. i = 2 => *(b+1) ie 4 is replaced by *(b+2)+5 ie 6+5
4. i = 3 => *(b+1) ie 4 is replaced by *(b+3)+5 ie 8+5
5. i = 4 => *(b+1) ie 4 is replaced by *(b+4)+5 ie 10+5
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers