Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

1/7/2018

Mosul University
Mechatronics Engineering

Programming
1st Class
Instructor : Osamah Abdulwahid Taha
Lecture (6)

The if/else Statement


• The if/else statement will execute one set of statements when the if
condition is true, and another set when the condition is false.

• if (condition)
{
statement set 1;
}
else
{
statement set 2;
}

1
1/7/2018

Example : (Program to find if a number is


even or odd)
int main() {
int x;
cout<<"Enter an integer number : ";
cin>>x;

if(x%2==0)
cout<<"The number is even";
else
cout<<"the number is odd";
}

• What if we add :
cout<<“Hi”; after cout<<“even”<<endl;
What will happen??
Will the compiler show an Error?
Try it yourself.

2
1/7/2018

The if/else if Statement


• The if/else if statement is a chain of if statements. They perform their
tests, one after the other, until one of them is found to be true.

Example :

#include <iostream>
using namespace std;
int main()
{
int num;
cout<<"Enter number value : \n";
cin>>num;

3
1/7/2018

if(num == 1)
cout<<“one”;
else if(num == 2)
cout<<“two”;
else if(num == 3)
cout<<“three”;
else
cout<<“not”;
return 0;
}

Logical Operators
• And in C++ we write it &&
1 1 1
1 0 0
0 1 0
0 0 0

• Or in C++ we write it ||
1 1 1
1 0 1
0 1 1
0 0 0

• Not in C++ we write it !


0 1

1 0

4
1/7/2018

Example :
int main() {
cout<<(true && true)<<endl;
cout<<(true && false)<<endl;
cout<<(true || false)<<endl;
cout<<(false || false)<<endl;
cout<<(!true)<<endl;
cout<<(!false)<<endl;
cout<<(!(true && false))<<endl;
return 0;
}

Output :
1
0
1
0
0
1
1

5
1/7/2018

logical operators precedence


1- !
2- &&
3- ||

cout<<(false || !true && false) output : 0 Why?

Example : to print student grade


int main () {
int m;
cout<<“enter student mark : “;
cin>>m;
if (m>=90 && m<=100)
cout<<“Excellent”;
else if(m>=80 && m<90)
cout<<“Very Godd”;
else if(m>=70 && m<80)
cout<<“Good”;
else if(m>=60 && m<70)
cout<<“Average”;

6
1/7/2018

else if(m>=50 && m<60)


cout<<“pass”;
else if(m>=0 && m<50)
cout<<“fail”;
else
cout<<“Wrong mark!”;
return 0;
}
If we Enter 85 what is the output?
If we Enter 187665 what is the output?
Try yourself …

Nested if Statements
• To test more than one condition, an if statement can be nested inside another if statement.

if (condition) {
……
……
If(condition) {
…..
…..
}
…..
……
}

7
1/7/2018

Example : to check character status


int main() {
char x;
cout<<“Enter a charator : ”;
cin>>x;

if(x >= ‘A’ && x <= ‘z’) {


cout<<“letter”<<endl;
if(x >= ‘A’ && x<= ‘Z’) {
cout<<“Capital”<<endl; }
else if(x >= ‘a’ && x<= ‘z’) {
cout<<“Small”<<endl; }
}

else if(x >= ‘0’ && x <= ‘9’)


cout<<“number”<<endl;
else
cout<<“other”<<endl;
return 0;
}
What the program output if the user enter : B ?
b?
7?
Try it yourself ….

8
1/7/2018

if
if
if

else
else
else

You might also like