How to repeat an if statement

Hey ,

I stated coding 4 days ago and i thought i would write a small code . I want to repeat the if fuction if z != 1 or z != 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 if ( z == 1 )
		{
			
	    add Num;
		Num.getNum(x,y);
		
		cout << Num.addition();
		
	         }
		
	    if ( z == 2)
	        {
	    	Multiplication Numbers;
		Numbers.getNum(x,y);
		
	    	cout << Numbers.multiply();
	    	
		}
		else {
			cout << "Please enter one or two : ";
			//Here is the problem
		}
		

Thanks
Last edited on
Hi,

==>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
cout << "Please enter one or two : ";

do
{
		if ( z == 1 )
		{
			
	    add Num;
		Num.getNum(x,y);
		
		cout << Num.addition();
		
	         }
		
	    else if ( z == 2)
	    {
	    	Multiplication Numbers;
		Numbers.getNum(x,y);
		
	    	cout << Numbers.multiply();
	    	
		}
		else {
			cout << "Please enter one or two : ";
			//Here is the problem
	}
} while(z != 1 && z != 2);
Does that help you? :)
Does that help you? :)


No, I have a psychotic hatred for constructs like these:

} while(z != 1 && z != 2);

Better with a switch:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool valid = false;

while (!valid) {
  switch (z) {

    case 1:
       valid = true;  // after this case is executed, code continues after the while loop
       // your code here, consider making it a function 
       
       break;
    case 2:
       valid = true;
       // your code here
       break;
     default:
        std::cout << "Please enter 1 or 2\n"; 

  }
}


Look at the tutorial:
http://www.cplusplus.com/doc/tutorial/control/
Last edited on
Thanks guys i was able to write my program as i wished thanks to you :)
Topic archived. No new replies allowed.