[go: up one dir, main page]

0% found this document useful (0 votes)
13 views60 pages

Control Structures

This document provides an overview of control structures in C programming, including sequence, selection, and iteration structures. It covers logical expressions, if statements, switch statements, and various iteration methods such as while, do-while, and for loops. Additionally, it includes examples and explanations of how to implement these structures effectively in code.

Uploaded by

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

Control Structures

This document provides an overview of control structures in C programming, including sequence, selection, and iteration structures. It covers logical expressions, if statements, switch statements, and various iteration methods such as while, do-while, and for loops. Additionally, it includes examples and explanations of how to implement these structures effectively in code.

Uploaded by

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

Programming 1

Basics of C Language
Part III: Control Structures
Control Structures
Sequence structure

add myValue to total total = total + myValue;

add 1 to counter counter = counter + 1;

2 University of Oulu
Control Structures
Selection

Logical expressions & if selection structure


switch selection structure for several possible options

Iteration

• while iteration structure


• do-while iteration structure
• for iteration structure

University of Oulu
Control Structures
Selection structure

true
points >= 40 print ”Course passed”

false

4 University of Oulu
Control Structures
Selection structure

false true
print ”Course failed” points >= 40 print ”Course passed”

5 University of Oulu
Control You’ll learn how to have a
Structures program execute…

- Alternative tasks using control


structures
- Specific statements iteratively
using iteration structures

6 University of Oulu
Control Structures
Logical expressions & if selection structure
‒ Normally, the condition for the if selection
structure is expressed as a logical expression
‒ The result of an expression is a truth value
- false, expressed with value 0
- true, expressed with value 1 (all nonzero values)

7 University of Oulu
Control Structures
Algebraic equality C equality
Example of C
or relational or relational Meaning of C condition
condition
operator operator

> > x>y x is greater than y

< < x<y x is less than y

≥ >= x >= y x is greater than or equal to y

≤ <= x <= y x is less than or equal to y

= == x == y x is equal to y

≠ != x != y x is not equal to y

8 University of Oulu
Control Structures
Let’s assume the variables have the following values:
x = -5 Operator Condition Interpretation Value
MIN = -999.0
NUM = 999 > num1 > MIN num1 greater than MIN ?
exp = 1024
y=7
< exp < MAX exp less than MAX ?
MAX = 1024 >= x >= y x is greater than or equal to y ?
myLetter = ’J’
num1 = 1.5
<= x <= 0 x is less than equal to 0 ?
num2 = 999 == myLetter == ’J’ myLetter equals to letter ’J’ ?
!= num2 != NUM num2 is not equal to NUM ?

9 University of Oulu
Control Structures
Let’s assume the variables have the following values:
x = -5 Operator Condition Interpretation Value
MIN = -999.0
NUM = 999 > num1 > MIN num1 greater than MIN 1
exp = 1024 < exp < MAX exp less than MAX 0
y=7
MAX = 1024 >= x >= y x is greater than or equal to y 0
myLetter = ’J’ <= x <= 0 x is less than equal to 0 1
num1 = 1.5
num2 = 999 == myLetter == ’J’ myLetter equals to letter ’J’ 1
!= num2 != NUM num2 is not equal to NUM 0

10 University of Oulu
Control Structures
Basic form of if control structure in C
if (condition)
statement1;
else
statement2;

Sometimes the else-part can be left out


if (condition)
statement1;

11 University of Oulu
Control Structures
true
X>0 numPos = numPos + 1

false
true
X<0 numNeg = numNeg + 1
false
numZero = numZero + 1

12 University of Oulu
Control Structures
Example: Select the largest of the given three numbers and display it.

Designing the algorithm in a rough level…


1. Read three numbers num1, num2, num3
2. Save the largest number to variable largestNum
3. Print the largest number (largestNum)

Defining the step 2 in more detail…


2.1. Save the larger of the numbers num1 and num2 to variable largestNum
2.2. Save the larger of the numbers largestNum and num3 to variable largestNum

13 University of Oulu
Control Structures
Example: Select the largest of the given three numbers and display it.
Read three numbers
and display the largest
one of those.

num1 num1
num2 num2 largestNum largestNum
num3 num3

Find the largest Display the largest of


Read three numbers the three numbers.
number

14 University of Oulu
Control Structures

15 University of Oulu
Control Structures

16 University of Oulu
Control Structures
To include several statements in the body of an if, you must enclose
the set of statements in a block, within a pair of braces { }
if (condition) if (condition) { if (condition) {
statement1; statement1; statement1;
else … block … block
statement2; statementN; statementN;
} }
else else {
statement1; statement1;
… block
statementN;
}
17 University of Oulu
Control Example: Changing values of two
variables, x and y, so that the smaller
Structures value will be stored in variable x.

