Lecture-7

Transcription

Lecture-7
Programming Fundamental
Instructor Name:
Lecture-7
Today’s Lecture
 Repetition Structure (Loops)
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
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?
7
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.
8
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
9
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
10
Repetition Structure
While Loop Structure
 A while loop statement repeatedly executes a target statement as long as a
given condition is true.
Sysntax 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.
11
·
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.
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 starting from 1 is " << sum;
}
14
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
15
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).
16
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.
17
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.
18
Problem
• Write a program for sum of numbers by prompting upper
limit
• Write a program for sum of even number by prompting upper
limit
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.
21
While loop Cases
Case 1: Counter-controlled while loop
Case 2:Sentinel Controlled While Loop
Case 3:Flag-controlled while loops
Case 4: EOF-controlled while loop
Case 1- Counter-controlled while loop
Infinite loop - a loop that continues to execute endlessly is called an.
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.
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;
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.
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;
}
cout << "The sum of the entered numbers is " << sum <<
endl;
Telephone Digits
Write a program reads the letter codes A to Z
and prints the corresponding telephone digit.
Program will terminate when user press # button.
int main()
{
char letter;
cout << "Program to convert uppercase
\n letters to their corresponding \n
telephone digits. \n To stop the
program enter #."
<< endl;
cout << "Enter a letter: ";
cin >> letter;
cout << endl;
while (letter != '#')
{
cout << "The letter you entered is: "
<< letter << endl;
cout << "The corresponding telephone
\n digit is: ";
if (letter >= 'A' && letter <= 'Z')
switch (letter)
{
case 'A':
case 'B':
case 'C':
cout << "2"
break;
case 'D':
case 'E':
case 'F':
cout << "3"
break;
case 'G':
case 'H':
case 'I':
cout << "4"
break;
case 'J':
case 'K':
case 'L':
cout << "5"
break;
case 'M':
case 'N':
case 'O':
cout << "6"
break;
<<endl;
<< endl;
<< endl;
<< endl;
<< endl;
case 'P':
case 'Q':
case 'R':
case 'S':
cout << "7" << endl;
break;
case 'T':
case 'U':
case 'V':
cout << "8" << endl;
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
cout << "9" << endl;
}
else
cout << "Invalid input." <<
endl;
cout << "\n Enter another
uppercase "
<< "letter to find its "
<< "corresponding telephone
digit."
<< endl;
cout << "To stop the program
enter #."
<< endl;
cout << "Enter a letter: ";
cin >> letter;
cout << endl;
}
Getch();
}
Case-3Flag-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.
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 >
#include <cstdlib >
#include <conio.h >
using namespace std;
int main()
{
int num;
int guess;
bool done;
num = (rand() + time(0)) % 100;
done = false;
while (!done)
{
cout << "Enter an integer greater"
<< " than or equal to 0 and "
<< "less than 100: " <<endl;
cin >> guess;
cout << endl;
if (guess == num)
{
cout << "You guessed the correct "
<< "number." << endl;
done = true;
}
else
if (guess < num)
cout << "Your guess is lower "
<< "than the number.\n"
<< "Guess again!" << endl;
else
cout << "Your guess is higher "
<< "than the number.\n"
<< "Guess again!" << endl;
}
getch();
}
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 DOS environment, the end-of-file marker is
entered using ctrl+z.
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
Case 4: EOF-controlled while loop
Example:
int N, sum;
cout << "Enter the numbers to be added (for end enter ctrl+z):" << endl;
sum = 0;
cin >> N;
while (cin)
{
sum = sum + N;
cin >> N;
}
cout << "The sum of the entered numbers is " << sum << endl;
Sample Program 3
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
Practice Problem
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)
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
42
43