Second Laboratory Session
Second 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
Action
• Action is either a single
statement or a group of
statements within braces
Example
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
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
• 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,
No Boolean Yes
Expression
True? Statement(s)
Next Statement
While loop
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
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
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