We need a mechanism to compare things to take any decision. This involves using some operatios called Relational Operators. We have fundamental operators to compare two values.
- < Less than
- > Greater than
- == Equal to
- <= Less than or equal to
- >= Greater than or equal to
- != Not equal to
These operators compare two values and return true or false after comparison. We can use the Relational Operators to compare values of any basic data type, so all we need is to modify the behavior of the program.
The decision control structure in C can be implemented in C using:
- The if statement
- The if – else statement
- The conditional operators
The if statement by itself will execute a single statement or a group of statements when the condition following if is true
If the condition is false then a group of statements can be executed using else statement
The simple example of an if statement is:
if(varName == 20)
printf ("Value of the variable is 20");
We can use the block to specify the statements to pre executed if the given condition is true
if(varName == 20){ printf ("Value of the variable is 20");
printf ("Print what ever you want!!!");
}
These are three methods by way of which we can repeat a part of a program. They are:
- Using a for statement
- Using a while statement
- Using a do-while statement
The for statement is started with the keyword for . There are three expressions which appear with in a for statement.
- Initializing Expression
- Test Expression
- Increment Expression
It has the following standard form.
for (int i=0;i<= min; i++)
ans += i;
The while loop continues untill the specified condition is true. The general form of while loop is
while(condition)
loop statement
The do-while loop is similar to the while loop in that the loop continues as long as the specified loop condition remains true. The main difference is that the condition is checked at the end of the do-while statement. So do-while loop is always executed at least once. Its general form is
do{
loop statement
}while(condition)