Saturday, 5 October 2013

Decision Control Statements in C

DECISION CONTROL STATEMENTS

1. if Statement
2. if...else Statement
3. elseif Ladder
4. switch Statement
5. Conditional Operator

1.     if Statement - The if statement is a powerful decision making statement and is used to control the flow of execution of statements. The syntax and flowchart is shown below:

 

Syntax:     
            if (test expression)

{

    statement-block;

}

statement x;

 


·         The statement block may be a single statement or a group of statements.

·         The test expression may be a relational expression or logical expression.

·         If the test expression is true (i.e. it returns a nonzero value or 1) the statement-block will be executed, otherwise the statement block be skipped and execution will jump to the statement-x.

·         If condition is true both statement-block and statement-x are executed in sequence.

·         If there are only one statement in statement block then braces are not necessary otherwise these are necessary.

·         The indentation does not affect the logic of a program; it only enhance to increase the clarity of the program.

·         There can be any valid C statement inside if. It can be another if statement. It is called nesting of if.

 

2.     if … else Statement – With the if statement we can execute a group of statement when the condition is true but if condition is false we cannot execute a group of statements. It is possible with if… else statement. The syntax and flowchart is shown below:

Syntax:                                                                          


if (test expression)

{

     True block statement(s);

}

else

{

     False block statements(s);

}

Statement-x;

 

·         If the test expression is true then true-block stmt. will be executed, otherwise, false-block statement will be executed.

·         In either case, either true block or false block will be executed, not both.

·         Nesting of if-else statement – It is perfectly alright if we write an entire if – else construct withing, either the bosy of if statement or the body of   else statement. This is called ‘nesting’ of ifs.

 

3.     The else if Ladder - There is another way of putting ifs together when multipath decision are involved. A multipath decision is a chain of ifs in which the statement associated with each else is an if. It takes the following general form:

if (condition 1)

{   

statement block 1   

}

elseif (condition 2)

{   

statement block 2   

}

elseif (condition n)

{    

statement n;          

}

else

default-statement

 

statement-x

 

This construct is known as the else if ladder. The conditions are evaluated from the top (of the Ladder), downwards. As soon as a true condition is found, the statements associated with it are executed and the control is transferred to the statement-x (skipping the rest of the ladder).

 

When all the n conditions become false, then the final else containing the default-statement will be executed.

 

Example:
………..
If (code ==1)
    colour=”RED”;
else if (code==2)
    colour=”WHITE”;
else if (code==3)
    colour=”YELLOW”;
 else
    colour=”GREEN”;
     ……….
 

4.     switch Statement – 

 

The control statement which allows us to make a decision ffrom the number of choice is called a switch, or more correctly a switch-case-default, since these three keywords to together to make up the control statement. They most often appear as follows:

 

Syntax:                                                                            


switch (integer expression) 
{

     case 1:

                statements 1;

                break;

     case 2:

                statements2;

                break;

     ………….

     …………

     default:

          default-statement;

}

 

·         The integer expression following the keyword switch is any C expression that will yield an integer value. It could be and integer constant like 1, 2, 3 … or character constant ‘a’, ‘y’, ‘N’ or an expression that evaluate to an integer. Float value is not allowed in switch statement.

·         Which case statement will be satisfied by the value of switch that will be executed and after the execution the break statement exists the loop from the switch.

·         switch executes the case where the match is found and all the subsequent cases and the default as well.

·         There is no need of the default statement.

·         It is not necessary that we put the case statement in ascending order. We can kept them in any order.

·         We are also allowed to use char value in case and switch statements.

·         We can mix integer and character constant in different case of a switch.

·         Sometimes there may be not be any statement in some of the case in switch, but still they might turn out to be useful. This is shown below example.

·         Even if there are multiple statements to be executed in each case, there is no need to enclose those statements within a pair of braces. 

·         If we have no default case, then the program simply falls through the entire switch and continues with the next instruction (if any) that follows the control structure.

·         switch is the replacement for if because if after a better way of writing program as compare to if. There is no confusing more indentation as if in the switch.

·         There is one disadvantage that we cannot use any condition in case e.g. case I <= 20:

