0% found this document useful (0 votes)
16 views

Computer Programming C++ Chapter Two

You will learn the basics of c++

Uploaded by

Cabdilaahi Cali
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Computer Programming C++ Chapter Two

You will learn the basics of c++

Uploaded by

Cabdilaahi Cali
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Haramaya University, Institute of Technology

School of Electrical and Computer Engineering

Computer Programming

Chapter III

Control Structures

June 8, 2024 Programming


Chapter Objectives
2

 Discuss what decision and control structures are and why they are important

 Use conditional statements to control program flow

 Implement various types of loops for repetitive lines of code

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
Introduction
3

 Usually, statements in a program are executed one after the


other
That is
 In which they are written or

 In order of appearance in the program

 This is called sequential execution

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
Introduction (cont’d)
4

Example
Develop an algorithm, draw the flow chart, write a pseudo code and a C++ code to
add two numbers (integers)
I. Algorithm
Begin Calculation (the Program)
1. Input a Value for the 1st Variable
2. Input a Value for the 2nd Variable
3. Add the two values
4. Output the result
End Calculation

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
Introduction (cont’d)
5
II. Flow Chart III.Pseudo Code
start

Input a Begin adder


Input a
Input b Input b
c a
Add a and b and
store in c
+b
Print c
Output c End adder
end
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
Introduction (cont’d)
6 IV. C++ code
// a program to add two numbers
#include<iostream> // preprocessor directives
using namespace std; This construct is
int main(){ Sequential Execution
(The program
int a, b, c; statements execute
cout<<"Enter the first number : "; one after another)
cin>>a;
cout<<"Enter the second number : ";
cin>>b;
c = a + b;
cout<<" The Result is "<<c<<"\n";
return 0;
}
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
Introduction (Cont’d)
7

 Not many programs execute all their statements in strict order from
beginning to end.
 Most programs (like many humans) decide what to do in response to
changing circumstances.
 The flow of control jumps from one part of the program to another,
depending on decision to make in the program.
 Program statements that cause such jumps are called control
statements
 There are two major categories: loops and decisions.
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
Control Structures
8

 There are cases where we want to change sequential execution


 We have various C++ constructs (Control Structures) that enable the
programmer to change sequential execution
 These are
1. Conditional Structures (if and else)

2. Repetitive Structures or loops (while, do-while and for)

3. Divergence of Control(break, continue, exit and goto)

4. Selective structure (switch)


Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
1.Conditional Structures (if and else)
9

 A selection (condition) structure is used to choose among


alternative course of action
 For example
If student scores greater than or equal to 50 print passed else print failed
 The general form of the if-else structure is
No
if(condition) semicolon
Statement1; // group of statements  If condition is true,
 statement1 is executed
else
Statement2 ;// here also we can have  If condition is false,
// group of statements  statement2 is executed

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
1.Conditional Structures (if and else)…
10

 If structure is a single-entry/single-exit structure


Score
false >= 50 true
Score true Print Print Print
>= 50 passed failed passed
false

if (score >= 50)


cout<<"Passed the exam ";
if(score >= 50) else
cout<<"Passed the exam "; cout<<"failed the exam ";
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
1.Conditional Structures (if and else)…
11
 The if + else structure can also be concatenated
if (score >= 80)
cout<<"Excellent! Your Grade is A";  Note
elseif (score >= 70)
cout<<"Your Grade is B";
 If more than one instruction
