0% found this document useful (0 votes)
5 views53 pages

Control Structures in C++

The document provides an overview of control structures in C programming, detailing their importance in determining the execution order of tasks. It categorizes control structures into sequential, selection, and iteration, and elaborates on selection structures including if, if-else, and switch-case statements with examples. Additionally, it discusses nested if statements, dangling else issues, and provides pseudocode and C code for various programming scenarios.

Uploaded by

marvel05ashinze
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)
5 views53 pages

Control Structures in C++

The document provides an overview of control structures in C programming, detailing their importance in determining the execution order of tasks. It categorizes control structures into sequential, selection, and iteration, and elaborates on selection structures including if, if-else, and switch-case statements with examples. Additionally, it discusses nested if statements, dangling else issues, and provides pseudocode and C code for various programming scenarios.

Uploaded by

marvel05ashinze
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/ 53

CSC 211: COMPUTER PROGRAMMING I

CONTROL STRUCTURES
 Control structure statements specify the order in which
tasks are executed in a programming language

 Control Statements in C are used to execute/transfer the


control from one part of the program to another depending
on a condition.

 The control structure mechanisms provided by C allow for


the production of concise, logically structured programs
CONTROL STRUCTURES contd
 There are three types of control structures:
 Sequential
 Selection/Decision/ Conditional
 Iteration(Repetition or Loop)
Sequence Structures
 This involves execution of simple steps that are in order,
that is no loop or decision is involved.
 Thus in sequence structure one step is executed after
another.
Examples
 Write a C++ program to calculate the monthly salary of
a worker whose salary is calculated hourly based on
the number of hours worked.
Selection Structure
 Selection structure is basically for decision making.
 The following statements are selection (decision/
conditional) statements in C++ programming language:
 If statement
 If-else statement
 If else-if ladder
 Nested if
 Switch case
If Statement
 The if statement is used to check some given condition and
perform some operations depending upon the correctness
of that condition.
if(expression){
//code to be executed
}

 How if statement works?


 The if statement evaluates the test expression inside the
parenthesis ().
 If the test expression is evaluated to true, statements inside
the body of if are executed.
 If the test expression is evaluated to false, statements inside
the body of if are not executed.
Selection Structure (IF … THEN)
 Write a pseudo code to only admit student whose age
is up to 16 years.
 Input data
 Student age
 Output data
 Offer admission letter
 Processing requirement
 Compare if student age>=16 years
 Write the pseudo code and the code in C
Pseudocode:
 Step1: start
 Step2: Input student age
 Step3: IF student age is greater than or equal to 16

THEN
 print “Offer Admission Letter”
 ENDIF
 Step4: Stop
 Code in C++:

#include<iostream>
int main()
{
int student_age;
cout<<"Enter the age if student: ";
cin>> student_age;
if (student_age >= 16)
{
cout<<“Offer Admission Letter”;
}
return 0;
}
Selection Structure (IF … THEN)
 Write a pseudo code to to check if a number is an even
number
 Input data
 Number
 Output data
 Number is even
 Processing requirement
 Number = Number%2== 0
 Write the pseudo code and the code in C
Pseudocode:
 Step1: Start
 Step2: Input number
 Step3: IF number modulus 2 is equal to 0

THEN
 print “Number is an even number”
 ENDIF
 Step4: Stop
 Code:
#include<iostream>
int main()
{
int number;

cout<<"Enter a number:";
cin>>number;

if(number%2==0)
{
cout<<number << “is an even number";
}
return 0;
}
If….else Statement
 The if-else statement is used to perform two operations for a single
condition. The if-else statement is an extension to the if statement using
which, we can perform two different operations, i.e., one is for the
correctness of that condition, and the other is for the incorrectness of
the condition.
if(expression){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}
 How if...else statement works?
If the test expression is evaluated to true,
 statements inside the body of if are executed.
 statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,
 statements inside the body of else are executed
 statements inside the body of if are skipped from execution.
