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

 

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