Lecture 6 1
Lecture 6 1
While Loop
Infinite Loop
Practice Problems
Repetition Structure
We can see similar phenomenon in the practical life. e.g., in the payroll system,
few procedures such as salary generation method for regular employees
are same.
Such procedures are repeatedly applied while dealing with the employees.
So repetition is very useful structure in the programming.
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;
- And you can apply the same method for calculating sum of 20, 30,
40, 50 or even 100 whole numbers.
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.
Repetition Structure
Problem Statements
Write a program for sum of numbers by prompting(input from user) upper limit.
Write a program for product of odd number by prompting user lower and
upper limit.
Repetition Structure
while Loop Cases
The exact number of pieces of data is not know, but the last entry is a
special value, called a sentinel.
if it does not equal the sentinel, the body of the while loop
Executes.
sum = 0;
cin >> n;
while (n != 0)
{
sum = sum + n;
cin >> n;
}
cout << "The sum of the entered numbers is " << sum <<
endl;
Case 2-Sentinel Controlled Condition
The while statement executes until there are no more data items.
If the program has reached the end of the input data 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
Note. In the DOS environment, the end-of-file marker is entered using ctrl+z.
Case 4: EOF-controlled Condition
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 entered numbers is " << sum <<
endl;
Factorial Number Problem
Problem Statement
Calculate the factorial of a given
number
Solution
N(N-1)(N-2)………….3.2.1
Factorial Number Problem
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
3 - 1 digit
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 a given upper limit
separately
using forloop structure. Also draw flow chart of the program.
only one