0% found this document useful (0 votes)
111 views34 pages

CS-114 Fundamentals of Computer Programming: Control Statements - III

The document provides an overview of iteration statements in C++, specifically while loops, do-while loops, and for loops. It discusses the basic syntax and flow of while and do-while loops, including examples of counting loops, conditional loops, and avoiding infinite loops. Key points covered include initializing and updating loop counters, checking loop conditions, and executing code blocks repeatedly until the condition becomes false. Examples are provided to calculate sums and averages using loops.

Uploaded by

Abdullah Riasat
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)
111 views34 pages

CS-114 Fundamentals of Computer Programming: Control Statements - III

The document provides an overview of iteration statements in C++, specifically while loops, do-while loops, and for loops. It discusses the basic syntax and flow of while and do-while loops, including examples of counting loops, conditional loops, and avoiding infinite loops. Key points covered include initializing and updating loop counters, checking loop conditions, and executing code blocks repeatedly until the condition becomes false. Examples are provided to calculate sums and averages using loops.

Uploaded by

Abdullah Riasat
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/ 34

CS-114

Fundamentals of Computer
Programming

Lecture 7
Control Statements – III

Course Instructor: NUST Institute of Civil


Aisha Shabbir Institute of Geographical Information Systems
Engineering (NICE)
Road Map for Today
• Control Statements
 Selection
• if
• switch
 Iteration
• while
• do…while
• for
 Jump
C++ Iteration/Repetition
Statements
OVERVIEW
 We often need to do repetitive calculations in order to
solve complex problems

 To perform repetitive calculations in a program we need


iterative statements that let us execute the same block of
code multiple times

Programming Foundations I
4
OVERVIEW
 C++ has three kinds of iterative statements
 The while loop
 The for loop
 The do-while loop

Programming Foundations I
5
ITERATIVE
STATEMENTS

PART 1
WHILE LOOPS
WHILE LOOPS
 A while loop iteratively executes a block of code
 We need to specify the following:
 The initialization code to execute before the loop
 The logical expression for continuing iteration
 The block of code to be repeated inside the loop

 The program will execute block of code repeatedly as long


as the while condition remains true
 The program will not execute block of code when the while
condition becomes false

Programming Foundations I
7
WHILE LOOPS
 The C++ syntax of the while loop is:

// initialization statement
while ( logical expression )
{
// block of statements to be repeated
// update variables in logical expression
}

Programming Foundations I
8
The while statement
• A repetition statement specifies that a program
should repeat an action while some condition
remains true.
The while statement
A while loop is a “pre test” loop - the condition is
tested before the loop body is executed

while(condition)
statement;

while(condition)
{
statement(s);
}
The while statement - Example

// Local variable declaration:


int a = 10;
Output:
Value of a: 10
// while loop execution Value of a: 11
while( a < 15 )
{ Value of a: 12
cout << “Value of a: " << a << endl;Value of a: 13
a++;
} Value of a: 14
The while statement - Example

// Local variable declaration:


int product = 10;

// while loop execution


while( product <= 100 )
product *= 3;
Flowchart Representation of “while”

Part of program
before iteration

Logical expression FALSE


(loop condition)

TRUE

Part of program
Loop Body after iteration

13
COUNTING LOOPS
 Often need to perform an operation fixed number of times
 We can use a counting loops to do this operation

 We need to do the following:


 Initialize the loop counter
 While counter has NOT reached desired value
• Perform desired operations
• Increment loop counter
• Check loop counter again

Programming Foundations I
14
COUNTING LOOPS
// Counting loop example
int Count = 0; con-var
while (Count < 10) // conditional variable
{
cout << Count << " squared=" << Count*Count << endl;//
independent
Count = Count + 1; // con-var
}

 This while loop will execute the block of code 10 times


 Count values will go from 0,1,2,3,4,5,6,7,8,9, 10
 When Count equals 10 we do not execute block of code

CSCE 2004 - Programming Foundations I


15
COUNTING LOOPS
// Another counting loop example
int Number = 1;
while (Number <=10)
{
cout << Number << " halved=" << Number /2 << endl;
Number = Number + 1;
}

 This while loop will execute the block of code 10 times


 Number values will go from 1,2,3,4,5,6,7,8,9,10, 11
 When Number equals 11 we do not execute block of code

CSCE 2004 - Programming Foundations I


