Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

ARREZA | BARIA | BATAICAN | ESMERO | PARAISO

CONTROL STRUCTURES IN C++


CPE01: FUNDAMENTALS OF COMPUTER AND PROGRAMMING
MODULE 5 | GROUP 5
CPE01 | PARAISO

CONTROL STRUCTURES IN C++

A computer program is not limited to


a linear sequence of instructions.
There are times when it has to make
decisions or repeat codes. C++ has
three different types of control
structures that serve to specify what
has to be done by the program, when
and under which circumstances.
CPE01 | PARAISO

THREE KINDS OF CONTROL STRUCTURES IN C++

The C++ three kinds of control


structures, which also refer to as
control statements:

1. Sequence Statement
2. Selection Statements
3. Repetition Statements
CPE01 | PARAISO
C++ CONDITIONS AND IF STATEMENTS

C++ supports the usual logical conditions C++ has the following conditional
from mathematics: statements:

• Less than: a < b • Use if to specify a block of code to be


• Less than or equal to: a <= b executed, if a specified condition is true

• Greater than: a > b • Use else to specify a block of code to be


executed, if the same condition is false
• Greater than or equal to: a >= b
• Use else if to specify a new condition to
• Equal to: a == b test, if the first condition is false
• Not Equal to: a != b • Use switch to specify many alternative
blocks of code to be executed
CPE01 | PARAISO
1. SEQUENTIAL STRUCTURE

• A sequential control EXAMPLE:


structure is where the n1 = 5 //statement 1
statements are executed
in sequence. n2 = 6 //statement 2
• The sequence structure sum = n1 + n2 //statement 3
directs the computer to
process the program
instructions, one The series of statements above will be
another, in the order executed in order, where statement 1 will
listed in the program. be executed first, then to be followed by
statement 2 and, finally, statement 3.
CPE01 | PARAISO
2. SELECTION STRUCTURE
Selection Structure simply involves a number of conditions or parameters which
decides one out of several written modules. The structures which use these type of
logic are known as Conditional Structures.

Selection Structures can be of


three types:

1. Single Alternative
2. Double Alternative
3. Multiple Alternatives
CPE01 | PARAISO
2. SELECTION STRUCTURE | SINGLE ALTERNATIVE

SINGLE ALTERNATIVE
This structure has the form:

If (condition) then:
[Module A]
[End of If structure]
CPE01 | PARAISO
2. SELECTION STRUCTURE | SINGLE ALTERNATIVE
EXAMPLE 1 EXAMPLE 2

#include <iostream> #include <iostream>


using namespace std; using namespace std;
int main() int main()
{ {
int i = 10; int i = 10;
if (i < 15) { if (i > 15) {
cout << "10 is less than 15 \n"; cout << "10 is greater than 15 \n";
} }
cout << "Ang gwapo mo Vissel"; cout << "Ang gwapo mo Vissel";
} }
CPE01 | PARAISO
2. SELECTION STRUCTURE | DOUBLE ALTERNATIVES

DOUBLE ALTERNATIVE

This structure has the form:

If (Condition), then:
[Module A]
Else:
[Module B]
[End if structure]
CPE01 | PARAISO
2. SELECTION STRUCTURE | DOUBLE ALTERNATIVES
EXAMPLE 1 EXAMPLE 2
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() int main()
{ {
int i = 20; int i = 25;
if (i == 10) if (i > 15)
cout << "i is 10"; cout << "i is greater than 15";
else else
cout << "i is 20\n"; cout << "i is smaller than 15";
cout << "Ang gwapo mo talaga Vissel"; return 0;
return 0; }
}
CPE01 | PARAISO
2. SELECTION STRUCTURE | MULTIPLE ALTERNATIVES
MULTIPLE ALTERNATIVES
This structure has the form:

If (condition A), then:


[Module A]
Else if (condition B), then:
[Module B]
..
..
Else if (condition N), then:
[Module N]
[End If structure]
CPE01 | PARAISO
2. SELECTION STRUCTURE | MULTIPLE ALTERNATIVES
EXAMPLE 1 EXAMPLE 2
#include <iostream> #include <iostream>

using namespace std; using namespace std;

int main() int main()


