0% found this document useful (0 votes)
13 views57 pages

Programming Fundamentals Repetition Structure: Loops: Dr. Ashfaq Hussain Farooqi

The document covers programming fundamentals related to loops and control structures, including increment and decrement operators, while loops, do-while loops, for loops, and nested loops. It explains the mechanics of each loop type, input validation, counters, and the use of control statements like break and continue. Additionally, it provides examples and flowcharts to illustrate the concepts discussed.

Uploaded by

Sadia Awan
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)
13 views57 pages

Programming Fundamentals Repetition Structure: Loops: Dr. Ashfaq Hussain Farooqi

The document covers programming fundamentals related to loops and control structures, including increment and decrement operators, while loops, do-while loops, for loops, and nested loops. It explains the mechanics of each loop type, input validation, counters, and the use of control statements like break and continue. Additionally, it provides examples and flowcharts to illustrate the concepts discussed.

Uploaded by

Sadia Awan
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/ 57

Programming Fundamentals

Repetition Structure: Loops


Dr. Ashfaq Hussain Farooqi
The Increment and Decrement Operators
● ++ is the increment operator.

○ It adds one to a variable.


val++; is the same as val = val + 1;

● ++ can be used before (prefix) or after (postfix) a variable:

++val; val++;
● -- is the decrement operator.

○ It subtracts one from a variable.

val--; is the same as val = val - 1;

● The -- can be also used before (prefix) or after (postfix) a variable:

--val; val--;

2
Example program

3
Prefix vs. Postfix
● ++ and -- operators can be used in complex statements and expressions
● In prefix mode (++val, --val) the operator increments or decrements, then returns
the value of the variable
● In postfix mode (val++, val--) the operator returns the value of the variable, then
increments or decrements
● Examples:
int num, val = 12;
cout << val++; // displays 12,
// val is now 13;
cout << ++val; // sets val to 14,
// then displays it
num = --val; // sets val to 13,
// stores 13 in num
num = val--; // stores 13 in num,
// sets val to 12
4
Notes on Increment and Decrement
● Can be used in expressions:

result = num1++ + --num2;


● Must be applied to something that has a location in memory. Cannot have:

result = (num1 + num2)++;


● Can be used in relational expressions:

if (++num > limit)

pre- and post-operations will cause different comparisons

5
Introduction to Loops: The while Loop
● Loop: a control structure that causes a statement or statements to repeat
● General format of the while loop:

while (expression)

statement;

○ statement; can also be a block of statements enclosed in { }


● The while Loop – How It Works?
● expression is evaluated

○ if true, then statement is executed, and expression is evaluated again

○ if false, then the loop is finished and program statements following statement
execute
6
The Logic of a while Loop

7
The while loop in Program (example1)

8
Flowchart of the while Loop (program example1)

9
The while Loop is a Pretest Loop
● expression is evaluated before the loop executes.
● The following loop will never execute:

int number = 6;
while (number <= 5)
{
cout << "Hello\n";
number++;
}

10
Watch Out for Infinite Loops
● The loop must contain code to make expression become false
● Otherwise, the loop will have no way of stopping
● Such a loop is called an infinite loop, because it will repeat an infinite number of
times

○ Example of an Infinite Loop


int number = 1;
while (number <= 5)
{
cout << "Hello\n";
}
11
Using the while Loop for Input Validation
● Input validation is the process of inspecting data that is given to the program as input
and determining whether it is valid.
● The while loop can be used to create input routines that reject invalid data, and repeat
until valid data is entered.
● Here's the general approach, in pseudocode:

Read an item of input.


While the input is invalid
Display an error message.
Read the input again.
End While

12
Input Validation Example
cout << "Enter a number less than 10: ";
cin >> number;
while (number >= 10)
{
cout << "Invalid Entry!"
<< "Enter a number less than 10: ";
cin >> number;
}

13
Flowchart for Input Validation

14
Input Validation in Program

15
Input Validation in Program cont…

16
Counters
● Counter: a variable that is incremented or decremented each time a loop repeats
● Can be used to control execution of the loop (also known as the loop control variable)
● Must be initialized before entering loop

17
A Counter Variable Controls the Loop

18
The do-while Loop
The Logic of a do-while Loop
● do-while: a posttest loop – execute the
loop, then test the expression
● General Format:
do

statement; // or block in { }

while (expression);

● Note that a semicolon is required after


(expression)

19
An Example do-while Loop
int x = 1;
do
{
cout << x << endl;
} while(x < 0);

Although the test expression is false, this loop will execute one time
because do-while is a posttest loop.

20
A do-while Loop (Example Program)

