for Statement (Sample Program)

Sunday, July 29, 2012
Let’s write a program using for loop to find the sum of the squares of the integers from 1 to n. Where n is a positive value entered by the user (i.e. Sum = 12 + 22 + 32 + ……+ n2)

The code of the program is given below:


In the program we declared three variables i, n and sum. We prompted the user to enter a positive number. We stored this number in the variable n. Then we wrote a for loop. In the initialization part, we initialized variable i with value 1 to start the counting from 1. In the condition statement we set the condition i less than or equal to n (number entered by the user) as we want to execute the loop n times. In the increment statement, we incremented the counter variable by 1. In the body of the for loop we wrote a single statement sum += i * i ;. This statement takes the square of the counter variable ( i )and adds it to the variable sum. This statement is equivalent to the statement sum = sum + ( i * i ) ; Thus in each iteration the square of the counter variable (which is increased by 1 in each iteration ) is added to the sum. Thus loop runs n times and the squares of numbers from 1 to n are summed up. After completing the for loop the cout statement is executed which displays the sum of the squares of number from 1 to n.

Following is the output when the number 5 is entered.


Tips:
  • Comments should be meaningful, explaining the task
  • Don’t forget to affect the value of loop variable in while and do-while loops
  • Make sure that the loop is not an infinite loop
  • Don’t affect the value of loop variable in the body of for loop, the for loop does this by itself in the for statement
  • Use pre and post increment/decrement operators cautiously in expressions

Increment Decrement Operators

We have seen that in while, do-while and for loop we write a statement to increase the value of a variable. For example, we used the statements like counter = counter + 1; which adds 1 to the variable counter. This increment statement is so common that it is used almost in every repetition structure (i.e. in while, do-while and for loop). The C language provides a unary operator that increases the value of its operator by 1. This operator is called increment operator and sign ++ is used for this. The statement counter = counter + 1; can be replaced with the statement

counter ++ ;


The statement counter++ adds 1 to the variable counter. Similarly the expressions i = i + 1 ; and j = j + 1 ; are equivalent to i++ ; and j++; respectively. There is also an operator -- called decrement operator. This operator decrements, the value of its operand by 1. So the statements counter = counter - 1; and j = j - 1; are equivalent to counter--; and j--; respectively.

The increment operator is further categorized as pre-increment and post-increment. Similarly, the decrement operator, as pre-decrement and post-decrement.

In pre-increment, we write the sign before the operand like ++j while in post-increment, the sign ++ is used after the operand like j++. If we are using only variable increment, pre or post increment does not matter. In this case, j++ is equivalent to ++j. The difference of pre and post increment matters when the variable is used in an expression where it is evaluated to assign a value to another variable. If we use pre-increment ( ++j ), the value of j is first increased by 1. This new value is used in the expression. If we use post increment ( j++ ),the value of j is used in the expression. After that it is increased by 1. Same is the case in pre and post decrement.

If j = 5, and we write the expression

x = ++ j ;


After the evaluation of this expression, the value of x will be 6 (as j is incremented first and then is assigned to x). The value of j will also be 6 as ++ operator increments it by 1.

If j = 5, and we write the expression

x = j++ ;


Then after the evaluation of the expression, the value of x will be 5 (as the value of j is used before increment) and the value of j will be 6.
The same phenomenon is true for the decrement operator with the difference that it decreases the value by 1. The increment and decrement operators affect the variable and update it to the new incremented or decremented value.

The operators ++ and -- are used to increment or decrement the variable by 1. There may be cases when we are incrementing or decrementing the value of a variable by a number other than 1. For example, we write counter = counter + 5; or j = j – 4;. Such assignments are very common in loops, so C provides operators to perform this task in short. These operators do two things they perform an action (addition, subtraction etc) and do some assignment.

These operators are +=, -=, *=, /= and %=. These operators are compound assignment operators. These operators assign a value to the left hand variable after performing an action (i.e. +, -, *, / and %). The use of these operators is explained by the following examples.

