0% found this document useful (0 votes)
19 views

Chapter Two

Uploaded by

werkezebo5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Chapter Two

Uploaded by

werkezebo5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

CHAPTER TWO

Control Structures

November 28, 2023


Outline
 Control structures
 Conditional structure
 Iteration structure(Loops)
 Jump Statement
 Selective structure

 Function
 Arguments passed by value and by reference
2
Introduction
The order in which statements in a program are executed is
called flow of that program.
Programmers can control which instruction to be executed in a
program, which is called flow control.
Flow control in a program is typically sequential, from one
statement to the next.
But we can also have execution that might be divided to other
paths by branching statements.
Or perform a block of statement repeatedly until a condition
fails by Repetition or looping.
3
…continued
Flow control is an important concept in programming because it
will give all the power to the programmer to decide what to do
to execute during a run and what is not, therefore, affecting the
overall outcome of the program.

4
Conditional Structure
If statement
It is sometimes desirable to make the execution of a statement
dependent upon a condition being satisfied.
The syntax :
if (expression)
statement;
The pseudocode statement:-
If student’s grade is greater than or equal to 60
Print “Passed”
C++ if statement is as follows:
if ( grade > = 60 )
cout « " Passed " ; 5
…continued
If/else statement
It allows the programmer to specify an action to perform
when the condition is true and a different action to perform
when the condition is false.
For example, the pseudocode statement
If student's grade is greater than or equal to 60
Print "Passed “
else
Print " Failed "
6
…continued
The preceding pseudocode if/else structure can be written in C++ as:
if ( grade > = 60 )
cout « " Passed " ;
else
cout « "Failed" ;

C++ provides the conditional operator ( ? : ) ,which is closely


related to the if/else structure. The conditional operator is C++'s
only ternary operator-it takes three operands.
The above if/else statement can be replaced with the following line
of code:-
cout « ( grade >= 60 ? " Passed " : " Failed " ) ;
7
…continued
Nested if/else statement
 A selection statement can be used within another selection statement,
called nesting statements.

When if/else statements are nested, the compiler uses the following rule
to parse the compound statement: Match each else with the last
unmatched if.

A frequently-used form of nested if statements involves the else part


consisting of another if/else statement. 8
…continued
For example: nested if/else statements to check if a character is a digit, upper letter,
lower letter or special character:
int main() {
if (ch >= '0' && ch <= '9')
kind = digit;
else {
if (ch >= 'A' && ch <= 'Z')
kind = upperLetter;
else {
if (ch >= 'a' && ch <= 'z')
kind = lowerLetter;
else
kind = special; }
}
}
9
…continued
else if structure
Nested if/else statements are often used to test a sequence of parallel
alternatives, where only the else clauses contain further nesting.
The above nested if/else code can also be written using the else if construct as
shown below:
int main () {
if (ch >= '0' && ch <= '9')
kind = digit;
else if (cha >= 'A' && ch <= 'Z')
kind = capitalLetter;
else if (ch >= 'a' && ch <= 'z')
kind = smallLetter;
else
kind = special; } 10
Iteration Structure(Loops)
A loop statement allows us to execute a statement or group of
statements multiple times
 when you need to execute a block of code several times—looping
C++ programming language provides the following types of loop to
handle looping requirements.
For Loop
The for statement (for loop) is similar to the while statement, but
has two additional components: an expression which is evaluated
only once before everything else, and an expression which is
evaluated once at the end of each iteration.
11
…continued
The general form of the for statement is:
for(expression1 ; expression2 ; expression3)
statement;
(Where expression1 is initialization;
expression2 is condition, and
expression3 is update.
initialization, condition, and update are optional expressions,
and statement is any executable statement.)
12
…continued
The sequence of events that generate the iteration is:
1. evaluate the initialization expression;
2. if the value of the condition expression is false, terminate the loop;
3. execute the statement;
4. evaluate the update expression;
5. repeat steps 2–4.
The general for loop is equivalent to the following while loop:
expression1 ;
while(expression2){
statement;
expression3 ;
}
13
…continued
 C++ allows the first expression in a for loop to be a variable definition.