·         The break statement when used in a switch, takes the control outside the switch. However, use of continue will not take the control to the beginning of switch.

·         We can nest the switch statement.

·         If here is no break statement then all the statements given below of satisfied case will be executed simultaneously

 

5.     Conditional operator ( … ? ... : … )


Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example:

c=(c>0)?10:-10;

If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.

C Operators Priority and Associativity - C Operators Precedence


C Operator Precedence Table


This page lists C operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied.

Operator
Description
Associativity
( )
[ ]
.
->
++ --
Parentheses (function call) (see Note 1)
Brackets (array subscript)
Member selection via object name
Member selection via pointer
Postfix increment/decrement (see Note 2)
left-to-right
++ --
+ -
! ~
(type)
*
&
sizeof
 
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (convert value to temporary value of type)
Dereference
Address (of operand)
Determine size in bytes on this implementation
right-to-left
*  /  %
Multiplication/division/modulus
left-to-right
+  -
Addition/subtraction
left-to-right
<<  >>
Bitwise shift left, Bitwise shift right
left-to-right
<  <=
>  >=
Relational less than/less than or equal to
Relational greater than/greater than or equal to
left-to-right
==  !=
Relational is equal to/is not equal to
left-to-right
&
Bitwise AND
left-to-right
^
Bitwise exclusive OR
left-to-right
|
Bitwise inclusive OR
left-to-right
&&
Logical AND
left-to-right
| |
Logical OR
left-to-right
? :
Ternary conditional
right-to-left
=
+=  -=
*=  /=
%=  &=
^=  |=
<<=  >>=
Assignment
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment
right-to-left
,
Comma (separate expressions)
left-to-right
Note 1:
Parentheses are also used to group sub-expressions to force a different precedence; such parenthetical expressions can be nested and are evaluated from inner to outer.
Note 2:
Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the statement completes execution). So in the statement y = x * z++; the current value of z is used to evaluate the expression (i.e., z++ evaluates to z) and z only incremented after all else is done. See postinc.c for another example.

 

Operators and Expressions in C


2.1       OPERATORS & EXPRESSIONS

An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. they usually form a part of the mathematical or logical expressions. C supports a number of operators, they can be classified as below:

1.       Arithmetic Operators (+, –, *, /, %)

2.       Relational Operators (<, >, <=, >=, ==, !=)

3.       Logical Operators (&&, ||, !)

4.       Assignment Operators (=, compound  assignment operators: +=, -=, *=, /=, %=)

5.       Increment & Decrement Operators (++, - - )

6.       Conditional Operators (…?... : …)

7.       Bitwise Operators (~, <<, >>, &, |, ^)

8.       Other Special Operators (sizeof)

 

1.      Arithmetic Operators

All the arithmetic operators provided by C are listed in the table:

Arithmetic Operators
Operator
Meaning
+
Addition / Unary plus
-
Subtraction / Unary minus
*
Multiplication
/
Division
%
Modulo division

 

·         The unary minus ‘-‘ in effect, multiplies its single operand by -1. Therefore, a number preceded by a minus sign changes its sign.

·         The modulo division operator ‘%’ produces the reminder of an integer division.

Behavior of ‘/’ operator-

Ex.      result = op1 / op2

DT of op1
DT of op2
Data type of result
int
int
int (fractional part truncated not rounded)
float
int
float
int
float
float
float
float
float

 

Example:

int a=10, b=3;

int v1 = a+b, v2 = a-b, v3 =  a*b;

       float v4 = (float)a/b;

       int  v5 = a%b, v6 = b%a, v7 = -a+b;

printf(“%d %d %d %f %d %d”, v1,v2,v3,v4,v5,v6,v7);      

 

Output:

10, 7, 30, 3.333333, 1, 3,  -7

 

·         ‘/’  can be used to check whether a number is completely divisible by another number or not.

Example:





int main()

{  int a, b;

   printf(“\nEnter tow numbers: “);

   scanf(“%d%d”,&a,&b);

   if (a == (a/b)*b);

       printf(“\n%d is completely divisible by %d”,a,b);

   else

       printf(“\n%d is not completely divisible by %d”,a,b);

   return 0;

}






 

