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

Control Statements

This document covers control statements in C++, detailing flow control, conditional statements (if and switch), and looping statements (for, while, do-while). It explains the syntax and usage of each type of statement, including examples and exercises for practice. Additionally, it discusses other statements like break, continue, goto, and return, providing insights into their functionality within loops and functions.

Uploaded by

adonyasmelaku785
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Control Statements

This document covers control statements in C++, detailing flow control, conditional statements (if and switch), and looping statements (for, while, do-while). It explains the syntax and usage of each type of statement, including examples and exercises for practice. Additionally, it discusses other statements like break, continue, goto, and return, providing insights into their functionality within loops and functions.

Uploaded by

adonyasmelaku785
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Control Statements

Chapter 03
Contol Statements
Flow Control / Control flow: the order in which statements
are executed.
- It is typically sequential but may be diverted to other paths
by branch statement.
- C++ provides different control statements
1. Conditional Statement
2. Looping / Iteration statement
3. Other statements
Conditional Statements
1. If Statement
- execute statements depending on a condition being staisfied.
- syntax: if ( expression / condition )
statement;
This statement executes if and only if the
expression inside the parenthesis results
to true / condition becomes true

- the syntax above is used if you want to execute single statememt for
the condition.
- If you want to execute more than 1 statement when
condition/ expression is true, use the syntax below:
if (expression)
{
statement1; you surround your statements
with open and close curly
statement2; bracket {} (block statement
}
- If you want to execute statement if the condition is not true:
syntax: if (expression)
statement1; statement1 wil be executed if
the expression/condition is true
else
statement2;

statement2 wil be executed if


the expression/condition is false
If you are executing multiple statements:
syntax: if (expression)
{
statement1;
statement2;
}
else if()
{
statement3;
statement4;
}
- If statements can be nested ( if statements inside another
statement)
syntax: if (condition)
{
statement1;...
if (condition)
{
statement2; ...
}
}
It is good practice to use curly bracket even if you execute one
statement.
2. Switch statement
- It provides a way of choosing between sets of alternative
based on expression.
syntax: switch ( expression)
{
case label1:
expression is evaluated and
statement;
outcome is compared to each
break;
labels as they appear in order until
case label2:
a match is found.
statement;
break; ...
default: Default case is executed if none of
statement; the case labels match the
break; expression.
}
If statement vs Switch Statement
- If-statement verifies relational expression as well as logical
expression.
- Switch Statement tests for equality
2. Looping / iterating
Statements
- It is a piece of code which executes automatically repeatedly.
Example: printing out hello world 5 times in a row
objective - repeat statement
- One complete execution - Iteration
- test conditions control the iteration.
 If the test conditions is true: execution continues
 if the test conditions is false: it exits the loop
Clock
Ringing Alarm Clock

Sleeping

Breathing
Structure of a loop statement (ICU)
I ( Initialization )
• we start with initialized variable
• Keeps track of where we are in a loop
• AKA counter variable

C ( Condition )
• tells when the loop should stop

U ( Update )
• updates the counter variable
• it's the action that changes the state of the loop, allowing it to progress
towards the end condition
Types of Loop Statement
1. for Loop
2. while loop
3. do-while loop
1. for loop
- allow you to repeat a block of code a number of times.
- syntax:
for ( initialization ; test condition ; update)
{
// loop body
}

- initialization: starting point of the loop


- test condition: condition that loop checks before each iteration
- update : step that happens after each iteration in loop
: increment/decrement
1. for (int i = 1; i <= 5; ++i) {
cout << "Hello world" << endl;
}

2. for (int i = 10; i >= 1; --i) {


cout << i << " ";
}
Exercise
1. Write a C++ program that prints all the numbers from 1 to 10.
2. Write a C++ program that prints all the even numbers from 1 to 10.
3. Write a C++ program that prints all the odd numbers from 1 to 25.
4. Write a C++ program that calculates the sum of all the numbers from
1 to 50.
5. Write a C++ program that calculates the sum of all the even numbers
from 1 to 100.
6. Write a C++ program that calculates the sum of the first 20 multiples
of 3.
nested for loop
- A nested for loop is when a for loop is placed inside another for loop.
- The inner loop is executed completely for each iteration of the outer loop.
- This allows you to iterate over two or more sets of data simultaneously,
creating a grid-like structure.

for ( initialization; condition; update ) {

for ( initialization; condition; update ) {

}
}
1. for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
std::cout << "*";
}
std::cout << std::endl;
}
2. for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
std::cout << "*";
}
std::cout << std::endl;
}
1. while loop
- The while statement (also called while loop) provides a way of
repeating a statement while a condition holds true.
The general form of the while statement is:

