C++ Programming - Functions - Discussion

Discussion Forum : Functions - Programs (Q.No. 6)
6.
Which of the following statement is correct about the program given below?
#include<iostream.h> 
class IndiaBix
{ 
    public:
    void Bix(int x = 15)
    {
        x = x/2; 
        if(x > 0)
            Bix(); 
        else
            cout<< x % 2; 
    } 
};
int main()
{
    IndiaBix objIB;
    objIB.Bix();
    return 0; 
}
The program will display 1.
The program will display 2.
The program will display 15.
The program will go into an infinite loop.
The program will report error on compilation.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
8 comments Page 1 of 1.

Neha said:   7 years ago
Right @Jitendra.

It gives error segmentation fault.

Jitendra said:   8 years ago
It gives an error segmentation fault then how it goes to an infinite loop?

Aaditya Gupta said:   10 years ago
Is it not necessary to declare a data member x? "x=x/2"?

Here x is argument of function can we directly change it w/o second variable?

Anirudh said:   1 decade ago
This is one of the good question based on the understanding of scope of a variable along with the Default parameter concept.

During its first call the if condition gets true and the statement with in if gets executed thereafter function is called again. Now the variable "X" does not exist anymore and it against becomes equal to 15 and the process continues in this fashion resulting into a Infinite Loop.
(2)

Manish said:   1 decade ago
x=15 is a default argument, so whenever Bix() is called inside if block then Bix(x=15) is called so value of x is always 15.

Tsaone said:   1 decade ago
x = 15.
x is assigned 15.
x = x/2 means x = 15/2.

statement if x>0
bix();
means if the answer output after dividing 15 by 2 is greater than zero then bix() should repeat else if less than 15 display result.

*Therefore the statement goes into an endless looping because all answers will be greater than 15 hence repetition of one function.

Vishal said:   1 decade ago
x=15
x=15/2
x=7
x>0 so again call function Bix() with default parameter, x=15
So x is set to 15
So infinite loop.
(1)

Sathya said:   1 decade ago
x=15, then 15/2=7.5 again it goes to the condition x/2 hence it has an infinite loop

Post your comments here:

Your comments will be displayed after verification.