16
COUNTING LOOPS
// Zero iterations loop
int Value = 101;
while (Value < 17)
{
cout << Value << " doubled=" << Value*2 << endl;
Value = Value + 1;
}

 This while loop will execute the block of code 0 times


 The initial value of the Value variable is too large to enter
the loop, so the block of code is skipped over

CSCE 2004 - Programming Foundations I


17
CONDITIONAL LOOPS
 We often need to vary the number of iterations based on
the data values
 Conditional loops allow us to process data until given
situation arises

 We need to do the following:


 Perform initialization code
 While the condition remains TRUE
• Perform desired operations
• Check terminating condition again

CSCE 2004 - Programming Foundations I


18
CONDITIONAL LOOPS
// Another conditional loop example
int Val = 54;
int Cnt = 0;
while ((Val % 3) == 0)
{
cout << Val << " " << Cnt << endl;
Val = Val / 3;
Cnt = Cnt + 1;
}

 This while loop will count how many times Val can be
divided evenly by 3 (in this case Cnt=3 since 54=3*3*3*2)

CSCE 2004 - Programming Foundations I


19
INFINITE LOOPS
 It is possible to create while loops which execute forever
 These infinite loops are often unplanned and unwanted

 Occasionally infinite loops are used on purpose


 This is not recommended, but you may see it in other
programmer's code

CSCE 2004 - Programming Foundations I


20
INFINITE LOOPS
// Infinite loop example
while (true)
cout << "Hello Mam\n";

 This while loop will print “Hello Mam” on the screen in an


infinite loop until you get bored and kill the program

CSCE 2004 - Programming Foundations I


21
INFINITE LOOPS
// Accidental infinite loop
int Total = 0;
int Count = 0;
while (Count < 10)
{
Total = Total + Count;
Cout << "total=" << Total << endl;
}

 We forgot to increment the variable Count inside the loop


so it will always be equal to 0, giving us an infinite loop

CSCE 2004 - Programming Foundations I


22
INFINITE LOOPS
// Potential infinite loop
int Height = 0;
while (Height < 42)
{
cout << "Enter height: ";
cin >> Height;
}

 This loop will execute over and over until the user enters a
Height value >= 42
 This code could go in an infinite loop if the user types a
string like “height” instead an integer value

CSCE 2004 - Programming Foundations I


23
The while statement – Example
• Calculate the sum of first 10 natural numbers.
Common Mistakes in while-extra semicolon

while (num < minimum);


{
cout << “Enter a number”;
cin >> num;
}
“do…while” loop

In addition to the while loop, C++ also offers the


do-while and for loops.

A do-while loop is similar to a while loop, but it is


in “post-test” format.
“do…while” loop

do {
statement(s);
} while(condition);

Note the Semicolon


here. It is part of the
syntax & missing it will
give an error.
Flowchart Representation of “do…while”

Part of program
before iteration
Loop Body

Logical expression FALSE


(loop condition)

TRUE

Part of program
Loop Body after iteration

28
“do…while” - Example

A program that averages 3 test scores


and it repeats as many times as the
user wishes.
“do…while” - Example
#include <iostream>
using namespace std;

int main()
{
int score1, score2, score3;
float average;
char again;

do {
cout << "Enter 3 scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average << ".\n";
cout << "Do you want to average another set? (Y/N) ";
cin >> again;
} while (again == 'Y' || again == 'y');
} while ( ? );
return 0;
}
“do…while” - Example
#include <iostream>Output with a Sample Input
using namespace std;
Enter 3 scores and I will average them: 80 90 70 [Enter]
int main() The average is 80.
{ Do you want to average another set? (Y/N) y [Enter]
int score1, score2, score3;
float average;
Enter 3 scores and I will average them: 60 75 88 [Enter]
char again; The average is 74.333336.
Do you want to average another set? (Y/N) n [Enter]
do {
cout << "Enter 3 scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average << ".\n";
cout << "Do you want to average another set? (Y/N) ";
cin >> again;
} while (again == 'Y' || again == 'y');

return 0;
}
“do…while” - Example
#include <iostream>
using namespace std; Output
int main ()
value of a: 10
{ value of a: 11
// Local variable declaration value of a: 12
int a = 10;

// do loop execution
do {
cout << "value of a: " << a
<< endl;
a = a + 1;
} while( a < 13 );

return 0;
}
“do … while …” vs “while …”
• Almost the same
• Prefer “do … while …” when we are
guaranteed to execute loop body at least once
• Prefer “while …” if loop body may not be
executed at all
• Programmer’s choice

33

You might also like