Vous êtes sur la page 1sur 51

The Decision Control Structure

OPERATORS

 An operator is a symbol which helps the user to give


instruction to the computer to do a certain mathematical
or logical manipulations. Operators are used in C language
program to operate on data and variables.
 C has a rich set of operators which can be classified as
follows:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators
All the basic arithmetic operations can be carried out in
C. All the operators have almost the same meaning as in
other languages. Both unary and binary operations are
available in C language. Unary operations operate on a
singe operand, therefore the number 5 when operated
by unary – will have the value –5.
Arithmetic Operators
Operator Meaning
+ Addition or Unary Plus
– Subtraction or Unary Minus
* Multiplication
/ Division
% Modulus Operator
 Examples of arithmetic operators are:
x + y , x - y , -x + y , a * b + c , -a * b etc.,
here a, b, c, x, y are known as operands. The modulus
operator is a special operator in C language which
evaluates the remainder of the operands after division.
Integer Arithmetic
When an arithmetic operation is performed on two
whole numbers or integers than such an operation is
called as integer arithmetic. It always gives an integer
as the result. Let x = 27 and y = 5 be 2 integer numbers.
Then the integer operation leads to the following
results.
x + y = 32 , x – y = 22 , x * y = 115 , x % y = 2 , x / y = 5
In integer division the fractional part is truncated.
Floating point arithmetic

When an arithmetic operation is preformed on two real


numbers or fraction numbers such an operation is
called floating point arithmetic. The floating point
results can be truncated according to the properties
requirement. The remainder operator is not applicable
for floating point arithmetic operands.
Let x = 14.0 and y = 4.0 then
x + y = 18.0 , x – y = 10.0 , x * y = 56.0 , x / y = 3.50
Mixed mode arithmetic

When one of the operand is real and other is an integer


and if the arithmetic operation is carried out on these
2 operands then it is called as mixed mode arithmetic.
If any one operand is of real type then the result will
always be real thus 15/10.0 = 1.5
2. Relational Operators
 Often it is required to compare the relationship
between operands and bring out a decision and
program accordingly. This is when the relational
operator come into picture. C supports the following
relational operators.
OPERATOR MEANING
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
 It is required to compare the marks of 2 students, salary of 2
persons, we can compare them using relational operators.
 A simple relational expression contains only one relational
operator and takes the following form.
exp1 relational operator exp2
 Where exp1 and exp2 are expressions, which may be simple
constants, variables or combination of them. Given below is
a list of examples of relational expressions and evaluated
values.

6.5 <= 25 TRUE , -65 > 0 FALSE , 10 < 7 + 5 TRUE

Relational expressions are used in decision making


statements of C language such as if, while and for
statements to decide the course of action of a running
program.
4. Assignment Operators
 The Assignment Operator evaluates an expression on the right of
the expression and substitutes it to the value or variable on the
left of the expression.
Example: x = a + b
 Here the value of a + b is evaluated and substituted to the variable
x.
In addition, C has a set of shorthand assignment operators of the
form.
 var oper = exp;
 Here var is a variable, exp is an expression and oper is a C binary
arithmetic operator. The operator oper = is known as shorthand
assignment operator
Example: x + = 1 is same as x = x + 1
 The commonly used shorthand assignment operators are as
follows
Shorthand assignment operators
STATEMENT WITH SIMPLE STATEMENT WITH
ASSIGNMENT OPERATOR SHORTHAND OPERATOR

a=a+1 a += 1

a=a–1 a -= 1

a = a * (n+1) a *= (n+1)

a = a / (n+1) a /= (n+1)

a=a%b a %= b
The if Statement
 Syntax:
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 parentheses.
If the condition, whatever it is, is true, then the
statement is executed.
 If the condition is not true then the statement is not executed;
instead the program skips past it.

 Example:
/* Demonstration of if statement */ main( )
{
int num ;

printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ;

if ( num <= 10 )

printf ( "What an obedient servant you are !" ) ;

}
 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.

Excersice :While purchasing certain items, a discount of


10% is offered if the quantity purchased is more than
1000. If quantity and price per item are input through
the keyboard, write a program to calculate the total
expenses.
/* Calculation of total expenses */ main( )
{
int qty, dis = 0 ; float rate, tot ;
printf ( "Enter quantity and rate " ) ; scanf ( "%d %f",
&qty, &rate) ;

if ( qty > 1000 ) dis = 10 ;

tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ; printf (


"Total expenses = Rs. %f", tot ) ;

}
The if-else Statement
 The if statement by itself will execute a single