·         /’ can be used to truncate last digit of a number by dividing the number by 10.

Example–





int main()

{   int a, digit;

    printf(“\nEnter a number of more than two digits: “);

    scanf(“%d”,&a);

    digit = a/10;

    printf(“\nThe remaining number is : %d”, a);

    return 0;

}




Behavior of Modulus operator (%) –

·         The property of modulus operator is used to generate numbers in a restricted range. The expression  a % b  will generate number ranging from 0 to b-1.

 

For example:

 x % 100 will generate numbers from 0 to 99 for any value of x.

 

·         The modulus operator is also used to extract last digit of a number. x%10 will always give the last digit of the number x.

 

For example: 

153 % 10 à 3, 

7842 % 10 à 2, 

98 % 10 à 8, 

4 % 10 à4.

 

Ø  Integer arithmeticWhen both operands in a single arithmetic expression are integer then expression is called integer expression and the operation is called integer arithmetic.

Ø  Real arithmeticWhen arithmetic expression has only real operands this it is called real arithmetic. A real operand may assume value either in decimal or exponential notation.

Ø  Mixed-mode arithmeticWhen one of the operand is real and the other is integer, the expression is called a mixed-mode arithmetic expression.

 

2.      Relational Operators

We often compare two quantities and depending on their relation, take certain decisions. The compression can be done with the help of relational operators. Relational operators check relationship between two operands. If the relation is true, it returns value 1 and if the relation is false, it returns value 0.

For example:     a > b

Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.

Relational operators are used in decision making and loops in C programming. C supports six relational operators as listed in below:

 

Operator
Meaning of Operator
Example
==
Equal to
5==3 returns false (0)
> 
Greater than
5>3 returns true (1)
< 
Less than
5<3 returns false (0)
!=
Not equal to
5!=3 returns true(1)
>=
Greater than or equal to
5>=3 returns true (1)
<=
Less than or equal to
5<=3 return false (0)

 

·         The expression containing a relational operator is termed as a relational expression.
E.g.   a + b  >=  c + 5.

·         The value of a relational expression is either 0 (false) or 1 (true).
e.g. 
a = 10 < 20;                          then a = 1 
a = 10 > 20;                          then a = 0

·         A simple relational expression contains only one relational operator and takes the form:
AE-1 relational operator  AE-2,
where AE-1 and AE-2 are arithmetic expressions which may be simple constants, variables or combination of them.

Eg. (2+3) > (1+2);

·         When arithmetic expression are used on either side of a relational operator, the arithmetic expressions will be evaluated first and then the result is compared i.e. arithmetic operators have a higher priority over relational operator.

·         Relational expressions are used in decision statements such as if, while, for etc.

 

3.      Logical Operators

Logical operators are used to combine expressions containing relation operators. In C, there are 3 logical operators:

Operator
Meaning of Operator
Example
&&
Logial AND 
If c=5 and d=2 then,((c==5) && (d>5)) returns false.
||
Logical OR
If c=5 and d=2 then, ((c==5) || (d>5)) returns true.
!
Logical NOT
int c=5;
!(c==5) returns false (0).

Explanation

For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either the expression should be true. Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is true, !(c==5) is false.

 

The logical operator &&  and ||  are used when we want to test more than ore  condition and make decision e.g.   a > b  &&  x = = 10;

·         An expression which combines tow or more relational expressions  is known as logical expression or a compound relational expression.

·         Like the simple relational expressions, a logical expression also yields a value of 0 (false) or 1 (true), according to the truth table shown below, where a  and  b  are any relational expressions:            

a
b
a && b
a || b
!a
!b
0
0
0
0
1
1
0
1 (non-zero)
0
1
1
0
1 (non-zero)
0
0
1
0
1
1 (non-zero)
1 (non-zero)
1
1
0
0

Ex.          x=11, y=6, z=1

        Value = x > 9 && y!=3                     o/p:  Value = 1,

        Value = ! (x>9 && y!= 23)             o/p:  Value = 0

