0% found this document useful (0 votes)
12 views63 pages

Chapter 3-Computer Programming-Control Statements

This document covers control statements in computer programming, specifically focusing on looping, conditional/branching statements, and the switch statement in C++. It explains various types of selection statements such as one-way if, two-way if-else, multi-way if-else, and nested if statements, along with their syntax and examples. Additionally, it discusses the switch statement and conditional expressions, providing practical programming examples and quizzes for comprehension.

Uploaded by

rajizerihun140
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views63 pages

Chapter 3-Computer Programming-Control Statements

This document covers control statements in computer programming, specifically focusing on looping, conditional/branching statements, and the switch statement in C++. It explains various types of selection statements such as one-way if, two-way if-else, multi-way if-else, and nested if statements, along with their syntax and examples. Additionally, it discusses the switch statement and conditional expressions, providing practical programming examples and quizzes for comprehension.

Uploaded by

rajizerihun140
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Computer Programming (CP)

Unit-3
Control
Statements

Admas Abtew
Faculty of Computing and
Informatics
Jimma Technology Institute, Jimma
[email protected]
+251912499102
 Looping
Outline
 Control flow
 The 3 Basic Structures in
Programming Languages
 Sequence
 Selection/conditional
 Loop
1.Control of Flow

A flow control statement can cause a change in the


subsequent controls of flow to differ from the natural
sequential order in which the instructions are listed.
 Flow control roughly categorized into 3. These are:
1. Conditional/Branching/selection statements
2. Iteration/Looping/Repetition statements
3. Jumping statements

CP  Unit 3-Control Statements 3


Cont’d…
 Loop

True
Condition? Statement

False
Statement

True
Condition?

False

CP  Unit 3-Control Statements 5


1. Conditional or Selection Statements

 The program can decide which statements to execute


based on a condition.
 C++ provides several types of selection
statements:
1. one-way if statements,
2. two-way if-else statements,
3. nested if and multi-way if-else statements,
4. switch statements, and
CP  Unit 3-Control Statements 6
1.1. The One-way if statement
 The syntax for a one-way if statement is shown here:

if (Boolean_expression)
{
statement(s);
}
It executes an action if and only if the condition is true.

CP  Unit 3-Control Statements 7


Cont’d…

 If the boolean-expression evaluates to true, the statements in the


block are executed.
#include<iostream.h>
int main()
{
int grade;
cout<<“Enter the student grade: ”;
cin>>grade;
if ( grade >= 50 )
cout << “\n Passed“;
return 0;
}
 The braces can be omitted if they enclose a single statement.
 E.g., if (i > 0)
cout << "i is positive" << endl;
CP  Unit 3-Control Statements 8
Cont’d…

 Write a program that prompts the user to enter an integer. If the


number is a multiple of 5, display Hello Five. Also, if the number is
even, display Hello Even.
Ans. #include <iostream>
using namespace std;
int main() { int number;
cout << "Enter an integer: ";
cin >> number;
if (number % 5 == 0) cout << "Hello Five!" << endl;
if (number % 2 == 0) cout << "Hello Even!" << endl;
return 0;
}

CP  Unit 3-Control Statements 9


1.2. Two-way if-else statement
 An if-else statement decides which statements to
execute based on if the condition is true or false.
Flowchart
if (Boolean_expression)
{
Syntax

statement(s);
}
else
{
statement(s);
}

CP  Unit 3-Control Statements 10


Cont’d…
#include<iostream.h>
int main()
{
int grade;
cout<<“Enter the student grade: ”;
cin>>grade;
if ( grade >= 50 )
cout << “\n Passed“;
else
cout << “\n Failed“;
return 0;
}
CP  Unit 3-Control Statements 11
Cont’d…
// Program to check whether an integer is positive or negative
// This program considers 0 as a positive number
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if (number >= 0)
{
cout << "You entered a positive integer: " <<
number << endl;
}
else
{
cout << "You entered a negative integer: " <<
number << endl;
}
cout << "This line is always printed.";
return 0; CP  Unit 3-Control Statements 12
1.2.1. The Multi-Way if-else Statement
The syntax of the if...else if...else statement is:
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
• This style, called multi-way if-else statements, avoids deep
indentation and makes the program easy to read.

