When I use functions I get the desired result which is:-
1)The command window asks me to give input every time so I can input 'q' as many times as I want and can even enter 'e' to exit
2) Every time I press 'q' score decreases by 1
whereas in the code without functions the following happens:-
1) I press 'q' and the score keeps decreasing indefinitely
2) Cannot enter another input like 'e' once entered 'q'
#include<iostream>
using namespace std;
int main()
{
char h;
cin>>h;
int n = 10;
do{
system("cls");
cout<<"score is"<<n;
if(h == 'q')
{
n=n-1;
}
}while(h != 'e');
return 0;
}
CODE 2 with FUNCTION:-
#include<iostream>
using namespace std;
char input;
int n = 10;
bool over = false;
void ip()
{
system("cls");
cout<<"score is"<<n;
cin>>input;
switch(input)
{
case 'q':
n--;
break;
case 'e':
over = true;
break;
}
}
int main()
{
do{
ip();
}while(!over);
return 0;
}
Please explain to me how is the program looping through the function and how is it looping through the 'IF' statement alone. Because the condition statement is there in the function also (switch statement) so why isn't the function decreasing the score or the value of 'n' indefinitely??
Aucun commentaire:
Enregistrer un commentaire