C++ Programming - Functions - Discussion

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

Sowmiya said:   7 years ago
@All. According to me.

void BixArray::BixFunction()
{
static int i = 0, j = 4;
i++;
j--;
if(j > 0)
BixFunction();
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i--;
j++;
}
when j>0,bix function is called again,Initially i=0,j=4,
Then i++ leads to i=1,then j-- leads to j=3,
i=1,j=3->if(3>0)call bixfunction()
i=2,j=2->if(2>0)call bixfunction()
i=3,j=1->if(1>0)call bixfunction()
i=4,j=0->if(0>0)condition fails,so it skips to the next line,
Now,i=4,j=0
tmp=arr[i]implies tmp=arr[4]->element in 4th index is stored in tmp.
arr[i]=arr[j]implies arr[4]=arr[0]->element in 0th index is stored in 4th index.
arr[j]=tmp implies arr[0]=tmp->element in te\mp stored in 0th index.
so this implies swap(element in 0th index,element in 4th index)

It results in;
objArray--------->{5,6,3,9,0} here a[0]=5,a[4]=0
swap(a[0],a[4]) then objArray-------------> {0,6,3,9,5}

Mehak said:   7 years ago
The answer is correct because bixfunction is being called recursively so i++ will keep on incrementing again and again n will reach to the last element when i=4.

Similarly, j will keep on decrementing and will reach j=0.

Only one swap between 0 (first element) and 5 (last element) will take place.

At last, I will decrement and j will increment and function returns back. At last, array will be (d) 06395.

Cham said:   8 years ago
The swapping has been done in such a way "i" is pointing to starting position and "j" is pointing to the last position so, I think option "b" is true.

Meet said:   8 years ago
I think the answer should be (B) 09365.

Can anyone give the correct explanation?

Johnny said:   8 years ago
How did you tell that option (B) is correct.

Explain it @Meet.

Vijayeta said:   8 years ago
How the answer is 06395? please someone explain me.

Gayathry said:   9 years ago
Can anyone explain this?

Post your comments here:

Your comments will be displayed after verification.