You are on page 1of 18

Decision Making and branching

C Decision Making Home


1 Conitional Statements If Statement | If-Else
2 Nesting of Statements Nested If-Else | Else-If Ladder
3 Multiple Condition inside If
4 Multiple Statements in If Block
4 Introduction to Switch Statement
5 Rules of Using Switch Case
6 Invalid Ways of Using Switch Case
7 Conditional Operation : ?: Operator | Rules
8 Jumping Statements : Goto Statement | Break
Syntax :
if(expression)
statement1;
Explanation :
Expression is Boolean Expression
It may have true or false value

Meaning of If Statement :
It Checks whether the given Expression is Boolean or not !!
If Expression is True Then it executes the statement otherwise jumps to
next_instruction
Sample Program Code :
void main()
{
int a=5,b=6,c;
c = a + b ;

if (c==11)
printf("Execute me 1");

printf("Execute me 2");
}
Output :
Execute me 1
If Statement :
if(conditional)
{
Statement No 1
Statement No 2
Statement No 3
.
.
.
Statement No N
}
Note :
1. More than One Conditions can be Written inside If statement.
2. Opening and Closing Braces are required only when Code after if statement
occupies multiple lines.
if(conditional)
Statement No 1;

Statement No 2;
Statement No 3;
In the above example only Statement 1 is a part of if Statement.
1. Code will be executed if condition statement is True.
2. Non-Zero Number Inside if means TRUE Condition
if(100)
printf("True Condition");
Program flow of If Statement :


If-else Statement in C Programming
We can use if-else statement in c programming so that we can check any condition and
depending on the outcome of the condition we can follow appropriate path. We have true
path as well as false path.
Syntax :
if(expression)
{
statement1;
statement2;
}
else
{
statement1;
statement2;
}

next_statement;
Explanation :
If expression is True then Statement1 and Statement2 are executed
Otherwise Statement3 and Statement4 are executed.
Sample Program on if-else Statement :
void main()
{
int marks=50;
if(marks>=40)
{
printf("Student is Pass");
}
else
{
printf("Student is Fail");
}
}Output :
Student is PassFlowchart : If Else Statement

Consider Example 1 with Explanation :
Consider Following Example -
int num = 20;

if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is True.
if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True.
Else Part executed if Condition Statement is False.
else
{
printf("False Block");
}
Consider Example 2 with Explanation :
More than One Conditions can be Written inside If statement.
int num1 = 20;
int num2 = 40;

if(num1 == 20 && num2 == 40)
{
printf("True Block");
}
Opening and Closing Braces are required only when Code after if statement occupies
multiple lines. Code will be executed if condition statement is True. Non-Zero Number Inside
if means TRUE Condition
If-Else Statement :
if(conditional)
{
//True code
}
else
{
//False code
}

Note :
Consider Following Example -
int num = 20;

if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}
1. If part Executed if Condition Statement is True.
if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True.
2. Else Part executed if Condition Statement is False.
else
{
printf("False Block");
}
3. More than One Conditions can be Written inside If statement.
int num1 = 20;
int num2 = 40;

if(num1 == 20 && num2 == 40)
{
printf("True Block");
}
4. Opening and Closing Braces are required only when Code after if statement
occupies multiple lines.
5. Code will be executed if condition statement is True.
6. Non-Zero Number Inside if means TRUE Condition






Program Flow of If-Else Statement :

Compound If Statement in C Programming :
void main ( )
{
int num = 10 ;
if(num > 0)
{
printf ("\nNumber is Positive");
printf ("\nThis is The Example of Compound Statement");
}
}
Output of Program :
Number is Positive
This is The Example of Compound Statement
Explanation of Compound If Statement :
In C Programming, Any block of the code is written or embedded inside the pair of the curly
braces. If condition specified inside the if block is true then code block written inside the
pair of curly braces will be executed.
printf ("\nNumber is Positive");
printf ("\nThis is The Example of Compound Statement");
Note : We can write any number of statements inside block if condition is true

Single Statement after if Does not Require Opening and Closing Braces : Tutorial on
If

1. Single Statement after if Does not Require Opening And Closing Braces
2. Example :
void main ( )
{
int x = 10 ;
if ( x > 0 )
printf (n Number is Positive);
}