loop condition
initialization;
while ( test expression )
{ statement;
update; loop body: executed and
the whole process is
} repeated
Scenario: Imagine you are trying to wake up in the morning for school.
Example: You keep snoozing your alarm clock until you finally get out of
bed. The while loop can represent this process, where the condition is
while (stillInBed)
snooze alarm

Scenario: You want to go to a concert, but the tickets are expensive. You
decide to save up your allowance and money from doing chores to buy
the ticket.
Example: You start with 0 ETB and need to save 1000 ETB for the ticket.
while ( totalSaved < 1000 )
do chores, save allowance, check total saved.
1. int I = 0;
while ( I < 10 ) {
cout << I << “ “;
I ++;
}

2. int x=1;
while ( x <= 3 ){
cout<<”hello”;
x++;
}
3. int x=5, y=5;
while ( x == y ){
cout<<”hello”;
}
Exercise
1. Write a C++ program that prints all the numbers from 1 to 10 using a
while loop.
2. Write a C++ program that prints all the even numbers from 1 to 20
using a while loop.
3. Write a C++ program that prints all the odd numbers from 1 to 25
using a while loop.
4. Write a C++ program that calculates the sum of all the numbers from
1 to 50 using a while loop.
5. Write a C++ program that calculates the sum of all the even numbers
from 1 to 100 using a while loop.
6. Write a C++ program that calculates the sum of the first 20 multiples
of 3 using a while loop.
2. do-while loop
The do statement (also called do loop) is similar to the while statement,
except that its body is executed first and then the loop condition is
examined.
The general form of the do statement is:
loop body: executed and
the whole process is
do repeated
statement;
while(expression);
loop condition
while loop vs do-while loop
1. int i=0; 2. int i=0;
do { while(i>0) {
cout<<”hi from do-while”; vs cout<<”hi from while”;
} while(i>0); }

3. int count = 0;
do {
cout<<count;
count++;
} while (count < 5);
for loop vs while loop vs do-
while loop
• for loops are used when you know the exact number of times you
need to repeat something (e.g., a 60-second countdown).
• while loops are used when you need to repeat something as long as a
certain condition is true (e.g., the alarm time has not been reached).
• do-while loops are used when you need to do something at least
once, and then repeat it as long as a certain condition is true (e.g., the
stopwatch is still running).
Other statements
1. break statement
2. continue statement
3. go-to statement
4. return statement
1. continue statement
- terminates current iteration and moves to the next iteration.
- applies to the loop immedietly enclosing this statement.
- can’t be used outside loop statements
syntax:
continue;
Example: for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
cout << i << " ";
Exercise
1. Write a C++ program that calculates the sum of all the numbers from 1
to 50. The program should not add/skip numbers that are divisible by 3 or 5.
2. Write a C++ program that calculates the sum of all the even numbers
from 1 to 100 using a while loop and continue statement.

* When the continue statement appears inside nested loops, it applies to


the loop immediately enclosing it, and not to the outer loops
for ( ..... ){
for (.....){
continue;
}
}
2. break statement
- statement used for terminating loop / switch statement
- it appears inside a loop or switch body
- the break statement is applied to the loop immedietly enclosing it like
continue statement.
- it can not be used outside loop/switch statement.
syntax:
break;
1. int num, sum = 0;
while (true) {
cout << "Enter a number (0 to stop): ";
cin >> num;
if (num == 0) {
break;
}
sum += num;
}
cout << "The sum of the numbers is: " << sum << endl;
2. for (int i = 1; i <= 3; i++) {
cout << "Outer Loop Iteration " << i << ":" << endl;
for (int j = 1; j <= 5; j++) {
if (j == 3) {
break;
}
cout << " Inner Loop: " << j << endl;
}
}
3. go-to statement
- provide lowest-level of jumping
- allow you to jump from one part of a code to another part inside the
same code.
Example : you are cooking and you missed one step. so you go back
and do that step.
- syntax: goto label;

label:
statement;
for(int i=0; i<=10; i++){
if(i % 2 == 0) {
goto even;
}
cout<<"odd";
}

even:
cout<<"goto statement";
4.return statement
- statement that enables a function to return a value
- The type of this value should match the return type of the function.
Syntax: return value;
Example : int main (void)
{
cout << "Hello World\n";
return 0;
}
1. int main(){
if(2 == 2) {
cout<<"hi";
return 0;
}
cout<<"bye";
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy