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)

if/else Sample Program

Problem Statement
A shopkeeper announces a package for customers that he will give 10 % discount on all bills and if a bill amount is greater than 5000 then a discount of 15 %. Write a C program which takes amount of the bill from user and calculates the payable amount by applying the above discount criteria and display it on the screen.

Solution
In this problem we are going to make decision on the basis of the bill amount, so we will be using if statement. We declare three variables amount, discount and netPayable and initialize them. Next we prompt the user to enter the amount of the bill. After this we implement the if statement to test the amount entered by the user. As we see in the problem statement that if the amount is greater than 5000 then the discount rate is 15 % otherwise (i.e. the amount is less than or equal to 5000) the discount rate is 10 %. So we check the amount in if statement. If it is greater than 5000 then the condition is true then the if block is executed otherwise if amount is not greater than 5000 then the else block is executed.
The analysis and the flow of the program is shown by the following flow chart.


The complete program code is given below :


In the program we declared the variables as double. We do this to get the correct results (results may be in decimal points) of the calculations. Look at the statement which calculates the discount. The statement is
discount = amount * (15.0 / 100) ;
Here in the above statement we write 15.0 instead of 15. If we write here 15 then the division 15 / 100 will be evaluated as integer division and the result of division (0.15) will be truncated and we get 0 and this will result the whole calculation to zero. So it is necessary to write at least one operand in decimal form to get the correct result by division and we should also declare the variables as float or double. We do the same in the line discount = amount * (10.0 / 100);

A sample execution of the program is given below



Tips:
  • Always put the braces in an if/else structure
  • Type the beginning and ending braces before starting typing inside them
  • Indent both body statements of an if and else structure
  • Be careful while combining the conditions with logical operators
  • Use if/else structure instead of a number of single selection if statements

For previous lesson click here: Logical Operators
For next lesson click here: Repetition Structure (Loop)


the easiest way to learn programming
introduction to programming
if/else Sample Program

Logical Operators

There are many occasions when we face complex conditions to make a decision. This means that a decision depends upon more than one condition in different ways. Here we combine the conditions with AND or OR. For example, a boy can be selected in basket ball team only if he is more than 18 years old and has a height of 6 feet. In this statement a boy who wants to be selected in the basket ball team must have both the conditions fulfilled. This means that AND forces both the conditions to be true. Similarly we say that a person can be admitted to the university if he has a BCS degree OR BSC degree. In this statement, it is clear that a person will be admitted to the university if he has any one of the two degrees.
In programming we use logical operators ( && and || ) for AND and OR respectively with relational operators. These are binary operators and take two operands. These operators use logical expressions as operands, which return TRUE or FALSE.
The following table (called truth table) can be used to get the result of the && operator and || operator with possible values of their operands. It is used to explain the result obtained by the && and || operators.

Expression 1Expression 2Expression 1 && Expression 2Expression 1 || Expression 2
TrueFalsefalseTrue
TrueTruetrueTrue
FalseFalsefalseFalse
FalseTruefalseTrue

The && operator has a higher precedence than the || operator. Both operators associate from left to right. An expressions containing && or || is evaluated only until truth or falsehood is known. Thus evaluation of the expression (age > 18) && (height > 6) will stop immediately if age > 18 is false (i.e. the entire expression is false) and continue if age > 18 is true (i.e. the entire expression could still be true if the condition height > 6 is true ).

There is another logical operator that is called logical negation. The sign ! is used for this operator. This operand enables a programmer to ‘reverse’ the meaning of a condition. This is a unary operator that has only a single condition as an operand. The operator ! is placed before a condition. If the original condition (without the ! operator) is false then the ! operator before it converts it to true and the statements attached to this are executed.
Look at the following expression



Here the cout statement will be executed if the original condition (age > 18) is false because the ! operator before it reverses this false to true.

The truth table for the logical negation operator ( ! ) is given below.
Expression! Expression
truefalse
falsetrue

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


the easiest way to learn programming
introduction to programming
Logical Operators

