Unit ii chapter 2 Decision making and Branching in C

2,783 views 39 slides Dec 07, 2021
Slide 1
Slide 1 of 39
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39

About This Presentation

Unit ii chapter 2 Decision making and Branching in C
MRS.SOWMYA JYOTHI
REFERENCE: PROGRAMMING IN C BY BALAGURUSWAMY


Slide Content

DECISION MAKING and
BRANCHING
REFERENCE: PROGRAMMING IN C BY BALAGURUSWAMY
MRS. SOWMYA JYOTHI, SDMCBM, MANGALORE

Branching:
•TheClanguageprogramspresenteduntilnowfollowsasequential
formofexecutionofstatements.Manytimesitisrequiredtoalterthe
flowofthesequenceofinstructions.
•Clanguageprovidesstatementsthatcanaltertheflowofa
sequenceofinstructions.ThesestatementsarecalledControl
statementsorDecision-makingstatements..
•Thesestatementshelptojumpfromonepartoftheprogramto
another.
•Thecontroltransfermaybeconditionalorunconditional.
•Decisionmakingisusedtoseewhetheraparticularconditionhas
occurredornotandthendirectthecomputertoexecutecertain
statementsaccordingly.

Decision making statements are used to execute a part of statement
based on some condition and exclude other.
•C language possesses such decision-makingcapabilities by
supporting the following statements:-
1.If statement
2.Switch statement
3.conditional operator statement
4.gotostatement

Decision making with if Statement:
•Theifstatementisapowerfuldecision-makingstatementandisused
tocontroltheflowofexecutionofstatements.
•Itisbasicallyatwo-waydecisionstatementandisusedinconjunction
withanexpression.
Theifstructurehasthefollowingsyntax
•if (condition)
statement;
•Itallowsthecomputertoevaluatetheexpressionfirstandthen
dependingonwhetherthevalueoftheexpressionistrue(ornon-zero)
or‘false’(zero),ittransfersthecontroltoaparticularstatement.

The different forms of if statement are:-
1. simple if statement
2. if …else statement
3. Nested if statement
4. else ..if ladder

Simple if statement:-
The general form of a simple ifstatement is as follows,
if (test expression)
{
statement-block;
}
statement –x;
• Here, the statement block may contain a single statement or a
group of statements.
•If the test expression is truethen the statement block will be
executed; otherwise it will be skipped to the statement –x.

Example program
Calculate the absolute value of an integer
# include <stdio.h>
void main ()
{
intnumber;
printf("Type a number:");
scanf("%d", &number);
if (number < 0)
number = -number;
printf("The absolute value is %d \n", number);
}

•The above program checks the value of the input number to see if it
is less than zero.
•If it is then the following program statement which negates the
value of the number is executed.
•If the value of the number is not less than zero, we do not want to
negate it then this statement is automatically skipped.
•The absolute number is then displayed by the program, and program
execution ends.

•The if else construct:
•The syntax of the If else construct is as follows:-
if (test expression)
statement1;
else
statement2;

•Theifelseisactuallyjustanextensionofthegeneralformatofif
statement.
•Iftheresultofthetestexpressionistrue,thenprogramstatement1
isexecuted,
•otherwiseprogramstatement2willbeexecuted.
•Ifanycaseeitherprogramstatement1isexecutedorprogram
statement2isexecutedbutnotbothwhenwritingprogramsthis
elsestatementissofrequentlyrequiredthatalmostallprogramming
languagesprovideaspecialconstructtohandlethissituation.

For example:
•Program to find whether a number is negative or positive
#include <stdio.h>
void main ()
{
intnum;
printf("Enter the number");
scanf("%d", &num);
if (num< 0)
printf("The number %d is negative“,num);
else
printf("The number %d is positive“,num);
}

#include<stdio.h>
intmain()
{
intnumber;
printf("Enter a number: ");
scanf("%d",&number);
if(number%2==0)
{ printf("%d is an even number",number);
}
else
{
printf("%d is an odd number",number);
}
return 0;
}

In the above program
•the If statement checks whether the given number is less than 0.
•If it is less than zero then it is negative therefore the condition
becomes true then the statement
The number is negative is executed.
•If the number is not less than zero the If else construct skips the first
statement and prints the second statement declaring that the
number is positive.

Compound Relational tests:
•C language provides the mechanisms necessary to perform compound
relational tests.
•A compound relational test is simple one or more simple relational tests
joined together by either the logical AND or the logical OR operators.
•These operators are represented by the character pairs && // respectively.
•The compound operators can be used to form complex expressions in C.
a) if (condition1 && condition2 && condition3)
b) if (condition1 || condition2 || condition3)

#include <stdio.h>
intmain()
{
char ch;
printf("Enter any character: ");
scanf("%c", &ch);
if((ch>= 'a' && ch<= 'z') || (ch>= 'A' && ch<= 'Z'))
{
printf("Character is an ALPHABET.");
}
else
{
printf("Character is NOT ALPHABET.");
}
return 0;
}