CP  Unit 3-Control Statements 13


Multi-Way if-else flowchart

CP  Unit 3-Control Statements 14


Multi-way if-esle flowchart to assign grade.

CP  Unit 3-Control Statements 15


Example
#include<iostream.h>
int main()
{
int grade;
cout<<“Enter the student grade: ”;
cin>>grade;
if ( grade >= 90 )
cout << “\n You Get Grade A “;
else if ( grade >= 80 )
cout << “\n You Get Grade B “;
else if ( grade >= 70 )
cout << “\n You Get Grade C “;
else if ( grade >= 60 )
cout << “\n You Get Grade D “;
else
{
cout << “\n You Get Grade F“;

}
return 0;
}
CP  Unit 3-Control Statements 16
1.3 Nested if Statement
 An if statement can be inside another if statement to
form a nested if statement.
 Its syntax is:
// outer if statement
if (condition1)
{
// statements
// inner if statement
if (condition2)
{
// statements
}
}

CP  Unit 3-Control Statements 17


Nested if Statement
if (i > k)
{
if (j > k)
cout << "i and j are greater than k" << endl;
}
else
cout << "i is less than or equal to k" << endl;

The if (j > k) statement is nested inside the if (i > k).


The nested if statement can be used to implement multiple alternatives.

CP  Unit 3-Control Statements 18


Nested if flowchart

CP  Unit 3-Control Statements 19


// C++ program to find if an integer is even or odd or neither (0)
// using nested if statements
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
// outer if condition
if (num != 0) {
// inner if condition
if ((num % 2) == 0) {
cout << "The number is even." << endl; }
// inner else condition
else {
cout << "The number is odd." << endl; } }
// outer else condition
else {
cout << "The number is 0 and it is neither even nor odd." << endl;
}
cout << "This line is always printed." << endl;
}
CP  Unit 3-Control Statements 20
Home Work
 Suppose x = 3 and y = 2; show the output, if any, of the
following code. What is the output if x = 3 and y = 4? What
is the output if x = 2 and y = 2?
 Draw a flowchart of the code.
if (x > 2) {
if (y > 2) {
int z = x + y;
cout << "z is " << z << endl;
}
}
else
cout << "x is " << x << endl;

CP  Unit 3-Control Statements 21


1.4. The switch Statement

CP  Unit 3-Control Statements 22


The switch Statement

switch (condition)
The switch {
case value1:
Statement statement11;
...
 Multiple selection break;
structure case value2:
statement21;
 Performs different actions ...
for different test break;
expression values
...
 Less general than nested
if-else statement case valueN:
 integer test expression statementN1;
...
only break;
 test for equality only default:
statementD;
...
}

CP  Unit 3-Control Statements 23


THE SWITCH STATEMENT FLOWCHART

CP  Unit 3-Control Statements 24


Cont’d…

switch (expression)
{ The switch Statement
case value1:
statement11;
(cont’d)
...  Uses 4 keywords
break;
case value2:  switch
statement21;  identifies
... start of switch
break; statement
 expression in parentheses
...
(switch expression) evaluated
case valueN: & its value compared to
statementN1; various alternative (case)
...
break; values within compound
default: statement that follows
statementD;
...
}

CP  Unit 3-Control Statements 25


Cont’d…

switch (expression) The switch Statement (cont’d)


{
case value1:  Uses 4 keywords (cont’d)
statement11;
...  Case
break;  identifies possible entry points
case value2:
statement21; of switch statement
...  comparison done in order in
break;
which case values are listed
...  execution begins with
case valueN: statement immediately
statementN1; following case value that
... matched value of switch
break;
default: expression
statementD;
...
}

