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.

Manikanth said:   1 decade ago
Void type cannot return anything to the main function.

Kajal said:   10 years ago
See everyone here the function is passed by reference. So changes will occur moreover in the statement.

For (i=0; i<n; i++).

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

N=5;

So * (b+1) is the second element. Thus in first iteration value of 2nd element i.e. 4 will become.

For i=0; 2+5=7.

i=1;then (b+1)=4+5=9.

i=2;then (b+2)=6+5=11.

i=3;then (b+3)=8+5=13.

i=4;then (b+4)=10+5=15.

So only change 2 second element hence output.

2 15 6 8 10.

Sujitha S said:   9 years ago
Which is the correct answer A or B?

Rahul W said:   9 years ago
Nice and well explanation, Thank you all guys!

Mahesh said:   8 years ago
1. The problem is in the form of call by value. So it has to print in called method. But in the given problem, printf statement was in the calling method.

Mahesh said:   8 years ago
According to the logic, answer should be 7, 9, 11, 13, 15. But answer shows 2, 15, 6, 8.

How it is correct?

Pratik patel said:   1 decade ago
for(i=0; i<n; i++)
*(b+1) = *(b+i)+5; /*( b[1]=b[i]+5 ) . */

End time loop.
b[1] = b[5]+5.
b[1] = 10+5.
b[1] = 15.

Ans = 2, 15, 6, 8, 10.

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.

Nakul said:   8 years ago
What is the prototype of change function?

Suraj said:   8 years ago
The answer is B @Devendar.


Post your comments here:

Your comments will be displayed after verification.