elseif (score >= 60) (statement) is to be executed under a
cout<< "Your Grade is C";
condition we group them using curly
elseif (score >= 50) Compoun
cout<< "Your Grade is D"; d brace ({ })
else Statement
s
 These statements are called
{
cout<< "Your Grade is F ";  compound statements or
cout<< "You have to repeat the
course ";  block of statements
} University, HiT, School of Electrical and Computer
Haramaya
Saturday, June 8, 2024
Engineering
Examples
12
//1. demonstrates if with multiline body // 2. demonstrates if...else statement
// compound statement #include <iostream>
#include <iostream> using namespace std;
using namespace std; int main()
int main() {
{ int x;
int x; cout << “\n Enter a number: “;
cout << “Enter a number: “; cin >> x;
cin >> x; if( x > 0 )
if( x > 100 ) { cout << “You entered positive ineger \n”;
cout << “The number “ << x; else
cout << “ is greater than 100 \n”; cout << “You entered 0 or negative itneger \
} n”;
return 0; return 0;
} }
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
Exercises 1
13
1. Write a program to read three integer numbers and print the largest one among these numbers
Input: three integers
Output: the largest of the three
2. Body Mass Index Calculator (BMI) calculator formulas for calculating BMI is:
BMI = WeightInKg / HeightInMeters2
 Create a BMI calculator application that reads the user’s weight and height then calculates and
displays the user’s body mass index.
 Input: Weight In Kg and Height In Meters
 Output:
• Print “Underweight” if the BMI result is less than 18.5
• Print “Normal” if the BMI result is between 18.5 and 24.9
• Print “Overweight” if the BMI result is between 25 and 29.9
• Print “Obese” if the BMI result is 30 or greater
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
Exercises 1…
14

3. A shop will give discount of 10% if the cost of purchased quantity is more than 1000
birr
 Ask user for quantity
 Suppose, one unit will cost 100 (the price)

 Calculate the total cost


 Judge and print total cost for user
 Note:
 If price > 1000 then reduce 10% of the amount
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
Exercises 1…
15

4. A student will not be allowed to sit in exam if his/her attendance is


less than 80%. Write a program that

 Take following input from user


 Number of classes held
 Number of classes attended
 And print
 percentage class attended
 whether student is allowed to sit in exam or not

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
Exercises 1…
16

5. Write a program that solves a quadratic equation in the form of


ax2 + bx + c = 0.
 The program takes a, b, and c from the user and may calculates

 R1 and R2 using the following formula

 R1 = (-b + sqrt(b2 - 4ac))/2a and


 R2 = (-b - sqrt(b2 - 4ac))/2a
 The program will prompts the user to enter values for a, b, and c and displays the

result based on the discriminant


 If the discriminant is positive, display the two roots
 If the discriminant is 0, display the one root
 Else, display “The equation has no real roots”
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops
17

 A repetitive structure allows the program to specify that an action is to be


repeated while some condition remains true
Example
 While there are more items on my shopping list purchase next item
and cross it off my list

 Describes the repetition that occurs during shopping trip

 The condition “there are more items on my shopping list” may be


true or false
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops (cont’d)
18

I. The while structure (loop) // example

The general form of while loop is #include<iostream>


using namespace std;
while(expression) No int main()
semi {
statement; colon int n;
cout<<"Enter Starting Number: ";
cin>>n;
while(n > 0)
n-- {
cout<<n<<" , ";
n--;
}
true cout<<"Fire. \n";
n>0 Print n }

Output if n = 10
false 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Fire.
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops (cont’d)
19

II. The do-while structure (loop)


The same functionality as the while loop except that the condition in the do- while loop
is evaluated after the execution of the statements instead of before the statement in
the while loop
The general form of do-while loop is
do
{
statement; Observe the
semicolon here!
}while(expression);
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops (cont’d)
20

// example
#include<iostream>
using namespace std;
int main()
{
Print n int n;
cout<<"Enter Starting Number: ";
cin>>n;
n-- do
{
cout<<n<<" , ";
n--;
true }
n>0 while(n > 0);
cout<<"Fire. \n";
return 0;
false }

Output if n = 10
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Fire.
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops (cont’d)
21 // example
#include<iostream> Enter a Number (0 to end): 123
using namespace std; You entered 123
int main() Enter a Number (0 to end): 90
{ You entered 90
unsigned int n; Enter a Number (0 to end): 12
do You entered 12
Enter a Number (0 to end): 0
{
You entered 0
cout<<"Enter a Number (0 to end): "; Loop Terminated!
cin>>n;
cout<<"you entered <<n<<" \n ";

}
while(n != 0);
cout<<"Loop Terminated!";
return 0;
}
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops (cont’d)
22