CP  Unit 3-Control Statements 26


Cont’d…

switch (expression) The switch Statement (cont’d)


{
case value1:  Uses 4 keywords (cont’d)
statement11;
...  break
break;  identifies end of each case & forces
case value2: immediate exit from switch statement
statement21;  once entry point established, no
...
break; further case evaluations done; all
statements within compound
... statement executed unless break
statement is encountered
case valueN:  if omitted, all statements in
statementN1; compound statement following entry
...
break; point (including default case) are
default: executed
statementD;
...
}

CP  Unit 3-Control Statements 27


Cont’d…

switch (expression) The switch Statement


{
case value1: (cont’d)
statement11;
...  Uses 4 keywords (cont’d)
break;  default
case value2:
statement21;  identifies default action
... when no match between
break; case value & switch
... expression value exists
 optional (if switch
case valueN:
statementN1; expression value does not
... match any case value, no
break; statement is executed
default:
statementD; unless default is
... encountered)
}
 invariably placed at bottom
of switch statement (by
CP  Unitvirtue of its purpose); break
3-Control Statements 28
E.g. Simple Calc. using switch
• A switch statement executes statements based on the value
of a variable or an expression.

CP  Unit 3-Control Statements 29


Cont’d…
 #include <iostream>  Commenting Grades using
using namespace std; switch statement.
int main () {
char grade = ‘B’;
switch(grade) {
case ‘A’ : cout << “Excellent!” << endl;
break;
case ‘B’ :
case ‘C’ : cout << “V. Good!” << endl;
break;
case ‘D’ : cout << “Poor!” << endl;
break;
case ‘F’ : cout << “Fail!” << endl;
break;
default : cout << “Invalid grade” << endl;
}cout << "Your grade is " << grade << endl;
return 0; V. Good!
} Your grade is B
CP  Unit 3-Control Statements 30
Cont’d…
• Here is an example which has fall-throughs.
• Suppose we want to print the number of days in the nth month of the
year, taking n as the input. Here is the program.

CP  Unit 3-Control Statements 31


Cont’d…

CP  Unit 3-Control Statements 32


Cont’d…
// A program which identifies the input character is vowel, consonant or space
#include<iostream.h>
int main()
{
char ch;
cout<<“Enter a character ";
cin>>ch;
switch(ch)
{
case 'a‘: case 'e‘: case 'i': case 'o': case 'u‘: //means if(ch==‘a’ || ch==‘e’ || ch==‘i’ || ch==‘o’
|| ch==‘u’ )
cout<<"vowel";
break;
case ' ':
cout<<"space";
break;
default:
cout<<"consonant";
break;
}
return 0;
} CP  Unit 3-Control Statements 33
Nested switch Statement
. #include <iostream>
using namespace std;
int main ( )
{
This is outer switch
int a = 100;
This is inner switch
int b = 200; The value of a is : 100
switch (a) { The value of b is : 200
case 100:
cout << "This is outer switch" << endl;
switch (b) {
case 200:
cout << "This is inner switch" << endl;
}
}
cout << "The value of a is : " << a << endl;
cout << "The value of b is : " << b << endl;
return 0;
}
CP  Unit 3-Control Statements 34
1.5. The Conditional Expressions
.

• A conditional expression evaluates an expression based on


a condition.
Syntax: boolean-expression ? expression1 :
expression2;

• For example, the following statement assigns 1 to y if x is


greater than 0, and -1 to y if x is less than or equal to 0.

if (x > 0) y=x>0?
1 : -1;  You might want to assign a variable
y = 1; a value that is restricted by certain
else conditions.
y = -1; E.g. int max = (a>b) ? a : b;

CP  Unit 3-Control Statements 35


Quiz
.

1. Write a program to accept any character from keyboard and