Expression Solving inside if Statement : C programming
Arithmetic expression can be solved inside if statement. In this case expression will be
evaluated first and then result will be checked to decide the flow of code.
void main ()
{
int num = 56;
if(num % 2 == 0) // Expression
printf ("\nNumber is Even");
else
printf ("\nNumber is Odd");
}
Explanation of Statement :
Consider the if statement
if(num % 2 == 0)
above if statement contain simple expression which will be evaluated like this -
Result of Expression = (num % 2 == 0)
= (56 % 2 == 0)
= (0 == 0)
Now we can say that result of above expression is true thus if statement condition becomes
true and if block gets executed.
Expression Solving : Arithmetic Operation
We will consider different verities of statements , Please refer below table -
If Statement
Expression
Result
Comment
if(60) True Positive Number inside if will execute if block
if(0) True
Zero Number inside if will make condition false and else
block gets executed
if(-60) True
Negative number will be considered as true and if block gets
executed
if(20 - 20 +
50)
True
Expression will be executed and then it will be checked
whether it is non-zero or zero
Non Zero Number is considered as true and Zero will be considered as false

C switch case statement
Why we should use Switch Case ?
1. One of the classic problem encountered in nested if-else / else-if ladder is called
problem of Confusion.
2. It occurs when no matching else is available for if .
3. As the number of alternatives increases the Complexity of program increases
drastically.
4. To overcome this , C Provide a multi-way decision statement called Switch
Statement
See how difficult is this scenario ?
if(Condition 1)
Statement 1
else
{
Statement 2
if(condition 2)
{
if(condition 3)
statement 3
else
if(condition 4)
{
statement 4
}
}
else
{
statement 5
}
}
First Look of Switch Case
switch(expression)
{
case value1 : body1
break;

case value2 : body2
break;

case value3 : body3
break;

default : default-body
break;
}
next-statement;
Flow Diagram :


*Steps are Shown in Circles.
How it works ?
Switch case checks the value of expression/variable against the list of case values and
when the match is found , the block of statement associated with that case is
executed
Expression should be Integer Expression / Character
Break statement takes control out of the case.
Break Statement is Optional.
01:#include<stdio.h>
02:void main()
03:{
04:int roll = 3 ;
05:switch ( roll )
06: {
07: case 1:
08: printf ( " I am Pankaj ");
09: break;
10: case 2:
11: printf ( " I am Nikhil ");
12: break;
13: case 3:
14: printf ( " I am John ");
15: break;
16: default :
17: printf ( "No student found");
18: break;
19: }
20:}
As explained earlier -
1. 3 is assigned to integer variable roll
2. On line 5 switch case decides We have to execute block of code specified in 3rd
case.
3. Switch Case executes code from top to bottom.
4. It will now enter into first Case [i.e case 1:]
5. It will validate Case number with variable Roll. If no match found then it will jump
to Next Case..
6. When it finds matching case it will execute block of code specified in that case.
See how Switch Case works using Graphical Picture

Rules of Using Switch Case in C Programming
1. Case Label must be unique
2. Case Labels must ends with Colon
3. Case labels must have constants / constant expression
4. Case label must be of integral Type ( Integer,Character)
5. Case label should not be floating point number
6. Switch case should have at most one default label
7. Default label is Optional
8. Default can be placed anywhere in the switch
9. Break Statement takes control out of the switch
10. Two or more cases may share one break statement
11. Nesting ( switch within switch ) is allowed.
12. Relational Operators are not allowed in Switch Statement.
13. Macro Identifier are allowed as Switch Case Label.
14. Const Variable is allowed in switch Case Statement.
15. Empty Switch case is allowed.
Syntax of Switch Case :
switch ( expression )
{
case label1 :
body1
break;

case label2 :
body2
break;

case label3 :
body3
break;

default :
default-body
break;
}
next-statement;

Rule 1 : Case Label must be unique
int id = 3 ;
switch(id)
{
case 1: printf("C Programming Language");
break;
case 2: printf("C++ Programming Language");
break;
case 2: printf("Web Technology");
break;
default : printf("No student found");
break;
}

