Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Decision Making & Branching

• The order in which a computer executes the statements in a program is known as Flow of Control.
• Flow of control is normally sequential, i.e., when one statement is finished executing, control passes to the next statement in the program.
• Control statement: A set of statements that alter the flow of control within a program.
• C provides two types of control statements:
1. Selection: They allow the user to select a set of statements for execution depending on the result of a condition. They are also known as decision
statements.
2. Iteration: Using Iteration, a set of statements can be executed repeatedly until a certain condition is fulfilled.

/* program to check if the given two numbers are equal or not */


• #include<stdio.h> void main()
#include <stdio.h> void main ( )
{
int a,b,sum;
{ int num1 , num2;
printf(“Enter a and b value”); scanf(“%d printf(" Enter the values for Numl and Num2\n"); scanf("%d %d", &numl,&num2);
%d”,&a,&b); sum=a+b; if(num1==num2)
printf("Entered numbers are equal\n"); else
printf(“sum is:”,sum); getch();
printf("Entered numbers are not equal\n"); }
}
Different types of conditional control structures available in 'C' are
1) if - statement
2) if else statement
3) else –if ladder
4) Nested if statement
5) switch statement

if..Statement
General Form:
if (test expression) {
statement-block }
statement – x;

• 'statement - block' may be a single statement or a group of statements.


