0% found this document useful (0 votes)
2 views44 pages

2017 Chapter Three Computer Programming (ECEg 1052)

The document provides an overview of control structures in C++ programming, categorizing them into sequential, selection, and iteration structures. It details various selection methods such as if statements, if-else statements, and switch statements, as well as loop structures like for, while, and do-while loops. Additionally, it discusses nested loops and jump statements that alter the flow of control within a program.

Uploaded by

sami1998born
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)
2 views44 pages

2017 Chapter Three Computer Programming (ECEg 1052)

The document provides an overview of control structures in C++ programming, categorizing them into sequential, selection, and iteration structures. It details various selection methods such as if statements, if-else statements, and switch statements, as well as loop structures like for, while, and do-while loops. Additionally, it discusses nested loops and jump statements that alter the flow of control within a program.

Uploaded by

sami1998born
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/ 44

Computer Programming -ECEG 1052

1
Email:[email protected]
Computer Programming -ECEG 1052

Introduction
✓ in c++ control structures control the flow of execution of a program.
✓ They allow you to control the order in which statements are executed based on certain conditions or to
repeat a set of statements multiple times.
✓ Control structures are fundamental to implementing logic and decision-making in your programs.
✓ Control structures in C++ can be broadly categorized into three types:
▪ Sequential control structure
▪ Selection control structure
▪ Iteration(reptation) control structure

2
Email:[email protected]
Computer Programming -ECEG 1052

Sequence Structure
Sequential control structures are the most basic form of control flow, where statements are executed in the order
they appear in the program.

#include <iostream> Explanation:


using namespace std;
Statement 1: Initializes a with the value 5.
int main() { Statement 2: Initializes b with the value 10.
int a = 5; // Statement 1
Statement 3: Calculates the sum of a and b and stores it in sum.
int b = 10; // Statement 2
int sum = a + b; // Statement 3 Statement 4: Outputs the value of sum to the console.
cout << "Sum is: " << sum; // Statement 4
Statement 5: Ends the main function.
return 0; // Statement 5
}

3
Email:[email protected]
Computer Programming -ECEG 1052

Selection/Branching/conditional Structure
▪ Selection control structures allow the program to make decisions and execute different
blocks of code based on whether certain conditions are true or false.
▪ There are various ways to do selection in C++.
▪ if statement
▪ if-else statement
▪ if-else-if ladder
▪ nested if statement
▪ switch statements

4
Email:[email protected]
Computer Programming -ECEG 1052

if statement
Example:-Write a c++ code to check if a
▪ The if statement is the most basic form of selection given number is equal to zero.
control. It executes a block of code if a specified
condition is true. #include <iostream>
using namespace std;
Flowchart
int main()
if (condition) { {
// Code to execute if condition is true int num;
} cout<<"please enter any number to compare with
zero";
Example: cin>>num;
int score = 85; if(num==0)
if (score >= 60) { cout<<"the number is equal to zero“<<endl;
cout << "Pass" << endl; return 0;
} }
If score is greater than or equal to 60, it prints "Pass".

5
Email:[email protected]
Computer Programming -ECEG 1052

if …else statement
The if-else statement allows you to execute one block of
code if the condition is true and another block if the
condition is false. Flowchart

Syntax
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}
6
Email:[email protected]
Computer Programming -ECEG 1052

if …else statement
int score = 55;
if (score >= 60)
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}

Output:
Pass
7
Email:[email protected]
Computer Programming -ECEG 1052

Class Work
• What is the printout of the code in following if number is 30? What if number is 35?

8
Email:[email protected]
Computer Programming -ECEG 1052

