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

Lecture 8

The document discusses the concept of repetition structures, specifically loops, in programming using C++. It covers various types of loops such as while loops, counter-controlled loops, infinite loops, and sentinel-controlled loops, along with examples and problem statements for practice. The lecture emphasizes the importance of loops in executing repetitive tasks efficiently within programs.
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)
2 views40 pages

Lecture 8

The document discusses the concept of repetition structures, specifically loops, in programming using C++. It covers various types of loops such as while loops, counter-controlled loops, infinite loops, and sentinel-controlled loops, along with examples and problem statements for practice. The lecture emphasizes the importance of loops in executing repetitive tasks efficiently within programs.
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/ 40

Programming Fundamental

Instructor Name: Mohabbat Ali


Lecture-8
Today’s Lecture

 Repetition Structure (Loops)

 Analyzing Repetition Structure Problem

 While Loop

 Counter Control Loop

 Infinite Loop

 While Loop Cases

 Practice Problems

2
Repetition Structure

 Programs are not limited to a linear sequence of statements.

 During its process, a program may repeat segments of code, or take


decisions and bifurcate.

 To add a list of numbers a variable for each number and one for the total
would need to be declared. For a different number of values, recoding
would be required. .

 For that purpose, C++ provides flow control statements that serve to
specify what has to be done by our program, when, and under which
circumstances.

 C++ has three repetition structures that repeat statements over and over
until certain conditions are met
3
Repetition Structure

 In our day to day life, most of the things are repeated.

 Days and nights repeat themselves 30 times a month.

 Four seasons replace each other every year.

 We can see similar phenomenon in the practical life. For example, in the
payroll system, some procedures are same for all the employees.

 These are repeatedly applied while dealing with the employees.

4
Repetition Structure

 So repetition is very useful structure in the programming.

 Programming languages provide various control structures that allow for


more complicated execution paths.

What are Loops?


 A Repetition Structure (loop) statement allows us to execute a statement or
group of statements multiple times

 Loops repeat a statement a certain number of times, or while a condition


is fulfilled.

5
Repetition Structure

Problem Statement
 Print the sum of first 10 whole numbers.

Solution
 Following statement may be the one way to do it

cout<<“Sum of First 10 Whole


Number
is:”<<1+2+3+4+5+6+7+8+9+10;
This method is perfectly fine as the syntax is correct. And you can apply the
same method for calculating sum of 20,30,40,50 or even 100 whole
numbers.

What if you have to calculate sum of first 1000 numbers or


more?
6
Repetition Structure

Analyze the Problem


 We have to calculate sum of first 1000 numbers
 We will start from 1 and end at 1000. so our first integer is 1
 How will you find the next integer?
 You have to simply add 1 to the integer and find the next which is
2
 To Find the next integer what you need to do?
 You have to simply add 1 to the previous integer (2) and find
the next which is 3
 So whenever we have to find out the next integer, we have to add 1 to the
previous integer.

7
Repetition Structure

Solution of Problem
 We have to calculate the sum of first 100 numbers.
 What you need to store sum value?
 We will take a variable sum of type int
 Initialize the variable with some valid value.
 What would be that valid value?
int sum=0;
 For sum always initialize with zero
 For product always initialize with one
 Start with 1 and add it to sum (sum would become 0+1=1)
 Get next integer by adding 1 to previous integer i.e. 2 and add it to
sum (sum would become 1+2=3)
 Repeat previous step until you reach 100

8
Repetition Structure

Solution of Problem
 Have you noticed any thing in the solution different?

?
 We are adding 1 to previous integer and the new integer to sum and we are
repeating this procedure again and again.
 This is what we call as REPETITION .
 C++ provides many looping constructs
 We will start with while loop structure

9
Repetition Structure

While Loop Structure


 A while loop statement repeatedly executes a target statement as long as a
given condition is true.
 Syntax of While Loop is
while(condition)
{
statement(s);
}
 Here, statement(s) may
be a single statement or
a block of statements.
 The condition may be any expression, and true is any non-zero value. The
loop iterates while the condition is true.
 When the condition becomes false, program control passes to the line
immediately following the loop.
10
Repetition Structure

While Loop Structure


 In C++, while is a reserved word.
 The expression acts as a decision maker. It is called the loop condition.
 The statement can be either a simple or compound statement. It is called
the body of the loop.

Explanations:
(Step 1) If logical Expression evaluates to true, the statement executes.
(Step 2) The logical Expression is reevaluated. The body of the loop
continues to execute until the logical expression is false.