• If the test expression is true, the statement- block will be executed; otherwise the statement - block will be skipped and the control will jump to the statement
-x.
• Example : C program to accept a number and prints if it is an odd number. #include <stdio.h>
void main( ) {
int num;
printf(" Enter the number\n"); scanf("%d ", &num);
if((num%2)!=0)
printf(" %d is an odd number\n”,num); }
If....else Statement
The if….else structure is used to execute one set of statements when the condition is satisfied and another set of statements when the condition is not met.
The general Syntax:

if(condition)
{ statement block1} else
{ statement block2} Statement - x
Example:
/* program to check if the given two numbers are equal or not */
#include <stdio.h>
void main ( ) {
int num1 , num2;
printf(" Enter the values for Numl and Num2\n"); scanf("%d %d", &numl,&num2); if(num1==num2)
printf("Entered numbers are equal\n"); else
printf("Entered numbers are not equal\n"); }

Nesting of if - else Statements


Nested if- else statements are useful when there are multiple conditions and different statements are to be executed for each condition. The logic execution is
illustrated below.

Example:
/* program to find the largest among three numbers*/ #include <stdio.h>
void main( )
{ int a,b,c;
printf(" Enter the values for A,B,C\n”'); scanf("%d %d %d",
&a,&b,&c);
if( a > b )
{ if ( a > c)
printf(" A is the largest\n"); else
printf("C is the largest\n"); }
else
{ if ( b> c)
printf(" B is the largest\n"); else
printf("C is the largest\n"); }
}
The else if ladder
There is another way of putting ifs together when multi-path decisions are involved.

• The conditions are evaluated from the top (of the ladder) to downwards.
• As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statement x (skipping the
rest of the ladder) which is an immediate statement outside if -else if -else construct.
• When all the n conditions become false, then the final else containing the default statement will be executed

Example:
/* Program to print the grade of marks */ #include <stdio.h>
void main()
{ int marks;
printf(" Enter Marks \n”);
scanf("%d “,&marks);
if (marks >=70))
printf(“Distinction);
else if(marks >=60)
printf(“ First Class”);
else if(marks >=50)
printf(“Second Class”); else
if (marks >=40)
printf (“Third Class \n”); else
printf(“Fails”);
}
The Switch Statement is a multiway branching structure that allows a programer to select statement for execution out of a set of alternatives.
switch( expression ) {
case value-1:
Block-1; Break;
case value-2:
Block-2; Break;
case value-n:
Block-n; Break;
default:
Block-1; Break;
}
Statement-x;
• The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements
associated with that case is executed.
• When switch statement is executed the expression is first evaluated. Its value is
then compared against the values value - 1, value - 2 ,....
• if a case label is found whose value matches with the value of the expression, then the block of statements that follows the case are executed.
• The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to
the statement – x following the switch.
• The default is an optional case. When present, it will be executed if the value of the expression does not match with any of the case values.
• If not present, no action takes place if all matches fail and the control goes to the statement-x.

Program to accept day number and display corresponding week day. #include <stdio.h>
void main() {
int dayno;
printf(" Enter Daynumber \n”);
scanf("%d “,&dayno); switch(dayno)
{
case 1: printf(“Sunday”); break;
case 2: printf(“Monday”); break;
case 3: printf(“Tues day”); break;
case 4: printf(“Wednesday”); break;
case 5: printf(“Thursday”); break;
case 6: printf(“Fri day”); break;
case 7: printf(“Saturday”); break;
default: printf(“ Invalid Day number”);
} }
Rules for switch statement:
➢ The expression is an integer expression or characters. ➢ Case labels must be constants or constant expressions. ➢
Case labels must be unique.
Ø No two case labels can have the same value. ➢ Case labels must end with colon(:).
➢ Braces { } are not required around these blocks.
➢ The break statement transfers the control out of the switch statement. ➢ The break statement is optional, i.e., two or more case labels may belong
to the same statement.
➢ The default statement is optional. If present, it will be executed when the expression does not find a matching case label.
➢ There can be at most one default label.
➢ The default statement is usually placed at the end. ➢ It is permitted to nest switch statements

The (Ternary) (?: ) Operator:

The ternary operator has three operands, the first of which is Boolean expression, and the second and third are expressions that compute to a value:
Value=( Expression1) ? Expression2: Expression3
The operator returns the value of expression2 if expression1 is true, else it returns the value of expression3.
It is equivalent to:
if (First expression)
Value = Second_expression; else
Value = Third _expression;

• The conditional operator may be nested for evaluating more complex assignment decisions. • For example, consider the weekly salary of a salesgirl
who is selling some domestic products. • If x is the number of products sold in a week, her weekly salary is given by
4x+100 for x < 40
Salary = 300 for x = 40 4.5x+150
for x > 40
This complex expression can be written using if else statement as follows:

if(x<=40) if(x<40)
salary = 4*x+100; else
salary = 300;
else
salary = 4.5*x+150; using
ternary operator:
salary = (x!=40)? ((x<40)? (4*x+100) : (4.5*x+150) : 300;

Example:
Program display maximum of two numbers using ternary operators

#include <stdio.h> main()


{
int a,b;
printf(“Enter two numbers \n”); scanf(“%d %d”, &a,&b);
a>=b ? printf(“A is big”) : printf(“B is big”); }

The goto statement


• Transfers the control unconditionally from one point to another in program.
• It requires a label in order to identify the place where the branch is to be made. • A label is any valid variable name , and it must be followed by colon.
• Label is placed immediately before the statement where the control is to be transferred.
• The label can be any where in program either before or after goto label; #include<stdio.h>
void main() {
int n;
LOOP: printf("Enter a positive number"); scanf("%d",&n);
printf("%d",n); if(n<0) goto LOOP;
}
Looping:
• Loops in 'C' cause a set of statements in a program to be executed repeatedly while an expression is true.
• Repeated execution of set of statements until the condition is satisfied is called looping.
• When the expression becomes false, the loop terminates and the control passes to the statement following the loop.
• A loop in a program therefore consists of two segments, one known as the body of the loop and the other known as the control statement.
• The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.
• There are three kinds of loops in 'C’
i) while
ii) do - while
iii) for

while statement
• This is called “pre-tested” looping structure.
• In this structure, the checking of condition is done at the beginning. • The condition must be satisfied before the execution of the
statements.
• The set of statements in the block is executed again and again until the test condition is true.
• If the test condition becomes false, the control is transferred out of the block.

Syntax: while(test condition) {


Statement-1; Statement-2;
……..
}
Statement n+1;
The execution of this statement works as follows:

1.The test condition if first evaluated .


2.If the test condition is false, while statement is terminated and the control goes out of the structure.
3.If test condition is true, then the statements in the structure will be executed and the control returns to the test condition.
Example: Program to display first 10 natural numbers.

#include<stdio.h> void main()


{ int i=0; while(i<=10)
{
printf(“%d”, i); i++;
}}

do - while() Loop
• In the while loop test condition is evaluated before executing any of the statements within the loop. Therefore, the body of the loop may not be executed at all if
the condition is not satisfied at the very beginning of the loop where as ,
• in do - while loop construct, test condition is evaluated after the execution of the statements. This loop is called “post-tested” loop.
• The general format of do - while loop construct is do
{
body of the loop }
while (test expression);

The execution of this statement works as follows:


1. The set of statements in the block is first executed once. 2. The test condition is then evaluated.
3. The value of the test condition is false, then the do… while statement is terminated and the control goes out of the structure.
4. If the value of the test condition is true, then control goes back to the beginning of the structure and the statements in the structure are executed again.
Example: Program to display first 10 natural numbers.

#include<stdio.h> void
main()
{
int i=0; do
{
printf(“%d”, i); i++;
}
while (i<=10);
}

for statement
• for statement is also called the fixed execution looping structure. This structure is used when we know exactly how many times a particular
set of statements is to be repeated.

Syntax: for(initiazation; condition; increment/decrement) {


Statement-
1;
Statement-
2; ……..
}
Statement n+1;
The execution of this structure is as follows:
1. Expression 1 is evaluated and the counter variable is assigned initial value.
2. Expression 2 is then executed, i.e, the value of the counter variable is checked to see whether it has exceeded the final value, if not the statements in the structure
are executed once.
3. Control is sent back to the beginning of the structure and Expression 3 is evaluated, i.e., the value of the counter variable is either increased or decreased
depending on the statement used.
4. Step 2 is repeated again and again until the counter variable exceeds the final value.

Example: Program to display the numbers from 0 to 10 */

#include <stdio.h> void main( )


{
int i;
for (i=0;i <=10;i++) printf ("%d\n",i);
}

Nested Loops:
• If one looping statement is enclosed in another looping statement, then such a sequence of statements is called as nested loops.
• Whenever nested loops are used, the inner loop must be completely enclosed by the outer loop.
Example: for(row=1;row<=4;row++) {
for(col=1;col<=row;col++) printf(“ * ”);
printf(“\n”);
} OUTPUT: *

* *
* * *
* * * *
Infinite Loops:
If we do not use any expressions in a for statement, then the loop will run for an infinite amount of time. The loops which do not terminate are
called as infinite loops.
Example:
for(; ;)
printf(“C Programming ”);

Comparison of the Three Looping Statements


• For loop is appropriate when you know in advance how many times the loop will be executed.
• The other two loops are more suitable in the situations where the total number of iterations is not known the while loop should be preferred
when you may not want to execute the loop body even once and the do-while loop should be preferred when you are sure to execute the loop
body at least once.

break Statement
• The break statement is used to terminate loops. It can be used within a while loop do while loop or for loop.
• When a break is encountered within a loop, control automatically passes to the first statement after the loop.
Example: void
main() {
int i;
for(i=0;i<=10;i++)
{
if(i==5) break;
printf(“%d ”,i); }
}
Output will be 0 1 2 3 4
continue Statement
when a continue is encountered inside any loop, control automatically passes to the beginning of the loop.
Example: void main() {
int i; for(i=0;i<=10;i++) {
if(i==5 || i==7) continue;
printf(“%d ”,i); }
} Output will be 0 1 2 3 4 6 8 9 10

exit() Statement:
• exit() is a standard library function that is used to immediately terminate the program.
• When exit() is encountered in the program, the program is immediately terminated and the control is transferred back to the operating system.
• The general form of an exit() function is, exit(int return_code);
where return_code is optional.
• Generally zero is used as return_code to indicate normal program termination. • Other nonzero value for return_code indicates the occurrence of an error
within the programs.
• The use of exit() function requires the inclusion of the header file <stdlib.h>

You might also like