·         In expression with && operator if first part of expression has the value 0 then the second part will not checked, because in logical AND if first condition is false then whole expression will false, no need to check second part.

·         In expression with || operator if first part of expression has the value 1  then the second part will not checked, because in logical OR if first condition is true then whole expression will true, no need to check second part.

Examples– 

Open the parenthesis for the condition

(i)  !(a < b)                                                   Ans. ! (a) >=  ! (b)

(ii)  !(c1 && c2)                          Ans.  ! (c1) || ! (c2)


1.      Assignment Operators

The most common assignment operator is =. This operator assigns the value in right side to the left side.

For example:

var=5  //5 is assigned to var

a=c;   //value of c is assigned to a

5=c;   // Error! 5 is a constant.

 

Compound Assignment Operators:

Operator
Example
Same as
+=
a+=b
a=a+b
-=
a-=b
a=a-b
*=
a*=b
a=a*b
/=
a/=b
a=a/b
%=
a%=b
a=a%b

 

2.      Increment & Decrement Operators

In C, ++ and -- are called increment and decrement operators respectively. Both of these operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts 1 to operand respectively. For example:

Let a=5 and b=10
a++;  //a becomes 6
a--;  //a becomes 5
++a;  //a becomes 6
--a;  //a becomes 5 


When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and then only increment it. This can be demonstrated by an example:

#include <stdio.h>

int main()

{

                int c=2,d=2;

                printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.

printf("%d",++c);   //this statement increments 1 to c then, only c is displayed.

return 0;

}

Output

2
4
 
 


 

3.      Conditional Operators

Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example:

c=(c>0)?10:-10;

If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.

 

4.      Bitwise Operators

Bitwise operators are special types of operators that are used in programming the processor. In processor, mathematical operations like: addition, subtraction, addition and division are done using the bitwise operators which makes processing faster and saves power.

Operators
Meaning of operators
&
|
^
~
<< 
>> 

Bitwise AND operator in C programming.


The output of logical AND is 1 if both the corresponding bits of operand is 1. If either of bit is 0 or both bits are 0, the output will be 0. It is a binary operator(works on two operands) and indicated in C programming by & symbol. Let us suppose the bitwise AND operation of two integers 12 and 25.

12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
 
Bit Operation of 12 and 25
  00001100
& 00011001
  ________
  00001000  = 8 (In decimal)

As, every bitwise operator works on each bit of data. The corresponding bits of two inputs are check and if both bits are 1 then only the output will be 1. In this case, both bits are 1 at only one position, i.e, fourth position from the right, hence the output bit of that position is 1 and all other bits are 0.


 

#include<stdio.h>

void main()

{

                int a=12,b=25;

                printf("Output=%d",a&b);           // Output=8

                getchar();

} 

Bitwise OR operator in C


The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1. In C Programming, bitwise OR operator is denoted by |.

12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
 
Bitwise OR Operation of 12 and 25
  00001100
| 00011001
  ________
  00011101  = 29 (In decimal)
 
Example:
 

#include<stdio.h>

void main()

{

                int a=12,b=25;

                printf("Output=%d",a&b);           // Output=8

                getchar();

} 

C Programming Bitwise XOR(exclusive OR) operator


The output of bitwise XOR operator is 1 if the corresponding bits of two operators are opposite(i.e., To get corresponding output bit 1; if corresponding bit of first operand is 0 then, corresponding bit of second operand should be 1 and vice-versa.). It is denoted by ^.

12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
 
Bitwise XOR Operation of 12 and 25
  00001100
| 00011001
  ________
  00010101  = 21 (In decimal)
 
Example: 

#include<stdio.h>

int main()

{   int a=12,b=25;

    printf("Output=%d",a^b);    // Output=21

    return 0;

}

 

Bitwise compliment operator


Bitwise compliment operator is an unary operator(works on one operand only). It changes the corresponding bit of the operand to opposite bit,i.e., 0 to 1 and 1 to 0. It is denoted by ~.

35=00100011 (In Binary)
 
Bitwise complement Operation of 35
~ 00100011 
  ________
  11011100  = 220 (In decimal)