{ {
int i = 20; int i = 25;
if (i == 10) if (i >= 0 && i <= 10)
cout << "i is 10"; cout << "i is between 0 and 10" << endl;
else if (i == 15)
else if (i >= 11 && i <= 15)
cout << "i is 15";
cout << "i is between 11 and 15" << endl;
else if (i == 20)
else if (i >= 16 && i <= 20)
cout << "i is 20";
cout << "i is between 16 and 20" << endl;
else
else
cout << "i is not present";
cout << "i is greater than 20" << endl;
return 0;
}
}
CPE01 | BATAICAN
2. SELECTION STRUCTURE

The C++ three kinds of control


structures, which also refer to as
control statements:

• The if Statement
• The if-else Statement
• The if-else-if ladder
• The switch-case Statement
CPE01 | BATAICAN
2. SELECTION STRUCTURE | THE IF STATEMENT

The C++ if statement is


the most simple decision
making statement. It is
used to decide whether a
certain statement or
block of statements will
be executed or not based
on a certain type of
condition.
CPE01 | BATAICAN
2. SELECTION STRUCTURE | THE IF STATEMENT
SYNTAX: IF CONDITION WITH COMPOUND STATEMENT

If (condition) The statement may either be a single statement or a compound


statement. If compound statement Is used, it is necessary to
statement; enclose it in a begin and an end brace ({ }). This is the general
EXAMPLE: form of the if condition with a compound statement.

If (number < 0)
cout<<”The number is negative\n”; SYNTAX:
If (condition)
{
The message “The number is negative“ will statement 1;
be displayed if the value of a number is less statement 2;
than zero. This means that the condition is statement 3;
equal to true. statement 4;
}
CPE01 | BATAICAN
2. SELECTION STRUCTURE | THE IF-ELSE STATEMENT

• An if statement may also


optionally contain a
second statement, the
else clause which is to be
executed if the condition
is not met.
• The if-else statement is a
conditional statement that
chooses one out of two
alternative courses of
actions.
CPE01 | BATAICAN
2. SELECTION STRUCTURE | THE IF-ELSE STATEMENT

SYNTAX: EXAMPLE:
if (condition) if (num < 0)
statement 1; cout<<num<<”is a negative number\n”;
else else
statement 2; cout<<num<<”is a positive number\n”;

Statement1 is executed if the condition In the example above, if a number read is


is true, if the condition is false less than 0 then it would print the message
statement2 will be executed. “Number is a negative number”, otherwise
the message would be “Number is a positive
number”.
CPE01 | BATAICAN
2. SELECTION STRUCTURE | THE IF-ELSE STATEMENT

IF-ELSE CONDITIONS WITH COMPOUND STATEMENTS


SYNTAX:
if (condition)
{ If the condition is true, the
statement 1;
statement 2; statement block after the
statement 3; condition will be executed. If the
} condition return a false value,
else
{ the statement block following
statement 1; else will be executed.
statement 2;
statement 3;
}
CPE01 | BATAICAN
2. SELECTION STRUCTURE | THE IF-ELSE-IF LADDER

If we want to make a multi-way


decision based on several
conditions, the most general way
of doing this is by using the else if
variant on the if statement. This
works by cascading several
comparisons. As soon as one of
these gives a true result, the
following statement or block is
executed, and no further
comparisons are performed.
CPE01 | BATAICAN
2. SELECTION STRUCTURE | THE IF-ELSE-IF LADDER
• The conditions are evaluated SYNTAX: EXAMPLE:
from top to bottom. As soon as if (condition) if (result >= 75)
true condition is found, the statement; cout<<”Passed: Grade A\n”;
statement associated with it is else if (condition) else if (result >=60)
executed, and the rest of the statement; cout<<”Passed: Grade B\n”;
ladder is bypassed. else if (condition) else if (result >== 45)
• If none of the conditions are statement; cout<<”Passed: Grade C\n”;
true then the final else will be : else
executed. The final else often : cout<<”Failed\n”;
acts as a default condition; that else
is, if all other conditional tests statement; The above example shows the use of the
fail then the last else statement if-else-if ladder which tells us if the value
is performed. If the final else is currently stored in the variable result is
not present and all other equivalent to a passing mark A, B, C or
conditions are false, then no failed.
action will take place.
CPE01 | BATAICAN
2. SELECTION STRUCTURE | SAMPLE PROBLEMS
EXAMPLE 1 EXAMPLE 2
#include<iostream> #include<iostream>

using namespace std;


