CS 201 Lecture No 6

Lecture Handout

Introduction to programming

Lecture No. 6

__Reading Material__

Deitel& Deitel – C++ How to Program chapter 2

2.7, 2.8, 2.9, 2.20

Summary

- Repetition Structure (Loop)
- Overflow Condition
- Sample Program 1
- Sample Program 2
- Infinite Loop
- Properties of While loop
- Flow Chart
- Sample Program 3
- Tips

Repetition Structure (Loop)

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. So repetition is very useful structure in the programming.

Let’s discuss a problem to understand it thoroughly. We have to calculate the sum of first

10 whole numbers i.e. add the numbers from 1 to 10. Following statement may be one

way to do it.

cout<< “Sum of first 10 numbers is = “ << 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;

This method is perfectly fine as the syntax is right. The answer is also correct. This

procedure can also be adopted while calculating the sum of numbers from 1 to 100. We

can write the above statement adding all the digits from 1 to 100. But this method will not

be suitable for computing the sum of numbers from 1 to 1000.The addition of a very big

number of digits will result in a very ugly and boring statement. Let’s analyze it

carefully. Our first integer is 1, is there any other way to find out what is the next integer?

Yes, we can add 1 to the integer and get the next integer which is 2. To find the next

integer (i.e. 3) we add 1 to the previous integer (i.e. 2) and get the next integer which is 3.

So whenever we have to find out the next integer, we have to add 1 to the previous

integer.

We have to calculate the sum of first 1000 integers by taking a variable sum of type int. It

is a good programming practice to initialize the variable before using it. Here, we

initialize the variable sum with zero.

int sum = 0;

Now we get the first integer i.e. 1. We add this to the sum (sumbecomes 0 + 1 = 1). Now

get the next integer which can be obtained by adding 1 to the previous integer i.e. 2 and

add it to the sum (sumbecomes 1 + 2 = 3). Get the next integer by adding 1 to the

previous integer and add it to the sum (sumbecomes 3 + 3 = 6) and so on. This way, we

get the next integer by adding 1 to the previous integer and the new integer to the sum. It

is obvious that we are repeating this procedure again and again i.e. adding 1 to the

previous integer and add this new integer to the sum. So we need some repetition

structure in the programming language. There are many looping constructs in C

Language. The repetition structure we are discussing in this lecture is 'while loop

structure'. ‘while’ is also a key word of 'C' so it cannot be used as a variable name.

While means, 'do it until the condition is true'. The use of while construct can be helpful

in repeating a set of instructions under some condition. We can also use curly braces with

while just like we used with if. If we omit to use the braces with while construct, then

only one statement after while will be repeatedly executed. For good programming

practices, always use braces with while irrespective of the number of statements in while

block. The code will also be indented inside the while block as Indentation makes the

code easy to understand.

The syntax of while construct is as under:

while ( Logical Expression ) {

statement1;

statement2;

………….

}

The logical expression contains a logical or relational operator. While this logical

expression is true, the statements will be executed repeatedly. When this logical

expression becomes false, the statements within the while block, will not be executed.

Rather the next statement in the program after whileblock, will be executed.

Let’s discuss again the same problem i.e. calculation of the sum of first 1000 integers

starting from 1. For this purpose, we need a variable to store the sum of integers and

declare a variable named sum. Always use the self explanatory variable names. The

declaration of the variable sum in this case is:

int sum = 0;

The above statement has performed two tasks i.e. it declared the variable sum of type int

and also initialized it with zero. As it is good programming practice to initialize all the

variables when declared, the above statement can be written as:

int sum;

sum = 0;

Here we need a variable to store numbers. So we declare a variable number of type int.

This variable will be used to store integers.

int number;

As we have declared another variable of int data type, so the variables of same data type

can be declared in one line.

int sum, number;

Going back to our problem, we need to sum up all the integers from 1 to 1000. Our first

integer is 1. The variable number is to be used to store integers, so we will initialize it by

1 as our first integer is 1:

number = 1;

Now we have two variables- sum and number. That means we have two memory

locations labeled as sum and number which will be used to store sum of integers and

integers respectively. In the variable sum, we have to add all the integers from 1 to 1000.

So we will add the value of variable number into variable sum, till the time the value of

number becomes 1000. So when the value of number becomes 1000, we will stop adding

integers into sum. It will become the condition of our while loop. We can say sum the

integers until integer becomes 1000. In C language, this condition can be written as:

while ( number <= 1000 ) {

………Action ………

}

The above condition means, 'perform the action until the number is 1000 or less than

1000'. What will be the Action? Add the number, the value of number is 1 initially, into

sum. This is a very simple statement:

sum = sum + number;

Let’s analyze the above statement carefully. We did not write sum = number; as this