18 University of Oulu
Control Structures
Thus, sequential execution of statements is achieved by using
blocks, i.e., writing the statements within a pair of braces { }

Style is free, but…


- Indentation is important!
- Clariry
- Readability

19 University of Oulu
Control Structures
if (condition)
if (condition) { {
statement1; statement1;
… …
statementN; statementN;
} }
else { else
statement1; {
… statement1;
statementN; …
} statementN;
20
} University of Oulu
Control Structures
Nested if control structures, example…
We have three integers, namely numPos, numNeg and numZero. The
value of each will be increased by one if the value of variable x is
greater than, less than or equal to zero, version 1, accordingly.
if (x > 0)
numPos = numPos +1;
else
if (x < 0)
numNeg = numNeg + 1;
else
numZero = numZero + 1;
21 University of Oulu
Control Structures
Nested if control structures
The same task (previous slide) can optionally be executed with
sequential if control structures as follows, version 2.
if (x > 0)
Which do you think is a better? numPos = numPos +1;
Version 1 or version2?
if (x < 0)
numNeg = numNeg + 1;

if (x == 0)
numZero = numZero + 1;
22 University of Oulu
Control Structures
Nested if control structures
Version 3…
if (x > 0)
numPos = numPos +1;
else if (x < 0)
numNeg = numNeg + 1;
else
numZero = numZero + 1;

23 University of Oulu
Control switch selection structure
Structures ‒ Multiple-selection structure.
switch (expression) { ‒ Performs one of many
case identifier1:
statement; different optional actions,
break;
case identifier2:
depending on the value of an
statement; expression.
break;
case …
case identifierN;
‒ Once the case is found, a
statement; block of statement(s)
break;
default: associated with that specific
statement;
break;
case is executed.
}
24 University of Oulu
Control Structures - switch
‒ The value of the expression – either of type char or int – is compared,
starting from the top, to each identifier in the case-rows, until a matching
value is found.
‒ The identifiers are unique constants. The idenfiers end with a colon (’:’).
‒ When a matching case is found, the statements (after that) are executed
until a break statement is found at the end of the case.
‒ A break statement causes control to exit the switch statement.
‒ If there is no matching case (for the value of the expression), the
optional default case can be executed (if it exists) and control exits the
switch statement.

25 University of Oulu
Control Structures - switch
true break
false
true
break
false

false
true
break

26 University of Oulu
Control Structures

Example
switch structure defining the
expected lifetime for a light bulb
based on its wattage.

University of Oulu
Control Structures
Example
switch structure defining
the expected lifetime for a
light bulb based on its
wattage.

28 University of Oulu
Control Structures
Example
switch structure displaying the
name of the color specified by
the given character of the
color.
The possible values for color
are:
‒ ‘R’ for “red”
‒ ‘B’ for “blue” and
‒ ‘Y’ for “yellow”

29 University of Oulu
Control Structures
Example
switch structure displaying the
name of the color specified by
the given character of the
color.
The possible values for color
are:
‒ ‘R’ for “red”
‒ ‘B’ for “blue” and
Notice – if the user enters some other letter, ‒ ‘Y’ for “yellow”
or a correct letter as a lower-case letter, the
program does not print anything!

30 University of Oulu
Control Structures
Remember for switch
- The expression in switch can only be of type char or int
(e.g., not double or a string)
- Normally, add a break statement to the end of each case
(unless otherwise required)
- Have a default case when possible

31 University of Oulu
Control Structures
Iteration statement
The nature of a task will define whether there is a
need to use iteration or not.
1. Does the problem include repeatable steps?
2. Do we know, already in advance, how many times a step needs to be
repeated?
3. How do we know how many times a step needs to be repeated?

32 University of Oulu
Control Structures
while iteration statement

Initialization of the control variable


while (condition) {
statement;

}
33 University of Oulu
Control Structures while
1. The control variable need to be initialized.
2. The condition will check the value of the control variable. If the condition is
true, the statement(s) in the body of the while statement will be executed.
The value of the control variable may have to be changed.
3. The statement in the body of the while statement will be iterated as long as
the condition remains true.
4. When the condition becomes false, the control exits the while statement
and the execution of the program will continue from the statement
following the while structure.

34 University of Oulu
Control Structures

Example with while


Print the letter ‘a’ as many
times as the user has defined.

35 University of Oulu
Control do-while iteration statement
Structures
Initialization of the control variable
do
statement;
while (condition);

Initialization of the control variable