using namespace std;
int main ()
int main()
{
{
int grade;
int grade; cout<<"\nEnter your grade: ";
cout << "\nEnter your grade: "; cin>>grade;

cin>>grade; if (grade >= 75)

if(grade>=75) cout<<"Passed\n";

else if (grade >= 70)


cout << "Passed\n" ;
cout<< "Incomplete\n";
else
else
cout << "Failed\n" ;
cout<<"Failed\n";
return 0; return 0;

} }
CPE01 | ARREZA
2. SELECTION STRUCTURE | THE SWITCH-CASE STATEMENT

• Switch is a multi-branch
decision statement in
C++ that tests a list of
integer and character
constants. When a match
is found, a statement
block is executed.
CPE01 | ARREZA
2. SELECTION STRUCTURE | THE SWITCH-CASE STATEMENT

SYNTAX: • The default statement is executed if


switch (variable) no match found is found. The default
{ is optional and, if not present, no
case constant1: statement sequence; action takes place if all matches fail.
break;
case constant2: statement sequence; • When a match is found, the
break; statement associated with that case is
case constant3: statement sequence; executed until the break statement is
break;
default: statement sequence;
reached or, in the case of the default
} (or last case of no default is present),
the end of the switch statement is
encountered.
CPE01 | ARREZA
2. SELECTION STRUCTURE | THE SWITCH-CASE STATEMENT

There are three important things to know about the switch statement:

1. The switch differs from if in that switch can only test for equality,
whereas the if can evaluate a relational or logical expression.
2. No two case constants in the same switch can have identical
values. Of course, a switch statement enclosed by an outer switch
may have case constants that are the same.
3. If character constants are used in the switch, they are automatically
converted to their integer values.
CPE01 | ARREZA
2. SELECTION STRUCTURE | THE SWITCH-CASE STATEMENT
BREAK
• The break statement has two uses,
the first one is to terminate a case in
the switch statement, while the
second one is to terminate a loop
and bypass the normal loop
conditional tests.
• When a break statement is
encountered inside the loop, the
loop is immediately terminated and
the program control resumes at the
next statement following the loop.
CPE01 | ARREZA
2. SELECTION STRUCTURE | THE SWITCH-CASE STATEMENT
EXAMPLE: OUTPUT:
#include<iostream>
using namespace std;
int main()
{
int num;
cout<<"input a number from 1 to 5: ";
cin>>num;
switch (num)
{
case 1:cout<<"ONE";
break;
case 2:cout<<"TWO";
break;
case 3:cout<<"THREE";
break;
case 4:cout<<"FOUR";
break;
case 5:cout<<"FIVE";
break;
default: cout<<"Number is out of range";
}
return 0;
}
CPE01 | ARREZA
2. SELECTION STRUCTURE | THE SWITCH-CASE STATEMENT

SWITCH CASE THAT HAS COMMON switch (ch)


STATEMENTS {
case ‘A’:/*this has a common
These are switch statements that statement*/
have a common statement block case ‘a’:cout<<”APPLE”;
but different case constants. The case ‘B’:
statement will accept small case ‘b’:cout<<”BANANA”;
characters and capital letters but case ‘C’:
has a common statement. case ‘c’:cout<<”CARROT”;
default:cout<<”Not an ABC character”;
}
CPE01 | ARREZA
2. SELECTION STRUCTURE | THE SWITCH-CASE STATEMENT
Duplication of similar actions to several alternatives Duplications are eliminated by arranging cases with
is avoided using the switch statement. similar actions in groups.
EXAMPLE: EXAMPLE:
switch (major_code) switch (major_code)
{ {
case 1:cout<<”Science Student”; case 1:
break; case 3:
case 2:cout<<”Art Student”; case 5:
break; cout<<”Science Student”;
case 3:cout<<”Science Student”; break;
break; case 2:
case 4:cout<<”Art Student”; case 4:
break; cout<<”Art Student”;
case 5:cout<<”Science Student”; }
}
CPE01 | ESMERO
3. REPETITION STRUCTURE

In C++, and all other modern


programming languages, loops
allow a set of instruction to be
performed until a certain
condition is reached. This
condition maybe predefined as
in the for loop, or open-ended
as in the while and do loops.
CPE01 | ESMERO
3. REPETITION STRUCTURE
Every programming language has a construct that can be used to define controlled repetition (or
loops) on a program block. A program block that is executed repeatedly by a repetition
statement is called loop body. The repetition is controlled by a condition (or predicate) that is
associated with the repetition statements:
CPE01 | ESMERO
3. REPETITION STRUCTURE
These are two types of repetition statements:

• A pretest repetition statement • A posttest repetition statement