Else-if Ladder
The else-if ladder allows you to check multiple conditions in sequence. If the first condition is
false, it checks the next one, and so on.
int score = 75;
if (condition1)
Syntax: if (score >= 90)
{
{
// Code to execute if condition1 is true
cout << "Grade A" << endl;
}
}
else if (condition2)
else if (score >= 80)
{
{
// Code to execute if condition2 is true
cout << "Grade B" << endl;
}
}
else if (condition3)
else if (score >= 70) {
{
cout << "Grade C" << endl;
// Code to execute if condition3 is true
} else {
}
cout << "Grade D" << endl;
else
}
{ // Code to execute if all conditions are false }
9
Email:[email protected]
Computer Programming -ECEG 1052

Example: Compare a number with Zero


// to demonstrate if---else ladder
#include <iostream>
using namespace std;
int main(){
int num;
cout<<"please enter any number to compare with zero"<<endl;
cin>>num;

if(num>0){
cout<<"the number is greater than zero"<<endl;
}
else if(num<0){
cout<<"the number is less than zero"<<endl;
}
else {
cout<<"the number is equal to zero"<<endl;
}
return 0;
}
10
Email:[email protected]
Computer Programming -ECEG 1052

Nested if statement if (condition1)


{
• A nested if statement is an if statement that // Code to execute if condition1 is true
is placed inside another if or else if (condition2)
statement. {
• This allows for more complex decision- // Code to execute if both condition1 and condition2 are true
making by checking multiple conditions }
in a hierarchical manner. else {
• When you have a situation where one // Code to execute if condition1 is true but condition2 is false
condition depends on another, nested if }
}
statements are useful.
else
{
• Syntax of Nested if Statements // Code to execute if condition1 is false
• The general syntax of a nested if }
statement is as follows:

11
Email:[email protected]
Computer Programming -ECEG 1052

#include <iostream>
using namespace std;
int main() {
int age,income;
cout<<"Enter age:";
cin>>age;
cout<<"\nEnter income";
cin>>income;
if (age >= 18) {
cout << "You are eligible to vote." << endl;
if (income > 20000) {
cout << "You are also eligible for a credit card." << endl;
} else {
cout << "You do not meet the income requirement for a credit card." << endl;
}
} else {
cout << "You are not eligible to vote." << endl;
}
return 0;
} 12
Email:[email protected]
Computer Programming -ECEG 1052

switch Statement
The switch statement is used to execute different blocks of code based on the value of a variable.
It is particularly useful when you have multiple conditions based on the same variable.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
// You can have as many cases as needed
default:
// Code to execute if expression doesn't match any case
}

13
Email:[email protected]
Computer Programming -ECEG 1052

Example

char grade = 'B';


switch (grade) {
case 'A':
cout << "Excellent" << endl;
break;
case 'B':
cout << "Good" << endl;
break;
case 'C':
cout << "Fair" << endl;
break;
default:
cout << "Invalid grade" << endl;
}

14
Email:[email protected]
Computer Programming -ECEG 1052

Class work
Write a C++ program that prompts the user to enter two numbers and select an operation
(+, -, *, or /). The program should then perform the chosen operation and display the result.
If division by zero is attempted, display an error message. If an invalid operator is entered,
print "Invalid operation". Use a switch statement to implement the operations and handle
edge cases.

15
Email:[email protected]
Computer Programming -ECEG 1052

Conditional (Ternary) Operator


The conditional operator is a shorthand for the if-else statement. It is a ternary operator because it takes three
operands.

Syntax:

condition ? expression1 : expression2;


➢ You might want to assign a variable a value that is restricted by certain conditions.

int a = 10;
int b = (a >= 10) ? 100 : 200;
cout << "b is: " << b << endl;

16
Email:[email protected]
Computer Programming -ECEG 1052

Loop (Repetitions/Iteration) Structure in C++


Loops are essential control structures in programming that allow a block of code to be executed
repeatedly based on a given condition.
They are used to perform repetitive tasks efficiently, such as iterating over arrays, processing
data, or performing calculations until a certain condition is met.
In C++, there are three primary types of loops:
1.for Loop
2.while Loop
3.do-while Loop

17
Email:[email protected]
Computer Programming -ECEG 1052

for Loop
Previous statement in the program
The for loop is used when you know the exact number of
iterations you want to perform. It consists of three parts: Initialization
initialization, condition, and increment/decrement.
False
Condition
Syntax:
for (initialization; condition; increment/decrement) { True
// Code to execute in each iteration Body
}
Update

