C++ Programming - Functions - Discussion

Discussion Forum : Functions - Programs (Q.No. 33)
33.
What will be the output of the following program?
#include<iostream.h> 
struct IndiaBix
{
    int arr[5]; 
    public:
    void BixFunction(void);
    void Display(void);
};
void IndiaBix::Display(void)
{
    for(int i = 0; i < 5; i++) 
        cout<< arr[i] << " " ;
}
void IndiaBix::BixFunction(void)
{
    static int i = 0, j = 4; 
    int tmp = arr[i]; 
    arr[i]  = arr[j]; 
    arr[j]  = tmp   ; 
    i++;
    j--;
    if(j != i) BixFunction();
}
int main()
{
    IndiaBix objBix = {{ 5, 6, 3, 9, 0 }};
    objBix.BixFunction();
    objBix.Display();
    return 0; 
}
0 9 3 6 5
9 3 6 5 0
5 6 3 9 0
5 9 3 6 0
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
2 comments Page 1 of 1.

Anthony Dawson said:   8 years ago
The key here is i & j are local static to IndiaBix::BixFunction().

On calling IndiaBix::BixFunction() the first time i = 0 and j = 4. This causes the first call of IndiaBix::BixFunction() to swap the 1st and last elements of the array. i.e. {0, 6, 3, 9, 5}. Then increment i and decrement j such that i = 1 and j = 3. The statement j != i is therefore true and IndiaBix::BixFunction() is called again.

On the second call to IndiaBix::BixFunction() i = 1 and j = 3 because they are static. This causes the second call of IndiaBix::BixFunction() to swap the 2nd and 4th elements of the array. i.e. {0, 9, 3, 6, 5}. Then increment i and decrement j such that i = 2 and j = 2. This time the statement j != i is false so that is the end of the recursion.

This leaves IndiaBix::Display() to print "0 9 3 6 5 ".

Hope this helps.
(1)

Divya said:   8 years ago
Please explain this.

Post your comments here:

Your comments will be displayed after verification.