21
do-while Loop Notes
● Loop always executes at least once
● Execution continues as long as expression is true, stops repetition when
expression becomes false
● Useful in menu-driven programs to bring user back to menu to make another choice

22
The for Loop
● Useful for counter-controlled loop
● General Format:

for(initialization; test; update)

statement; // or block in { }

● No semicolon after the update expression or after the )

23
for Loop - Mechanics
for(initialization; test; update)

statement; // or block in { }

1) Perform initialization
2) Evaluate test expression
○ If true, execute statement

○ If false, terminate loop execution


3) Execute update, then re-evaluate test expression

24
Flowchart of for loop

25
for Loop – Example: Program1
int count;

for (count = 1; count <= 5; count++)


cout << "Hello" << endl;

26
Flowchart (Example: Program1)

27
A for Loop (Example Program2)

28
Closer look and Flowchart (Example:Program2)

29
When to Use the for Loop?
● In any situation that clearly requires

○ an initialization

○ a false condition to stop the loop

○ an update to occur at the end of each iteration


● The for loop is a pre-test loop
● The for loop tests its test expression before each iteration, so it is a pretest loop.
● The following loop will never iterate:

for (count = 11; count <= 10; count++)


cout << "Hello" << endl;

30
For loop instead of while or do-while loops

31
for Loop - Modifications
● You can have multiple statements in the initialization expression.
● Separate the statements with a comma:

int x, y; Initialization Expression


for (x=1, y=1; x <= 5; x++)
{
cout << x << " plus " << y
<< " equals " << (x+y)
<< endl;
}

32
for Loop - Modifications
● You can also have multiple statements in the test expression. Separate
the statements with a comma:
Test
Expression
int x, y;
for (x=1, y=1; x <= 5; x++, y++)
{
cout << x << " plus " << y
<< " equals " << (x+y)
<< endl;
}
33
for Loop - Modifications
● You can omit the initialization expression if it has already been done:

int sum = 0, num = 1;


for (; num <= 10; num++)
sum += num;
● You can declare variables in the initialization expression:

int sum = 0;

for (int num = 0; num <= 10; num++)

sum += num;

○ The scope of the variable num is the for loop.

34
Differences of while/do while and for loop
For Loop While Loop
• It is used when the number of iterations • It is used when the number of iterations is
is known. not known.
• In case of no condition, the loop is • In case of no condition, an error will be
repeated infinite times. shown.
• Initialization is repeated if carried out
• Initialization is not repeated.
during the stage of checking.
• Statement of Iteration is written after
• It can be written at any place.
running.
• Initialization can be in or out of the loop • Initialization is always out of the loop.
• The nature of the increment is simple. • The nature of the increment is complex.
• Used when initialization is simple. • Used when initialization is complex. 35
Deciding Which Loop to Use
● The while loop is a conditional pretest loop

○ Iterates as long as a certain condition exits

○ Validating input

○ Reading lists of data terminated by a sentinel

● The do-while loop is a conditional posttest loop

○ Always iterates at least once

○ Repeating a menu

● The for loop is a pretest loop

○ Built-in expressions for initializing, testing, and updating


36
Keeping a Running Total
● running total: accumulated sum of numbers from each repetition of loop
● accumulator: variable that holds running total
int sum=0, num=1; // sum is the

while (num <= 10) // accumulator

{ sum += num;

num++;

cout << "Sum of numbers 1 – 10 is"

<< sum << endl;

37
Logic for Keeping a Running Total

38
A Running Total (Example Program)

39
Sentinels
● sentinel: value in a list of values that indicates end of data
● Special value that cannot be confused with a valid value, e.g., -999 for a test score
● Used to terminate input when user may not know how many values will be entered

Output:
#include <iostream>
using namespace std;
Please enter a number not
int main() equal to 0
{
int n = 99; // make sure n isn’t initialized to 0 5
cout << "Please enter a number not equal to 0" << endl;
while (n != 0) // loop until n is 0 4
cin >> n; // read a number into n
cout << "Sorry! you have entered a 0" << endl;
8
return 0; 0
}
Sorry! you have entered a
0
40
A Sentinel (Example: program)

41
Nested Loops
● A nested loop is a loop inside the body of another loop
● Inner (inside), outer (outside) loops:

for (row=1; row<=3; row++) //outer

for (col=1; col<=3; col++)//inner

cout << row * col << endl;

42
Example program
#include <iostream>
using namespace std;

int main() {
Output:
// Outer loop Outer: 1
for (int i = 1; i <= 2; ++i) { Inner: 1
Inner: 2
cout << "Outer: " << i << "\n"; // Executes 2 times Inner: 3
Outer: 2
// Inner loop Inner: 1
Inner: 2
for (int j = 1; j <= 3; ++j) { Inner: 3
cout << " Inner: " << j << "\n"; // Executes 6 times (2 *
3)
}
}
return 0;
} 43
Nested for Loop (Example: Program)