Twist in bitwise complement operator in C Programming


Output of ~35 shown by compiler won't be 220, instead it shows -36. For any integer n, bitwise complement of n will be -(n+1). To understand this, you should understand the concept of 2's complement.

2's Complement


Two's complement is the operation on binary numbers which allows number to write it in different form. The 2's complement of number is equal to the complement of number plus 1. For example:

 Decimal              Binary                  2's complement

   0                           00000000             -(11111111+1) = -00000000 = -0(decimal)

   1                           00000001             -(11111110+1) = -11111111 = -256(decimal)

   12                        00001100             -(11110011+1) = -11110100 = -244(decimal)

   220                      11011100             -(00100011+1) = -00100100 = -36(decimal)

Note: Overflow is ignored while computing 2's complement.

If we consider the bitwise complement of 35, 220(in decimal) is converted into 2's complement which is -36. Thus, the output shown by computer will be -36 instead of 220.

How is bitwise complement of any number N=-(N+1)?


bitwise complement of N= ~N (represented in 2's complement form)
2'complement of ~N= -(~(~N)+1) = -(N+1)
 

#include<stdio.h>

int main()

{  

     printf("complement=%d\n",~35);  //-36

    printf("complement=%d\n",~-12); // 11

     getch();

    return 0;

} 

Shift Operator in C programming


There are two shift operators in C programming: Right shift operator and Left shift operator.

Right Shift Operator


Right shift operator moves the all bits towards the right by certain number of bits which can be specified. It is denoted by >>.

212 = 11010100 (In binary)

212>>2 = 00110101 (In binary) [Right shift by two bits]

212>>7 = 00000001 (In binary)

212>>8 = 00000000

212>>0 = 11010100 (No Shift)

Left Shift Operator


Left shift operator moves the all bits towards the left by certain number of bits which can be specified. It is denoted by <<.

212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 =11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)
 

#include <stdio.h>

int main()

{

    int num=212,i;

    for (i=0;i<=2;++i)

        printf("Right shift by %d: %d\n",i,num>>i);

    

     printf("\n");

 

    for (i=0;i<=2;++i)

        printf("Left shift by %d: %d\n",i,num<<i);   

   

     return 0;

}
Output:
 
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53
 
Left Shift by 0: 212
Left Shift by 1: 424
Left Shift by 2: 848

Interesting thing to note in Left and Right Shift


For any positive number, right shift is equal to integer division of that number by (shift bit plus one) and for any integer left shift is equal to the multiplication of that number by (shift bit plus one).

5.      Other Special Operators

 

(a)    sizeof – operator:

The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.

Syntax:

sizeof unary-expression 
sizeof ( type-name )

The operand is either an identifier that is a unary-expression, or a type-cast expression (that is, a type specifier enclosed in parentheses). The unary-expression cannot represent a bit-field object, an incomplete type, or a function designator. The result is an unsigned integral constant. The standard header STDDEF.H defines this type as size_t.

When you apply the sizeof operator to an array identifier, the result is the size of the entire array rather than the size of the pointer represented by the array identifier.

When you apply the sizeof operator to a structure or union type name, or to an identifier of structure or union type, the result is the number of bytes in the structure or union, including internal and trailing padding. This size may include internal and trailing padding used to align the members of the structure or union on memory boundaries. Thus, the result may not correspond to the size calculated by adding up the storage requirements of the individual members.

If an unsized array is the last element of a structure, the sizeof operator returns the size of the structure without the array.

buffer = calloc(100, sizeof (int) );

This example uses the sizeof operator to pass the size of an int, which varies among machines, as an argument to a run-time function named calloc. The value returned by the function is stored in buffer.

     static char *strings[] ={
          "this is string one",
          "this is string two",
          "this is string three",
         };
     const int string_no = ( sizeof strings ) / ( sizeof strings[0] ); 
In this example, strings is an array of pointers to char. The number of pointers is the number of elements in the array, but is not specified. It is easy to determine the number of pointers by using the sizeof operator to calculate the number of elements in the array. The const integer value string_no is initialized to this number. Because it is a const value, string_no cannot be modified.