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

Second Laboratory Session

The document discusses control structures in programming, including selection statements like if/else and switch statements, as well as repetition statements like while and do-while loops. It provides syntax examples and explanations of how each type of control structure directs program flow. Key points covered include branching vs sequential flow, the syntax and use of if/else, switch, and loop statements, and the differences between while, do-while, and for loops.

Uploaded by

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

Second Laboratory Session

The document discusses control structures in programming, including selection statements like if/else and switch statements, as well as repetition statements like while and do-while loops. It provides syntax examples and explanations of how each type of control structure directs program flow. Key points covered include branching vs sequential flow, the syntax and use of if/else, switch, and loop statements, and the differences between while, do-while, and for loops.

Uploaded by

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

Third Laboratory Session

Control Structures
Control Structure
• A control structure is a control statement and the statements whose
execution it controls
• Most programming languages follow a single thread of control (or
scheduling)
Control Flow or Flow of Control
• Flow of control is the order in which a program performs
actions.
• Up to this point, the order has been sequential.
• A branching statement (Selection Statements) chooses
between two or more possible actions.
• A loop statement repeats an action until a stopping condition
occurs.
Selection/branching Statements
• A selection statement chooses between two or more paths of
execution
• Two general categories:
• Two-way selectors
• Multiple-way selectors
Selection
• It is often the case that depending upon the value of an expression
we want to perform a particular action
• Two major ways of accomplishing this choice
• if-else-if statement
• if-else statements “glued” together

• Switch statement
• An advanced construct
The Basic If Statement

• Syntax
if (Expression)
Action Expression

• If the Expression is true then


true false
execute Action

Action
• Action is either a single
statement or a group of
statements within braces
Example

if (Value < 0) { Is our number negative?


Value = -Value;
If}Value is less than Value < 0
zero then we need to
update its value to
true false
that of its additive
inverse If Value is not less
than zero then our
Value = -Value number is fine as is

Our number is
now definitely
nonnegative
Sorting Two Numbers
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
if (Value1 > Value2) {
int RememberValue1 = Value1;
Value1 = Value2;
Value2 = RememberValue1;
}
cout << "The input in sorted order: "
<< Value1 << " " << Value2 << endl;
Semantics Are the numbers
out of order
Rearrange value1
and value2 to value2 < value1
put their values
in the proper
order true false

int rememberValue1 = value1


value1 = value2
value2 = rememberValue1

The numbers were


rearranged into the
proper order
The numbers were
initially in order
The numbers are in
order
The if-else statement
• The if-else structure directs the computer to select between two
statements based on the result of a comparison.
• For example, suppose you need to calculate the area of a circle, given
the radius as an input value.
• If the input is a negative number, you want to print a message, using
one cout statement, that the radius can’t be a negative value;
otherwise, you calculate and print the circle’s area, using a second
cout statement.
The If-Else Statement
• Syntax
if (Expression)
Action1
else
Action2 Expression
• If Expression is true then execute
Action1 otherwise execute Action2 true false

if (v == 0) {
cout << "v is 0"; Action1 Action2

}
else {
cout << "v is not 0";
}
Finding the Max
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
int Max;
if (Value1 < Value2) {
Max = Value2;
}
else {
Max = Value1;
}
cout << "Maximum of inputs is: " << Max <<
endl;
Finding the Max Is Value2 larger than Value1

Yes, it is . So Value2 is
larger than Value1. In
this case, Max is set No, its not. So Value1
to Value2 is at least as large as
Value2. In this case,
Value1 < Value2 Max is set to Value1
true false

Max = Value2 Max = Value1

Either case, Max is set