44
Example Program
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n = 0; Output:
while (n < 2) outer while loop
{ Inner while loop
Inner while loop
cout << "outer while loop" << endl; outer while loop
int m = 0; Inner while loop
while (m < 2) Inner while loop
{
cout << "Inner while loop" << endl;
m++;
}
n++;
}
return 0;
} 45
Nested Loops - Notes
● Inner loop goes through all repetitions for each repetition of outer loop
● Inner loop repetitions complete sooner than outer loop
● Total number of repetitions for inner loop is product of number of repetitions of the
two loops.

46
Control statements (jump statemnets)
● Break (break)
● Continue (continue)
● Goto statement (goto)
● Return statement (return)

47
Control statements (Break statement)
● Breaking Out of a Loop

○ Can use break to terminate execution of a loop

○ Use sparingly if at all – makes code harder to understand and debug

○ When used in an inner loop, terminates that loop only and goes back to outer loop
int i = 0;
#include <iostream>
using namespace std;
while (i < 10) {
cout << i << "\n"; Output:
0
int main() {
for (int i = 0; i < 10; i++) {
Output:
i++; 1
if (i == 4) { 2
break; 0 if (i == 4) { 3
1
}
cout << i << "\n"; 2 break;
3
} }
return 0;
} }
48
Flowchart of break statement

49
Control statements (continue statements)
● The continue Statement
○ Can use continue to go to end of loop and prepare for next repetition

■ while, do-while loops: go to test, repeat loop if test passes

○ Use sparingly – like break, can make program logic hard to follow

#include <iostream> Output:


using namespace std; Output: int i = 0; 0
0 while (i < 10) { 1
int main() { 1 if (i == 4) { 2
for (int i = 0; i < 10; i++) { 2 i++; 3
if (i == 4) { 3 continue; 5
continue; 5 } 6
} 6 cout << i << "\n"; 7
cout << i << "\n"; 7 i++; 8
} 8 } 9
return 0; 9
} 50
Flowchart of continue statement

51
Program1
#include<iostream>
#include<string> Output:
using namespace std; Hello world
int main() { Hello world
int n = 5; Hello world
while (n--) { Hello world
cout << "Hello world" << endl; Hello world
}
return 0;
}

52
Program2
#include<iostream>
using namespace std;
Output:
int main() {
c = 12
int n = 5;
int c=n++ + ++n;
cout<<"c = "<<c;
}

53
Program3 Output:
it is out of control
it is out of control
it is out of control
#include<iostream> it is out of control
it is out of control
using namespace std; it is out of control
int main() { it is out of control
it is out of control
for (;;) it is out of control
it is out of control
cout<<"it is out of control"<<endl; it is out of control
it is out of control
} it is out of control
it is out of control
it is out of control
it is out of control
it is out of control
it is out of control
it is out of control
it is out of control
it is out of control
.
.
. 54
Ranged based loop (foreach loop)
● In C++11, a new range-based for loop was introduced to work with collections such as
arrays and vectors.
#include <iostream>
● Its syntax is:
using namespace std;

int main() {
for (variable : collection) {
int num_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// body of loop for (int n : num_array) {


cout << n << " ";
}
}
return 0;
● To avoid datatype conflict use the variable } Output: 1 2 3 4 5 6 7 8 9 10
Type as auto.

55
Pros and cons of Ranged based (foreach loop)
● pros of foreach loop

○ It eliminates the possibility of errors and makes the code more readable.

○ Easy to implement

○ Does not require pre-initialization of the iterator


● cons of foreach loop

○ Cannot directly access the corresponding element indices

○ Cannot traverse the elements in reverse order

○ It doesn’t allow the user to skip any element as it traverses over each one of them
56
Example program
// This program raises the user's number to the powers
// of 0 through 10.
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
double value;
char choice;
int count =0;
cout << "Enter a number: ";
cin >> value;
cout << "This program will raise " << value;
cout << " to the powers of 0 through 10.\n";
while(value<=10)
{
cout << value << " raised to the power of ";
cout << count << " is " << pow(value, count);
cout << "\nEnter Q to quit or any other key ";
cout << "to continue. ";
count ++;
cin >> choice;
if (choice == 'Q' || choice == 'q')
break;
}
return 0;
} 57

You might also like