Handout-3 CSM-1101
Handout-3 CSM-1101
To Know syntax and use of if, if … else, Nested if, if … else if … else,
switch Selection Statements.
To Know about relational and logical operators of C/C++ language and their use.
To know about order of execution of relational and logical operators with others
operators.
To know syntax of wile, do-while, for statements (loops).
To know working of above loops with examples.
To learn about goto, continue and break statements.
To learn about conditional operator
Selection Structures:
Syntax: if (expression)
Statement;
If the expression is true, then the statement is executed; otherwise the statement is
ignored.
For example, let marks be an integer variable. To check the value of marks to see if it is
more than 75 and print PASS if it is more than 75 we would write
If marks is less than or equal to 75 then the print statement is ignored and nothing is
printed.
If suppose that in addition to printing PASS we would like to add 5 bonus marks then we
would write
1
{
marks = marks + 5 ;
cout<<“PASS”<<endl ;
}
As seen above if there is more than one statement (compound statement) to be done after
checking the expression result, then the statements should be enclosed between
parentheses. If there is only one statement (simple statement) to be executed after if then
the parenthesis becomes optional (you can remove it). Note that there is no semi-
colon at the end of the if or else statement.
Syntax: if (expression)
statement 1;
else
statement 2;
If the expression is true, then the statement 1 is executed; otherwise the statement 2 is
executed if expression is false.
For example, to find the larger of two variables x and y and print the answer and assign
the larger value to max variable and smaller value to min variable, we would write :
if ( x > y )
{
max = x ;
min = y ;
cout<<“ x is BIG”<<endl ;
}
else
{
max = y ;
min = x ;
cout<<“ y is BIG”<<endl;
}
Check for the parenthesis used for more than one statement after if and else.
2
The most commonly used relational operators are
> for greater than
>= for greater than or equal to
< for less than
<= for less than or equal to
== for equal to
!= for not equal to
These operators are used in the expression of if statement. The expression having these
operators is called Logical expression.
Examples:
To check if the value of the integer variable x is more than 5 and less than 10 or equal to
15, we write
To check if the value of the float variable a is not equal to 1.5 or less than or equal to 2.5
but more than or equal to 1.5, we write
Syntax: if ( expression 1 )
statement 1;
else if ( expression 2 )
statement 2;
.
.
else if ( expression n )
statement n;
else
3
statement e;
For example, to check the value of the variable marks and print the message accordingly,
we would write
Nested if statements:
There can be if statements inside if and else statements which can be used to implement
decisions with several alternatives.
For example,
if ( x > 2.5 )
{ p=p+1;
if ( x < 3.5 )
n = n + 1;
else
m = m + 1;
}
else
{
if ( x > 1.5 )
s=s+1;
else
t = t + 1;
}
In the above example, if x is greater than 2.5 then 1 is added to p and it is checked if x is
less than 3.5. If it is so, then 1 is added to n. If x is more than 3.5, 1 is added to m. If x is
4
less than 2.5, the execution comes directly to the else part without doing anything to p, n,
m and it is checked if x is more than 1.5. If it is so 1 is added to s else 1 is added to t.
switch (expression)
{
case value 1:
statement 1;
break ;
case value 2:
statement 2;
break ;
:
:
case value n:
statement n;
break ;
default:
statement e;
}
Here it is checked whether the value of expression matches any of the case values.
For example, to check the value of the character variable color and print the message
accordingly, we write
switch (color)
{
case „R‟:
cout<<“red”<<endl ; break ;
case „B‟:
cout<<“blue”<<endl ; break ;
case „Y‟:
cout<<“yellow”<<endl ; break ;
default:
cout<<“black”<<endl ; break ;
}
The single quotes ‘R’,’B’,’Y’ are used because of the color being character variable. If
color is „R‟ then red is printed and the other cases are not checked, however if color is
not red then other cases are checked until a match is found. If no match is found then the
default value of black is printed.
5
Operator Precedence:
Operator Precedence
* , /, % . IInd
+, _ . IIIrd
Examples:
Example#1:
/***********************************************************************
************************************************************************
Write a program that calculates and displays the reciprocal of an integer, both as a
common fraction and a decimal fraction. A typical output line would be :
The program should display a Reciprocal undefined message for an input of zero.
************************************************************************
************************************************************************
/
#include<iostream.h>
6
void main ()
{
int number;
float reciprocal;
cout<<"please Enter an integer number: ";
cin>>number;
if (number>0 || number<0)
{
reciprocal = 1.0/number;
cout<<"\nThe reciprocal of " <<number <<" is = "<<"1/"<<number<<" or "<<reciprocal<<endl;
}
else
cout<<"\nReciprocal undefined"<<endl;
} // end of main
Sample Output:
Example#2:
/***********************************************************************
************************************************************************
**********************
Write an interactive program that contains a compound if statement and that may
be used to compute the area of a square (area=side2 ) or a triangle
(area=base*height/2) after prompting
the user to type the first character of the figure name (S or T).
************************************************************************
************************************************************************
*********************/
Using If statement.
#include<iostream.h>
void main ()
{
int side, height, base, area;
7
char D,S,T;
cout<<"If you want area of a square press S or T for area of triangle :";
cin>>D;
if (D=='S')
{
cout<<"Please input the side : ";
cin>>side;
area=side*side;
cout<<"The area = "<<area<<endl;
}
else if (D=='T')
{
cout<<"Enter base and height of the triangle :";
cin>>base>>height;
area=(0.5)*base*height;
cout<<"The area of triangle is ="<<area<<endl;
}
else
{
cout<<"Dear !, Your choice must be either S or T only "<<endl;
cout<<"\nPlease try again !";
}
} // end of main
Sample Output:
/***********************************************************************
********************************
Using Switch statement
************************************************************************
*******************************/
#include<iostream.h>
void main( )
{
char choice;
double side, height, base, area;
8
cout<<"[To find the shape's area choose either 'S' for square , or 'T' for
triangle] : ";
cout<<"\nEnter your choice to find the area : ";
cin>>choice;
switch(choice)
{
case 'S': cout<<"\nEnter its side: ";
cin>>side;
area = (side * side);
cout<<"The area of square is = "<<area<<" unit
square"<<endl;
break;
default: cout<<"Sorry ,your choice is not included \nPlz try again "<<endl;
}
} // end of main
Sample Output:
9
Looping Structures:
While statement:
A conditional loop is one whose continued execution depends on the value of a logical
expression. In the above syntax as long as the expression is true the statement (or
statements if enclosed within braces) is executed. When the expression evaluates to false
the execution of the statement(s) stops and program continues with the other following
statements.
Example:
In the above example, as long as the entered value of number is greater than 100 the loop
continues to ask to enter a value for number. Once a number less than or equal to 100 is
entered it stops asking. If in the beginning itself the value of number is less than or equal
to 100, then the loop is not at all executed.
Note: In the while loop the expression is tested before the loop body statements are
entered. So, if the expression is false in the beginning the loop body is never entered.
do…while statement :
Syntax: do
statement
while (expression) ;
10
Here, the expression is tested after the statement(s) are executed. So, even if the
expression is false in the beginning the loop body is entered at least once. Here also like
the while statement, as long as the expression is true the statement (or statements if
enclosed within braces) is executed. When the expression evaluates to false the execution
of the statement(s) stops and program continues with the other following statements.
Example:
do
{
cout<<“Enter a number\n” ;
cin>>number ;
} while (number > 100) ;
In the above example, as long as the entered value of number is greater than 100 the loop
continues to ask to enter a value for number. Once a number less than or equal to 100 is
entered it stops asking.
Note: In the conditional looping using while and do…while the number of times the loop
will be executed is not known at the start of the program.
for statement :
Syntax:
In the iterative looping using for loop the number of times the loop will be executed is
known at the start of the program. In the above syntax, the expression 1 is the
initialization statement which assigns an initial value to the loop variable. The expression
2 is the testing expression where the loop variable value is checked. If it is true the loop
body statement(s) are executed and if it is false the statements(s) are not executed. The
expression 3 is usually an increment or decrement expression where the value of the loop
variable is incremented or decremented.
Example:
for (count = 0 ; count < 10 ; count++)
{
cout<<(“Enter a value\n” ;
cin>>num ;
11
num = num + 10 ;
cout<<“NUM = “<<num<<endl ;
}
In the above example the integer variable count is first assigned a value of 0, it is
initialized. Then the value of count is checked if it is less than 10. If it is < 10 the loop
body asks to enter a value for num. Then the value of count is incremented by 1 and
again count is checked for less than 10. If it is true the loop body is again executed and
then the count is incremented by 1 and checked for < 10. It keeps on doing like this until
the count is >= 10. Then the loop stops. So, here the loop is executed 10 times.
Note: The increment operation is written as ++ and decrement operation is written as --.
The increment increases the value by 1 and decrement decreases the value by 1.
Example (i):
for loop :
#include<iostream.h>
void main()
{
int num,square,limit;
cout<<"Please Input value of limit : ";
cin>>limit;
12
for (num=0; num < limit; ++num)
{
square = num*num;
cout<<" "<<num<<" "<<square<<endl;
} // end of for
} // end of main
Sample Output:
Example (ii). :
/*****************************************************************
*
Program Showing a Sentinel-Controlled for loop.
To Compute the sum of a list of exam scores.
******************************************************************/
#include <iostream.h>
#define SENTINEL -99
void main()
{
int sum = 0, /* sum of scores input so far */
score; /* current score */
cout<<"Enter first score (or "<<SENTINEL <<" to quit)> ";
for(cin>>score; score != SENTINEL; cin>>score)
{
sum += score;
cout<<"Enter next score ("<<SENTINEL<<" to quit)> ";
} // end of for loop
cout<<"\nSum of exam scores is = "<<sum<<endl;
} // end of main
Sample Output:
13
Example (iii):
#include<iostream.h>
void main()
{
int n, m, p, i = 3, j = 9;
n = ++i * --j;
m = i + j--;
p = i + j;
Sample Output:
14
C++ continue statement
The continue statement works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place,
skipping any code in between. Continue statement causes the loop to skip the remainder
of its body and immediately retest its condition prior to reiterating.
For the for loop, continue causes the conditional test and increment portions of the loop
to execute. For the while and do...while loops, program control passes to the conditional
tests.
Syntax
The syntax of a continue statement in C++ is:
continue;
Flow Diagram
15
Example of Continue statement:
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
cout<<"MCA Semeser-I 2017-18"<<endl<<endl;
// do loop execution
do {
if( a == 15)
{
// skip the iteration.
a = a + 1;
continue;
}
return 0;
}
Sample output:
16
Use of break statement in C++:
It terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the
loop.
It can be used to terminate a case in the switch statement (covered in the next
chapter).
If you are using nested loops (i.e., one loop inside another loop), the break statement will
stop the execution of the innermost loop and start executing the next line of code after the
block.
Syntax
The syntax of a break statement in C++ is:
break;
Example:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
cout<<"\n\nWelcome to AMU in 2017-18 session"<<endl<<endl;
// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
17
Return 0;
}
Sample output:
Transfers control to the labeled statement. Though it is not advised to use goto statement
in your program.
A goto statement provides an unconditional jump from the goto to a labeled statement in
the same function.
NOTE: Use of goto statement is highly discouraged because it makes difficult to trace
the control flow of a program, making the program hard to understand and hard to
modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.
Syntax
The syntax of a goto statement in C++ is:
goto label;
..
.
label: statement;
Where label is an identifier that identifies a labeled statement. A labeled statement is any
statement that is preceded by an identifier followed by a colon (:).
18
Example:
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
cout<<"\n\nWelcome to AMU in 2017-18 session"<<endl<<endl;
// do loop execution
LOOP: do {
if( a == 15) {
// skip the iteration.
a = a + 1;
goto LOOP;
}
return 0;
}
Sample output:
19
Example:
#include<iostream.h>
void main()
{
int i=1;
start : cout<<"i= "<<i<<endl;
i=i+2;
if (i<=20)
goto start;
}
Sample output:
Example:
#include <iostream.h>
void main ()
{
int a = 1;
loop: // label stament
cout<<"a= "<<a<<endl;
a++;
if (a < 10) goto loop ; // jump statement
}
Sample output:
20
Example:
#include <iostream.h>
int main ()
{
for (int i = 0; i<100; i++)
{
cout<<"i= "<<i<<endl;
if (i == 10); // This code prints value only upto 10.
break;
}
return 0;
}
Sample output:
21
Example:
#include <iostream.h>
int main ()
{
for (int i = 0; i<100; i++)
{
if (i == 10);.
continue ;
cout<<"i= "<<i<<endl;
}
return 0;
}
Sample output:
Conditional operator ( ? : )
The conditional operator evaluates an expression returning a value if that expression is
true and a different one if the expression is evaluated as false. Its format is: condition?
result1 : result2. If condition is true the expression will return result1, if it is not it will
return result2. 7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
22
Example:
//Write a program to find the greatest of two numbers.
#include <iostream.h>
#include <iomanip.h>
void main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout<<setw(5)<<c<<endl;
}
Sample output:
23
Exercises
Q1.
The nested conditional statement shown below has been written by an inexperienced
C/C++ programmer. The behavior of the statement is not correctly represented by the
formatting.
if (n < 10)
if (n > 0)
cout << "The number is positive." << endl;
else
cout << "The number is ______________." << endl;
a. What is the output of the statement if the variable n has the value 6 ? If n has the value
16 ? If n has the value 2 ?
Q2.
Rewrite the following code fragment so that it uses a "do...while..." loop to accomplish
the same task.
int n;
cout << "Enter a non-negative integer: ";
cin >> n;
while (n < 0)
{
cout << "The integer you entered is less than zero." << endl;
cout << "Enter any number greater than zero ";
cin >> n;
}
Q3.
What is the output when the following code fragment is executed?
int p = 5;
while (p > 0)
{
24
--p;
cout << p << endl;
}
Q4.
Write a program using while loop to print the Fibonacci series upto ‘n’ terms.
Q5.
Rewrite the above program using for loop.
Q6.
What is the value of ‘c’ in the following code segment.
a = 10;
b=a++;
c=++a+b;
-----------------------------------
25