display whether it is vowel or not.
2. Write a program that gives grade based on the following
> 95 –> A+ 70 - 74 –> B
scale using if85else statement:
- 94 –> A 65 - 69 –> B-
80 - 84 –> A- 60 - 64 –> C+
75 - 79 –> B+ 50 - 59 –> C
<50 – F
3.Write a program that display greatest of three numbers using if
statement accept input from user.

CP  Unit 3-Control Statements 36


Quiz
.

4. Write a program that accepts three numbers from the user and prints "increasing" if
the numbers are in increasing order, "decreasing" if the numbers are in decreasing
order and "Neither increasing nor decreasing order" otherwise.

5. Write a program to calculate sum, average and check your grade status, if pass or
fail.

Hint: accept at least three course marks then calculate the total, and average of your
mark, the status will be based on average value. Display the total mark, average and
status.

CP  Unit 3-Control Statements 37


2. Iteration or Looping Statements
.

 it is required to repeatedly evaluate a statement or a whole


block of statements with increment/decrement of some data in
order to arrive at a result.
 Repeated evaluation of statements is called iteration and
recursion. However, iteration is about looping.
 C++ provides
1. for statements,
several and statements:
types of iteration

2. while statements,
3. do … while statements,

CP  Unit 3-Control Statements 38


2.1. The for loop
.
• The for loop iterates a section of C++ code for a
fixed number of times
• The for loop runs as long as the test condition is
true.
for ( init; cond; inc /dec ) {
statement;
}

CP  Unit 3-Control Statements 39


Cont’d…
The for Statement
Problem: print numbers 1 through 10 on standard output
Solution using for statement

#include <iostream.h>
int main()
{
int counter;
for (counter = 1; counter <= 10; counter++)
cout << counter << endl;
return(0);
}

CP  Unit 3-Control Statements 40


Cont’d…
.
The for Statement (cont’d)
control limiting value of
variable control variable

for (counter = 1; counter <= 10; counter++)

for initial value of updating


keyword control variable control variable

CP  Unit 3-Control Statements 41


Cont’d…
.
Example: This code displays even numbers from 0 to 100:

#include<iostream>
using namespace std;
int main(){
for (int i=1;i<=100;i++){
if(i %2==0){
cout<<i <<endl;
}
}
}

CP  Unit 3-Control Statements 42


2.2. The while loop
.

Syntax: while (conditional expression)


statements;
 This implies the statement following it will be carried out as
long as the conditional expression evaluates true, i.e. it is
more than zero.
E.g. let variables n, i and Sum are declared as integers.
The number n is initialized as 10, Sum as 0 and i as 0.
while (i <= n)
Sum += i++;
cout << “Sum 0 to 10 = ” << Sum
<<endl;
 The process is repeated again and again till i =10. So Sum
will become 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.
CP  Unit 3-Control Statements 43
Cont’d…
. Problem: print numbers 1 upto 10 on
standard output
Solution using while statement
#include <iostream.h>
int main()
{
int counter;
counter = 1;
while (counter <= 10)
{
cout << counter << endl;
counter++;
}
return 0;
}
CP  Unit 3-Control Statements 44
Cont’d…
. /*Calculate the average of 5 numbers. */
#include <iostream.h>
int main()
{
float average;
int Number,counter=0,sum=0;
while(counter<5)
{
cout <<“\n Enter the number”;
cin>>Number;
sum=sum+Number;
counter++;
}
average=sum/5;
cout<<“\n The average is:”<<average;
return 0;
}
CP  Unit 3-Control Statements 45
What will be the output?
.

counter = 0;
while (counter < 5)
{
cout << "\nI love ice cream!";
counter++;
}

WHAT ABOUT THIS ONE?


counter = 0;
while (counter < 5)
{
cout << "\nI love ice cream!";
}
CP  Unit 3-Control Statements 46
2.3 The do-while Statement
. In short: executes body once then
repeatedly executes body while condition
remains
do true
keyword do