11
Repetition Structure

12
Repetition Structure

using namespace std;


#include<iostream>

main()
{
int sum, number;
sum = 0;
number = 1;

while(number
<= 100)
{
sum = sum + number;
number = number +
1;
}

cout << "The sum of first 100 integers


13
starting from 1 is " << sum;
Repetition Structure

Counter Control Repetition


 The example code on previous slides prints sum of first 100 numbers

 The declaration at start names the control variable (number), declares it to


be an integer, reserves space for it in memory and sets it to an initial value
of 1.
 Declarations that require initialization are, in effect, executable
statements.
 The declaration and initialization of number also could have been
accomplished with the statement

int number=1;
 We use both methods of initialization
14
Repetition Structure

Counter Control Repetition


 The statement

number = number + 1;
increments the loop counter by 1 each time the loop's body is performed
 The statement

sum = sum + number;


adds next number to previous value of sum
 The loop-continuation condition in the while statement determines
whether the value of the control variable is less than or equal to 100
(the final value for which the condition is TRUE).

15
Repetition Structure

Counter Control Repetition


 The body of this while executes even when the control variable is 100. The
loop terminates when the control variable is greater than 100 (i.e., when
number becomes 101).
 The while condition can be made more concise by initializing number to 0
and by replacing the while statement with
while ( ++number <=
100 ) sum=sum + number;
 By using ++ in condition we will no longer required to use
statement number=number+1 to increment value of number.
Leave more discussion on ++ for upcoming lectures.

16
Repetition Structure

Infinite Loop
 A loop becomes infinite loop if a condition never becomes false.
 Simply if the loop increment statement

number=number+1;
Changes to

number=number-1;
 The loop will become infinite, because the loop condition will never be
false. It means the value of number will always remain less than the
upperlimit.

17
Repetition Structure

Problem Statements
 Write a program for sum of numbers by prompting upper limit

 Write a program for sum of numbers by prompting lower limit

 Write a program for sum of numbers by prompting upper and lower


limit

18
While Loop Cases

Case 1: Counter-controlled while loop

Case Sentinel Controlled While Loop


2:
Case 3: Flag-controlled while loops

Case EOF-controlled while loop


4:

19
Case 1- Counter-Controlled While loop

 Infinite loop - A loop that continues to execute endlessly.

 An infinite loop just never ends - loops and loops forever, because the
stopping condition is never met.

 Case 1: Counter-controlled while loop

 The exact number of pieces of data is known – for example it is N

 The counter is initialized to 0, then is evaluated to be <= N, then


incremented in the body of the loop.

20
Case 1- Counter-Controlled While loop

Example:
int i, sum;
sum = 0;
i = 1;

while (i
<= 100)
{
sum = sum + i;
i=i+1;
}
cout << "The sum
of the first 100
numbers is " <<
sum << endl;

21
Case 2-Sentinel Controlled While Loop

Case 2: Sentinel-controlled while loop


 The exact number of pieces of data is not know, but the last entry is a
special value, called a sentinel

 The first item is read before the while statement


if it does not equal the sentinel, the body of the while statement
executes

 Each additional item is read within the while statement.

22
Case 2-Sentinel Controlled While Loop

Example
int N, sum;
cout << "Enter the numbers to be added (for a sentinel enter 0):" <<
endl; sum = 0;
cin >> N;
while (N !=
0)
{
sum = sum + N;
cin >> N;
}
23
cout << "The
Case 2-Sentinel Controlled While Loop

Telephone Digit Example


Write a program reads the letter codes A to Z and prints the corresponding
telephone digit. Program will terminate when user press # button.

24
int main() case 'C':
{ cout << "2" <<endl;
char letter; break;
cout << "Program to convert uppercase case 'D':
\n letters to their corresponding \n case 'E':
telephone digits. \n To stop the case 'F':
program enter #." cout << "3" << endl;
<< endl; break;
cout << "Enter a letter: "; case 'G':
cin >> letter; case 'H':
cout << endl; case 'I':
while (letter != '#') cout << "4" << endl;
{ break;
cout << "The letter you case 'J':
entered is: " case 'K':
<< letter << endl; case 'L':
cout << "The corresponding cout << "5" << endl;
telephone
\n digit is: ";
if (letter >= 'A' && letter <= 'Z') break;
switch (letter) case 'M':
{ case 'N':
case 'A': case 'O':
case 'B': cout << "6" << endl;
break;
case 'P': else
case 'Q': cout << "Invalid input." <<
case 'R': endl;
case 'S': cout << "\n Enter another
cout << "7" << endl; uppercase "
break; << "letter to find its "
case 'T': << "corresponding telephone
case 'U': digit."
case 'V': << endl;
cout << "8" << endl; cout << "To stop the program
break; enter #."
case 'W': << endl;
case 'X': cout << "Enter a letter: ";
case 'Y': cin >> letter;
case 'Z': cout << endl;
cout << "9" << endl; }
} Getch();
}
Case-3 Flag-controlled while loops

Case 3: Flag-controlled while loops


 Uses a boolean variable to control the loop

 the boolean variable is set to either true or false

 While the expression evaluates to true, the loop statement continues

 The Boolean variable must be set/reset within the while statement.

28
Number Guessing Game

 Generate a random number between 0 and 1000.


If the user guesses the number correctly, the program

outputs an appropriate message. Otherwise, the program


checks whether the guessed number is less than the
random number. And display message accordingly.
uses the function rand of the header file cstdlib to

generate a random number.


 rand()
 returns an int value
using namespace std;
#include<iostream>
#include <conio.h>
#include <cstdlib>
main()
{
int
i=rand();
cout<<i;
getch();
}
Number Guessing Game
To convert it to an integer greater than or equal to 0 and
less than 100.
rand() % 100
It is possible that every time you run your program, the
function rand gives the same random number. In this case,
you can use the function time, of the header file ctime, to
include the time. The function time returns time as a long
value. The following expression uses both the functions
rand and time to generate a random integer greater
than or equal to 0 and less than 100:
(rand() + time(0)) % 100;
#include <iostream > if (guess == num)
#include <cstdlib > {
#include <conio.h > cout << "You guessed the correct "
<< "number." << endl;
using namespace std;
done = true;
int main()
}
{ else
int num; if (guess < num)
int guess; cout << "Your guess is
bool done; lower "
num = (rand() + time(0)) % << "than the number.\
100; done = false; n"
while (!done) << "Guess again!" << endl;
else
{
cout << "Your guess is
cout << "Enter an integer
higher "
greater" << "than the number.\n"
<< " than or equal to 0 and " << "Guess again!" << endl;
<< "less than 100: " }
<<endl; cin >> guess; getch();
cout << endl; }
Case 4: EOF-controlled while loop