statement will replace the contents of sum and the previous value of sum will be wasted

as this is an assignment statement. What we did? We added the contents of sum and

contents of numberfirst (i.e. 0 + 1) and then stored the result of this (i.e. 1) to the sum.

Now we need to generate next integer and add it to the sum. How can we get the next

integer? Just by adding 1 to the integer, we will get the next integer. In ‘C’, we will write

it as:

number = number + 1;

Similarly in the above statement, we get the original contents of number (i.e. 1). Add 1 to

them and then store the result (i.e. 2) into the number. Now we need to add this new

number into sum:

sum = sum + number;

We add the contents of sum (i.e. 1) to the contents of number (i.e. 1) and then store the

result (i.e. 2) to the sum. Again we need to get the next integer which can be obtained by

adding 1 to the number. In other words, our action consists of only two statements i.e.

add the number to the sum and get the next integer. So our action statements will be:

sum = sum + number;

number = number + 1;

Putting the action statements in while construct:

while ( number <= 1000 ) {

sum = sum + number;

number = number + 1;

}

Let's analyze the above while loop. Initially the contents of number is 1. The condition in

while loop (i.e. number <= 1000) will be evaluated as true, contents of sum and contents

of number will be added and the result will be stored into sum. Now 1 will be added to

the contents of number and numberbecomes 2. Again the condition in while loop will be

evaluated as true and the contents of sum will be added to the contents of number .The

result will be stored into sum. Next 1 will be added to the contents of number and number

becomes 3 and so on. When numberbecomes 1000, the condition in while loop evaluates

to be true, as we have used <= (less than or equal to) in the condition. The contents of

sum will be added to the contents of number(i.e. 1000) and the result will be stored into

the sum. Next 1 will be added to the contents of number and numberbecomes 1001. Now

the condition in while loop is evaluated to false, as number is no more less than or equal

to 1000 (i.e. number has become 1001). When the condition of while loop becomes false,

loop is terminated. The control of the program will go to the next statement following the

ending brace of the while construct. After the whileconstruct, we can display the result

using the cout statement.

cout << “ The sum of first 1000 integers starting from 1 is “ << sum;

The complete code of the program is as follows:

/* This program calculate the sum of first 1000 integers */

#include <iostream.h>

main()

{

//declaration of variables

int sum__,__number; //Initialization of the variables

sum = 0;

number = 1;

// using the while loop to find out the sum of first 1000 integers starting from 1

while(number <= 1000)

{

// Adding the integer to the contents of sum

sum = sum + number;

// Generate the next integer by adding 1 to the integer

number = number + 1;

}

cout << "The sum of first 1000 integers starting from 1 is " << sum;

}

The output of the program is:

The sum of first 1000 integers starting from 1 is 500500

While construct is a very elegant and powerful construct. We have seen that it is very

easy to sum first 1000 integers just with three statements. Suppose we have to calculate

the sum of first 20000 integers. How can we do that? We just have to change the

condition in the while loop (i.e. number <= 20000).

Overflow Condition:

We can change this condition to 10000 or even more. Just try some more numbers. How

far can you go with the limit? We know that integers are allocated a fixed space in

memory (i.e. 32 bits in most PCs) and we can not store a number which requires more

bits than integer, into a variable of data type, int. If the sum of integers becomes larger

than this limit (i.e. sum of integers becomes larger than 32 bits can store), two things can

happen here. The program will give an error during execution, compiler can not detect

such errors. These errors are known as run time errors. The second thing is that 32 bits of

the result will be stored and extra bits will be wasted, so our result will not be correct as

we have wasted the information. This is called overflow. When we try to store larger

information in, than a data type can store, overflow condition occurs. When overflow

condition occurs either a run-time error is generated or wrong value is stored.

Sample Program 1:

To calculate the sum of 2000 integers, we will change the program (i.e. the while

condition) in the editor and compile it and run it again. If we need to calculate the sum of

first 5000 integers, we will change the program again in the editor and compile and run it

again. We are doing this work again in a loop. Change the program in the editor, compile,

execute it, again change the program, compile and execute it and so on. Are we doing this

in a loop? We can make our program more intelligent so that we don’t need to change the

condition every time. We can modify the condition as:

int upperLimit;

while (number <= upperLimit)

where upperLimit is a variable of data type int. When the value of upperLimit is 1000,

the program will calculate the sum of first 1000 integers. When the value of upperLimit is

5000, the program will calculate the sum of first 5000 integers. Now we can make it re-

usable and more effective by requesting the user to enter the value for upper limit:

cout << “Please enter the upper limit for which you want the sum ”;

cin >> upperLimit;

We don’t have to change our program every time when the limit changes. For the sum of

integers, this program has become generic. We can calculate the sum of any number of

integers without changing the program. To make the display statement more