Next statement in the program 18


Email:[email protected]
Computer Programming -ECEG 1052

Example Explanation:

Initialization (int i = 0): Sets the starting value of the loop counter i to 0
#include <iostream> Condition (i < 5): Checks if i is less than 5. If true, the loop continues.
using namespace std; Increment (i++): Increases the value of i by 1 after each iteration.
Code Block: Prints the current iteration number.
int main() { output
for (int i = 0; i < 5; i++) {
cout << "Iteration " << i << endl; Iteration 0
} Iteration 1
Iteration 2
return 0; Iteration 3
} Iteration 4

19
Email:[email protected]
Computer Programming -ECEG 1052

Example 2
#include <iostream> Output
using namespace std; 9
8
int main() 7
{ 6
5
for(int i=9;i>=0;i--){
4
cout<<i<<endl; 3
} 2
1
return 0; 0
}

20
Email:[email protected]
Computer Programming -ECEG 1052

Nested and infinite for loop


▪ Nested and infinite for loop is possible
▪ An infinite loop continues executing endlessly unless explicitly stopped using break or
external signals.
▪ Structure
for(int i=0; i<10;i++){
for(int j=5;j>0;j++){ // j is always non-negative, loop never ends
cout<<i+j<<endl;}}
• Infinite for Loop
for( ; ;) // Runs forever

21
Email:[email protected]
Computer Programming -ECEG 1052

while Loop
Example
The while loop is used when the number of iterations is
not known and depends on a condition. The loop #include <iostream>
continues as long as the condition is true. using namespace std;

Syntax: int main() {


int i = 0;
while (condition) { while (i < 5) {
// Code to execute as long as condition is true cout << "Iteration " << i << endl;
} i++;
OUTPUT: }
Iteration 0 return 0;
Iteration 1 }
Iteration 2
Iteration 3
Iteration 4
22
Email:[email protected]
Computer Programming -ECEG 1052

Example down counter


#include <iostream>
using namespace std; Output
int main() 9
8
{ 7
int i = 9; 6
5
while(i>=0){ 4
cout<<i<<endl; 3
2
i--; } 1
return 0; 0

}
23
Email:[email protected]
Computer Programming -ECEG 1052

Nested and infinite while loop


▪ Nested while loop is possible
▪ Structure
while(condition1){
while(condition2){
Statements ;
}//end the second while
}//end the first while
▪ Infinite while Loop
While(true){
Statements;
}

24
Email:[email protected]
Computer Programming -ECEG 1052

do-while Loop
The do-while loop is similar to the while loop, but the condition is checked after the code block is executed,
ensuring that the code block is executed at least once.
#include <iostream>
Syntax: using namespace std;
do {
// Code to execute at least once, then as long as condition is true int main() {
} while (condition); int i = 0;
do {
cout << "Iteration " << i << endl;
i++;
} while (i < 5);
return 0;
}

25
Email:[email protected]
Computer Programming -ECEG 1052

Example
#include <iostream>
using namespace std; Output
int main() 9
{ 8
int i = 9; 7
do { 6
5
cout<<i<<endl;
4
i--; 3
} 2
while(i>=0); 1
return 0; 0
}

26
Email:[email protected]
Computer Programming -ECEG 1052

Nested Loops
Loops can be nested within each other to handle more complex scenarios, such as iterating over
multi-dimensional arrays or performing operations that require multiple levels of repetition.
Example:
#include <iostream>
using namespace std; (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)

int main() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << "(" << i << "," << j << ") ";
}
cout << endl;
}
return 0;
} 27
Email:[email protected]
Computer Programming -ECEG 1052

Jump Statements in C++


Jump statements are used to alter the flow of control in a program by transferring control to
another part of the program.
They allow you to skip over certain parts of the code or exit loops and functions prematurely.
In C++, the primary jump statements are:
1.break Statement
2.continue Statement
3.return Statement
4.goto Statement
28
Email:[email protected]
Computer Programming -ECEG 1052

break statement

• A break statement may appear inside a loop (while do, or for) or a