If/else Structure

We have seen that the if structure executes its block of statement(s) only when the condition is true, otherwise the statements are skipped. The if/else structure allows the programmer to specify that a different block of statement(s) is to be executed when the condition is false. The structure of if/else selection is as follows.



Thus using this structure we can write the construct of our program as:



In this construct, the program checks the condition in if statement .If the condition is true, then the line "Amer is greater than Amara" is printed. Otherwise (if condition is not true), the statement related to else is executed and the message "Amer is younger than Amara" is printed. Here in if/else structure an important thing is that the else part is executed for all the cases (conditions) other than the case which is stated in the if condition.
And in the comparison, we know that there are three conditions i.e. first value is greater than the second value, first value is less than the second value and first value is equal to the second value. Here in the above program construct the else part competes the greater than conditions and covers both less than and equal to conditions.
Thus in the above program construct, the message "Amer is younger than Amara" is displayed even if Amer’s age is the same as Amara’s age. This is logically incorrect and so to make this correct, we should display the message "Amer is younger than or is of the same age as Amara". Now this statement describes both the cases other than the one ‘Amer is greater than Amara'.
The use of else saves us from writing different if statements to compare different conditions, in this way it cover the range of checks to complete the comparison.
If we want to state the condition "Amer is greater than or is of the same age as Amara’s" then we use the greater than or equal to operator (i.e. >=) in the if statement and less than operator ( < ) in the else statement to complete the comparison. It is very important to check all the conditions while making decisions for good, complete and logical results. Make sure that all cases are covered and there is no such case in which the program does not respond. The flow chart of our program with if/else structure will be as follow.



For previous lesson click here: IF Sample Program 1
For next lesson click here: Logical Operators


the easiest way to learn programming
introduction to programming
If/else Structure

IF Sample Program 1

Now let’s see the usage of relational operators by an example. There are two students Amer and Amara. We take their ages from the user, compare them and tell who is older?
As there are two students to be compared in terms of age, we need to declare two variables to store their ages. We declare two variables AmerAge and AmaraAge of type int. The variable names are one continuous word as we can’t use spaces in a variable name.
Here is an important point about variables declaration. We should assign an initial value (preferably 0 for integers) to variables when we declare them. This is called initialization of variables.
We can do this in one line while declaring a variable like int x = 0; This statement will declare a variable of name x with data type int and will assign a value 0 to this variable. Initializing a variable in this way is just a matter of style. You can initialize a variable on a separate line after declaring it. It is a good programming practice to initialize a variable.
Now we prompt the user to enter Amer’s age and store it into variable AmerAge. Then similarly we get Amara’s age from the user in the variable AmaraAge.
While comparing the ages, we will use the if statement to see whether Amer’s age is greater than Amara’s. We will use > (greater than) operator to compare the ages. This can be written as if ( AmerAge > AmaraAge) .
With this if statement, we write the statement cout << "Amer is greater than Amara" ; It’s a simple one line test i.e. ‘if Amer’s age is greater than Amara's’, then display the message ‘Amer is older than Amara’. Flow chart of the sample program:


The complete code of the program is given below.



In our program, we write a single statement with the if condition. This statement executes if the condition is true. If we want to execute more than one statements, then we have to enclose all these statements in curly brackets { }. This comprises a block of statements which will execute depending upon the condition. This block may contain a single statement just like in our problem. So we can write the if statement as follow.



A sample execution of the program results the following output.



Now think what happens if the condition in the if statement is not true i.e. Amer’s age is not greater than Amara’s. In this case, if the user enters Amer’s age less than Amara’s, then our program does nothing. So to check this condition, another if statement after the first if statement is required. Then our program will be as:



Now our program decides properly about the ages entered by the user.
After getting ages from the user, the if statements are tested and if statement will be executed if the condition evaluates to true.

For previous lesson click here: Flow Charting
For next lesson click here: If/else Structure


the easiest way to learn programming
introduction to programming
IF Sample Program 1

Flow Charting

