Hello just started learning and I don't understand what I'm doing wrong here , so here is the problem, when I input the string and choose 1 it continues but then when I want the program to exit with 2 I have to input it couple of times why is that happening?
in main()
firstly rep is called in while (rep()!=true)
then you enter name and then 1
rep is called again
this time you enter name and then 2
it returns 1 and get back to previous rep which ends without any return statement
so 0 is returned.
Hence we enter in while loop where rep is called again.It will be called once more while cond. is checked again
Now if you press 2 after name then 1 is returned and condition get false and it exits else it goes again
int main()
{
clrscr();
int name,ans,end;
cout << "\n Enter Name:";
cin >> name;
cout << "\n Hi " << name;
cout << "\n Do Want To Stay <Y/N>";
cin >> ans;
if ( ans == Y )
{
cout << "\n yay Your Staying!";
// rest of your code or you can make a loop
}
else
{
cout << "\n Bye...";
cin >> end;
}
}
#include <iostream>
usingnamespace std;
int func(){
cout << "Compare some numbers \n";
int a;
cout << "Enter a number";
cin >> a;
int b;
cout << "Enter a second number \n";
cin >> b;
if (a==b){
cout << a <<" is equal to " << b;
}elseif (a>b){
cout << a << " is bigger than " << b ;
}elseif (a<b){
cout << a << " is less than " << b;
}
cout << endl;
cout << "Go Again? Yes=1 No=2\n";
int e;
cin >> e;
if (e==1){
func();
}elseif(e==2){
return 1;
}
}
int main()
{
while (func()!=true){
func();
}
return 0;
}
That example looks a bit odd as well. Function func() has only one return statement, return 1; so it must always return a logical true result.
Because of that, this code:
1 2 3
while (func()!=true){
func();
}
will call the function func(), the result will be true, so the while () condition is false and the body of the loop is never executed.
Therefore, main() could be simplified to just:
1 2 3 4 5 6
int main()
{
func();
return 0;
}
As for the option to go again, it's usually better to use a loop rather than having the function call itself. Notice the boolean variable again and the while loop.
void func()
{
bool again = true;
while (again)
{
cout << "Compare some numbers \n";
int a;
cout << "Enter a number ";
cin >> a;
int b;
cout << "Enter a second number ";
cin >> b;
if (a==b)
cout << a <<" is equal to " << b;
elseif (a>b)
cout << a << " is bigger than " << b ;
else
cout << a << " is less than " << b;
cout << endl;
cout << "Go Again? Yes=1 No=2\n";
int e;
cin >> e;
if (e!=1)
again = false;
}
}
void func()
{
char again = '1';
int a, b;
while (again == '1')
{
cout << "Compare some numbers \n";
cout << "Enter a number ";
cin >> a;
cout << "Enter a second number ";
cin >> b;
if (a==b)
cout << a <<" is equal to " << b;
elseif (a>b)
cout << a << " is bigger than " << b ;
else
cout << a << " is less than " << b;
cout << endl;
cout << "Go Again? Yes=1 No=2\n";
cin >> again;
}
}