understandable, we can change our cout statement as:

cout << “ The sum of first “ << upperLimit << “ integers is “ << sum;

Sample Program 2:

Problem statement:

Calculate the sum of even numbers for a given upper limit of integers.

Solution:

We analyze the problem and know that while statement will be used. We need to sum

even numbers only. How can we decide that a number is even or not? We know that the

number that is divisible by 2 is an even number. How can we do this in C language? We

can say that if a number is divisible by 2, it means its remainder is zero, when divided by

2. To get a remainder we can use C’s modulus operator i.e. %. We can say that for a

number if the expression (number % 2) results in zero, the number is even. Putting this in

a conditional statement:

If ( ( number % 2) == 0 )

The above conditional statement becomes true, when the number is even and false when

the number is odd (A number is either even or odd).

The complete code of the program is as follows:

/* This program calculates sum of even numbers for a given upper limit of

integers */

#include <iostream.h>

main()

{

//declaration of variables

int sum, number, upperLimit;

sum = 0;

number = 1;

// Prompt the user to enter upper limit of integers

cout << “Please enter the upper limit for which you want the sum ” ;

cin >> upperLimit;

// using the while loop to find out the sum of first 1000 integers starting from 1

while(number <= upperLimit)

{

// Adding the even integer to the contents of sum

if ( ( number % 2 ) == 0 )

{

sum = sum + number;

}

// Generate the next integer by adding 1 to the integer

number = number + 1;

}

cout << "The sum of even numbers of first “ << upperLimit << “ integers starting

from 1 is " << sum;

}

The output of the program is:

Please enter the upper limit for which you want the sum 10

The sum of even numbers of first 10 integers starting from 1 is 30

Suppose if we don’t have modulus operator in the C language. Is there any other way to

find out the even numbers? We know that in C integer division gives the integer result

and the decimal portion is truncated. So the expression (2 * (number / 2)) gives the

number as a result, if the number is even only. So we can change our condition in if

statement as:

if ( ( 2 * ( number /2 ) ) == number )

Infinite Loop:

Consider the condition in the while structure that is (number <= upperLimit) and in the

while block the value of number is changing (number = number + 1) to ensure that the

condition is tested again next time. If it is true, the whileblock is executed and so on. So

in the while block statements, the variable used in condition must change its value so that

we have some definite number of repetitions. What will happen if we do not write the

statement number = number + 1; in our program? The value of number will not change,

so the condition in the while loop will be true always and the loop will be executed

forever. Such loops in which the condition is always true are known as infinite loops as

there are infinite repetitions in it.

Property of while loop:

In the above example, if the user enters 0, as the value for upper limit. In the while

condition we test (number <= upperLimit) i.e. number is less than or equal to upperLimit

( 0 ), this test return false. The control of the program will go to the next statement after

the whileblock. The statements in while structure will not be executed even for a single

time. So the property of while loop is that it may execute zero or more time.

The while loop is terminated, when the condition is tested as false. Make sure that the

loop test has an adequate exit. Always use braces for the loop structure. If you forget to

put the braces, only one statement after the while statement is considered in the while

block.

Flow Chart:

At first, we will draw a rectangle and write while in it. Then draw a line to its right and

use the decision symbol i.e. diamond diagram. Write the loop condition in the diamond

and draw a line down to diamond which represents the flow when the decision is true. All

the repeated processes are drawn here using rectangles. Then a line is drawn from the last

process going back to the while and decision connection line. We have a line on the right

side of diamond which is the exit of while loop. The while loop terminates, when the loop

condition evaluates to false and the control gets out of whilestructure.

Here is the flow chart for sample program 2:

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

By looking at the problem, we can see that there is a repetition of multiplication of

numbers. A loop is needed to write a program to solve a factorial of a number. Let's think

in terms of writing a generic program to calculate the factorial so that we can get the

factorial of any number. We have to multiply the number with the next decremented

number until the number becomes 1. So the value of number will decrease by 1 in each

repetition. factorial = 1;

number = 1;

// Prompt the user to enter upper limit of integers

cout << “Please enter the number for factorial ” ;

cin >> number;

// using the while loop to find out the factorial

while(number > 1)

{

factorial = factorial * number;

number = number - 1;

}

cout << "The factorial is “ << factorial;

}

Exercise:

1) Calculate the sum of odd integers for a given upper limit. Also draw flow chart of

the program.

2) 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.

Tips

• Always use the self explanatory variable names

• Practice a lot. Practice makes a man perfect

• While loop may execute zero or more time

• Make sure that loop test (condition) has an acceptable exit.

Here is the code of the program.

/*This program calculates the factorial of a given number.*/

#include <iostream.h>

main()

{

//declaration of variables

int factorial, number;

__//Initialization of the variables__