There are different techniques that are used to analyze and design a program. We will use the flow chart technique. A flow chart is a pictorial representation of a program. There are labeled geometrical symbols, together with the arrows connecting one symbol with other.
A flow chart helps in correctly designing the program by visually showing the sequence of instructions to be executed. A programmer can trace and rectify the logical errors by first drawing a flow chart and then simulating it.

The flow chart for the if structure is shown in the figure below.



For previous lesson click here: Conditional Statements
For next lesson click here: IF Sample Program 1


the easiest way to learn programming
introduction to programming
Flow Charting

Conditional Statements

Tuesday, June 12, 2012
In every day life, we are often making decisions. We perform different tasks while taking decisions. For example, the statement ‘Bring one litre of milk while returning home from college, if the milk shop is open’ involves this phenomenon.
In this statement, there is an element of decision making. We bring one litre of milk if the shop is open. And if the shop is closed, we come back to home without milk.
Thus we are making a decision on the condition that the shop is open. The decision-making process is everywhere in our daily life. We see that the college gives admission to a student if he has the required percentage in his previous examination and/or in the entry test. Similarly administration of a basketball team of the college decides that the students having height more than six feet can be members of the team.
For writing interesting and useful programs, we have to develop the decision making power in them.
Now we will see what kind of decisions are in programming and how these can be used.

Every programming language provides a structure for decision making.
'C' also provides this structure. The statement used for decisions in 'C' language is known as the 'if statement'. The if statement has a simple structure. That is



We explain it as if condition is true, then execute the statement or a group of statements. Here the condition is a statement which explains the condition on which a decision will be made. We can understand it from the example that Ali can become the member of the basket ball team if he has a height more than six feet .In this case, the condition will be



We have written the condition in English language. Now let's see how we can implement this in terms of variables, operators and C statements. In the program, we will write the condition in parentheses, followed by a statement or group of statements to be executed.
Now here is the concept of block of statements. We use braces { } to make a group (block) of a number of statements. We put ‘{’ before first statement and ‘}’ after the last statement. Thus if we have to do many things after the if statement. The structure of if statement becomes as under



Note the indentation of the lines and semi-colon after each statement. Semi-colons are necessary after every C statement. The indentation is only a matter of style. It makes the code easy to read and understand from where a block starts, ends and what kind of block it is. It does not affect the logic of the program. But the braces can affect the logic. We can also write a comment line to state the purpose of code block.
Let's consider a simple example to explain the if statement. Suppose, we have ages of two students (say for the time being we have got these ages in variables). These variables are- age1 and age2. Now we say that if the age1 is greater than age2, then display the statement ‘Student 1 is older than student 2’.
The coding for this program will be as below



Here, in our code we see a new operator i.e. ‘ > ‘ (greater than) in the if statement. We need such operators (like greater than, less than, equal to etc) while making decisions. These operators are called 'relational operators'. These are almost the same relational operators we use in algebra.
Following table summarizes the relational operators.








AlgebraicIn C languageExampleMeaning
Greater than > > x > yx is greater than y
Equal to = == x == yX is equal to y
Less than < < x < yX is less than y
Greater than or equal to>=x >= yx is greater than or equal to y
Less than or equal to<=x <= yx is less than or equal to y
Not equal to!=x != yx is not equal to y

Note that there is no space between ==, >=, <= and !=. These are considered as single operators. The operator == (equal to) is different from the operator =. We know that operator = is the assignment operator which is used in assignment statement to assign a value to a variable. Don't confuse the assignment operator (=) with equal to operator (==). If we write single = in condition of if statement. For example, if we write if ( x = 2 ), the compiler will not give error. This means that it is not a syntax error. The conditional expression in if statement returns a value. In this case, x = 2 will also have some value but it will not in the form of true or false. So it will create a logical error. So be careful while using equal to condition in if statement. For previous lesson click here: Use of Operators
For next lesson click here: Flow Charting


the easiest way to learn programming
introduction to programming
Conditional Statements

 

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