computes a value for its associate first executes the loop body and
predicate before entering the loop then computes the predicate. If
body, and will execute the loop the predicate is true, the loop body
body as long as the predicate is executes again; otherwise; the
true. Once the predicate repetition terminates.
computes to false, repetition
stops and the program control
pauses to the next statement that
follows the repetition statement
CPE01 | ESMERO
3. REPETITION STRUCTURE

In C++, the three statements for


repetition are:
• The while statement, which is a
pre-test repetition statement.
• The for statement, which is also a
pre-test repetition statement.
• The do-while statement, which is
a post-test repetition statement.
CPE01 | ESMERO
3. REPETITION STRUCTURE | FOR LOOP

The for loop lets us keep performing an


action over and over on our data until a
condition (which we specify) becomes true.

SYNTAX:
for (initialization ; condition ; increment)
/statement
CPE01 | ESMERO
3. REPETITION STRUCTURE | FOR LOOP

EXAMPLE: OUTPUT:
#include <iostream>
using namespace std;

int main()
{

for (int i = 1; i <= 5; i++) {


cout << "Hello World\n";
}

return 0;
}
CPE01 | BARIA
3. REPETITION STRUCTURE | WHILE LOOP

The while loop in C++ is used in


situations where we do not know the
exact number of iterations of loop
beforehand. The loop execution is
terminated on the basis of the test
condition.
SYNTAX:
While ( Expression )
Statement
/* end while */
CPE01 | BARIA
3. REPETITION STRUCTURE | WHILE LOOP

EXAMPLE: OUTPUT:
#include<iostream>
using namespace std;
int main()
{
int number;
number=0;
while (number<3)
{
cout<<"Congratulations\n";
number=number+1;
}
return 0;
}
CPE01 | BARIA
3. REPETITION STRUCTURE | DO-WHILR LOOP

the do-while loop checks its condition


and the bottom of the loop. This
means that a do-while loop will
always execute at least once.

SYNTAX:
do
{
statement;
}
while (condition);
CPE01 | BARIA
3. REPETITION STRUCTURE | DO-WHILR LOOP
do
the most common use of the do-while
{
loop is in a menu-selection routine. cout<<”Choose an operation “;
Because, you will always want a menu- cout<<”[1] Addition \n”;
selection routine to execute at least cout<<”[2] Subtraction \n”;
once, the do-while loop is an obvious cout<<”[3] Multiplication \n”;
cout<<”[4] Division \n”;
choice. By testing for a valid response at cout<<”Enter your choice: “;
the bottom of the loop, you can re- cin>>choice;
prompt the user until a valid response is } while(choice<1 || choice>4);
entered. The following program
fragment shows how to add a do-while After the options have been displayed, the
loop onto the menu for the four basic program will loop until a valid option is
operations program. selected. Loops can also be nested.
CPE01 | BARIA
3. REPETITION STRUCTURE | DO-WHILE LOOP

EXAMPLE 1 OUTPUT:
#include<iostream>
using namespace std;
int main()
{
int num;
do
{
cin>>num;
}
while(num>100);
return 0;
}

This program uses a do-while loop


to read numbers from the
keyboard until one is less than 100
CPE01 | BARIA
3. REPETITION STRUCTURE | IF AND DO-WHILE LOOP SAMPLE

EXAMPLE 2 OUTPUT:
#include <iostream>
using namespace std;
int main()
{
int number=44;
int guess;
cout<<"Guess a number between 1 and 100\n";
do{
cout<<"Enter your guess: ";
cin>>guess;
if (guess > number)
cout<<"Too high\n";
if (guess < number)
cout<<"Too low\n";
} while (guess != number);
cout<<"You win. The answer is "<<number;
return 0;
}
REFERENCES/SOURCES

circuitstoday.com. https://www.circuitstoday.com/control-structures-in-c-and-cpp
cplusplus.com. http://www.cplusplus.com/doc/oldtutorial/control/
Geeks for Geeks. https://www.geeksforgeeks.org/control-structures-in-programminglanguages/
Little Drops. https://www.cpp.thiyagaraaj.com/control-structures
informIT https://www.informit.com/articles/article.aspx?p=1321841&seqNum=2#:~:text=C%2B%2B%20has%20only%20three%20kinds,while).
w 3 s c h o o l s . c o m . https://www.w3schools.com/cpp/cpp_conditions.asp
https://www.cs.fsu.edu/~myers/c++/notes/control1.htm

You might also like