Loops and Iteration: Introduction To Algorithms and Programming

You might also like

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

INTRODUCTION TO ALGORITHMS AND PROGRAMMING

LOOPS AND ITERATION


By: Eng. Nariman M Ajeilo
LOOPS AND ITERATION

REVIEW
▸ Conditional statements:

▸ The modulus operator is %


▸ We can find the size of a variable using sizeof(datatype). For example sizeof(char),
sizeof(int)
LOOPS AND ITERATION

REVIEW

▸ Write C++ program to display the largest number among three numbers

THE LOGICAL AND OPERATOR IS &&


THE LOGICAL OR OPERATOR IS ||
LOOPS AND ITERATION

REVIEW
LOOPS AND ITERATION

WHAT IS A LOOP?
▸ It is a conditional iterative statement which is used to check for certain
conditions and then repeatedly execute a block of code as long as those
conditions are met
LOOPS AND ITERATION

START
LOOPS AND FLOW CHARTS
SHUT DOWN WATER TAP
OPEN WATER TAP

DRY YOUR HANDS


PUT SOAP ON HANDS

END
CLEAN HANDS WITH WATER

YES ARE NO
HANDS
CLEAN?
LOOPS AND ITERATION

ITERATIONS

▸ There are 3 possible ways to iterate:


For loops

While loops

Do-while loops
LOOPS AND ITERATION

FOR LOOPS

▸ Used when the number of iterations is known

▸ Uses a counter, normally known as index (i)


LOOPS AND ITERATION

WHILE LOOPS

▸ Used when the number of iterations isn’t know, but the condition is clear
LOOPS AND ITERATION

DO-WHILE LOOPS

▸ Do-while loops are variant of while loops

▸ This loop will execute the code block once, before checking if the condition is
true, then it will repeat the loop as long as the condition is true.
LOOPS AND ITERATION

WHY TO USE LOOPS?

▸ Write a c++ program that prints “Hello world!” five times on the screen
Without for loop With for loop
LOOPS AND ITERATION

EXAMPLE 1 (FOR LOOP)

▸ Write a C++ program that prints numbers between 1 and 20


LOOPS AND ITERATION

EXAMPLE 1 (FOR LOOP)


LOOPS AND ITERATION

EXAMPLE 2 (FOR LOOP)

▸ Write a C++ program that prints numbers between two numbers chosen by the
user
LOOPS AND ITERATION

EXAMPLE 2 (FOR LOOP)


LOOPS AND ITERATION

EXAMPLE 3 (FOR LOOP)

▸ Write a C++ program that sums up the numbers between two numbers chosen
by the user and then find the average of those number.
LOOPS AND ITERATIONS

EXAMPLE 3 (FOR LOOP)


LOOPS AND ITERATION

EXAMPLE 4 (FOR LOOP)

▸ Write a C++ program that prints even numbers from 0 to 100


LOOPS AND ITERATION

EXAMPLE 4 (FOR LOOP)


LOOPS AND ITERATION

EXAMPLE 5 (WHILE LOOP)

▸ Write a C++ program that prints “Hello” ten times using while loop
LOOPS AND ITERATION

EXAMPLE 5 (WHILE LOOP)


LOOPS AND ITERATION

EXAMPLE 6 (WHILE LOOP)

▸ Write a C++ program that reverse a number (example: 4392 => 2934)
LOOPS AND ITERATION

EXAMPLE 6 (WHILE LOOP)


LOOPS AND ITERATION

EXAMPLE 7 (DO-WHILE LOOP)

▸ Write a C++ program to display numbers from 1 to 5 using do-while loop


LOOPS AND ITERATION

EXAMPLE 7

You might also like