Let’s say we have an expression, counter = counter + 5;. The equivalent of this expression is counter += 5;. The statement counter += 5; does two tasks. At first, it adds 5 to the value of counter and then assigns this result to counter. Similarly the following expressions


can be written in equivalent short statements using the operators ( +=, -=, *=, /=, %= ) as follows


Note that there is no space between these operators. These are treated as single signs. Be careful about the operator %=. This operator assigns the remainder to the variable. These operators are alternate in short hand for an assignment statement. The use of these operators is not necessary. A programmer may use these or not. It is a matter of style.

for Statement (Sample Program)

Saturday, July 28, 2012
Let’s take an example to explain for loop. We want to write a program that prints the table of 2 on the screen.
In this program, we declare a variable counter of type int. We use this variable to multiply it by 2 with values 1 to 10. For writing the table of 2, we multiply 2 by 1, 2, 3 .. upto 10 respectively and each time display the result on screen. So we use for loop to perform the repeated multiplication.

Following is the code of the program that prints the table of 2.


This is a simple program. In the for statement, we initialize the variable counter to 1 as we want the multiplication of 2 starting from 1. In the condition clause, we set the condition counter <= 10 as we want to repeat the loop for 10 times. And in the incrementing clause, we increment the variable counter by 1. In the body of the for loop, we write a single statement with cout. This single statement involves different tasks. The portion ‘<< “2 x “’ displays the string “2 x “ on the screen. After this, the next part ‘<< counter’ will print the value of counter. The ‘<< “ = ”’ will display ‘ = ‘ and then the next part ‘<< 2 * counter’ will display the result of 2 multiply by counter and the last <<”\n” ( the new line character) will start a new line. Thus in the first iteration where the value of counter is 1, the cout statement will display the following line


2 x 1 = 2


After the execution of cout statement, the for statement will increment the counter variable by 1. Thus value of counter will be 2. Then condition will be checked which is still true. Thus the body of for loop (here the cout statement) will be executed again having the value of counter 2. So the following line will be printed.

2 x 2 = 4


The same action will be repeated 10 times with values of counter from 1 to 10. When the value of counter is 11, the condition ( counter <= 10 ) will become false and the loop will terminate. The output of the above program is as the following.






Now what will we do, if some one says us to write a table of 3, or 4 or 8 or any other number. Here comes the point of re-usability and that a program should be generic. We write a program in which a variable is used instead of a hard code number. We prompt the user to enter the number for which he wants a table. We store this number in the variable and then use it to write a table. So in our previous example, we now use a variable say number where we were using 2. We also can allow the user to enter the number of multipliers up to which he wants a table. For this, we use a variable maxMultiplier and execute the loop for maxMultiplier times by putting the condition counter <= maxMultiplier. Thus our program becomes generic which can display a table for any number and up to any multiplier. Thus, the code of our program will be as below:






The output of the program is shown as follows:


Here is a guideline for programming style. We should avoid using constant values in our calculations or in long routines. The disadvantage of this is that if we want to change that constant value later, then we have to change every occurrence of that value in the program. Thus we have to do a lot of work and there may be some places in code where we do not change that value. To avoid such situations, we can use a variable at the start and assign that constant value to it and then in the program use that variable. Thus, if we need to change the constant value, we can assign the new value to that variable and the remaining code will remain the same. So in our program where we wrote the table of 2, we can use a variable (say number) and assign it the value 2. And in cout statement we use this variable instead of constant 2. If we want that the program should display a table of 5, then we just change the value of the variable. So for good programming, use variables for constant values instead of explicit constant values.

for Statement

Let’s see what we do in a loop. In a loop, we initialize variable(s) at first. Then we set a condition for the continuation/termination of the loop. To meet the condition to terminate the loop, we affect the condition in the body of the loop. If there is a variable in the condition, the value of that variable is changed within the body of the loop. If the value of the variable is not changed, then the condition of termination of the loop will not meet and loop will become an infinite one. So there are three things in a loop structure i.e. (i) initialization, (ii) a continuation/termination condition and (iii) changing the value of the condition variable, usually the increment of the variable value.