correctly
An If-Else-If Statement
if ( nbr < 0 ){
cout << nbr << " is negative" << endl;
}
else if ( nbr > 0 ) {
cout << nbr << " is positive" << endl;
}
else {
cout << nbr << " is zero" << endl;
}
Example 1
Example 2
Example 3
Example 4
Example 5
Reading Assignments
• Read up on nested if statements.
• You will be tested on this.
Switch Statement
• An if-else chain is used in programming applications when one set of
instructions must be selected from many possible alternatives.
• A switch statement is an alternative to the if-else chain for situations
when the condition involves comparing an integer expression
with a specific value.
• It has this general form:
Switch Statement – Flowchart
Switch Statement
• It works in the following way: switch evaluates
expression and checks if it is equivalent to
constant1; if it is, it executes group-of-
statements-1 until it finds the break statement. When
it finds this break statement, the program jumps to the end of
the entire switch statement (the closing brace).
Switch Statement
• If expression was not equal to constant1, it is then checked
against constant2. If it is equal to this, it executes group-
of-statements-2 until a break is found, when it
jumps to the end of the switch.

• Finally, if the value of expression did not match any of the previously
specified constants (there may be any number of these), the program
executes the statements included after the default: label, if it exists
(since it is optional).
Switch Statement
A Switch Statement
switch (ch) {
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
cout << ch << " is a vowel" << endl;
break;
default:
cout << ch << " is not a vowel" << endl;
}
THE switch Vs. if-else
• The switch and if-else are selection statements and they both
let you select an alternative out of many alternatives by testing
an expression. However there are some differences in their
operation and they are,

1.The switch statement differs from the if statement in that switch


can only test for equality where as if can evaluate a relational or
logical expressions i.e multiple conditions.
THE switch Vs. if-else
2.The switch statement selects its branches by testing the value
of same variable (against the set of constants) where as the if
else construction lets you to use a series of expressions that
may involve unrelated variables and complex expressions.
THE switch Vs. if-else
3. The if-else is more versatile of two statements where as
switch cannot. Each switch case label must be a single value.

4. The if-else statement can handle floating point tests also


apart from integer and character tests where as switch cannot
handle floating point tests. The case labels of switch must be
an integer or character.
C++ flow control statements
Sequence
• the default Branching: Repetition
• C++ automatically executes the • while
next instruction unless you use a • do-while
branching statement
• for
Loops
• Three types
• Indeterminate loops
• while (<boolean expression>) statement;
• do statement while (<boolean expression>);
• Counted loop
• for ( <initial condition>; <terminal condition>; <increment> ) statement;
Repetition: Loops
• Structure:
• Usually some initialization code
• body of loop
• loop termination condition
• Several logical organizations
• counting loops
• sentinel-controlled loops
• infinite loops
• minimum of zero or minimum of one iteration
• Several programming statement variations
• while
• do-while
• for
While loops
• Boolean expression is tested
• If the result is true, the statement or statement block following the loop is
executed. Otherwise the loop is exited and the statement after the loop is
executed.
• Repeat until the expression is false
While Loop

No Boolean Yes
Expression
True? Statement(s)

Next Statement
While loop

while ( value < max ) {


// do some things
value++;
}

Important!
You must modify one of the variables in
the while boolean expression in the loop.
If you don’t…
You will have an infinite loop
While Example
• List out a table of numbers and their squares. Ask the user for the
minimum and maximum number for the table.
• Ask for the two values
• Check that nStart is less than nEnd
• Start number with nStart
• while number is less than or equal nEnd
• Print out number and its square
• Increment number by one
Do While loops
• Statement or Statement Block is executed
• Boolean expression is tested
• If the result is true, execution continues at the top of the loop. Otherwise the
loop is exited and the statement after the loop is executed.
• Repeat until the expression is false
Do While Loop

Statement(s)

No Yes
Boolean
Expression
True?

Next Statement
For loop
• Most powerful loop
• Three sections
• An initialization section. Use this section to setup initial values. This section usually has
one or more assignment statements.
• A test section. This must be a boolean expression. If the expression is true, then the
loop is entered or continues. Otherwise control is transferred to the statement after the
loop body
• An increment section. One or more statements that modify the variable(s) in the test
section. Usually used to increment a variable.
For example
• List out a table of numbers and their squares. Ask the user for the
minimum and maximum number for the table.
• Ask for the two values
• Check that nStart is less than nEnd
• Start number with nStart
• while number is less than or equal nEnd
• Print out number and its square
• Increment number by one
for

