Control Structures - CPP PDF
Control Structures - CPP PDF
Flowcharts:
• A flowchart is a graphical representation of an algorithm.
• Flowcharts are drawn using special-purpose symbols, such as
ovals, rectangles, diamonds and small circles.
• These symbols are connected by arrows called flowlines.
Example:
-Write a program that reads a number and prints out “even” if the
number is even or “odd” if the number is odd.
Pseudocode:
Input number
If number is even
Then Print “even”
Else print “odd”
Flowchart:
Begin
Enter number
End
Problem:
Write the flowchart for the following problem:
Write a program that prompts the user to enter a number and writes:
• “A negative number has been entered” if the number is
negative.
• “0 has been entered” if the number is 0
• “A positive number has been entered” if the number is positive.
Selection statements:
Conditions:
A selection in a program allows us to choose between two or more
actions depending on whether a condition is true or false. This
condition is based on a comparison of two items, and is usually
expressed with one of the following relational operators:
< less than
> greater than
== equal
<= less than or equal to
>= greater than or equal to
!= not equal to
The statement:
if ( x != 0.0) compares the value of x to 0.0 and has one alternative,
which is executed when x is not equal to 0.0.
If x is equal to 0.0, the addition is not performed.
The statement:
sum= sum + x;
causes the value of x to be added to the value of sum and the new
value obtained to be saved in the variable sum.
Full program:
#include <iostream>
int main(void) {
float x, sum;
sum = 100.0;
cout <<"Please enter a real number \n";
cin>> x;
if (x!= 0.0)
sum = sum + x;
cout<<”This is the sum ”<< sum;
return 0;
}
Program Output:
Run 1:
Please enter a real number
23.0
This is the sum 123.00000
Run 2:
Please enter a real number
0.0
This is the sum 100.00000
Form:
if (condition)
statementT ;
else
statementF ;
Full Program:
#include <iostream>
using namespace std;
int main(void) {
int grade;
cout << "Please enter the grade \n";
cin>> grade;
if (grade >= 60)
cout<< "Passed”;
else
cout<< “Failed”;
return 0;
}
For example:
We want to write a program that determines the service charge for a
bank account based on the account balance. When the account balance
is less than $1000, then there is a fee of $5 on the balance and a
message is printed informing us about it. If the balance is above the
amount, another message is sent.
Algorithm:
Begin
End
account balance= account balance – fee
Full Program:
#include <iostream>
using namspace std;
int main(void) {
double account_balance;
int fee=0;
cout << "Please enter the account_balance: \n";
cin>> account_balance;
if (account_balance <=1000.00)
{cout << "Fee is due”;
fee=5;}
else
cout << “No fee is due”;
account_balance= account_balance - fee;
cout << “The account balance is ”<< account_balance;
return 0;}
Nested ifs:
Nested if/else structures test for multiple cases by placing if/else
structures inside if/else structures.
In C++, an else statement always refers to the nearest if statement that
is within the same block as the else and not already associated with an
if.
if (expri) {
if (exprj)
statement1;
if (exprk)
statement2;/*this if is */
else
statement3;/*associated with this else*/
}/*end if
else
statement4;
Class Ship
ID Class
B or b Battleship
C or c Cruiser
D or d Destroyer
F or f Frigate
Begin
Read Class ID
F
T
Class = Print Cruiser
‘c’ or ‘C’
F
T
Class = Print Destroyer
’d’or ‘D’
T
Class =
‘F’ or ‘f’ Print Frigate
End
#include <iostream>
using namespace std;
int main(void) {
char Class_id;
cout<< “Enter ship class: ";
cin>> Class_id;
switch (Class_id) {
case 'B': cout<<”Battleship\n”; break;
case 'b': cout <<”Battleship\n"; break;
case 'C':
case 'c': cout<<”Cruiser\n"; break;
case 'D':
case 'd' : cout<<” Destroyer \n"; break;
case 'F':
case 'f' : cout<<”Fregate\n";
break;
default : cout<<”Unknown ship class<< Class_id<<endl;
}
return 0;
}
The general format for the switch statement is:
switch (variable) {
case value1:
statement;
statement;
......
break;
case value2:
statement;
.......
break;
default:
.......
.......
break;
}
if(plusminus == ‘a’ )
cout << num1 << “plus”<< num2 <<”is”
<<output;
else
if( plusminus == ‘s’ )
cout<< num1<< “minus”<< num2<<”is”
<<output;
return 0;
}
int main(void)
{
int plusminus, num1, num2, output;
cout<< "enter in two numbers ";
cin>> num1>> num2 ;
cout << "select an operator\n";
cout << "a=addition\n";
cout << "s=subtraction\n";
cin>>plusminus ;
switch(plusminus) {
default: cout<<"Invalid option selected\n";
case ‘a’: output= num1 + num2;
cout << num1<<”plus”<< num2<< “is” <<output;
break;
case ‘s’: output = num1 - num2;
cout<<num1<<” minus”<< num1<<”is”<< output;
}
return 0;
}
sum=0
number=1
False
END
number <= 20
True
Repetition Structures:
A repetition structure also called iteration or loop allows an action or a
set of instructions to be performed while some condition remains true.
There are 3 types of loop or repetition structures each one is suitable
for a specific type of problems.
Counter–Controlled Repetition:
Problem Statement:
A class of 10 students takes a quiz. The grades (integers in the range 0
to 100) are entered.
Determine the class average.
Input: Output
-number of students: -Class average.
-grade for each student
Processing: How do we get the class average ?
We have to sum the grades for the 10 students and then divide the sum
by the number of students.
So, we need a variable total that will be used to add up all the grades
for the class.
Set total to 0,
1-Read grade_s1
2-Add grade_s1 to total
Read grade_s2
Add grade_s2 to total
Read grade_s3
Add grade_s3 to total
…...
Read grade_s10
Add grade_s10 to total
int main(void) {
int counter, grade, total, average;
/* initialization phase */
total =0;
counter =1;
/*processing phase */
while (counter <= 10) {
cout<<“Enter grade: ” ;
cin>> grade;
total = total+ grade;
counter = counter +1;
}/*end while */
/*termination phase */
average = total /10;
cout<<” Class average is” <<average<<endl;
return 0;
}/*end main */
Pseudocode:
Set total to zero
Set student counter to zero
Read grade value
The while loop has four statements and they must be enclosed
between braces.
total = total+ grade;
counter = counter+ 1;
cout<< “Enter grade, -1 to end: “;
cin>> grade ;
The line:
average =(float) total /counter;
uses an operator, we call the cast operator
In the case above, the variable total is being “cast” into a float or
real value, so that the result of the division is a float rather than an
integer.
The operation is executed in this order:
1. The value of total is copied into a float representation
2. The division is performed, the result is a float
3. The result is assigned to the variable average, which is of type
float.
Input:
-10 test results
Output:
-Number of passes and failures.
-Recommendation on tuition.
Process:
To process the 10 test results.
if (passes > 8)
cout <<“Raise tuition\n”;
return 0;
}/* end main */
Efficiency pointers:
\* Analysis of examination results *\
#include <iostream>
main() {
\* initialization variables *\
int passes =0, failures = 0, student = 1, result;
while (student <= 10) {
cout << “Enter result (1=pass, 2 =fail):\n”;
cin>> result;
if (result == 1)
passes = passes + 1;
else
failures = failures + 1;
student = student + 1;
}\* end while *\
cout<< “Passed”<< passes <<endl;
cout<<“Failed ” <<<failures <<endl;
if (passes > 8)
cout <<“Raise tuition\n”;
return 0;}\* end main *\
So we have that :
variable= variable operator expression
Can be re-written as:
variable operator= expression
total +=1 (adds 1 to total), total *=2 (multiplies total by 2)
C++ provides the unary + and – so we can define numbers such as:
C++ also provides the unary increment operator ++ and the unary
decrement operator --.
a= 2; b= ++a
Value of a = 3
Value of b = 3
a= 2; c= a++
Value of a = 3
Value of c = 2
-Preincrement and postincrement forms have the
same effect, when incrementing or decrementing a variable in a
statement by itself.
a++ or ++a are equivalent
The ++ and -- operators can only be used with simple variables, so
++(x+1) is an error.
2. Sentinel-controlled repetition:
a. The precise number of iterations is not known in advance.
b. The sentinel value indicates “end of data”
c. Sentinel value must be distinct from regular, valid data.
Counter-controlled Repetition:
int main(void)
{
int counter =1;
while (counter <= 10) {
cout << counter;
++counter;
}
cout<<endl;
return 0;
}
cout<<”\n”;
return 0;
}/*end main */
Sample Program Output
1 2 3 4 5 6 7 8 9 10
for( counter = 1;
As the variable counter has just been initialized to 1, this condition is TRUE and so
the program statement
cout<< counter ;
is executed, which prints the value of counter to the screen, followed by a space
character.
++counter);
counter <= 10;evaluates as FALSE (0), and the for loop terminates,
and program control passes to the statement
cout<<endl; which prints a newline,
The program then terminates, as there are no more statements left to execute.
where:
1. expression1 initializes the loop’s control variable,
2. expression2 is the loop continuation condition,
3. and expression3 increments the control variable.
True
counter
<= 10 cout<<... ++counter
False
4. Vary the control variable over the following sequence of values: 99, 88, 77, 66, 55,
….0
Write a program that will sum all the even numbers from 2 to 100 using a for loop
#include <iostream>
using namespace std;
int main(void) {
int sum = 0, number;
for (number = 2; number <= 100; number += 2)
sum+= number;
cout<< “The sum of even numbers from 2 to 100 is ” << sum <<endl;
return 0;
}
while (condition);
do {
statement;
} while (condition);
do-while loop flowchart:
statement
True
Condition
False
#include <iostream>
using namespace std;
int main(void) {
int x;
for (x=1; x<=10; x++) {
if (x==5)
break;
cout<< x;
}//end for
cout << "\nBroke out of loop at “<< x <<endl;
return 0;
}//end main
Program Output:
1 2 3 4
Broke out of loop at x == 5
• In while and do-while loop, the loop continuation test is evaluated after the
continue is executed.
#include<stdio.h>
int main(void) {
int x;
for (x=1; x<=10; x++) {
if (x==5)
continue;
cout<< x;
}
cout<<”\n Used continue to skip printing the value 5"<<endl;
return 0;
}//end main
Program Output:
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
Relational and Logical Operators:
The term relational, in relational operator refers to the relationships that values
can have with one another for example ==, <=, !=, etc..
These operators are used to test a single condition.
In the term logical operator, logical refers to the ways these relationships can be
connected.
We can use these operators to form more complex conditions.
Operator Action
&& AND
|| OR
! NOT
p q p&&q p||q !p
0 0 0 0 1
0 nonzero 0 1 1
nonzero nonzero 1 1 0
nonzero 0 0 1 0
Precedence:
Both the relational and logical operators are lower in precedence than the
arithmetic operators.
The table below shows the relative precedence of the relational and logical
operators:
Highest:
These are caught by the compiler and happen when the programmer does
not follow the structure of a given construct. For example:
The program goes off and you loose the control: Infinite loops
The program performs an illegal operation: like Dividing by zero
The program gives unexpected results.
Putting a ; immediately after the if statement or the while, or for loops
This code sets half to 0 not 0.5! Why? Because 1 and 2 are integer
constants.
If both operands are integer variables and real division is desired, cast one of
the variables to double (or float).