SlideShare a Scribd company logo
1 of 32
Download to read offline
Control Structures The basic operations of a
C/C++ programming language are specified using
the following statements or structures
FOR MORE CLASSES VISIT
www.tutorialoutlet.com
Control Structures The basic operations of a C/C++ programming
language are specified using the following
statements or structures: the input statement
the output statement
the assignment statements
the single-way selection structure
the two-way selection structure
the multiple-way selection structure
the counter-controlled iteration structure, and
the logically-controlled iteration structure. The single-way selection,
the two-way selection, the multiple-way selection, the counter-
controlled
iteration and the logically-controlled iteration are collectively called
control structures. The specification of a controlled structure depends
on a logical expression called condition. Controlled structures may
also be specified using the following flowchart symbols: Flowchart
Symbols
SYMBOL
(a) (b) (c) (d) NAME
Terminal Input/Output Process Flow Lines DESCRIPTION
Indicates the beginning or the
end of an algorithm.
Indicates an input or an output
operation.
Indicates a computation or a
data manipulation. Used to connect the symbols
and to indicate the logic flow.
Indicates a decision point in an
algorithm. (e) Decision (f) Connector © 2013 Gilbert Ndjatou
Indicates an entry or an exit
from another part of the
flowchart. Page 57 Logical Expressions A logical expression (or
condition) is an expression that evaluates to either true or false. There
are two types of conditions: simple conditions and Compound
conditions. Simple Conditions A simple condition has the following
syntax:
<arithmetic expression> <relational operator>
<arithmetic expression>
Relational Operators
C/C++ Symbol Meaning < is less than > is greater than == is
equal to <= is less than or equal to >= is greater than or equal to
!= is not equal to Evaluations of simple conditions Assuming that the
variables are defined and initialized as follows:
int num1 = 5 , num2 = 7 , num3 = 2;
float fnum = 11.75;
char ch = ‘K’; Evaluate the following conditions:
a) num1 >= 5
b) fnum + 7.2 != fnum / 2
c) fnum * 2 > num1 + 20 © 2013 Gilbert Ndjatou d) num2 + 3 ==
num3 * 4
e) 3 * num1 + 4 < num3 * 2
f) ‘A’ <= ch Page 58 Solutions
a) num1 >= 5
5
>= 5
True d) num2 + 3 == num3 * 4
7 + 3 == 2 * 4
10
==
8
False b) fnum + 7.2 != fnum / 2
11.75 + 7.2 != 11.75 / 2
18.95 != 5.875
True e) 3 * num1 + 4 < num3 * 2
3*5+4 < 2*2
19 < 4
False c) fnum * 2 > num1 +20
11.75 *2 > 5 + 20
13.75 > 25
False f) ‘A’ <= ch
‘A’ <= ‘K’
True Characters are ordered according to their ASCII code
representations:
‘0' < ‘1' < ‘2' < . . . < ‘9' < ‘A’ < . . . < ‘Z’ < ‘a’ .
. . < ‘z’. Relational operators have a lower precedence than
arithmetic operators:
o In the absence of parentheses, arithmetic operations are evaluated
before any relational operation is
evaluated. However, it is a good programming practice to use
parentheses to clarify the meaning of logical
expressions.
For example: (fnum * 2) > (num1 + 20) Compound Conditions A
compound condition is built from simple conditions using logical
operators.
Logical Operators
C++ Symbol Meaning Evaluation AND <condition1>
&& <condition2> is true if and only if
both conditions are true || OR <condition1> ||
<condition2> is true if and only if at
least one of the two conditions is true ! NOT && © 2013
Gilbert Ndjatou !<condition> is true if and only if
<condition> is false Page 59 Evaluations of compound
conditions
True || True True || False True False || False True False True True
&& True True && False True False || True False
&& True False False && False False False There
is a short-circuit evaluation of a compound condition when you do not
have to evaluate
the right-most condition to get the true value of the compound
condition:
True || True and True || False True Therefore True True || True Also,
False && True and False && False False
Therefore False False && False Exercise CS1*
Assuming that the variables are defined and initialized as follows:
int num1 = 5, num2 = 7, num3 = 2;
float fnum = 11.75;
char ch = ‘K’;
Compute the true value of each of the following compound
conditions:
a) num1 >= 5 || num2 + 3 == num3
b) ‘A’ <= ch && fnum + 7.2 != 2.5
c) !(3 * num1 + 4 < num3 * 2) d) num2 + 3 == num3 * 4 || ch
>= ‘Z’
e) num1 < 3 && num2 > num3
f) !(fnum * 2 < num1 + 20) Solution
a) num1 >= 5 || num2 + 3 == num3
5 >= 5 ||
True
True © 2013 Gilbert Ndjatou d) num2 + 3 == num3 * 4 || ch >=
‘Z’
7 + 3 == 2 * 4
|| ‘K’ >= ‘Z’
10 == 8
|| False
False
|| False
False Page 60 b) ‘A’ <= ch
‘A’ <= ‘K’
True
True && fnum + 7.2 != 2.5
&& 11.75 + 7.2 != 2.5
&& 18.95 != 2.5
&&
True
True e) num1 < 3 && num2 > num3
5 < 3 &&
False
False c) !(3 * num1 + 4 < num3 * 2)
!( 3 * 5 + 4 < 2 * 2)
!( 19 < 4)
! False
True f) !(fnum * 2 < num1 + 20)
!(11.75 * 2 < 5 + 20)
!( 23.50 < 25)
!True
False Precedence of C/C++ Operators
Operator Order of Evaluation Precedence
!
Unary –
right to left
7
*
/
%
+
<
<=
>
<=
==
!=
&&
|| left to right 6 left to right 5 left to right 4 left to right
left to right
left to right 3
2
1 In the evaluation of an expression, operators with higher precedence
are evaluated before those with
lower precedence. Operators with the same precedence are evaluated
in the order specified in the “order of evaluation”
column. © 2013 Gilbert Ndjatou Page 61 Exercise CS2
Assuming that the variables are defined and initialized as follows:
int num1 = 9 , num2 = 5 , num3 = 10;
float fnum = 12.50;
char ch = ‘P’;
Evaluate the following conditions (using short circuit evaluation
whenever possible):
a) 2 * num1 - 5 >= 9 || fnum / 2 + 10 <= 6.5
b) num1 + num2 == num3 + 5 && 2 * num3 <= 4 *
num2
c) ! (num1 + 5 <= 13)
d) num1 + 5 = = 24 || num1 – 1 > num2 – 5
e) 2 * num1 - 5 >= 9 && fnum / 2 + 10 <= 6.5
f) num1 - num2 <= num1 / 3 || num1 * num2 > 100
g) num1 - 5 >= num3 || num2 < 15 && num1 >= 9
Accuracy of Floating-Point Values The fact that floating-point values
are approximated inside a computer makes it difficult to test for
the equality of floating-point values.
For example, if the variable fnum is defined as follows:
float
Then, the condition: fnum = 7.1; fnum / 2 == 3.55 may not be true.
The problem may be solved by assuming that two floating-point
values are equal if their difference
is relatively very small. This is done by testing if the absolute value of
their difference is less than a certain value chosen by
the programmer (for example 0.000001). Using the library function
fabs() that takes as argument a floating-point value and returns its
absolute value, the condition:
value1 == value2
is replaced with the condition: fabs(value1 - value2) < 0.000001
which tests whether the difference between the two values is small
enough so that we can make them
equal. © 2013 Gilbert Ndjatou Page 62 Evaluation of True and False
In the C/C++ programming language, false is represented by the
integer value 0, and any value other than 0 represents true. Therefore,
the following two conditions are equivalent (have the same true
value):
o Conditions value != 0 and value o Conditions value == 0 and ! value
(value is not zero means that it is true)
(value is zero means that !value is true) bool Data Type A variable
with data type bool can only hold the bool values true and false.
Examples:
bool flag = true;
bool condValue = false, HighTemperature, ExtremeTemperature;
double temperature;
HighTemperature = false
cin
>> temperature;
HighTemperature = (temperature >= 120)
ExtremeTemperature = (HighTemperature || (temperature <= -20);
Exercise CS3
1.
a)
b)
c) Which of the following conditions are equivalent (that means have
the same true value)?
num != 0
d) !num
num == 0
e) !(num == 0)
num 2. Suppose that a person’s age is stored in the variable age, his
number of children in the variable
numChild, his salary in the variable salary, and his height in the
variable height. Write the relational
expressions to specify the following conditions:
a. he is 45 year old.
b. he is more than 5.7 feet tall.
c. his salary is between 35,000 and 50,000.
d. he does not have 3 children.
e. he is either 6.0 feet tall, or he has less than 4 children.
f. he is not older than 35 and he has 2 or 3 children © 2013 Gilbert
Ndjatou Page 63 Two-Way Selection using the if-else Structure The
solutions of some problems require the CPU to test a condition and to
select the action to be
performed based on whether or not that condition is true. Example:
Suppose that at a party, you serve alcohol drinks only to guests who
are 21 or older, and a juice to
guests who are less than 21.
When a guest comes to get a drink, you first test his age: if he is 21 or
older, you serve him an
alcohol drink; otherwise you serve him a juice. The solutions of these
types of problems are written using a two-way selection structure
which is
specified using a flowchart as follows: False Condition True T-
Statement F-Statement Next-Statement It says to do the following:
Test condition
a. if it is true, perform the actions (T-Action) specified by T-
Statement,
b. otherwise, perform the actions (F-Action) specified by F-Statement.
Next-Statement is the statement that says what to do after any of the
actions (F-Action or T-Action)
above has been executed. A two-way selection structure is specified
in C++ using the if - else structure as follows:
if (<condition>)
<T-statement>
else
<F-statement>
<Next-Statement>
© 2013 Gilbert Ndjatou Page 64 <T-statement> is a single
statement that specifies the T-Action
<F-statement> is a single statement that specifies the <F-
Action>. Case Study CS1
Problem Statement
Write a program to read the age of an individual, and to output the
message “serve alcohol drink” if he is
21 or older, and the message “serve juice” otherwise. Your program
will then output the message
“thank you for using this program.” Program Logic
output: “Serve alcohol” or “Serve Juice”, depending on the
individual’s age. Input: an individual’s age. Variables: age (int) to
hold an individual’s age. Algorithm Specification (using a Flowchart)
start
Read
age
False True age >= 21 Write
“serve a juice” Write
“serve alcohol drink” Write
“Thank you for
using this program” Stop © 2013 Gilbert Ndjatou Page 65 Figure CS1
Using the if-else Structure
/*******************************************************
******************
Program to read the age of an individual and to output the type of
drink that he
should be served
********************************************************
*****************/
#include
<iostream>
using namespace std;
#define DRINKAGE
21
int main()
{
int age; // to hold an individual’s age /*----------------- read the
individual’s age------------------------*/
cout << “nnEnter the individual’s age please:t”;
cin
>> age;
/*--------determine what type of drink he should be served ---------*/
if (age >= DRINKAGE)
// he is over the drinking age
cout << endl << “Serve alcohol drink”;
else
// he can not drink alcohol
cout << endl << “Serve juice”;
cout << endl << “Thank you for using this program”;
return (0);
} Case Study CS2
Problem Statement
Write a program to read a positive integer value and to determine if it
is even or odd. If it is even,
print it with the message “EVEN”; otherwise, print it with the
message “ODD”. Program Logic
Output: the input value with the message “EVEN” or “ODD”,
depending on whether the input value
is even or odd. Input: an integer value. Variable: num (int) to hold the
input value. Note: An integer value is even if the remainder in its
division by 2 is 0; otherwise, it is odd. © 2013 Gilbert Ndjatou Page
66 Algorithm Specification (using a Flowchart)
Start Read
num False True num % 2 = 0 Write
num, “even” Write
num, “odd” Stop Figure CS2 Using the if - else Structure
/*******************************************************
*****************
Program to read an integer value and to determine if it is even or odd
********************************************************
****************/
#include
<iostream>
using namespace std;
int main()
{
int num; // to hold the value read /*---------------- read in an integer
value--------------------------*/
cout << “nnEnter an integer value please:t”;
cin
>> num;
/*----------------determine if it is even or odd --------------------*/
if (num %2 == 0)
// it is even
cout <<
endl
<<
num
<< “tEVEN”;
else
// it is odd
cout <<
endl << num
<< “tODD”;
return ( 0 );
} Exercise CS4
Write a C++ code segment to read an integer value and to determine if
it is a multiple of 5. If it is a
multiple of 5, print it with the message “MULTIPLE OF 5”,
otherwise, print it with the message NOT
MULTIPLE OF 5.”
© 2013 Gilbert Ndjatou Page 67 Exercise CS5
Write a C++ code segment to read a character and to determine if it is
a letter of the alphabet. If it is a
letter of the alphabet, print it with the message, “it is a letter”
otherwise, print it with the message, “it is
not a letter.” Compound Statement A compound statement has the
following syntax:
{
(One or more statements to be executed as a block) } Example
{
num2 = num1 + 5;
num1 = num1 +1;
cout << endl << “num1=t” << num1 << “n
num2=t” << num2;
} The statements of a compound statement are executed one after
another, starting with the first one in
the sequence. A compound statement may appear anywhere in a C++
program where a single statement may
appear. If you have to specify two or more statements as the T-
statement or the F-statement of an if-else
structure, these statements must be specified as a compound
statement. Case study CS3
Problem Statement
Write a program to read an integer value and to do the following: If
the value read is zero, print it with the message “INVALID
DIVISOR”. Otherwise read a second value and then compute and
print the quotient and the remainder in the
division of the second value by the first. At the end write the message
“Thank you for using this program.” © 2013 Gilbert Ndjatou Page 68
Program Logic
Output: the quotient and the remainder in the division of the second
value by the first or the
message “0 is invalid divisor” depending on the input. Input: one or
two integer values, depending on the value of the first. Variables:
divisor (int) to hold the first value. dividend (int) to hold the second
value. Note:
The second value is input and the quotient and the remainder in the
division of the second value
by the first are computed only if the first value is not zero. Algorithm
Specification (using a Flowchart)
Start Read
divisor False divisor == 0 True Write
divisor
“invalid divisor” Read
dividend Write
dividend / divisor
dividend % divisor Write
“Thank you” Stop © 2013 Gilbert Ndjatou Page 69 Figure CS3 Using
a Compound Statement in an if-else Structure
/*******************************************************
******************
Program to read two integer values and to compute the quotient and
the remainder in
the division of the second value by the first.
********************************************************
*****************/
#include
<iostream>
using namespace std;
int main()
{
int divisor,
dividend; // to hold the first value
// to hold the second value /*---------------------- read in the divisor-----
------------------*/
cout << “nnEnter the divisor please:t”;
cin
>> divisor;
/*-----read the dividend and compute the quotient and the remainder--
*/
if (divisor == 0)
// it is invalid
cout << endl << divisor << “tIS INVALID
DIVISOR”;
else
{
cout << “nnEnter the dividend please:t”;
cin
>> dividend;
cout << “nThe quotient in the division of:t”
<< dividend
<< “ by ” <<
divisor <<
“tis:t”
<< (dividend / divisor);
cout << “nand the remainder is:t”
<< (dividend % divisor);
}
cout << “nnThank you for using this program”;
return( 0 );
} Exercise CS6*
Assuming that all variables are properly defined and initialized, what
are the error(s) in each of the
following program segments?
a. cin >> num;
if (num = 5)
sum = num + 4;
else
sum = num + 10;
b. cin >> num;
if (num > 5 && <= 10)
cout << (num + 15);
else
cout << (num - 3); © 2013 Gilbert Ndjatou Page 70 c. cin
>> num;
if (num < 15)
result1 = 2 * num;
result2 = num + 20;
else
result1 = 5 * num;
result = result1 + result2;
cout << “nThe result is:t” << result; Exercise CS7*
Trace the execution of the following program segment and show its
output for each of the following
input values:
a. input: 4
b. input: 20
Line #
Statements
1
cin >> num;
2
if (num <10 )
{
3
num = num + 6;
4
cout << endl << “num =t” << num;
}
else
5
cout << endl << “num / 4 =t” << (num / 4);
6
cout << endl << “result =t”<< (2 * num); Exercise
CS8
Write a C++ code segment to read an integer value into variable
num1and another integer value into
variable num2 and to do the following: if the value in variable num1
is greater than the value in variable
num2 do the following: add 1 to the value in num1 and 5 to the value
in num2 and then print the result
of the product of the new value in num1 and the new value in num2;
otherwise, do the following:
subtract 1from the value in num1 and 5 from the value in num2 and
then print the result of the product of
the new value in num1 and the new value in num2. Exercise CS9
A department store offers a rebate of 5% if the total amount of the
purchase is at least 100 and a rebate
of 2% otherwise. A sale tax of 8.25 % is also imposed on the price of
each purchase (after the rebate).
Write a C++ code segment to read the unit price and the number of
items purchased, and to output the
amount of the rebate and the price (including taxes) of the purchase.
© 2013 Gilbert Ndjatou Page 71 Counter-Controlled Iteration using
the while Structure The solutions of some problems require the CPU
to repeat the execution of one or more statements a
certain number of times. Example:
Suppose that a candy bar costs 70 cents in a candy machine that only
accepts dimes. To buy a candy
bar from this machine, a user has to deposit a dime in the machine
seven times. The solutions of these types of problems are written
using a counter-controlled iteration (or loop)
which is specified using a flowchart as follows: counter = initial-value
False Counter < final-value True Body-of-the-Loop Next-
Statement Body-of- the- Loop
counter consists of the statements whose executions are repeated by
the CPU.
is called the loop counter
it is a variable that is used to hold the number of repetitions Next-
Statement is the first statement to be executed after the repetitions.
Initial/Final Value If the initial value is 0 (no execution is done yet),
then the final value must be the number of
executions. If the initial value is 1 (one execution is about to be done),
then the final value must be the number
of execution plus 1. Loop Increment After each execution of the
body-of-the-loop, the loop counter must be updated to reflect the
number
of executions.
The statement that you use to update the loop counter is called the
loop increment.
The loop increment is a statement in the body-of-the-loop. © 2013
Gilbert Ndjatou Page 72 Algorithm of the Candy Bar Machine (using
a flowchart) Start total = 0 count = 0 False True count < 7
Read
coin
total = total + coin Write
“Thank you” count = count + 1 Stop Specification of a Counter-
Controlled Iteration in C++ A counter-controlled iteration may be
specified in C++ using the while structure as follows:
counter = initial-value;
while (counter < final-value)
{
<Body-of-of the-loop (including the increment-statement)>
}
<Next-statement> © 2013 Gilbert Ndjatou Page 73 Algorithm
for the Candy Bar Machine Problem (in C++)
int total,
coin,
count; // to hold the total value of the coins
// to hold the value of a coin
// to hold the number of repetitions total = 0;
count = 0;
while ( count < 7 )
{
cin >> coin;
total += coin;
count ++;
}
cout << endl << “Thank You”; Case Study CS4
Problem Statement
Write a program to read 30 weight measurements in pounds and to
convert them into kilograms. Note
that 1 Lb = .454 Kgs.
Program Logic
Input: 30 weight measurements (in Lbs). Output: 30 weight
measurements (in Kgs). Variables:
count (int) to count the weight measurements: Initial value is 0 - Final
value is 30. pound (double) © 2013 Gilbert Ndjatou to hold a weight
measurement in Lbs. Page 74 Algorithm Specification (using a
flowchart) Start count = 0 False True count < 30
Read
pound
Write
.454 * pound count = count + 1 Write
“Thank you” Stop Figure CS4 Counter-Controlled Iteration using the
while Structure Line Number
1
/*******************************************************
******
2
Program to read 30 weight measurements in pounds and convert
3
them into kilograms
4
********************************************************
*****/
5
#include
<iostream.h>
6
#include
<iomanip.h>
7
#define
MAXCOUNT 30
8
#define
COEFICIENT .454
9
10
int main()
11
{
12
int count;
// to count weight measurements
13
double
pound,
// the current weight measurement in Lbs
14
© 2013 Gilbert Ndjatou Page 75 15
16
17
18
19
20
21
22
23
24
25
26
27 cout.setf(ios :: fixed);
// in order to use formatted
cout.setf(ios :: showpoint); // floating-point output
cout << setprecision(2); // 2 digits after the decimal point
/*read all weight measurements (Lbs) and convert them to Kgs*/
count = 0;
// no weight measurement is read so far
while (count < MAXCOUNT)
// repeat thirty times
{
cout
<<
“nEnter a weight measurement please:t”;
cin
>>
pound;
cout << “t = ” << (.454 * pound);
count ++;
}
28 29
27
28 cout << endl
return (0); << “Thank you”; } The body of the loop consists of
the statements in line 23 to line 26. The loop-counter is initialized in
line 20; and the loop-increment statement is in line 26. Exercise
CS10*
Assuming that all variables are properly defined, find the mistake(s)
in the specification of each of the
following while structures:
a.
while( count < 10 )
{
cin >> num;
cout << 2 * num;
count = count + 1;
} b.
while(count < 10)
{
count = 0;
cin >> num;
cout << 2 * num;
count = count + 1;
} c.
count = 0;
while(count < 10 )
{
cin >> num;
cout << 2 * num;
} Exercise CS11
Write a C++ code segment to read 50 temperature values in
Fahrenheit and to convert them to Celsius.
You convert a Fahrenheit temperature to Celsius by using the
following formula: Celsius = 5.0 / 9 *
(Fahrenheit - 32). © 2013 Gilbert Ndjatou Page 76 Using a Running
Total A running total is a variable that is used to compute the sum of
the values processed at ach iteration of
a loop: it is first initialized to 0 and each new value processed in the
loop is added to the previous total. Case Study CS5
Problem Statement Write a program to read 20 integer values and to
compute their sum.
Program Logic
Input: 20 integer values. Output: their sum. Variable:
count (int)
value to count the values: Initial value is 0 (no value is read so far);
Final value is 20. (int) totalValue (int) to hold the integer value read.
to hold the sum of the integer values read so far: Initial value is 0.
Algorithm Specification (using a Flowchart)
Start
totalValue = 0 count = 0 False count < 20 True Read
value totalValue = totalValue + value Write
totalValue count = count + 1 Stop © 2013 Gilbert Ndjatou Page 77
Figure CS5 Counter-Controlled Iteration using the while Structure
Line Number
1
/*******************************************************
******
2
Program to read twenty integer values and to compute their sum.
3
********************************************************
*****/
4
#include
<iostream>
5
using namespace std;
6
#define
MAXCOUNT
20
7
8
int main()
9
{
10
int count;
// to count values
11
value,
// to hold the value read
12
totalValue;
// the hold the sum of the values read so far
13
14
/*------read all values and compute their sum-------*/
15
totalValue = 0;
15
count = 0;
// no value has been read so far
16
while (count < MAXCOUNT)
// repeat twenty times
17
{
18
cout
<<
“nEnter an integer value please:t”;
19
cin
>>
value;
20
totalValue += value;
21
count++;
22
}
23
24
/*-----print the sum of all the values read----------*/
25
cout <<
“nnThe sum of all the values read is:t”
26
<<
totalValue;
27
return (0);
28
} Exercise CS12*
Each of the following code segments is supposed to read 10 integer
values and to compute their sum.
What is wrong in each of these code..