Selection Structure (IF … ELSE)
 Write a C program that prints “out of stock” if
quantity of goods at hand does not meet the order but
if it does calculate the new quantity and print it.
 Write a C program to check if a person is eligible to
vote or note.
Understanding and analysis of the problem (Example 1)
 Input data
 Ordered quantity
 Inventory stock
 Output data
 Out of order
 New quantity
 Processing requirement
 New quantity= inventory-order quantity
 Pseudocode:
 Step1: start
 Step2: Input inventory stock
 Step3: Input ordered quantity
 Step4: IF ordered quantity is greater than inventory stock THEN
 print “out of stock”
 ELSE
 calculate new quantity=inventory-ordered quantity
 print new quantity
 ENDIF
 Step5: Stop
 Write the code in C
 Code:
#include<iostream>
int main()
{
int invent_stk, order_qty, new_qty;
cout<<"Enter the stock in inventory: ";
cin>>invent_stk;
cout<<"Enter the quantity ordered: ";
cin>>0rder_qty;
if (order_qty > invent_stk)
{
cout<<“Out of Stock”;
}
else
{
new_qty = invent_stk – order_qty;
cout<<“The new quantity in stock is ” << new_qty;
}
return 0;
}
Understanding and analysis of the problem (Example 2
 Input data
 Student age
 Output data
 Offer admission letter
 Offer diploma application
 Processing requirement
 Compare if student age>=16 years
 Write the pseudo code and the code in C
Pseudocode:
 Step1: start
 Step2: Input student age
 Step3: IF student age is greater than or equal to 16 THEN
 print “Offer Admission Letter”
 ELSE
 print “Offer Diploma Application”
 ENDIF
 Step4: Stop
 Code:
#include<iostream>
int main()
{
int student_age;
cout<<"Enter the age if student: ";
cin>>student_age;
if (student_age >= 16)
{
cout<<“Offer Admission Letter”;
}
else
{
cout<<“Offer Diploma Application”;
}
return 0;
}
Classwork
 Write a psuedocode and code in C to check if a
number is even or odd using if…..else statement
 Write a psuedocode and code in C to check if a person
is eligible to vote or not
If….else if Statement
 The if-else-if ladder statement is an extension to the if-else statement. It
is used in the scenario where there are multiple cases to be performed
for different conditions.
if(condition1){
//code to be executed if condition1 is true
}
else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Selection Structure (IF … ELSE IF)
 Write a pseudo-code and code in C that checks
whether a number enter is 10, 50 or 100.
 Write a pseudo-code and code in C that calculates the
grades of students according to the following
specifications:
 A= 70 - 100
 B = 60 - 69
 C= 50 - 59
 D = 45 - 49
 E = 40 - 44
 F= 0 - 39
 Psuedocode for Number 1:
 Step1: Start
 Step 2: Input a number
 Step 3: compare IF the number is equal to 10 THEN
print “Number enter is equal to 10”
ELSE
IF the number is equal to 50 THEN
print “Number enter is equal to 50”
ELSE
IF the number is equal to 100 THEN
print “Number enter is equal to 100”
ELSE
print “Number entered does not match 10, 50 or 100”
ENDIF
ENDIF
ENDIF
Step 4: Stop
#include<iostream>
int main(){
int number;
cout<<"enter a number:";
cin>>number;
if(number==10){
cout<<"number is equals to 10";
}
else if(number==50){
cout<<"number is equal to 50";
}
else if(number==100){
cout<<"number is equal to 100";
}
else{
cout<<"number is not equal to 10, 50 or 100";
}
return 0;
}
 Psuedocode for Number 2:
 Step1: Start
 Step 2: Input a score
 Step 3: compare IF the score is greater than 85 and less than or equal to
100 THEN
print “Congrats!!! You earned Grade A”
ELSE
IF the score is greater than 60 and less than or equal to 85 THEN
print “You earned Grade B+”
ELSE
IF the score is greater than 40 and less than or equal to 60 THEN
print “You earned Grade B”
ELSE
IF the score is greater than 30 and less than or equal to 40 THEN
print “You earned Grade C”
ELSE
print “Sorry!!! You failed…. Please try again”
ENDIF
ENDIF
ENDIF
ENDIF
Step 4: Stop
#include <iostream>
int main()
{
int marks;
printf("Enter your marks?");
scanf("%d",&marks);
if(marks > 85 && marks <= 100)
{
cout<<"Congrats ! you scored grade A ...";
}
else if (marks > 60 && marks <= 85)
{
cout<<"You scored grade B + ...";
}
else if (marks > 40 && marks <= 60)
{
cout<<"You scored grade B ...";
}
else if (marks > 30 && marks <= 40)
{
cout<<"You scored grade C ...";
}
else
{
Classwork
 Write a pseudo-code and code in C that finds the
largest of three numbers using if…. else if statement.
Selection Structure (NESTED IF)
 This is a multiple selection structure
 NESTED IF statement: this is when there is an IF … ELSE
statement inside an IF statement or an IF THEN statement.
 Nested if statements are used if there is a sub condition to
be tested.
 Example: C program to check if a number is less than
100 or not. If it is less than 100 then check if it is odd or
even.
 Pseudocode:
 Step 1: Start
 Step 2: input a number
 Step 3: compare IF the number is less than 100
display the number is less than 100
IF number % 2 == 0
display “the number is an even number”
ELSE
display “the number is an even number”
ENDIF
ELSE
display “the number greater than or equal to 100”
ENDIF
Step 4: Stop
Selection Structure (Nested IF)
 Step 1: Start
 Step 2: input a number
 Step 3: compare IF the number is less than 100
display the number is less than 100
IF number % 2 == 0
display “the number is an even number”
ELSE
display “the number is an even number”
ENDIF
ELSE
display “the number greater than or equal to 100”
ENDIF
Step 4: Stop
 Code:
#include<iostream>
int main()
{
int num;
cout<<"Enter a number:";
cin>>num;
if(num<100)
{
cout<<"%d is less than 100n",num;
if(n%2 == 0)
cout<<num << “is even");
else
cout<<num << " is odd");
}
else
cout<<num<< " is equal to or greater than 100");
return 0;
}
Selection Structure (Nested IF)
 Example
 Write a pseudo code to greet a man welcome if his
language is one of the following:
 Yoruba
 Hausa
 Igbo
Selection Structure (Nested IF)
 Step1: start
 Step2: choose option
 1. Yoruba
 2. Hausa
 3. Igbo
 Step3: input an option
 Step4: compare IF the country = Nigeria
display choose an option
IF option = 1
greeting is “Kaabo”
ELSE
IF option = 2
greeting is “Saanu”
ELSE
greeting is “Nnewo”
ENDIF
ENDIF
Write the code in C
Dangling else
 The dangling else is a problem in programming of parser generators in which
an optional else clause in an if–then(–else) statement results in nested
conditionals being ambiguous.
 A construct in a programming language is ambiguity, if the construct can be
interpreted in more than 1 way
 Suppose we want to write a conditional statement to determine the
shipping rate to different state in Nigeria:

 To ship a 500kg packet within Lagos, the cost is N5,000 , except for Badagry
 To ship to Badagry (which is very remote), the cost N7,000
 To ship a 500kg packet outside Lagos, the cost is N10,000

double shippingCharge;

shippingCharge = 5,000; // Assume the cost is N5,000

if ( state is equal to “Lagos") )


if ( location is equal to “BADA" )
shippingCharge = 7,000; // Badagry will cost N7,000
else
shippingCharge = 10,000; // Outside Lagos is N10,000
 There are two ways to read the above program syntactically correctly

double shippingCharge; double shippingCharge;

shippingCharge = 5,000; shippingCharge = 5,000


if ( state is equal to “Lagos") if ( state is equal to “Lagos") )
if ( location is equal to “BADA" ) if ( location is equal to “BADA" )
shippingCharge = 7,000; shippingCharge = 7,000;
else else
shippingCharge = 10,000; shippingCharge = 10,000

 Resolving Dangling else:


 An else keyword always associates with the nearest preceeding if
keyword that does NOT cause a syntax error
 The use of { }
double shippingCharge;

shippingCharge = 5,000; // Assume the cost is N5,000

if ( state is equal to “Lagos")


{
if ( location is equal to “BADA" )
shippingCharge = 7,000; // Badagry will cost N7,000
}
else
shippingCharge = 10,000; // Outside Lagos is N10,000
Selection Structure (Switch Case)
 The switch statement in C is an alternate to if-else-if ladder
statement which allows us to execute multiple operations
for the different possible values of a single variable called
switch variable.
 Here, We can define various statements in the multiple
cases for the different values of a single variable.
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

How does the switch statement work?


 The expression is evaluated once and compared with the values of
each case label.
 If there is a match, the corresponding statements after the matching label are
executed. For example, if the value of the expression is equal to value2,
statements after case value2: are executed until break is encountered.
 If there is no match, the default statements are executed.
Note:
 If we do not use the break statement, all statements after the matching label
are also executed.
 The default clause inside the switch statement is optional.
 Rules for switch statement in C language
 1) The switch expression must be of an integer or character type.
 2) The case value must be an integer or character constant.
 3) The case value can be used only inside the switch statement.
 Let's try to understand it by the examples. We are assuming that there are
following variables.
 int x,y,z;
 char a,b;
 float f;

Valid Switch Invalid Switch Valid Case Invalid Case

switch(x) switch(f) case 3; case 2.5;

switch(x>y) switch(x+2.5) case 'a'; case x;

switch(a+b-2) case 1+2; case x+2;

switch(func(x, case 'x'>'y'; case 1,2,3;


y))
 Functioning of switch case statement
 First, the integer expression specified in the switch statement is
evaluated.
 This value is then matched one by one with the constant values given
in the different cases.
 If a match is found, then all the statements specified in that case are
executed along with the all the cases present after that case including
the default statement.
 No two cases can have similar values.
 If the matched case contains a break statement, then all the cases
present after that will be skipped, and the control comes out of the
switch.
 Otherwise, all the cases following the matched case will be executed.
Example
 Step1: Start
 Step2: declare x and y
 Step3: SWITCH (x>y && x+y>0)
case 1: Display “Hi”
Break;
case 0: Display “Bye”
Break;
default: Display “Hello Bye”
Step4: Stop
 Example:
#include <iostream>
int main()
{
int x = 10, y = 5;
switch(x>y && x+y>0)
{
case 1:
printf("hi");
break;
case 0:
printf("bye");
break;
default:
printf(" Hello bye ");
}

}
#include<iostream>
int main(){
int number=0;
cout<<"enter a number:";
cin>>number;
switch(number){
case 10:
cout<<"number is equals to 10";
break;
case 50:
cout<<"number is equal to 50";
break;
case 100:
cout<<"number is equal to 100";
break;
default:
cout<<"number is not equal to 10, 50 or 100";
}
return 0;
}
Example
 Write a pseudo code that informs new students about
Anchor grading system.
 Input data
 Grade
 Output data
 Student Score
 Processing requirement
Example
 Step1: start
 Step2: Input the grade
 Step3: SWITCH (grade)
case A: Display student score is 80 and above
Break;
case B: Display student score is between 61 and 79
Break;
case C: Display student score is between 50 and 60
Break;
case D: Display student score is between 45 and 49
Break;
case E: Display student score is between 40 and 44
Break;
case F: Display student score is below 40
Break;
default: Input correct grade
Step4: Stop
Classwork
 Write a pseudo code and code in C that create a simple
calculator (+, -, *, /) using switch case statement

You might also like