Rule 2 : Case Labels must ends with Colon
case 1 :
printf("C Programming Language");
break;
Rule 3 : Case labels must have constants / constant expression
case 1+1:
case 'A':
case 67:
these are allowed examples of switch case labels , however variables are not allowed in
switch case labels.
case var :
case num1 :
case n1+n2 :
Rule 4 : Case label must be of integral Type ( Integer,Character) whereas Case label
should not be floating point number
case 10:
case 20+20:
case 'A':
case 'a':
these are allowed examples and following are illegal examples -
case 10.12:
case 7.5:
Rule 5 : Switch case should have at most one default label
switch(roll)
{
case 1:
printf("C Programming Language");
break;
case 2:
printf("C++ Programming Language");
break;
case 2:
printf("Web Technology");
break;
default :
printf("Default Version 1");
break;
default :
printf("Default Version 2");
break;
}
It violets first rule.
Rule 6 : Default label is Optional
switch(roll)
{
case 1 :
printf("C Programming Language");
break;
case 2 :
printf("C++ Programming Language");
break;
case 2 :
printf("Web Technology");
break;
}
default statement is optional. It can be neglected.
Rule 7 : Default can be placed anywhere in the switch
switch(roll)
{
case 1 :
printf("C Programming Language");
break;
default:
printf("No Student Found");
break;
case 2 :
printf("C++ Programming Language");
break;
case 2 :
printf("Web Technology");
break;
}
Rule 8 : Break Statement takes control out of the switch
Rule 9 : Two or more cases may share one break statement
switch(alpha)
{
case 'a':
case 'A':
printf("Alphabet A");
break;
case 'b':
case 'B':
printf("Alphabet B");
break;
}
Rule 10 : Nesting ( switch within switch ) is allowed
switch(alpha)
{
case 'a':
case 'A':
printf("Alphabet A");
break;
case 'b':
case 'B':
switch(alpha)
{
}
break;
}
nesting of switch case is allowed in C.
Rule 11 : Relational Operators are not allowed in Switch Statement.
switch(num)
{
case >15:
printf("Number > 15");
break;
case =15:
printf("Number = 15");
break;
case <15:
printf("Number < 15");
break;
}
relational operators are not allowed as switch label.
Rule 12 : Macro Identifier are allowed as Switch Case Label.
#define MAX 2

switch(num)
{
case MAX:
printf("Number = 2");
break;
}
as preprocessor will replace occurrence of MAX by constant value i.e 2 therefor it is allowed.
Rule 13 : Const Variable is allowed in switch Case Statement.
int const var = 2;

switch(num)
{
case var:
printf("Number = 2");
break;
}

Conditional Operators [ ?: ] : Ternary Operator Statement in C
1. They are also called as Ternary Operator .
2. They also called as ?: operator
3. Ternary Operators takes on 3 Arguments
Syntax :
expression 1 ? expression 2 : expression 3
where
expression1 is Condition
expression2 is Statement Followed if Condition is True
expression2 is Statement Followed if Condition is False

Conditional Statement in C Programming Lanuage
Meaning of Syntax :
1. Expression1 is nothing but Boolean Condition i.e it results into either TRUE or
FALSE
2. If result of expression1 is TRUE then expression2 is Executed
3. Expression1 is said to be TRUE if its result is NON-ZERO
4. If result of expression1 is FALSE then expression3 is Executed
5. Expression1 is said to be FALSE if its result is ZERO
Example : Check whether Number is Odd or Even
#include<stdio.h>

int main()
{
int num;

printf("Enter the Number : ");
scanf("%d",&num);

flag = ((num%2==0)?1:0);

if(flag==0)
printf("\nEven");
else
printf("\nOdd");
}
More Simply we can write this program as -
#include<stdio.h>

int main()
{
int num;

printf("Enter the Number : ");
scanf("%d",&num);

(num%2==0)?printf("Even"):printf("Odd");

}
Big Note : Ternary Operator
Operator that works on 3 operands is called as tertiary operator. Ternary operator .
Goto Statement
goto label;
-------
-------
label :

Whenever goto keyword encountered then it causes the program to continue on the line , so
long as it is in the scope .
Types of Goto :
Forward
Backward

Note :





#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 10;

/* do loop execution */
LABEL10:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LABEL10;
}

printf("value of a: %d\n", a);
a++;

}while( a < 20 );

return 0;
}

output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19


Break Statement Simply Terminate Loop and takes control out of the loop.
Break in For Loop :
for(initialization ; condition ; incrementation)
{
Statement1;
Statement2;
break;
}

Break in While Loop :
initialization ;
while(condition)
{
Statement1;
Statement2;
incrementation
break;
}

Break Statement in Do-While :
initialization ;
do
{
Statement1;
Statement2;
incrementation
break;
}while(condition);

Way 1 : Do-While Loop




Way 2 : Nested for


Way 3 : For Loop


Way 4 : While Loop

You might also like