statement, or a group of statements, when the
expression following if evaluates to true.
 Can we execute one group of statements if the
expression evaluates to true and another group of
statements if the expression evaluates to false?
 Yes This is the purpose of the else statement
 Example 2.3: In a company an employee is paid as
under:
 If his basic salary is less than Rs. 1500, then HRA = 10%
of basic salary and DA = 90% of basic salary. If his
salary is either equal to or above Rs. 1500, then HRA =
Rs. 500 and DA = 98% of basic salary. If the employee's
salary is input through the keyboard write a program
to find his gross salary.
/* Calculation of gross salary */ main( )
{
float bs, gs, da, hra ;
printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ;
if ( bs < 1500 )
{
hra = bs * 10 / 100 ; da = bs * 90 / 100 ;
}
else
{
hra = 500 ;
da = bs * 98 / 100 ;
}
gs = bs + hra + da ;
printf ( "gross salary = Rs. %f", gs ) ;
}
Nested if-elses
/* A quick demo of nested if-else */ main( )
{
int i ;
printf ( "Enter either 1 or 2 " ) ; scanf ( "%d", &i ) ;
if ( i == 1 )
printf ( "You would go to heaven !" ) ;
else
{
if ( i == 2 )
printf ( "Hell was created with you in mind" ) ;
else
printf ( "How about mother earth !" ) ;
}
}
Use of Logical Operators
 C allows usage of three logical operators, namely, &&,
|| and !.
 These are to be read as ‘AND’ ‘OR’ and ‘NOT’
respectively.
 Most obviously, two of them are composed of double
symbols: || and &&. Don’t use the single symbol |
and &. These single symbols also have a meaning
 Example 2.4: The marks obtained by a student in 5
different subjects are input through the keyboard.
The student gets a
 division as per the following rules:
 Percentage above or equal to 60 - First division
 Percentage between 50 and 59 - Second division
 Percentage between 40 and 49 - Third division
 Percentage less than 40 - Fail
 Write a program to calculate the division obtained by
the student.
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5
);
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division ") ;
else
{
if ( per >= 50 )
printf ( "Second division" ) ;
else
{
if ( per >= 40 )
printf ( "Third division" ) ;
else
printf ( "Fail" ) ;
}
}
}
This leads to three disadvantages:
a) As the number of conditions go on increasing the
level of indentation also goes on increasing. As a
result the whole
program creeps to the right.
b)Care needs to be exercised to match the corresponding
ifs and elses.
c) Care needs to be exercised to match the
corresponding pair of braces.
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5
);
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division" ) ;
if ( ( per >= 50 ) && ( per < 60 ) )
printf ( "Second division" ) ;
if ( ( per >= 40 ) && ( per < 50 ) )
printf ( "Third division" ) ;
if ( per < 40 )
printf ( "Fail" ) ;
}
• from the second if statement, the && operator is
used to combine two conditions. ‘Second division’ gets
printed.
• if both the conditions evaluate to true. If one of the
conditions evaluate to false then the whole thing is
treated as false.
The else if Clause
The ! Operator
 The third logical operator is the NOT operator,
written as !.
 This operator reverses the result of the expression it
operates on.
 For example, if the expression evaluates to a non-zero
value
The Conditional Operators
 The conditional operators ? and : are sometimes
called ternary operators since they take three
arguments.
 In fact, they form a kind of foreshortened if-then-else.
Their general form is,
expression 1 ? expression 2 : expression 3
int x, y ;
scanf ( "%d", &x ) ;
y=(x>5?3:4);
This statement will store 3 in y if x is greater than 5,
otherwise it will store 4 in y.
LOOP CONTROL STRUCTURE
 This involves repeating some portion of the program
either a specified number of times or until a particular
condition I
 Using a for statement
 Using a while statement
 Using a do-while statements being satisfied.
The while Loop
The general form of while is as shown below:
initialise loop counter ;
increment loop counter ;
while ( test loop counter using a condition )
{
do this ;
and this ;
}
 The statements within the while loop would keep on
getting executed till the condition being tested
remains true.
 When the condition becomes false, the control passes