To implement these things, C provides a loop structure known as for loop. This is the most often used structure to perform repetition tasks for a known number of repetitions. The syntax of for loop is given below.


We see that a 'for statement' consists of three parts. In initialization condition, we initialize some variable while in continuation condition, we set a condition for the continuation of the loop. In third part, we increment the value of the variable for which the termination condition is set.

Let's suppose, we have a variable counter of type int. We write for loop in our program as


This 'for loop' will print on the screen 0, 1, 2 …. 9 on separate lines (as we use endl in our cout statement). In for loop, at first, we initialize the variable counter to 0. And in the termination condition, we write counter < 10. This means that the loop will continue till value of counter is less than 10. In other words, the loop will terminate when the value of counter is equal to or greater than 10. In the third part of for statement, we write counter = counter + 1 this means that we add 1 to the existing value of counter. We call it incrementing the variable.

Now let's see how this loop executes. When the control goes to for statement first time, it sets the value of variable counter to 0, tests the condition (i.e. counter < 10). If it is true, then executes the body of the loop. In this case, it displays the value of counter which is 0 for the first execution. Then it runs the incrementing statement (i.e. counter = counter + 1 ). Thus the value of counter becomes 1. Now, the control goes to for statement and tests the condition of continuation. If it is true, then the body of the loop is again executed which displays 1 on the screen. The increment statement is again executed and control goes to for statement. The same tasks are repeated. When the value of counter becomes 10, the condition counter < 10 becomes false. Then the loop is terminated and control goes out of for loop.

The point to be noted is that, the increment statement (third part of for statement) is executed after executing the body of the loop. Thus for structure is equivalent to a while structure, in which, we write explicit statement to change (increment/decrement) the value of the condition variable after the last statement of the body. The for loop does this itself according to the increment statement in the for structure. There may be a situation where the body of for loop, like while loop, may not be executed even a single time. This may happen if the initialization value of the variable makes the condition false. The statement in the following for loop will not be executed even a single time as during first checking, the condition becomes false. So the loop terminates without executing the body of the loop.


Use of Operators

Sunday, July 1, 2012
Here are sample programs which will further explain the use of operators in programming.

Problem Statement:

Write a program that takes a four digits integer from user and shows the digits on the screen separately i.e. if user enters 7531, it displays 1,3,5,7 separately.

Solution:

Let’s first analyze the problem and find out the way how to program it.

Analysis:
First of all, we will sort the problem and find out how we can find digits of an integer. We know that when we divide a number by 10, we get the last digit of the number as remainder. For example when we divide 2415 by 10 we get 5 as remainder. Similarly 3476 divided by 10 gives the remainder 6. We will use this logic in our problem to get the digits of the number. First of all, we declare two variables for storing number and the digit. Let’s say that we have a number 1234 to show its digits separately. In our program we will use modulus operator ( % ) to get the remainder. So we get the first digit of the number 1234 by taking its modulus with 10 (i.e. 1234 % 10). This will give us the digit 4. We will show this digit on the screen by using cout statement. After this we have to find the next digit. For this we will divide the number by 10 to remove its last digit. Here for example the answer of 1234 divided by 10 is 123.4, we need only three digits and not the decimal part. In C we know that the integer division truncates the decimal part to give the result in whole number only. We will use integer division in our program and declare our variable for storing the number as int data type. We will divide the number 1234 by 10 (i.e. 1234 / 10). Thus we will get the number with remaining three digits i.e. 123. Here is a point to be noted that how can we deal with this new number (123)? There are two ways, one is that we declare a new variable of type int and assign the value of this new number to it. In this way we have to declare more variables that means more memory will be used. The second way is to reuse the same variable (where number was already stored). As we have seen earlier that we can reassign values to variables like in the statement x = x + 1, which means, add 1 to the value of x and assign this resultant value again to x. In this way we are reusing the variable x. We will do the same but use the division operator instead of addition operator according to our need. For this purpose we will write number = number / 10. After this statement we have value 123 in the variable number.