Case 4: EOF-controlled while loop


 The while statement executes until there are no more data items

 If the program has reached the end of the input data or enters into the fail
state, the input stream variable returns false; in other cases, the input stream
variable returns true

 The first item is read before the while statement and if the input stream
variable is true, the while statement is entered; additional items are read
within the while statement.

 Note. In the D O S environment, the end-of-file marker is entered using ctrl+z.

33
Case 4: EOF-controlled while loop

Case 4: EOF-controlled while loop


 Until now, we have used an input stream variable, such as cin, and the
extraction operator, >>, to read and store data into variables. However, the
input stream variable can also return a value after reading data.

 If the program has reached the end of the input data, the input
stream variable returns the logical value false

34
Case 4: EOF-controlled while loop

Example
int N, sum;
cout << "Enter the numbers to be added (to end enter CTRL+Z):" <<
endl; sum = 0;
cin >> N;
while (cin)
{
sum = sum + N;
cin >> N;
}

cout << "The


sum of the 35
Factorial Number Problem

Problem Statement
Calculate the factorial of a given number

Solution

The factorial of a number N is defined as:

N(N-1)(N-2)………….3.2.1

36
Factorial Number Problem

37
Practice Problems

 Problem-1
Write a program that determine whether given number is prime or not?
(without using break statement)
 Problem-2
Write a program for Counting Digits and displaying their total count at the
end of the program.

 8713105 - 7 digits
 156 - 3 digits
 - 1 digit
 Problem-3
 Write a program of Euclid’s for gcd. Read the properties first and then start
your coding.
 Properties
1. gcd(a,a)=a
2. If a > b, then gcd(a,b) = gcd(a‐b,b)

38
Repetition Structure

Home Activities
 Calculate the sum of odd integers for a given upper limit. Also draw flow
chart of the program.
 Calculate the sum of even and odd integers separately for a given upper limit
using only one loop structure. Also draw flow chart of the program.
 Find the Factorial for the number input by the user.
 Flow Chart Must be practiced at home

39
40

You might also like