if (isupper(ch))
{
printf(“\n%cis uppercase alphabet.", ch);
}
else if(islower(ch))
{
printf(“\n%cis lowercase alphabet.", ch);
}
else
{
printf(“\n%cis not an alphabet.", ch);
} }

#include <stdio.h>
void main()
{
intmonth;
printf("Enter month number (1-12): ");
scanf("%d", &month);

if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 ||
month==12)
{
printf("31 days");
}
else if(month==4 || month==6 || month==9 || month==11) {
printf("30 days");
}
else if(month==2)
{
printf("28 or 29 days");
}
else
{
printf("Invalid input! Please enter month number between (1-12).");
}

Nested if Statement
Whenaseriesofdecisionsareinvolved,wemayhavetousemore
thanoneif..elsestatementinnestedform.
Theifstatementmayitselfcontainanotherifstatementisknownas
nestedifstatement.
Syntax:

if (test condition1)
{
if (test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}

•Theifstatementmaybenestedasdeeplyasyouneedto
nestit.
•Oneblockofcodewillonlybeexecutediftwoconditionsare
true.Condition1istestedfirstandthencondition2is
tested.
•Thesecondifconditionisnestedinthefirst.
•Thesecondifconditionistestedonlywhenthefirst
conditionistrueelsetheprogramflowwillskiptothe
correspondingelsestatement.

#include <stdio.h>
#include <conio.h>
void main()
{
intno;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);

if(no>0)
{
printf("\n\n Number is greater than 0 !");
}
else
{
if(no==0)
{
printf("\n\n It is 0 !");
}
else
{
printf("Number is less than 0 !");
}
}
getch();
}

The ELSE If Ladder:
• Theifsareputtogetherwhenmultipathdecisionsareinvolved.A
multipathdecisionisachainofifsinwhichthatstatementassociated
witheachelseisanif.
Syntax:
•if (condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
…..
else
default statement;
statement-x;

#include<stdio.h>
intmain()
{
intnumber;
printf("Enter a number: ");
scanf("%d",&number);

if(number>0)
{
printf("%d is a positive number", number);
}
else if(number<0)
{
printf("%d is a negative number", number);
}
else
{
printf("Number is zero");
}
}

if((ch>= 'a' && ch<= 'z') || (ch>= 'A' && ch<= 'Z'))
{
printf("%c is alphabet.", ch);
}
else if(ch>= '0' && ch<= '9')
{
printf("%c is digit.", ch);
}
else
{
printf("%c is special character.", ch);
}

•Example program using If else ladder to grade the student according
to the following rules.
Marks Grade
70 to 100
60 to 69
50 to 59
40 to 49
0 to 39
DISTINCTION
IST CLASS
IIND CLASS
PASS CLASS
FAIL

#include <stdio.h>
void main ()
{
intmarks
printf("Enter marks\n") ;
scanf("%d", &marks) ;
if (marks <= 100 && marks >= 70)
printf("\n Distinction") ;
else if (marks >= 60)
printf("\n First class");
else if (marks >= 50)
printf("\n second class");
else if (marks >= 35)
printf("\n pass class");
else
printf("Fail")
}

The Switch Statement:
•UnliketheIfstatementwhichallowsaselectionoftwoalternativesthe
switchstatementallowsaprogramtoselectonestatementfor
executionoutofasetofalternatives.
•Duringtheexecutionoftheswitchstatementonlyoneofthepossible
statementswillbeexecutedtheremainingstatementswillbeskipped.
•TheusageofmultipleIfelsestatementincreasesthecomplexityofthe
programsincewhenthenumberofIfelsestatementsincreaseitaffects
thereadabilityoftheprogramandmakesitdifficulttofollowthe
program.
•Theswitchstatementremovesthesedisadvantagesbyusingasimple
andstraightforwardapproach

switch(expression)
{
casevalue1: block-1
break;
casevalue2: block-2
break;
…………
default: default-block
break;
}
statement-x;

/*Program to find whether the number is odd or even*/
#include<stdio.h>
main()
{
intn;
printf(“Enter the number”);
scanf(“%d”,&n);
switch(n%2)
{
case0:printf(“\nThenumber%diseven",n);
break;
case1:printf(“\nThenumber%disodd\n",n);
break;
}
}

The ?: operator:-
•The conditional operator or ternary operator is useful for making two-way decisions.
This operator is a combination of ? and :, and takes 3 operands.
•The general form of use of the conditional operator is as follows:
Conditional expression ? expression1 : expression2
Example:
flag = (x < 0) ? 0 : 1;
• The conditional expression is evaluated first. If the result is nonzero, expression1
is evaluated and is returned as the value of the conditional expression. Otherwise,
expression2 is evaluated and its value is returned.
For example the statement
if (x <0)
flag=0;
else
flag=1;

The gotostatement:-
•C supports the gotostatement to branch unconditionally form one
point to another in the program.
gotolabel;
•Thegotostatementissimplestatementusedtotransfertheprogram
controlunconditionallyfromonestatementtoanotherstatement.
Eg:
•gotoread;

a>
gotolabel;
…………
…………
…………
Label:
Statement;
b>
label:
…………
…………
…………
gotolabel;
Thegotorequiresalabelinordertoidentifytheplacewherethe
branchistobemade.
Alabelisavalidvariablenamefollowedbyacolon.

#include <stdio.h>
main ()
{
intn, sum = 0, i= 0;
printf("Enter a number")
scanf("%d", &n)
loop:
i++;
sum += i
if (i< n)
gotoloop;
printf("\n sum of %d natural numbers = %d", n, sum);
}
Tags