III. The for structure (loop)


The general form of for loop is

for(initialization; condition; increment)


Statements;

se
No lon
m ic o
 It repeats the statement(s) while condition remain true

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops (cont’d)
23

 The for loop (how it works)


 Initialization will be executed first
 Only once

 Condition is checked

 Statement(s) is executed

 Finally increment is executed

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops (cont’d)
24

for loop general flowchart


Initialization

Increment

Condition true
Body of loop
?

false

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops (cont’d)
25

// example
#include<iostream>
using namespace std;

n
io

t
on

en
The fields in the for
at

iti

em
iz

nd
al

cr
loop are optional
iti

co

in
int main()
in

{ (they can be omitted)


for (int n = 10; n > 0; n--)
cout<<n<<" , ";
but the semi colon
cout<<"Fire!"; among them can not
return 0; be omitted
}

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Fire.
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops (cont’d)
26

// example
#include<iostream>
using namespace std; Notice the omitted
int main()
{ fields in the for loop
int i = 0;
for (;;)
but the semi colon
{ among them are not
cout<<i<<" , ";
i++;
if(i == 10)
{
cout<<"Fire!";
break;
}
}
return 0;
}

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Fire.
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
2. Repetitive Structures or Loops (cont’d)
27

 Optionally using comma operator (,) we can specify more than one instruction in
any fields
// example
#include<iostream>
using namespace std;
int main()
{
for (int n = 0, i = 20; n != i; n++, i--)
cout<<n<<" , "<<i<<" , ";
cout<<"\b";
return 0;
}
0, 20, 1, 19, 2, 18, 3, 17, 4, 16, 5, 15, 6, 14, 7, 13, 8, 12, 9, 11
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
3. Divergence of Control
28

 break

 continue

 goto and

 exit

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
The break Instruction
29

// example
#include<iostream>
using namespace std;
 Using break int main()
{
for (int n = 10; n > 0; n--)
{
 We can leave a loop cout<<n<<" , ";
if (n==3)
 even if the condition for it end {
is not reached yet cout<<"Countdown Aborted";
break;
}
}
return 0;
}

10, 9, 8, 7, 6, 5, 4, 3, Countdown Aborted


Haramaya University, HiT, School of Electrical and Computer
Engineering Saturday, June 8, 2024
The continue Instruction
30

// example
#include<iostream>
 The continue instruction using namespace std;
int main()
{
for (int n = 10; n > 0; n--)
 Causes the program to skip {
to the rest of the loop in the
if (n==5)
present iteration continue;
cout<<n<<" , ";
}
cout<<"Fire! ";
return 0;
}

10, 9, 8, 7, 6, 4, 3, 2, 1, Fire!
Haramaya University, HiT, School of Electrical and Computer
Engineering Saturday, June 8, 2024
The goto Instruction
31

// example
 goto allows
#include<iostream>
 to make absolute jump to another location using namespace std;
(point) in the program int main()
 The destination is identified by a label, {

which is then used as an argument for int n = 10;


loop:
the instruction cout<<n<<" , ";
 A label is made of a valid C++ n--;

identifier followed by colon(:) if (n > 0)


goto loop;
cout<<"Fire. \n";
}

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Fire!
Haramaya University, HiT, School of Electrical and Computer
Engineering Saturday, June 8, 2024
The exit function
32

// example
 The purpose of exit to terminate the
#include<iostream>
running program with a specified using namespace std;
code int main()
{
for(int n = 10; n > 0; n--)
 An exit code of 0 means the program {
terminates normally and any other if (n == 5)
code means that an error has occurred exit(0);
cout<<n<<" , ";
(happened)
}
cout<<"Fire.;
}

10, 9, 8, 7, 6
Haramaya University, HiT, School of Electrical and Computer
Engineering Saturday, June 8, 2024
4. Selective Structure (switch)
33

 There are situation when a program must take one of several actions