do {
statement;

} while (condition);
36 University of Oulu
Control Structures do-while
1. The control variable need to be initialized.
2. The statement in the body of the do-while statement will be executed at
least once.
3. The value of the control variable may have to be changed.
4. The condition will check the value of the control variable. If the condition is
true, the statement in the body of the do-while statement will be executed
again.
5. The statement in the body of the do-while statement will be iterated as long
as the condition remains true.
6. When the condition becomes false, the control exits the do-while statement
and the execution of the program will continue from the statement following
the do-while structure.
37 University of Oulu
Control Structures

Example with do-while


Print the letter ‘a’ as many
times as the user has defined.

38 University of Oulu
Control Structures

Example with do-while

Please notice the essential


difference to the if selection
structure, where a block would
be executed only once.

39 University of Oulu
Control Structures

Example
We will calculate the product of
integers entered by the user (using
while iteration) until the calculated
product is less than 1000.
The variable product has two roles…
a) It stores the result of the
calculation and…
b) It acts as a control variable
(product < 1000).
In the iteration, in each round, the old
value of the product variable is lost
(overwritten).
The program will remain in an “eternal
loop” if the user enters 0 (zero)!

40 University of Oulu
Control Structures
for iteration statement
‒ Initialization of the control variable
‒ Condition statement
‒ Update of the control variable (changing the value of it)
‒ It is essential to notice the role of the control variable. (In the
following examples we use control variables counter and
product).

41 University of Oulu
1 Executed once, before entering the loop

Control Structures 2 Condition, checked before each loop

3 Executed every time, after each loop

for iteration statement

1 2 3
for ( initialization ; condition ; increment )
{
statement; // one or more statements
}

42 University of Oulu
1 Executed once, before entering the loop

Control Structures 2 Condition, checked before each loop

for iteration statement 3 Executed every time, after each loop

required condition, true with Incrementing the


for semicolon
counter values less control variable
keyword separator
than 11

1 2 3
for (int counter = 1 ; counter <= 10 ; counter++)
Initialization of the control
required
variable (initially 1) semicolon
separator
43 University of Oulu
Control Structures for
1. First, the initialization will be done.
2. Second, the condition will be checked. If the condition is true, the statement
in the body of the for statement will be executed.
3. Third, the control variable will be incremented.
4. Next, the iteration will continue as in (2. & 3., i.e. checking the condition,
executing the statements in the body of the for statement and incrementing
the control variable) as long as the condition remains true.
5. When the condition becomes false, the control exits the for statement and
the execution of the program will continue from the statement following the
for structure.

44 University of Oulu
Control Structures

Example with for


Print the letter ‘a’ as many
times as the user has defined.

45 University of Oulu
Control Structures while

true

false

46 University of Oulu
Control Structures do-while

true

false

47 University of Oulu
Control Structures for

true

false
body increment
48 University of Oulu
Nested Control
Structures

University of Oulu
Control Structures
Nested Control Structures
Many programming tasks require nested control structures
(e.g., a selection within a loop or a loop within a loop)
Example:
A program that counts the number of real numbers
entered by the user that are different from zero. The
program exits when the user enters the pre-defined ”exit
sign” -999.9.

50 University of Oulu
Nested Control
Structures

Example
A program that counts the
number of real numbers
entered by the user that are
different from zero.
The program exits when the
user enters the pre-defined
”exit sign” -999.9.

51 University of Oulu
Control Structures

‒ In the previous example, we did


not know in advance how many
times a loop would need to be
executed, but asked the user to
enter the ”exit sign” when (s)he
wanted to stop.
‒ In the previous example, the
loop would stop if the user
entered -999.9.

University of Oulu
Control Structures
‒ Common format
read a line
as long as an exit sign has not been given
process the line
read next line

The next example will calculate the sum of given positive


integers…

53 University of Oulu
Control Structures

Example
A program calculating the sum
of given positive integers.
Do you notice?
• When would the program
stop?
• What is wrong with this
program?

54 University of Oulu
Nested Control The following examples will
Structures display a matrix of multiplication
table for numbers from 1 to 10
using different iteration
structures…
- for
- while
- do-while

55 University of Oulu
Nested Control
Structures

Example
Display multiplication table for
numbers from 1 to 10 using
for iteration structure

56 University of Oulu
Nested Control
Structures

Example
Display multiplication table for
numbers from 1 to 10 using
while iteration structure

57 University of Oulu
Nested Control
Structures

Example
Display multiplication table for
numbers from 1 to 10 using
do-while iteration structure

58 University of Oulu
Nested Control
Structures

Example
Study the following example…

59 University of Oulu
Remember to
practice !

“The greatest teacher, failure is.”


— Yoda

University of Oulu

You might also like