Again we will get the remainder of this number with the use of modulus operator, dividing the number by 10 (i.e. 123 % 10). Now we will get 3 and display it on the screen. To get the new number with two digits, divide the number by 10. Once again, we get the next digit of the number (i.e. 12) by using the modulus operator with 10, get the digit 2 and display it on the screen. Again get the new number by dividing it by 10 (i.e. 1). We can show it directly, as it is the last digit, or take remainder by using modulus operator with 10. In this way, we get all the digits of the number.
Now let’s write the program in C by following the analysis we have made. The complete C program for the above problem is given below. It is easy to understand as we are already familiar with the statements used in it.


The output of the program will be as following.

Problem Statement:
Write a program that takes radius of a circle from the user and calculates the diameter, circumference and area of the circle and display the result.

Solution:
In this problem we take the input (radius of a circle) from the user. So that we can use cin statement to prompt the user to enter the radius of a circle. We store this radius in a variable. We also need other variables to store diameter, circumference and area of the circle. To obtain the correct result, we declare these variables of type float, instead of int data type, as we know that the int data type stores the whole numbers only. Here in our problem the area or circumference of the circle can be in decimal values. After getting the radius we use the formulae to find the diameter, circumference and area of the circle and then display these results on the screen.

The solution of this program in coding form is given below.

A sample output of the above program is given below.

Tips:
  • Use descriptive names for variables
  • Indent the code for better readability and understanding
  • Use parenthesis for clarity and to force the order of evaluation in an expression
  • Reuse the variables for better usage of memory
  • Take care of division by zero
  • Analyze the problem properly, and then start coding (i.e. first think and then write)

For previous lesson click here: Examples of Expressions
For next lesson click here: Conditional Statements


the easiest way to learn programming
introduction to programming
Use of Operators

do-while Statement

Saturday, June 16, 2012
We have seen that there may be certain situations when the body of while loop does not execute even a single time. This occurs when the condition in while is false. In while loop, the condition is tested first and the statements in the body are executed only when this condition is true. If the condition is false, then the control goes directly to the statement after the closed brace of the while loop. So we can say that in while structure, the loop can execute zero or more times. There may be situations where we may need that some task must be performed at least once.
For example, a computer program has a character stored from a-z. It gives to user five chances or tries to guess the character. In this case, the task of guessing the character must be performed at least once. To ensure that a block of statements is executed at least once, C provides a do-while structure. The syntax of do-while structure is as under:



Here we see that the condition is tested after executing the statements of the loop body. Thus, the loop body is executed at least once and then the condition in do while statement is tested. If it is true, the execution of the loop body is repeated. In case, it proves otherwise (i.e. false), then the control goes to the statement next to the do while statement. This structure describes ‘execute the statements enclosed in braces in do clause when the condition in while clause is true.
Broadly speaking, in while loop, the condition is tested at the beginning of the loop before the body of the loop is performed. Whereas in do-while loop, the condition is tested after the loop body is performed. Therefore, in do-while loop, the body of the loop is executed at least once.

The flow chart of do-while structure is as follow:


Example

Let’s consider the example of guessing a character. We have a character in the program to be guessed by the user. Let’s call it ‘z’. The program allows five tries (chances) to the user to guess the character. We declare a variable tryNum to store the number of tries. The program prompts the user to enter a character for guessing. We store this character in a variable c.
We declare the variable c of type char. The data type char is used to store a single character. We assign a character to a variable of char type by putting the character in single quotes. Thus the assignment statement to assign a value to a char variable will be as c = ‘a’. Note that there should be a single character in single quotes. The statement like c = ‘gh’ will be a syntax error.