depending on the value of some variable or expression
 The switch statement provides
 a convenient alternative to the if when dealing with a multi-way branch

 Such situation arises when a program is processing


 command, events, menu choices etc …

 Its objective is to check several possible constant value for an


Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
expression
Engineering
Selective Structure (switch)…
34

 The general form of switch instruction


is
switch(expression)
{
case valueA:
StatementA1; // take action A
StatementA2;
break;
case valueB: // take action B
StatementB1;
StatementB2;
break;
default :
DefaultStatement;// take default action
break;
Haramaya}University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
Selective Structure (switch)…
35

 Where
 valueA, valueB etc are some integer or character constants
 The switch evaluates expression
 And then jumps to “case” labeled by the corresponding constant value or
 The default “case” if no match has been found
 The break statement is used to break out of the switch

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
Selective Structure (switch)…
36 Example
//a program that adds, subtracts, cin>> op;
//multiplies and divides two numbers switch(op)
#include<iostream> {
using namespace std; case ‘+’:
int main() cout<<a<<"+"<<b<<"="<<a+b; break;
{ case ‘-’:
double a, b; char op; cout<<a<<"-"<<b<<"="<<a-b; break;
cout<<" Enter the first Number "; case ‘*’:
cin>> a; cout<<a<<"*"<<b<<"="<<a*b; break;
cout<<" Enter the second Number "; case ‘/’:
cin>> b; cout<<a<<"/"<<b<<"="<<a/b; break;
cout<<" Enter the operation \n" default :
<<“ + for addition \n" cout<<"wrong operator !\nTry Again";
<<“ - for subtraction \n" }
<<“ * for multiplication \n" return 0;
Haramaya <<“ / forHiT,
University, division: ";
School of Electrical and Computer }
Engineering Saturday, June 8, 2024
Exercises 2
37

1. Develop a program in C++ that calculates the factorial of a given number. Use for loop to
calculate the factorial, & do – while loop to perform the operation as many times as user want
 Input: n for factorial and ch for repetition
 Output: factorial of n
2. Write a program which takes a number x from the user and displays = 1 + 2 + 3 + … + x
 Input: x
 Output: = 1 + 2 + 3 + … + x
3. e can be approximated by e1 = 1+ by the first n term using Taylor/Maclaurin series expansion.
Write a C++ program to approximate the value of e using n terms
 Input: n (number of terms)

 Output: approximate value of e

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering
Exercises 2…
38

4. Raising a number n to a power p is the same as multiplying n by itself p times.


Write a program that takes n (double) and p (int) from the user, and displays the result
computed (result = np)
Input: n (real number) and p (integer)
Output: result (np)
5. Write a C++ program that prints the following patterns (Use nested loops)
Input: n (integer)
Output: for n = 5
a. 1 2 3 4 5 b. 1 c. 1 d. 1
2 4 6 8 10 1 2 2 2 2 3
3 6 9 12 15 1 2 3 3 3 3 4 5 6
4 8 12 16 20 1 2 3 4 4 4 4 4 7 8 9 10
5 10 15 20 25 1 2 3 4 5 5 5 5 5 5 11 12 13 14 15
Haramaya University, HiT, School of Electrical and Computer
Saturday, June 8, 2024
Engineering
Exercises 2…
39
6. Design an algorithm and write a program in C++ that converts dates from the Ethiopian calendar to the
Gregorian calendar.
 Your program should take input in the form of an Ethiopian date (day, month, and year) and output

the corresponding Gregorian date.


 Consider the differences between the Ethiopian and Gregorian calendars, such as
 the number of days in a year, leap years, and the starting point of the calendars
 Implement any necessary calculations or adjustments to ensure accurate conversion.
 Test your program with various Ethiopian dates to verify its correctness and robustness
 Provide explanations or comments in your code to clarify the conversion process and any
assumptions made
 Example:
 ethiopian_day = 11, ethiopian_month = 9, ethiopian_year = 2010
 The Gregorian calendar equivalent is : 19, 05, 2018

Haramaya University, HiT, School of Electrical and Computer


Saturday, June 8, 2024
Engineering

You might also like