switch statement.
• It causes a jump out of these constructs and hence terminates them.
• A break statement only applies to the loop or switch immediately
enclosing it.
• It is an error to use the break statement outside a loop or a switch.

Email:[email protected]
Computer Programming -ECEG 1052

do{
Syntax
Statement/s
If(test expression) while (test expression)
{ {
break; Statement/s
} If(test expression) For (initial expression; test expression;
Statement/s { update expression)
} break;
While(test expression); }
Statement/s {
}
If(test expression)

{
break;
}
Statement/s
}
Email:[email protected]
Computer Programming -ECEG 1052

Write C++ program to add all number entered until the user
enters 0.

Email:[email protected]
Computer Programming -ECEG 1052

Class Work
#include <iostream>
using namespace std;
int main(){
int a = 10; // Local variable declaration
value of a: 10
do { value of a: 11
value of a: 12
cout << "value of a: " << a << endl;
value of a: 13
a = a + 1; value of a: 14
if( a > 15 ) break; value of a: 15
} while( a < 20 );

return 0;
}

Email:[email protected]
Computer Programming -ECEG 1052

continue statement
• continue statement causes the loop to skip the current iteration and goes for
next iteration.
• For the for loop, continue causes the conditional test and increment portions
of the loop to execute.
• For the while and do...while loops, program control passes to the conditional
tests.
• It is an error to use the continue statement outside a loop.

Email:[email protected]
Computer Programming -ECEG 1052

Syntax

Email:[email protected]
Computer Programming -ECEG 1052

Write a C++ program to display integer from 1 to 10 except 6 and 9.

Email:[email protected]
Computer Programming -ECEG 1052

Class Work: Show the output


int main () { value of a: 10
value of a: 11
int a = 10; // Local variable value of a: 12
do { value of a: 13
if( a == 15 ) { value of a: 14
value of a: 16
a = a + 1; value of a: 17
continue; value of a: 18
value of a: 19
}
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );
return 0;
}
Email:[email protected]
Computer Programming -ECEG 1052

return statement
• The return statement enables a function to return a value to its caller. It has the general
form:
• return expression;
• where expression denotes the value returned by the function. The type of this value should
match the return type of the function.
• For a function whose return type is void, expression should be empty:
• return;

Email:[email protected]
Computer Programming -ECEG 1052

Cont….

▪ The only function we have discussed so far is main, whose return type is
always int.
▪ The return value of main is what the program returns to the operating system
when it completes its execution.
▪ For example, its conventional to return 0 from main when the program
executes without errors. Otherwise, a non-zero error code is returned.

Email:[email protected]
Computer Programming -ECEG 1052

Exercises on Chapter three

▪ Write a Program to print half pyramid using *

Email:[email protected]
Computer Programming -ECEG 1052

• #include <iostream>
• using namespace std;
• int main() {
• int rows;
cout << "Enter number of rows: ";
• cin >> rows;
for(int i = 1; i <= rows; ++i) {
• for(int j = 1; j <= i; ++j) {
• cout << "* "; }
• cout << "\n"; }
• return 0; }

Email:[email protected]
Computer Programming -ECEG 1052

▪ Write a Program to print half pyramid using numbers

Email:[email protected]
Computer Programming -ECEG 1052

goto
• The code goto is used for moving back and forth in the program. Therefore, for using goto
statement one needs to put in a label.
• Syntax:

Email:[email protected]
Computer Programming -ECEG 1052

Write program calculates the average of numbers entered by user. If user enters negative number, it ignores the
number and calculates the average of number entered before it

# include <iostream> for (i = 1; i <= n; ++i)


{
using namespace std; cout << "Enter n" << i << ": ";
int main( ) cin >> num;

{ if (num < 0.0)


{
float num, average, sum = 0.0; goto jump;
}
int i, n; sum += num;
cout << "Maximum number of inputs: "; }
jump:
cin >> n; average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0; }
Email:[email protected]
Computer Programming -ECEG 1052

•End Of Chapter Three

Email:[email protected]

You might also like