CSC201 - Week8
CSC201 - Week8
Course Lecturer:
Haruna Musa
([email protected])
The if statement
The if..else statement
The Switch Statement
SELECTION
Sometimes you won’t want every statement
in your C++ program to execute every time
the program runs.
if (condition){
statements;
}
The condition includes any relational
comparison, and it must be enclosed in
parentheses.
The block of one or more C++ statements
is any C++ statement, such as an
assignment or cout, enclosed in braces.
The block of the if, sometimes called the body
of the if statement, is usually indented a few
spaces for readability.
Consider the following example:
if (expression){
statement1;
statement2;
statement3;
}
Here's a simple example of this usage:
If (condition)
Statement;
else
Statement;
Where condition is an integral expression and statement1
and statement2 are executed statements.
Example: this program is the same as the program above
except that, the if statement has been replaced by an if…else
statement.
#include<iostream>
int main()
{int n;
cout<<"enter a positive integers:";
cin>>n;
if (n%2 ==0)
cout<<"is even number"<<endl;
else
cout<<"is not an even number"<<endl;}
Statement Blocks
A statement block is a sequence of statements
enclosed by braces { } like this:
{ int temp = x; x = y; y = temp; }
Example: this program inputs two integers and then outputs them in increasing
order;
#include<iostream >
Int main()
{ int x, y;
Cout<< “enter the two integers:”;
Cin>>x>>y;
If (x>y)
{int temp = x; x =y; y =temp;} //swap x and y:
Cout<<x<< “<=”<<y<<endl;
}
Note that a C++ program itself is a statement
block preceded by int main().
Recall that the scope of a variable is that part
of program where the variable be used.
It extends from the point where the variable is
declared to the end of the block which that
declaration controls.
So a block can be used to limit the scope of a
variable, thereby allowing the same name to
be used for different variables in different
parts of the program.
#include<iosteam>
Int main()
{
Int n = 44;
Cout<< “n =”<<n<<endl;
{int n;
Cout<< “enter an integer:”;
Cin>>n;
Cout<< “n =”<<n<<endl;
}
{cout<< “n=”<<n<<endl;
}
{int n;
Cout<< “n=”<<n<<endl;
}
Cout<< “n=”<<n<<endl;
}
Compound Conditions
Conditions such as n%d and x>=y can be combined
to form compound conditions. This is done using
the logical operators && (and), // (or), and ! (not).
They are define by