Chapter Two
Chapter Two
Control Structures
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" ;
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.
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