to the first statement that follows the body of the
while loop.
 The condition being tested may use relational or
logical operators
int i = 1 ;
i <= 10 )
{
"%d\n", i ) ;
main( )
{
while (
printf (
i=i+1;
}
}
The for Loop
The general form of for statement is as under:

for ( initialise counter ; test counter ; increment counter


)
{
do this ;
and this ;
and this ;
}
/* Calculation of simple interest for 3 sets of p, n and r */
main ( )
{
int p, n, count ;
float r, si ;
for ( count = 1 ; count <= 3 ; count = count + 1 )
{
printf ( "Enter values of p, n, and r " ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "Simple Interest = Rs.%f\n", si ) ;
}
}
 Let us now examine how the for statement gets
executed:
 − When the for statement is executed for the first
time, the value of count is set to an initial value 1.
 − Now the condition count <= 3 is tested. Since
count is 1 the condition is satisfied and the body of
the loop is executed for the first time.
 Upon reaching the closing brace of for, control is
sent back to the for statement, where the value of
count gets incremented by 1.
 Again the test is performed to check whether the new
value of count exceeds 3.
 If the value of count is still within the range 1 to 3,
the statements within the braces of for are executed
again.
 The body of the for loop continues to get executed
till count doesn’t exceed the final value 3.
 When count reaches the value 4 the control exits
from the loop and is transferred to the statement (if
any) immediately after the body of for
The break Statement
 We often come across situations where we want to
jump out of a loop instantly, without waiting to get
back to the conditional test.
 The keyword break allows us to do this. When
break is encountered inside any loop, control
automatically passes to the first statement after the
loop.
 A break is usually associated with an if.
Consider the following program, which
illustrates this fact.
main( )
{
int i = 1 , j = 1 ;
while ( i++ <= 100 )
{
while ( j++ <= 200 )
{
if ( j == 150 )
break ;
else
printf ( "%d %d\n", i, j ) ;
}
 In this program when j equals 150, break takes the
control outside the inner while only, since it is
placed inside the inner while
The continue Statement
 In some programming situations we want to take the
control to the beginning of the loop, bypassing the
statements inside the loop, which have not yet been
executed.
 The keyword continue allows us to do this. When
continue is encountered inside any loop, control
automatically passes to the beginning of the loop.
main( ) The output of the above
{ program would be...
int i, j ; 12
for ( i = 1 ; i <= 2 ; i++ ) 21
{
for ( j = 1 ; j <= 2 ; j++ )
{
if ( i == j )
continue ;
printf ( "\n%d %d\n", i, j ) ;
}
}
}
 Note that when the value of i equals that of j, the
continue statement takes the control to the for loop
(inner) bypassing rest of the statements pending
execution in the for loop (inner).
The do-while Loop
do main( )
{ {
this ; do
and this ; {
and this ; printf ( "Hello there \n") ;
and this ; } while ( 4 < 1 ) ;
} while ( this condition is }
true ) ;
Summary
The three type of loops available in C are for, while, and
dowhile.
A break statement takes the execution control out
of the loop.
A continue statement skips the execution of the
statements after it and takes the control to the
beginning of the loop.
A do-while loop is used to ensure that the
statements within the loop are executed at least
once.
The ++ operator increments the operand by 1,
whereas, the -- operator decrements it by 1.
The operators +=, -=, *=, /=, %= are compound
assignment operators. They modify the value of the
operand to the left of them.
Using switch main( )
switch ( integer expression ) {
{ int i = 2 ;
case constant 1 : switch ( i )
do this ; {
case constant 2 : case 1 :
do this ; printf ( "I am in case 1 \n" ) ;
case constant 3 : case 2 :
do this ; printf ( "I am in case 2 \n" ) ;
default : case 3 :
do this ; printf ( "I am in case 3 \n" ) ;
} default :
printf ( "I am in default \n" ) ;
}
}
The goto Keyword
 Avoid goto keyword! They make a C programmer’s
life miserable.
Summary
When we need to choose one among number of
alternatives, a switch statement is used.
The switch keyword is followed by an integer or an
expression that evaluates to an integer.
The case keyword is followed by an integer or a
character
constant.
The control falls through all the cases unless the break
statement is given.
The usage of the goto keyword should be avoided as
it usually violets the normal flow of execution.

Vous aimerez peut-être aussi