for (int i = 1; i <= n; ++i)
sum += i;
 The above is equivalent to:
int i;
for (i = 1; i<= n; ++i)
sum += i;
 Any of the three expressions in a for loop may be empty.
 Removing all the expressions gives us an infinite loop. This loop's condition is assumed
to be always true:
for (;;) // infinite loop
Something;
for (; i != 0;) // is equivalent to:
while (i != 0) 14
…continued
For loops with multiple loop variables are not unusual. In such
cases, the comma operator is used to separate their
expressions:
for (i = 0, j = 0; i + j < n; ++i, ++j)
something;

15
…continued
For example,
for (inti = 1; i<= 3; ++i)
for (int j = 1; j <= 3; ++j)
cout << '(' << i << ',' << j << ")\n";

16
…continued
output: (1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
(3,3)

17
…continued
While Loop
The while statement (while loop) provides a way of repeating a
statement while a condition holds.
The general form of the while statement is:
while(expression)
statement;
First expression (called the loop condition) is evaluated. If the
outcome is nonzero then statement (called the loop body) is
executed and the whole process is repeated. Otherwise, the loop is
terminated.
18
…continued
For example, suppose we wish to calculate the sum of all
numbers from 1 to some integer denoted by n. This can be
expressed as:
i = 1;
sum = 0;
while (i<= n)
sum += i;

19
…continued
Do while Loop
The do statement (do loop) is similar to the while statement, except that its
body is executed first and then the loop condition is examined.
The general form of the do statement is:
do
statement;
while(expression);
First statement is executed and then expression is evaluated. If the outcome is
nonzero then the whole process is repeated. Otherwise, the loop is terminated.
The do loop is less frequently used than the while loop.
It is useful for situations where we need the loop body to be executed at least
once, regardless of the loop condition.
20
…continued
For example, suppose we wish to repeatedly read a value and
print its square, and stop when the value is zero. This can be
expressed as the following loop:
do {
cin>> n;
cout<< n * n << '\n';
} while (n != 0);
Unlike the while loop, the do loop is never used in situations
where it would have a null body.
21
Jump Statement
‘continue’ statement
The continue statement terminates the current iteration of a loop and
instead jumps to the next iteration. It is exiting from a loop.
 It is an error to use the continue statement outside a loop.
In while and do while loops, the next iteration commences from the loop
condition. In a “for” loop, the next iteration commences from the loop’s
third expression.
E.g. for(int n=10;n>0;n--) {
if(n==5) continue; //causes a jump to n--
cout<<n<< “,”;
}
22
…continued
 When the continue statement appears inside nested loops, it
applies to the loop immediately enclosing it, and not to the outer
loops.
For example, in the following set of nested loops, the continue
statement applies to the “for” loop, and not to the “while” loop.
E.g. while(more) {
for(i=0;i<n;i++){
cin>>num;
if(num<0)continue; //causes a jump to; i++
}}
23
…continued
‘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.
 Like the continue statement, 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 statement. 24
…continued
E.g.
for(n=10;n>0;n--) {
cout<<n<< “,”;
if(n == 3) {
cout<< “count down aborted!!”;
break;}
}
25
…continued
‘goto’ Statement
The goto statement provides the lowest-level of jumping.
 It has the general form:
goto label:
where label is an identifier which marks the jump destination
of goto.
The label should be followed by a colon and appear before a
statement within the same function as the goto statement
itself.
26
…continued
For example, the role of the break statement in the for loop in
the previous section can be emulated by a goto:
for(n=10;n>0;n--){
cout<<n<< “,”;
if(n = = 3) {
cout<< “count down aborted!!”;
goto out:
}
} out:cout<<“out of loop”;
27
Selective structure
Switch Statement
It implements a selection control flow (multiple-choice
statement). The switch statement provides a way of choosing
between a set of alternatives based on the value of an
expression.
The switch statement has four components: -
• Switch
• Case
• Default
• Break, Where Default and Break are Optional.
28
…continued
The General Syntax of Switch:
Switch(expression)
{
Case constant1:
Statements;
Break;
.
.
.
Case constant n:
Statements;
Break;
Default:
Statements;
}
29
Exercises
1.Write a single if statement that examines two integer variables
using only one else.
2.Examine this program and anticipate the output:
int main()
{
int a = 1, b = 1, c;
if (c = (a-b))
cout << "The value of c is: " << c;
return 0;
}
3.Write C++ programming for calculator using Switch. 30
Function
Modular programming is breaking down the design of a
program into individual components (modules) that can be
programmed and tested independently.
It is a requirement for effective development and
maintenance of large programs and projects. It is now divided
into several smaller parts which interact and which form the
whole program.
Modules in C++ are called functions.
A function is a subprogram that can act on data and return a
value. 31
…continued
Every C++ program has at least one function, main(). When
your program starts, main() is called automatically. main()
might call other functions, some of which might call still
others.
Each function has its own name, and when that name is
encountered, the execution of the program branches to the
body of that function. When the function returns, execution
resumes on the next line of the calling function.

32
…continued
When a program calls a function, execution switches to the function and
then resumes at the line after the function call.
Functions come in two varieties: user-defined and built-in.
 Built-in functions are part of your compiler package--they are supplied by the
manufacturer for your use.
 User-defined functions- requires that you first declare the function and that you
then define the function.
 The declaration tells the compiler the name, return type, and parameters of the function.
 The definition tells the compiler how the function works.

No function can be called from any other function that hasn't first been
declared.
The declaration of a function is called its prototype. 33
…continued
The general format of the function definition is :
func-type func-name(datatype argumnt1, datatype argumnt2…)
{
body of function
return (something)
}
Components of a function
declaring the type of a function
function name
function arguments
function body
34
…continued
Function Parameters
The arguments/ parameters may be classified under two groups: actual
and formal arguments.
A. Actual Arguments
 A variable/an expression contained in a function call that replaces the formal
parameter
B. Formal Arguments/dummy arguments
 The parameters present in a function definition
 When the function is invoked, the formal parameters are replaced by the actual
parameters.
35
…continued
void main(void) {
int x;
int square(int );
Cin>>x;
int v=square(x); //actual parameters
Cout<<v;
}
int square (int n) //formal parameters
{
int r=n*n;
return(r);
}
36
…continued
Value and Reference Parameters
An argument is a data passed from program to the function. In
function, we can pass a variable by the following ways:-
1. Passing by value
 The value of the actual parameter is passed to the formal parameter when
we call the function but the actual parameter are not changed.
 Changes made to the arguments do not affect the values in the calling
function(main).
2. Passing by Reference
 In C++, passing by reference is accomplished in two ways: using
pointers/address and using references
The original variable is passed to function
37
…continued
Rather than a copy being created within the scope of the
function, the actual original object is passed into the function.
Passing an object by reference allows the function to change the
object being referred to.
Eg->pass by value

38
…continued
#include <iostream.h>
Using namespace std;
void swap(int x, int y);
int main (){
int x = 5, y = 10;
Cout <<“Main. Before swap, x: “<<x<<“y:”<<y”\n”;
Swap(x,y);
Cout <<“Main. After swap, x:”<<x<<“y:”<<y<<“\n”;
return 0;
}
Void swap (int x,int y){
int temp;
cout <<“Swap. Before swap, X:”<<x<<“Y:”<<y<<“\n”;
temp = x;
x = y;
y = temp;
cout <<“Swap. After swap, X: ”<<x<<“Y: ”<<y”\n”;
}
39
…continued
Output:
Main. Before swap, x:5 y:10
Swap. Before swap, x: 5 y:10
Swap. After swap, x:10 y:5
Main. After swap, x:5 y:10

40
…continued
Example pass by reference and by pointer

41
Exercise
Exercise ( write a c++ program of the following by using a
user-defined functions)
a. Sum of two integers
b. The factorial of a number
c. Simple calculator(only arithmetic operations)

42
Thank you
Questions?

43
Next
Chapter 3
Compound Data Types
44

You might also like