More Related Content

What's hot

Mesics lecture 4 c operators and experssions
Mesics lecture  4   c operators and experssionsMesics lecture  4   c operators and experssions
Mesics lecture 4 c operators and experssions
eShikshak
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
bajiajugal
 

What's hot (20)

Decision making statements in C programming
Decision making statements in C programmingDecision making statements in C programming
Decision making statements in C programming
 
Mesics lecture 4 c operators and experssions
Mesics lecture  4   c operators and experssionsMesics lecture  4   c operators and experssions
Mesics lecture 4 c operators and experssions
 
[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Decision making statements in C
Decision making statements in CDecision making statements in C
Decision making statements in C
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
Variables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detailVariables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detail
 
Python : basic operators
Python : basic operatorsPython : basic operators
Python : basic operators
 
Lecture03(c expressions & operators)
Lecture03(c expressions & operators)Lecture03(c expressions & operators)
Lecture03(c expressions & operators)
 
Python tutorials for beginners | IQ Online Training
Python tutorials for beginners | IQ Online TrainingPython tutorials for beginners | IQ Online Training
Python tutorials for beginners | IQ Online Training
 
C tutorial
C tutorialC tutorial
C tutorial
 
L05if
L05ifL05if
L05if
 
Python operators
Python operatorsPython operators
Python operators
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
C – operators and expressions
C – operators and expressionsC – operators and expressions
C – operators and expressions
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 
Python Operators
Python OperatorsPython Operators
Python Operators
 

Similar to C/C++ programming language Something Great/tutorialoutletdotcom

Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
Karwan Mustafa Kareem
 
05 control structures 2
05 control structures 205 control structures 2
05 control structures 2
Jomel Penalba
 
Which if statement below tests if letter holds R (letter is a char .pdf
Which if statement below tests if letter holds R (letter is a char .pdfWhich if statement below tests if letter holds R (letter is a char .pdf
Which if statement below tests if letter holds R (letter is a char .pdf
aniarihant
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#
Raghu nath
 

Similar to C/C++ programming language Something Great/tutorialoutletdotcom (20)

Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
Control All
Control AllControl All
Control All
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
chap04-conditional.ppt
chap04-conditional.pptchap04-conditional.ppt
chap04-conditional.ppt
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 
05 control structures 2
05 control structures 205 control structures 2
05 control structures 2
 
Ch3
Ch3Ch3
Ch3
 
Which if statement below tests if letter holds R (letter is a char .pdf
Which if statement below tests if letter holds R (letter is a char .pdfWhich if statement below tests if letter holds R (letter is a char .pdf
Which if statement below tests if letter holds R (letter is a char .pdf
 
CIS 1403 lab 4 selection
CIS 1403 lab 4 selectionCIS 1403 lab 4 selection
CIS 1403 lab 4 selection
 
3.1 conditional statement
3.1 conditional statement3.1 conditional statement
3.1 conditional statement
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection Statements
 
C C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inC C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.in
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
Ch4
Ch4Ch4
Ch4
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#
 
C operators
C operatorsC operators
C operators
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 

Recently uploaded (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 

C/C++ programming language Something Great/tutorialoutletdotcom

  • 1. Control Structures The basic operations of a C/C++ programming language are specified using the following statements or structures FOR MORE CLASSES VISIT www.tutorialoutlet.com Control Structures The basic operations of a C/C++ programming language are specified using the following statements or structures: the input statement the output statement the assignment statements the single-way selection structure the two-way selection structure the multiple-way selection structure the counter-controlled iteration structure, and the logically-controlled iteration structure. The single-way selection, the two-way selection, the multiple-way selection, the counter- controlled iteration and the logically-controlled iteration are collectively called control structures. The specification of a controlled structure depends on a logical expression called condition. Controlled structures may also be specified using the following flowchart symbols: Flowchart Symbols
  • 2. SYMBOL (a) (b) (c) (d) NAME Terminal Input/Output Process Flow Lines DESCRIPTION Indicates the beginning or the end of an algorithm. Indicates an input or an output operation. Indicates a computation or a data manipulation. Used to connect the symbols and to indicate the logic flow. Indicates a decision point in an algorithm. (e) Decision (f) Connector © 2013 Gilbert Ndjatou Indicates an entry or an exit from another part of the flowchart. Page 57 Logical Expressions A logical expression (or condition) is an expression that evaluates to either true or false. There are two types of conditions: simple conditions and Compound conditions. Simple Conditions A simple condition has the following syntax: <arithmetic expression> <relational operator> <arithmetic expression> Relational Operators C/C++ Symbol Meaning < is less than > is greater than == is equal to <= is less than or equal to >= is greater than or equal to != is not equal to Evaluations of simple conditions Assuming that the variables are defined and initialized as follows: int num1 = 5 , num2 = 7 , num3 = 2;
  • 3. float fnum = 11.75; char ch = ‘K’; Evaluate the following conditions: a) num1 >= 5 b) fnum + 7.2 != fnum / 2 c) fnum * 2 > num1 + 20 © 2013 Gilbert Ndjatou d) num2 + 3 == num3 * 4 e) 3 * num1 + 4 < num3 * 2 f) ‘A’ <= ch Page 58 Solutions a) num1 >= 5 5 >= 5 True d) num2 + 3 == num3 * 4 7 + 3 == 2 * 4 10 == 8 False b) fnum + 7.2 != fnum / 2 11.75 + 7.2 != 11.75 / 2 18.95 != 5.875 True e) 3 * num1 + 4 < num3 * 2 3*5+4 < 2*2 19 < 4 False c) fnum * 2 > num1 +20 11.75 *2 > 5 + 20
  • 4. 13.75 > 25 False f) ‘A’ <= ch ‘A’ <= ‘K’ True Characters are ordered according to their ASCII code representations: ‘0' < ‘1' < ‘2' < . . . < ‘9' < ‘A’ < . . . < ‘Z’ < ‘a’ . . . < ‘z’. Relational operators have a lower precedence than arithmetic operators: o In the absence of parentheses, arithmetic operations are evaluated before any relational operation is evaluated. However, it is a good programming practice to use parentheses to clarify the meaning of logical expressions. For example: (fnum * 2) > (num1 + 20) Compound Conditions A compound condition is built from simple conditions using logical operators. Logical Operators C++ Symbol Meaning Evaluation AND <condition1> && <condition2> is true if and only if both conditions are true || OR <condition1> || <condition2> is true if and only if at least one of the two conditions is true ! NOT && © 2013 Gilbert Ndjatou !<condition> is true if and only if <condition> is false Page 59 Evaluations of compound conditions True || True True || False True False || False True False True True && True True && False True False || True False && True False False && False False False There
  • 5. is a short-circuit evaluation of a compound condition when you do not have to evaluate the right-most condition to get the true value of the compound condition: True || True and True || False True Therefore True True || True Also, False && True and False && False False Therefore False False && False Exercise CS1* Assuming that the variables are defined and initialized as follows: int num1 = 5, num2 = 7, num3 = 2; float fnum = 11.75; char ch = ‘K’; Compute the true value of each of the following compound conditions: a) num1 >= 5 || num2 + 3 == num3 b) ‘A’ <= ch && fnum + 7.2 != 2.5 c) !(3 * num1 + 4 < num3 * 2) d) num2 + 3 == num3 * 4 || ch >= ‘Z’ e) num1 < 3 && num2 > num3 f) !(fnum * 2 < num1 + 20) Solution a) num1 >= 5 || num2 + 3 == num3 5 >= 5 || True True © 2013 Gilbert Ndjatou d) num2 + 3 == num3 * 4 || ch >= ‘Z’ 7 + 3 == 2 * 4 || ‘K’ >= ‘Z’
  • 6. 10 == 8 || False False || False False Page 60 b) ‘A’ <= ch ‘A’ <= ‘K’ True True && fnum + 7.2 != 2.5 && 11.75 + 7.2 != 2.5 && 18.95 != 2.5 && True True e) num1 < 3 && num2 > num3 5 < 3 && False False c) !(3 * num1 + 4 < num3 * 2) !( 3 * 5 + 4 < 2 * 2) !( 19 < 4) ! False True f) !(fnum * 2 < num1 + 20) !(11.75 * 2 < 5 + 20) !( 23.50 < 25) !True
  • 7. False Precedence of C/C++ Operators Operator Order of Evaluation Precedence ! Unary – right to left 7 * / % + < <= > <= == != && || left to right 6 left to right 5 left to right 4 left to right left to right left to right 3 2 1 In the evaluation of an expression, operators with higher precedence are evaluated before those with
  • 8. lower precedence. Operators with the same precedence are evaluated in the order specified in the “order of evaluation” column. © 2013 Gilbert Ndjatou Page 61 Exercise CS2 Assuming that the variables are defined and initialized as follows: int num1 = 9 , num2 = 5 , num3 = 10; float fnum = 12.50; char ch = ‘P’; Evaluate the following conditions (using short circuit evaluation whenever possible): a) 2 * num1 - 5 >= 9 || fnum / 2 + 10 <= 6.5 b) num1 + num2 == num3 + 5 && 2 * num3 <= 4 * num2 c) ! (num1 + 5 <= 13) d) num1 + 5 = = 24 || num1 – 1 > num2 – 5 e) 2 * num1 - 5 >= 9 && fnum / 2 + 10 <= 6.5 f) num1 - num2 <= num1 / 3 || num1 * num2 > 100 g) num1 - 5 >= num3 || num2 < 15 && num1 >= 9 Accuracy of Floating-Point Values The fact that floating-point values are approximated inside a computer makes it difficult to test for the equality of floating-point values. For example, if the variable fnum is defined as follows: float Then, the condition: fnum = 7.1; fnum / 2 == 3.55 may not be true. The problem may be solved by assuming that two floating-point values are equal if their difference
  • 9. is relatively very small. This is done by testing if the absolute value of their difference is less than a certain value chosen by the programmer (for example 0.000001). Using the library function fabs() that takes as argument a floating-point value and returns its absolute value, the condition: value1 == value2 is replaced with the condition: fabs(value1 - value2) < 0.000001 which tests whether the difference between the two values is small enough so that we can make them equal. © 2013 Gilbert Ndjatou Page 62 Evaluation of True and False In the C/C++ programming language, false is represented by the integer value 0, and any value other than 0 represents true. Therefore, the following two conditions are equivalent (have the same true value): o Conditions value != 0 and value o Conditions value == 0 and ! value (value is not zero means that it is true) (value is zero means that !value is true) bool Data Type A variable with data type bool can only hold the bool values true and false. Examples: bool flag = true; bool condValue = false, HighTemperature, ExtremeTemperature; double temperature; HighTemperature = false cin >> temperature; HighTemperature = (temperature >= 120)
  • 10. ExtremeTemperature = (HighTemperature || (temperature <= -20); Exercise CS3 1. a) b) c) Which of the following conditions are equivalent (that means have the same true value)? num != 0 d) !num num == 0 e) !(num == 0) num 2. Suppose that a person’s age is stored in the variable age, his number of children in the variable numChild, his salary in the variable salary, and his height in the variable height. Write the relational expressions to specify the following conditions: a. he is 45 year old. b. he is more than 5.7 feet tall. c. his salary is between 35,000 and 50,000. d. he does not have 3 children. e. he is either 6.0 feet tall, or he has less than 4 children. f. he is not older than 35 and he has 2 or 3 children © 2013 Gilbert Ndjatou Page 63 Two-Way Selection using the if-else Structure The solutions of some problems require the CPU to test a condition and to select the action to be performed based on whether or not that condition is true. Example:
  • 11. Suppose that at a party, you serve alcohol drinks only to guests who are 21 or older, and a juice to guests who are less than 21. When a guest comes to get a drink, you first test his age: if he is 21 or older, you serve him an alcohol drink; otherwise you serve him a juice. The solutions of these types of problems are written using a two-way selection structure which is specified using a flowchart as follows: False Condition True T- Statement F-Statement Next-Statement It says to do the following: Test condition a. if it is true, perform the actions (T-Action) specified by T- Statement, b. otherwise, perform the actions (F-Action) specified by F-Statement. Next-Statement is the statement that says what to do after any of the actions (F-Action or T-Action) above has been executed. A two-way selection structure is specified in C++ using the if - else structure as follows: if (<condition>) <T-statement> else <F-statement> <Next-Statement> © 2013 Gilbert Ndjatou Page 64 <T-statement> is a single statement that specifies the T-Action <F-statement> is a single statement that specifies the <F- Action>. Case Study CS1 Problem Statement
  • 12. Write a program to read the age of an individual, and to output the message “serve alcohol drink” if he is 21 or older, and the message “serve juice” otherwise. Your program will then output the message “thank you for using this program.” Program Logic output: “Serve alcohol” or “Serve Juice”, depending on the individual’s age. Input: an individual’s age. Variables: age (int) to hold an individual’s age. Algorithm Specification (using a Flowchart) start Read age False True age >= 21 Write “serve a juice” Write “serve alcohol drink” Write “Thank you for using this program” Stop © 2013 Gilbert Ndjatou Page 65 Figure CS1 Using the if-else Structure /******************************************************* ****************** Program to read the age of an individual and to output the type of drink that he should be served ******************************************************** *****************/ #include <iostream> using namespace std;
  • 13. #define DRINKAGE 21 int main() { int age; // to hold an individual’s age /*----------------- read the individual’s age------------------------*/ cout << “nnEnter the individual’s age please:t”; cin >> age; /*--------determine what type of drink he should be served ---------*/ if (age >= DRINKAGE) // he is over the drinking age cout << endl << “Serve alcohol drink”; else // he can not drink alcohol cout << endl << “Serve juice”; cout << endl << “Thank you for using this program”; return (0); } Case Study CS2 Problem Statement Write a program to read a positive integer value and to determine if it is even or odd. If it is even, print it with the message “EVEN”; otherwise, print it with the message “ODD”. Program Logic
  • 14. Output: the input value with the message “EVEN” or “ODD”, depending on whether the input value is even or odd. Input: an integer value. Variable: num (int) to hold the input value. Note: An integer value is even if the remainder in its division by 2 is 0; otherwise, it is odd. © 2013 Gilbert Ndjatou Page 66 Algorithm Specification (using a Flowchart) Start Read num False True num % 2 = 0 Write num, “even” Write num, “odd” Stop Figure CS2 Using the if - else Structure /******************************************************* ***************** Program to read an integer value and to determine if it is even or odd ******************************************************** ****************/ #include <iostream> using namespace std; int main() { int num; // to hold the value read /*---------------- read in an integer value--------------------------*/ cout << “nnEnter an integer value please:t”; cin >> num; /*----------------determine if it is even or odd --------------------*/
  • 15. if (num %2 == 0) // it is even cout << endl << num << “tEVEN”; else // it is odd cout << endl << num << “tODD”; return ( 0 ); } Exercise CS4 Write a C++ code segment to read an integer value and to determine if it is a multiple of 5. If it is a multiple of 5, print it with the message “MULTIPLE OF 5”, otherwise, print it with the message NOT MULTIPLE OF 5.” © 2013 Gilbert Ndjatou Page 67 Exercise CS5 Write a C++ code segment to read a character and to determine if it is a letter of the alphabet. If it is a letter of the alphabet, print it with the message, “it is a letter” otherwise, print it with the message, “it is
  • 16. not a letter.” Compound Statement A compound statement has the following syntax: { (One or more statements to be executed as a block) } Example { num2 = num1 + 5; num1 = num1 +1; cout << endl << “num1=t” << num1 << “n num2=t” << num2; } The statements of a compound statement are executed one after another, starting with the first one in the sequence. A compound statement may appear anywhere in a C++ program where a single statement may appear. If you have to specify two or more statements as the T- statement or the F-statement of an if-else structure, these statements must be specified as a compound statement. Case study CS3 Problem Statement Write a program to read an integer value and to do the following: If the value read is zero, print it with the message “INVALID DIVISOR”. Otherwise read a second value and then compute and print the quotient and the remainder in the division of the second value by the first. At the end write the message “Thank you for using this program.” © 2013 Gilbert Ndjatou Page 68 Program Logic Output: the quotient and the remainder in the division of the second value by the first or the
  • 17. message “0 is invalid divisor” depending on the input. Input: one or two integer values, depending on the value of the first. Variables: divisor (int) to hold the first value. dividend (int) to hold the second value. Note: The second value is input and the quotient and the remainder in the division of the second value by the first are computed only if the first value is not zero. Algorithm Specification (using a Flowchart) Start Read divisor False divisor == 0 True Write divisor “invalid divisor” Read dividend Write dividend / divisor dividend % divisor Write “Thank you” Stop © 2013 Gilbert Ndjatou Page 69 Figure CS3 Using a Compound Statement in an if-else Structure /******************************************************* ****************** Program to read two integer values and to compute the quotient and the remainder in the division of the second value by the first. ******************************************************** *****************/ #include <iostream> using namespace std;
  • 18. int main() { int divisor, dividend; // to hold the first value // to hold the second value /*---------------------- read in the divisor----- ------------------*/ cout << “nnEnter the divisor please:t”; cin >> divisor; /*-----read the dividend and compute the quotient and the remainder-- */ if (divisor == 0) // it is invalid cout << endl << divisor << “tIS INVALID DIVISOR”; else { cout << “nnEnter the dividend please:t”; cin >> dividend; cout << “nThe quotient in the division of:t” << dividend << “ by ” << divisor << “tis:t”
  • 19. << (dividend / divisor); cout << “nand the remainder is:t” << (dividend % divisor); } cout << “nnThank you for using this program”; return( 0 ); } Exercise CS6* Assuming that all variables are properly defined and initialized, what are the error(s) in each of the following program segments? a. cin >> num; if (num = 5) sum = num + 4; else sum = num + 10; b. cin >> num; if (num > 5 && <= 10) cout << (num + 15); else cout << (num - 3); © 2013 Gilbert Ndjatou Page 70 c. cin >> num; if (num < 15) result1 = 2 * num; result2 = num + 20;
  • 20. else result1 = 5 * num; result = result1 + result2; cout << “nThe result is:t” << result; Exercise CS7* Trace the execution of the following program segment and show its output for each of the following input values: a. input: 4 b. input: 20 Line # Statements 1 cin >> num; 2 if (num <10 ) { 3 num = num + 6; 4 cout << endl << “num =t” << num; } else 5 cout << endl << “num / 4 =t” << (num / 4);
  • 21. 6 cout << endl << “result =t”<< (2 * num); Exercise CS8 Write a C++ code segment to read an integer value into variable num1and another integer value into variable num2 and to do the following: if the value in variable num1 is greater than the value in variable num2 do the following: add 1 to the value in num1 and 5 to the value in num2 and then print the result of the product of the new value in num1 and the new value in num2; otherwise, do the following: subtract 1from the value in num1 and 5 from the value in num2 and then print the result of the product of the new value in num1 and the new value in num2. Exercise CS9 A department store offers a rebate of 5% if the total amount of the purchase is at least 100 and a rebate of 2% otherwise. A sale tax of 8.25 % is also imposed on the price of each purchase (after the rebate). Write a C++ code segment to read the unit price and the number of items purchased, and to output the amount of the rebate and the price (including taxes) of the purchase. © 2013 Gilbert Ndjatou Page 71 Counter-Controlled Iteration using the while Structure The solutions of some problems require the CPU to repeat the execution of one or more statements a certain number of times. Example: Suppose that a candy bar costs 70 cents in a candy machine that only accepts dimes. To buy a candy
  • 22. bar from this machine, a user has to deposit a dime in the machine seven times. The solutions of these types of problems are written using a counter-controlled iteration (or loop) which is specified using a flowchart as follows: counter = initial-value False Counter < final-value True Body-of-the-Loop Next- Statement Body-of- the- Loop counter consists of the statements whose executions are repeated by the CPU. is called the loop counter it is a variable that is used to hold the number of repetitions Next- Statement is the first statement to be executed after the repetitions. Initial/Final Value If the initial value is 0 (no execution is done yet), then the final value must be the number of executions. If the initial value is 1 (one execution is about to be done), then the final value must be the number of execution plus 1. Loop Increment After each execution of the body-of-the-loop, the loop counter must be updated to reflect the number of executions. The statement that you use to update the loop counter is called the loop increment. The loop increment is a statement in the body-of-the-loop. © 2013 Gilbert Ndjatou Page 72 Algorithm of the Candy Bar Machine (using a flowchart) Start total = 0 count = 0 False True count < 7 Read coin total = total + coin Write
  • 23. “Thank you” count = count + 1 Stop Specification of a Counter- Controlled Iteration in C++ A counter-controlled iteration may be specified in C++ using the while structure as follows: counter = initial-value; while (counter < final-value) { <Body-of-of the-loop (including the increment-statement)> } <Next-statement> © 2013 Gilbert Ndjatou Page 73 Algorithm for the Candy Bar Machine Problem (in C++) int total, coin, count; // to hold the total value of the coins // to hold the value of a coin // to hold the number of repetitions total = 0; count = 0; while ( count < 7 ) { cin >> coin; total += coin; count ++; } cout << endl << “Thank You”; Case Study CS4 Problem Statement
  • 24. Write a program to read 30 weight measurements in pounds and to convert them into kilograms. Note that 1 Lb = .454 Kgs. Program Logic Input: 30 weight measurements (in Lbs). Output: 30 weight measurements (in Kgs). Variables: count (int) to count the weight measurements: Initial value is 0 - Final value is 30. pound (double) © 2013 Gilbert Ndjatou to hold a weight measurement in Lbs. Page 74 Algorithm Specification (using a flowchart) Start count = 0 False True count < 30 Read pound Write .454 * pound count = count + 1 Write “Thank you” Stop Figure CS4 Counter-Controlled Iteration using the while Structure Line Number 1 /******************************************************* ****** 2 Program to read 30 weight measurements in pounds and convert 3 them into kilograms 4 ******************************************************** *****/
  • 25. 5 #include <iostream.h> 6 #include <iomanip.h> 7 #define MAXCOUNT 30 8 #define COEFICIENT .454 9 10 int main() 11 { 12 int count; // to count weight measurements 13 double pound,
  • 26. // the current weight measurement in Lbs 14 © 2013 Gilbert Ndjatou Page 75 15 16 17 18 19 20 21 22 23 24 25 26 27 cout.setf(ios :: fixed); // in order to use formatted cout.setf(ios :: showpoint); // floating-point output cout << setprecision(2); // 2 digits after the decimal point /*read all weight measurements (Lbs) and convert them to Kgs*/ count = 0; // no weight measurement is read so far while (count < MAXCOUNT) // repeat thirty times
  • 27. { cout << “nEnter a weight measurement please:t”; cin >> pound; cout << “t = ” << (.454 * pound); count ++; } 28 29 27 28 cout << endl return (0); << “Thank you”; } The body of the loop consists of the statements in line 23 to line 26. The loop-counter is initialized in line 20; and the loop-increment statement is in line 26. Exercise CS10* Assuming that all variables are properly defined, find the mistake(s) in the specification of each of the following while structures: a. while( count < 10 ) { cin >> num; cout << 2 * num;
  • 28. count = count + 1; } b. while(count < 10) { count = 0; cin >> num; cout << 2 * num; count = count + 1; } c. count = 0; while(count < 10 ) { cin >> num; cout << 2 * num; } Exercise CS11 Write a C++ code segment to read 50 temperature values in Fahrenheit and to convert them to Celsius. You convert a Fahrenheit temperature to Celsius by using the following formula: Celsius = 5.0 / 9 * (Fahrenheit - 32). © 2013 Gilbert Ndjatou Page 76 Using a Running Total A running total is a variable that is used to compute the sum of the values processed at ach iteration of a loop: it is first initialized to 0 and each new value processed in the loop is added to the previous total. Case Study CS5 Problem Statement Write a program to read 20 integer values and to compute their sum.
  • 29. Program Logic Input: 20 integer values. Output: their sum. Variable: count (int) value to count the values: Initial value is 0 (no value is read so far); Final value is 20. (int) totalValue (int) to hold the integer value read. to hold the sum of the integer values read so far: Initial value is 0. Algorithm Specification (using a Flowchart) Start totalValue = 0 count = 0 False count < 20 True Read value totalValue = totalValue + value Write totalValue count = count + 1 Stop © 2013 Gilbert Ndjatou Page 77 Figure CS5 Counter-Controlled Iteration using the while Structure Line Number 1 /******************************************************* ****** 2 Program to read twenty integer values and to compute their sum. 3 ******************************************************** *****/ 4 #include <iostream> 5 using namespace std;
  • 30. 6 #define MAXCOUNT 20 7 8 int main() 9 { 10 int count; // to count values 11 value, // to hold the value read 12 totalValue; // the hold the sum of the values read so far 13 14 /*------read all values and compute their sum-------*/ 15 totalValue = 0;
  • 31. 15 count = 0; // no value has been read so far 16 while (count < MAXCOUNT) // repeat twenty times 17 { 18 cout << “nEnter an integer value please:t”; 19 cin >> value; 20 totalValue += value; 21 count++; 22 } 23
  • 32. 24 /*-----print the sum of all the values read----------*/ 25 cout << “nnThe sum of all the values read is:t” 26 << totalValue; 27 return (0); 28 } Exercise CS12* Each of the following code segments is supposed to read 10 integer values and to compute their sum. What is wrong in each of these code..