for ( <initialization>; <test>; <increment>)


For loop
Initialization

False True

Test
Condition

Statement(s)

Increment

Next Statement
Loop example
• Factorial
• Write a program that will calculate any number of factorials
• Factorial of n (n!)
• n * (n-1)!
• factorial 1= 1
Loop Design
• How do we know when to stop
• Ask user if they want to continue
• Assumption, at least one factorial will be calculated
• What type of loop should we use?
Loop Counting
• Minimum number of times
• A while loop will be executed?
• A do while loop will be executed?
• Maximum number of times
• A while loop will be executed?
• A do while loop will be executed?
Some practical considerations
when using loops
• The most common loop errors are unintended infinite loops and off-by-one errors in counting
loops
• Sooner or later everyone writes an unintentional infinite loop
• To get out of an unintended infinite loop enter ^C (control-C)
• Loops should tested thoroughly, especially at the boundaries of the loop test, to check for off-by-
one and other possible errors
• "Tracing" a variable (outputting its value each time through the loop) is a common technique
to test loop counters and troubleshoot off-by-one and other loop errors
COMPARISON OF LOOPS
• The for loop is appropriate when you know in
advance how many times the loop will be
executed.
• The other two loops while and do-while are more
suitable in the situations where it is known before
–hand when the loop will terminate.
• The while should be preferred when you may not
want to execute the loop body even once (in case
test condition is false), and the do-while loop
should be preferred when you are sure you want
to execute the loop body at least once.
JUMP STATEMENT - goto
• The goto statement is rarely used in the
programming.
• A goto statement can transfer the program control
anywhere in the program. The target destination
of a goto statement is marked by the label. The
syntax is,
goto label; //here you put semicolon
…….
…….
…….
label ://here you put colon
JUMP STATEMENT
• C++ has the four statements that perform an unconditional
branch. They are,
1. return
2. goto
3. break
4. continue
In addition to four statements C++ library function provides
exit() that helps you break out of the program.
JUMP STATEMENT – goto
Example

A=0;
start :
cout<<“\n”<<++a;
if(a<50) goto start;
NOTE:
Label may not immediately precede the closing right brace. If so
then a null statement may be used.
For example
…….
{ goto last;
…..
…..
last: // wrong!
}
NOTE:
For example
…….
{ goto last;
…..
…..
last: ; // null statement right!
}
NOTE:
• goto statement may not jump forward over the variable
definition.
main()
{
goto last; // Wrong! Jumping over the variable definition
char ch=‘a’;
……
last:
}
break STATEMENT

The break statement enables the program to skip over the


part of the code. A break statement terminates the smallest
enclosing while,do-while for or switch statement,
break STATEMENT -EXAMPLE
while (test expression)
{
statement
if(val>2000)
break;
…..
statement;
}
statement 3;
break STATEMENT -EXAMPLE
for( int;test expression;update expression)
{
statement
if(val>2000)
break;
…..
statement;
}
statement 3;
break STATEMENT -EXAMPLE

do {
statement
if(val>2000)
break;
…..
statement;
} while (test expression);
statement 3;
THE continue STATEMENT
• The continue statement is the another jump statement like the
break as the both the statements skips over the part of code but
the continue statement is some what different than the break.
Instead of forcing for termination it forces for the next iteration of
the loop to take place.
THE continue STATEMENT
EXAMPLE
while (test expression)
{
statement
if(condition)
continue;
…..
statement;
}
statement 3;
THE continue STATEMENT
EXAMPLE
for (int; test expression; updateexpression )
{
statement
if(condition)
continue;
…..
statement;
}
statement 3;
THE continue STATEMENT
EXAMPLE
do
{
statement
if(condition)
continue;
…..
statement;
} while (test expression);
statement 3;
THE exit() FUNTION
• The exit() function causes the program to terminate as soon as
it is encountered.
• The exit() function is a C++ standard library function defined in
process.h file.
which must be included in the program that uses exit() function

You might also like