{
{
(single statement or
body
compound statement) statement(s);

}
while (condition);
while
keyword condition
(enclosed in must
parenthesis) Have ;

CP  Unit 3-Control Statements 47


Cont’d…
.
 Problem: print numbers 1 through 10 on standard
output
 Solution using do-while statement
#include <iostream.h>
int main()
{ loop body
int counter;
counter = 1;
do
{ condition true
cout << counter << endl;
counter++;
} false
while (counter <= 10);
return 0;
}

CP  Unit 3-Control Statements 48


Cont’d…
Ex. The sum of any number of integers entered by the user.
int number,sum=0;
char loop_response;
do
{
cout << "\n Enter the number? ";
cin >> number;
sum+=number;
cout << "\nDo you want to do it again? y or n ";
cin >> loop_response;
} while (loop_response == 'y');
cout<<“\n The sum is :”<<sum;

CP  Unit 3-Control Statements 49


Cont’d…
.// print lowercase alphabet.
char ch = `a';
do
{
cout << ch << ` `;
ch++;
} while ( ch <= `z' );

CP  Unit 3-Control Statements 50


Flow of Control
. while versus do-while
#include <iostream.h> #include <iostream.h>
int main() int main()
{ {
int counter; int counter;
counter = 1; counter = 1;
while (counter <= 10) do
{ {
cout << counter << endl; cout << counter << endl;
counter++; counter++;
} } while (counter <= 10);
return(0); return(0);
} }

CP  Unit 3-Control Statements 51


3. Jumping Statements
.

 Loop control statements or jumping statements change execution from its


normal sequence.
 When execution leaves a scope, all automatic objects that were created in
that scope are destroyed.
 C++ supports the following jumping statements:
1. goto statements,
2. break statements,
3. continue statements, and

CP  Unit 3-Control Statements 52


3.1. The goto statement

CP  Unit 3-Control Statements 53


Cont’d…

• The code goto is used for moving back and forth in


the program. Therefore, for using goto statement
one needs to put in a label.
• Syntax:

CP  Unit 3-Control Statements 54


Example : goto Statement as a looping
. int main(){
int n , m;
cout<<“Write and enter two integers: ” ;
cin>> n >> m;
cout<< “You have written the numbers as n= ”<<n
<<“ and m = ”<<m <<endl;
Again: //The label Again, see colon at end.
if(n < m) n++; else m++;
if(n == m)
cout<<“Now m = ” << m<<“ and n = ” << n<<“\n”;
else
goto Again; //Jump back to Again making a loop
return 0;
}

CP  Unit 3-Control Statements 55


3.2. The break statement
.

• A break statement may appear inside a loop (while, do, or for) or a


switch statement.
• It causes a jump out of these constructs, and hence terminates
them.
• A break statement only applies to the loop or switch immediately
enclosing it.
• It is an error to use the break statement outside a loop or a switch.

CP  Unit 3-Control Statements 56


Cont’d…
.

CP  Unit 3-Control Statements 57


Cont’d…
#include <iostream>
using namespace std;

int main() {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
return 0;
}

CP  Unit 3-Control Statements 58


3.3. The continue statement
.

• continue statement causes the loop to skip the rest 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.
• It is an error to use the continue statement outside a loop.

CP  Unit 3-Control Statements 59


Cont’d…
.

CP  Unit 3-Control Statements 60


Cont’d…
 E.g. C++ program to display integer from 1 to 10 except 6 and 9.

CP  Unit 3-Control Statements 61


break vs. continue
.

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.

CP  Unit 3-Control Statements 62


Quiz
.
1. Write a program that calculates sum of numbers from 1 to 100.
2. Write a program that displays numbers between 0 -100 that are
divisible by 2, 3, and 5. The numbers displayed should be those
that can be divided by 2, 3, and 5 without remainder.
3. Write a program that calculates factorial using for loop, while loop
and do while loops. The program should accept the number and
then perform the calculation of the factorial.
4. Write a while loop that prints the average of numbers from 1 to 10

CP  Unit 3-Control Statements 63


End.

CP  Unit 3-Control Statements 64

You might also like