Introduction To Decisionmaking And Branching in C Language
Posted by
Ravi Kumar at Wednesday, August 31, 2011
Share this post:
|
C Language must be able to perform different sets
of actions depending on the circumstances. A C program is a
set of statements which are normally executed sequentially n
the order in which they appear. This happens when no options
or no repetitions of certain calculations are necessary.
However,in practice, we have a number of situations where we
may have to change the order of execution of statements based
on certain conditions,repeat a group of statements until
certain specified conditions are met. This involves a kind of
decision making to see whether a particular condition has
occurred or not and then direct the computer to execute certain
statements accordingly.
C has 4 decision making instructions, They are:
1. If -Else Statement
2. Switch Statement
3. Conditional Operator Statement
4. Goto Statement.
The IF Statement:
The IF Statement is a powerful decision
making statement and is used to control the flow of execution
of statements.
The General form of IF statement is look like this:
if(This condition is true)
execute this statement;
The keyword 'IF' tells the compiler that what follows
is a decision control instruction.The condition following the
keyword 'If' is always enclosed within a pair of Parenthesis.
It allows the computer to evaluate the expression
first and then depending on whether the value of the
expression (relation or condition) is 'TRUE' (non-zero)
or FALSE (zero),it transfers the control to a particular
statement. This point of program has two paths to follow
one for the TRUE condition and other is for FALSE condition.
As a general rule, we express a condition using 'C'
relational operators, the following table shows how they are
evaluated:
Hierarchy of operators:
Operator Type
! Logical NOT
*,/,% Arithmetic and Modulus
+, - Arithmetic
<>,<=,>= Relational
==,!= Relational
&& Logical AND
|| Logical OR
= Assignment
Demonstration of "IF" statement
Example:1
main()
{
int num;
printf("Enter a number less than 10");
scanf("%d",&num);
if(num <= 10)
printf(" How nice you are");
}
Description:
On execution of this program, if you type a number less
than or equal to 10, you get a message on the screen through
printf(). If you type some other number the program doesn't
do anything.