If Sec1
If Sec1
{statement}
c. if (condition)
{statement}
else if (condition)
{statement}
else
{statement}
2- Switch
Switch (expression)
...
1
EX1: write a c++ program that reads two integers and prints their maximum
include <iostream>
using namespace std;
int main()
{ int A,B;
cout<<"enter first number";
cin>>A;
cout<<"enter second number";
cin>>B;
if (A>B)
cout<<"A is bigger ";
else
cout<<"B is bigger ";
system("pause"); }
EX2: Write c++ program to read an integer number and then determine its type
odd or even (Q14 sheet 3)
#include <iostream>
using namespace std;
int main()
{
int n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
system("pause"); }
2
EX3: Write c++ program to read an integer number and then determine its
type positive or negative. (Q13 sheet 3)
#include <iostream>
using namespace std;
int main()
{
int x;
if ( x>0)
cout << x << " is positive.";
else if(x<0)
cout << x << " is negative.";
else
cout << x << " equals zero.";
system("pause"); }
3
EX4: Write a program to make a simple calculator, the program will ask the user
to enter 2 numbers and the operation symbol (+, -, * or /)then the program will
perform the required operation on the two numbers and print the result
(Q11 sheet 3)
#include <iostream>
using namespace std;
int main(){
Float first,second,result;
Char symbol;
Cout<<“enter first number:’;
Cin>>first;
Cout<<“enter operation symbol(*, /, + or -):”;
Cin>>symbol;
Cout<<“enter second number:”;
Cin>>second;
If(symbol == ‘+’) result = first + second;
else if (symbol == ‘-’) result = first - second;
else if (symbol == ‘*’) result = first * second;
else if (symbol == ‘/’)
{ if(second == 0)
{cout<<“you cannot divide by zero\n”; }
else result = first / second; }
system("PAUSE");}
4
Solution using switch-case
#include <iostream>
using namespace std;
int main(){
float first, second, result;
char symbol;
cout<<"enter first number:";
cin>>first;
cout<<"enter operation symbol(*, /, + or -):";
cin>>symbol;
cout<<"enter second number:";
cin>>second;
switch(symbol)
{
case'+': result = first + second; break;
case'-': result = first - second; break;
case'*': result = first * second; break;
case'/': if(second == 0)
{cout<<"you can not divide by zero\n";}
else result = first / second; break;
default: cout<<"you entered wrong operation symbol\n";}
cout<<"result of"<<first<<symbol<<second<<"="<<result<<"\n";
system("PAUSE");}