Here we use the do-while construct. In the do clause we prompt the user to enter a character. After getting character in variable c from user, we compare it with our character i.e ‘z’. We use if\else structure for this comparison. If the character is the same as ours then we display a message to congratulate the user else we add 1 to tryNum variable. And then in while clause, we test the condition whether tryNum is less than or equal to 5 (tryNum <= 5). If this condition is true, then the body of the do clause is repeated again. We do this only when the condition (tryNum <= 5) remains true. If it is otherwise, the control goes to the first statement after the do-while loop. If guess is matched in first or second try, then we should exit the loop. We know that the loop is terminated when the condition tryNum <= 5 becomes false, so we assign a value which is greater than 5 to tryNum after displaying the message. Now the condition in the while statement is checked. It proves false (as tryNum is greater than 5). So the control goes out of the loop. First look here the flow chart for the program.

The code of the program is given below.


There is an elegant way to exit the loop when the correct number is guessed. We change the condition in while statement to a compound condition. This condition will check whether the number of tries is less than or equal to 5 and the variable c is not equal to ‘z’. So we will write the while clause as while (tryNum <= 5 && c != ‘z’ ); Thus when a single condition in this compound condition becomes false, then the control will exit the loop. Thus we need not to assign a value greater than 5 to variable tryNum. Thus the code of the program will be as:

The output of the program is given below.


Here is another out put of the same program


For previous lesson click here: while exercises
For next lesson click here: coming soon


the easiest way to learn programming
introduction to programming
do-while Statement

while exercises

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 adequate exit.

For previous lesson click here: While Sample Program
For next lesson click here: do-while Statement


the easiest way to learn programming
introduction to programming
while exercises

While Sample Program

Problem statement:
Calculate the factorial of a given number.

Solution:
The factorial of a number N is defined as:


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.
Here is the flow chart for the factorial.



Here is the code of the program.



The output of the program is as follows:


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 adequate exit.

For previous lesson click here: While Flow Chart
For next lesson click here: while exercises


the easiest way to learn programming
introduction to programming
While Sample Program

While Flow Chart

The basic structure of while loop in structured flow chart is:


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 while structure.

So far, we have been drawing flow charts after coding the program but actually we have to draw the flow chart first and then start coding.

For previous lesson click here: Properties of while loop
For next lesson click here: While Sample Program


the easiest way to learn programming
introduction to programming
While Flow Chart

Properties 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 while block. 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. 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 while block 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. For previous lesson click here: sum of even numbers with while
For next lesson click here: While Flow Chart


the easiest way to learn programming
introduction to programming
Properties of while loop

sum of even numbers with while

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:


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:



The output of the program is:


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:




So far, we have been drawing flow charts after coding the program but actually we have to draw the flow chart first and then start coding.


Properties 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 while block. 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. 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 while block 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. For previous lesson click here: While Sample Program
For next lesson click here: Properties of while loop


the easiest way to learn programming
introduction to programming
sum of even numbers with while

While Sample Program

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:


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:


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:



Try to write the program.


For previous lesson click here: Repetition Structure (Loop)
For next lesson click here: sum of even numbers with while


the easiest way to learn programming
introduction to programming
While Sample Program

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.

Now we get the first integer i.e. 1. We add this to the sum (sum becomes 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 (sum becomes 1 + 2 = 3). Get the next integer by adding 1 to the previous integer and add it to the sum (sum becomes 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:


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 while block, 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:


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:


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.



As we have declared another variable of int data type, so the variables of same data type can be declared in one line.


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:


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:



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:


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 number first (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:


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:


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:


Putting the action statements in while construct:


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 number becomes 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 number becomes 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 number becomes 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 while construct, 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:

The output of the program is:


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.

For previous lesson click here: if/else Sample Program
For next lesson click here: While Sample Program


the easiest way to learn programming
introduction to programming
Repetition Structure (Loop)

 

introduction to programming Copyright © 2011-2012 | Powered by Blogger