SlideShare a Scribd company logo
1 of 43
UNIT II - CONTROL STATEMENTS AND
INTRODUCTION TO PROBLEM SOLVING
Chapter-I
CONTROL STATEMENTS
Mr. JAVVAJI VENKATRAO
Assistant Professor
Department of CSE
SREE VIDYANIKETHAN ENGINEERING COLLEGE (Autonomous)
TIRUPATI
 Understanding meaning of a statement and statement block
 Learn about decision type control constructs in C and the way
these are used
 Learn about looping type control constructs in C and the
technique of putting them to use
 Learn the use of special control constructs such as goto,
break, continue, and return
 Learn about nested loops and their utility
1. LEARNING OBJECTIVES
2. CONTROL STATEMENTS INCLUDE
Selection
Statements
• if
• if-else
• switch
Iteration
Statements
• for
• while
• do-while
Jump
Statements
• goto
• break
• continue
• return
Program Control
Statements/Constructs
Selection/Branching
Conditional
Type
if if-else
if-else-
if
switch
Unconditional
Type
break continue goto
Iteration/Looping
for while
do-
while
PROGRAM CONTROL
STATEMENTS/CONSTRUCTS IN ‘C’
Operators
<
>
==
<=
>=
!=
&&
||
!=
!
OPERATORS
To Specify Symbol Used
less than <
greater than >
less than or
equal to
greater than or
equal to
<=
>=
To Specify Symbol Used
Equal to ==
Not equal to !=
Logical AND &&
Logical OR ||
Negation !
RELATIONAL
OPERATORS
Equality and Logical
Operators
 If an expression, involving the relational operator, is true, it is
given a value of 1. If an expression is false, it is given a value
of 0. Similarly, if a numeric expression is used as a test
expression, any non-zero value (including negative) will be
considered as true, while a zero value will be considered as
false.
 Space can be given between operand and operator (relational
or logical) but space is not allowed between any compound
operator like <=, >=, ==, !=. It is also compiler error to
reverse them.
 a == b and a = b are not similar, as == is a test for equality,
a = b is an assignment operator. Therefore, the equality
operator has to be used carefully.
 The relational operators have lower precedence than all
arithmetic operators.
POINTS TO NOTE
The following declarations and
initializations are given:
int x=1, y=2, z=3;
Then,
The expression x>=y evaluates to 0 (false).
The expression x+y evaluates to 3 (true).
The expression x=y evaluates to 2 (true).
A FEW EXAMPLES
NOT
operator
(!) AND
operator
&& OR
operator
||
LOGICAL OPERATORS MAY BE MIXED WITHIN RELATIONAL
EXPRESSIONS BUT ONE MUST ABIDE BY THEIR PRECEDENCE
RULES WHICH IS AS FOLLOWS:
© Oxford University Press 2013. All rights reserved.
Operators Associativity
() ++ (postfix) -- (postfix) left to right
+ (unary) - (unary) right to left
++ (prefix) -- (prefix) * / % left to right
+ - left to right
< <= > >= left to right
== != left to right
&& left to right
|| left to right
?: right to left
= + = - = * = / = right to left
, (comma operator) left to right
OPERATOR SEMANTICS
© Oxford University Press 2013. All rights reserved.
Selection Statements
The Conditional Operator
The switch Statement
CONDITIONAL EXECUTION AND
SELECTION
One-way decisions using if statement
Two-way decisions using if-else statement
Multi-way decisions
Dangling else Problem
SELECTION STATEMENTS
Flowchart for if construct
if(TestExpr)
stmtT; T F
ONE-WAY DECISIONS USING IF STATEMENT
TestExpr
stmtT
Algorithm C Program
1. START #include <stdio.h>
int main()
{
int a, b, c, max;
printf(“nEnter 3 numbers”);
scanf(“%d %d %d”, &a, &b, &c);
max=a;
if(b>max)
max=b;
if(c>max)
max=c;
printf(“Largest No is %d”, max);
return 0;
}
2. PRINT “ENTER THREE
NUMBERS”
3. INPUT A, B, C
4. MAX=A
5. IF B>MAX THEN MAX=B
6. IF C>MAX THEN MAX=C
7. PRINT “LARGEST
NUMBER IS”, MAX
8. STOP
WRITE A PROGRAM THAT PRINTS THE
LARGEST AMONG THREE NUMBERS.
© Oxford University Press 2013. All rights reserved.
Flowchart of if-else
construct
The form of a two-way
decision is as follows:
if(TestExpr)
stmtT;
else
stmtF;
TWO-WAY DECISIONS USING IF-ELSE
STATEMENT
© Oxford University Press 2013. All rights reserved.
TestExpr
stmtT stmtF
Algorithm C Program
1. START #include <stdio.h>
int main()
{
int a, b, c, max;
printf(“nEnter 3 numbers”);
scanf(“%d %d %d”, &a, &b, &c);
max=a;
if(b>max)
max=b;
if(c>max)
max=c;
printf(“Largest No is %d”, max);
return 0;
}
2. PRINT “ENTER THREE
NUMBERS”
3. INPUT A, B, C
4. MAX=A
5. IF B>MAX THEN MAX=B
6. IF C>MAX THEN MAX=C
7. PRINT “LARGEST
NUMBER IS”, MAX
8. STOP
WRITE A PROGRAM THAT PRINTS THE
LARGEST AMONG THREE NUMBERS.
© Oxford University Press 2013. All rights reserved.
if-else-if ladder
if(TestExpr1)
stmtT1;
else if(TestExpr2)
stmtT2;
else if(TestExpr3)
stmtT3;
.. .
else if(TestExprN)
stmtTN;
else
stmtF;
General format of switch
statements
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}
MULTI-WAY DECISIONS
© Oxford University Press 2013. All rights reserved.
FLOWCHART OF AN IF-ELSE-IF CONSTRUCT
© Oxford University Press 2013. All rights reserved.
TestExpr
TestExpr2
TestExprN
TestExpr3
stmtT2
stmtTN
stmtT3
stmtTF
stmtT1
#include <stdio.h>
int main()
{
int x;
printf(“n ENTER THE NUMBER:”);
scanf(“%d”, &x);
if(x > 0)
printf(“x is positive n”);
else if(x == 0)
printf(“x is zero n”);
else
printf(“x is negative n”);
return 0;
}
THE FOLLOWING PROGRAM CHECKS WHETHER A
NUMBER GIVEN BY THE USER IS ZERO, POSITIVE, OR
NEGATIVE
© Oxford University Press 2013. All rights reserved.
 When any if statement is
written under another if
statement, this cluster is
called a nested if.
 The syntax for the
nested is given here:
Construct 1 Construct 2
if(TestExprA)
if(TestExprB)
stmtBT;
else
stmtBF;
else
stmtAF;
if(TestExprA)
if(TestExprB)
stmtBT;
else
stmtBF;
else
if(TestExprC)
stmtCT;
else
stmtCF;
NESTED IF
© Oxford University Press 2013. All rights reserved.
A PROGRAM TO FIND THE LARGEST AMONG
THREE NUMBERS USING THE NESTED LOOP
#include <stdio.h>
int main()
{
int a, b, c;
printf(“nEnter the three numbers”);
scanf(“%d %d %d”, &a, &b, &c);
if(a > b)
if(a > c)
printf(“%d”, a);
else
printf(“%d”, c);
else
if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
return 0;
}
 This classic problem occurs
when there is no matching
else for each if. To avoid this
problem, the simple C rule is
that always pair an else to the
most recent unpaired if in the
current block. Consider the
illustration shown here.
 The else is automatically
paired with the closest if. But,
it may be needed to associate
an else with the outer if also.
DANGLING ELSE PROBLEM
© Oxford University Press 2013. All rights reserved.
Use of null else
Use of braces to
enclose the true
action of the
second if
With null
else
With braces
if(TestExprA)
if(TestExprB)
stmtBT;
else
;
else
stmtAF;
if(TestExprA)
{
if(TestExprB)
stmtBT;
}
else
stmtAF;
SOLUTIONS TO DANGLING ELSE
PROBLEM
© Oxford University Press 2013. All rights reserved.
An Example
 It has the following
simple format:
expr1 ? expr2 : expr3
It executes by first
evaluating expr1, which
is normally a relational
expression, and then
evaluates either expr2, if
the first result was true,
or expr3, if the first
result was false.
#include <stdio.h>
int main()
{
int a,b,c;
printf(“n ENTER THE TWO
NUMBERS:”);
scanf(“%d %d”, &a, &b);
c=a>b? a : b>a ? b :-1;
if(c==-1)
printf(“n BOTH NUMBERS
ARE EQUAL”);
else
printf(“n LARGER NUMBER IS
%d”,c);
return 0;
}
6. THE CONDITIONAL OPERATOR
© Oxford University Press 2013. All rights reserved.
The C switch construct
The general format of a
switch statement is
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}
THE SWITCH STATEMENT
© Oxford University Press 2013. All rights reserved.
© Oxford University Press 2013. All rights reserved.
 The switch differs from the else-if in that switch
can test only for equality, whereas the if
conditional expression can be of a test expression
involving any type of relational operators and/or
logical operators.
 A switch statement is usually more efficient than
nested ifs.
 The switch statement can always be replaced with
a series of else-if statements.
SWITCH VS NESTED IF
© Oxford University Press 2013. All rights reserved.
 A loop allows one to execute
a statement or block of
statements repeatedly. There
are mainly two types of
iterations or loops –
unbounded iteration or
unbounded loop and bounded
iteration or bounded loop.
 A loop can either be a pre-
test loop or be a post-test
loop as illustrated in the
diagram.
ITERATION AND REPETITIVE
EXECUTION
© Oxford University Press 2013. All rights reserved.
Expanded Syntax of “while” and
its Flowchart Representation
while statement is a
pretest loop. The basic
syntax of the while
statement is shown below:
“WHILE” CONSTRUCT
© Oxford University Press 2013. All rights reserved.
#include <stdio.h>
int main()
{
int c;
c=5; // Initialization
while(c>0)
{ // Test Expression
printf(“ n %d”,c);
c=c-1; // Updating
}
return 0;
}
This loop contains all the
parts of a while loop.
When executed in a
program, this loop will
output
5
4
3
2
1
AN EXAMPLE
© Oxford University Press 2013. All rights reserved.
float x;
x = 0.0;
while(x != 1.1)
{
x = x + 0.1;
printf(“1.1 minus %f equals %.20gn”, x, 1.1 -x);
}
The above loop never terminates on many computers, because
0.1 cannot be accurately represented using binary numbers.
Never test floating point numbers for exact equality, especially
in loops.
The correct way to make the test is to see if the two numbers
are ‘approximately equal’.
TESTING FOR FLOATING-POINT ‘EQUALITY’
© Oxford University Press 2013. All rights reserved.
 The general form of the for statement is as follows:
for(initialization; TestExpr; updating)
stmT;
for construct
flow chart
“FOR” CONSTRUCT
© Oxford University Press 2013. All rights reserved.
#include <stdio.h>
int main()
{
int n, s=0, r;
printf(“n Enter the Number”);
scanf(“%d”, &n);
for(;n>0;n/=10)
{
r=n%10;
s=s+r;
}
printf(“n Sum of digits %d”, s);
return 0;
}
EXAMPLE
© Oxford University Press 2013. All rights reserved.
The C do-while loop
The form of this loop
construct is as
follows:
do
{
stmT; /* body of
statements would be
placed here*/
}while(TestExpr);
8.3 “DO-WHILE” CONSTRUCT
© Oxford University Press 2013. All rights reserved.
With a do-while statement, the body of the
loop is executed first and the test expression is
checked after the loop body is executed. Thus,
the do-while statement always executes the
loop body at least once.
POINT TO NOTE
© Oxford University Press 2013. All rights reserved.
#include <stdio.h>
int main()
{
int x = 1;
int count = 0;
do {
scanf(“%d”, &x);
if(x >= 0) count += 1;
} while(x >= 0);
return 0;
}
AN EXAMPLE
© Oxford University Press 2013. All rights reserved.
WHICH LOOP SHOULD BE USED???
© Oxford University Press 2013. All rights reserved.
Some methods of controlling repetition in a program are:
 Using Sentinel Values
 Using Prime Read
 Using Counter
THERE ARE NO HARD-AND-FAST RULE
REGARDING WHICH TYPE OF LOOP SHOULD BE USED
The control is
unconditionally
transferred to the
statement associated
with the label specified
in the goto statement.
The form of a goto
statement is
goto label_name;
The following program is used
to find the factorial of a
number.
#include <stdio.h>
int main()
{
int n, c;
long int f=1;
printf(“n Enter the
number:”);
scanf(“%d”,&n);
if(n<0)
goto end;
for(c=1; c<=n; c++)
f*=c;
printf(“n FACTORIAL IS %ld”,
f);
end:
return 0;
}
GOTO STATEMENT
© Oxford University Press 2013. All rights reserved.
“return” statements
“break” statements
“continue” statements
10. SPECIAL CONTROL STATEMENTS
© Oxford University Press 2013. All rights reserved.
break continue
1. It helps to make an early
exit from the block where it
appears.
1. It helps in avoiding the
remaining statements in a
current iteration of the loop
and continuing with the next
Iteration
2. It can be used in all control
statements including switch
construct.
2. It can be used only in loop
constructs.
“BREAK” AND “CONTINUE” STATEMENTS
 A nested loop refers to
a loop that is contained
within another loop.
 If the following output
has to be obtained on
the screen
1
2 2
3 3 3
4 4 4 4
then the corresponding
program will be
#include <stdio.h>
int main()
{
int row, col;
for(row=1;row<=4;++row)
{
for(col=1;col<=row;++col)
printf(“%d t”, row);
printf(“n”);
}
return 0;
}
NESTED LOOPS
 Writing expressions like a<b<c or a==b==c etc.
 Use of = instead of ==
 Forgetting to use braces for compound statement
 Dangling else
 Use of semicolon in loop
 Floating point equality
COMMON PROGRAMMING ERRORS

More Related Content

What's hot

Chapter 4 flow control structures and arrays
Chapter 4 flow control structures and arraysChapter 4 flow control structures and arrays
Chapter 4 flow control structures and arrays
sshhzap
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
Ravi_Kant_Sahu
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
PRN USM
 
Chapter 8 - Conditional Statement
Chapter 8 - Conditional StatementChapter 8 - Conditional Statement
Chapter 8 - Conditional Statement
Deepak Singh
 

What's hot (20)

Control structure
Control structureControl structure
Control structure
 
Chapter 4 flow control structures and arrays
Chapter 4 flow control structures and arraysChapter 4 flow control structures and arrays
Chapter 4 flow control structures and arrays
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
LOOPS AND DECISIONS
LOOPS AND DECISIONSLOOPS AND DECISIONS
LOOPS AND DECISIONS
 
Control structures in C
Control structures in CControl structures in C
Control structures in C
 
Conditional statement
Conditional statementConditional statement
Conditional statement
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 
Chapter 8 - Conditional Statement
Chapter 8 - Conditional StatementChapter 8 - Conditional Statement
Chapter 8 - Conditional Statement
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Control structures selection
Control structures   selectionControl structures   selection
Control structures selection
 
If statements in c programming
If statements in c programmingIf statements in c programming
If statements in c programming
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
If-else and switch-case
If-else and switch-caseIf-else and switch-case
If-else and switch-case
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Control structure of c language
Control structure of c languageControl structure of c language
Control structure of c language
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Control structures in c
Control structures in cControl structures in c
Control structures in c
 

Similar to unit2 C-ProgrammingChapter 2 Control statements.pptx

[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
yasir_cesc
 

Similar to unit2 C-ProgrammingChapter 2 Control statements.pptx (20)

C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 
M C6java6
M C6java6M C6java6
M C6java6
 
control statements
control statementscontrol statements
control statements
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
PPS-UNIT4.pptx
PPS-UNIT4.pptxPPS-UNIT4.pptx
PPS-UNIT4.pptx
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
 
7 decision-control
7 decision-control7 decision-control
7 decision-control
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
C fundamental
C fundamentalC fundamental
C fundamental
 
Absolute Java 5e Savitch Test Bank
Absolute Java 5e Savitch Test BankAbsolute Java 5e Savitch Test Bank
Absolute Java 5e Savitch Test Bank
 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlIntroduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
 
C operators
C operatorsC operators
C operators
 
CONTROL STMTS.pptx
CONTROL STMTS.pptxCONTROL STMTS.pptx
CONTROL STMTS.pptx
 
Module 2- Control Structures
Module 2- Control StructuresModule 2- Control Structures
Module 2- Control Structures
 
Control structuresin c
Control structuresin cControl structuresin c
Control structuresin c
 
C Programming - Decision making, Looping
C  Programming - Decision making, LoopingC  Programming - Decision making, Looping
C Programming - Decision making, Looping
 

Recently uploaded

Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 

Recently uploaded (20)

Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSUNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 

unit2 C-ProgrammingChapter 2 Control statements.pptx

  • 1. UNIT II - CONTROL STATEMENTS AND INTRODUCTION TO PROBLEM SOLVING Chapter-I CONTROL STATEMENTS Mr. JAVVAJI VENKATRAO Assistant Professor Department of CSE SREE VIDYANIKETHAN ENGINEERING COLLEGE (Autonomous) TIRUPATI
  • 2.  Understanding meaning of a statement and statement block  Learn about decision type control constructs in C and the way these are used  Learn about looping type control constructs in C and the technique of putting them to use  Learn the use of special control constructs such as goto, break, continue, and return  Learn about nested loops and their utility 1. LEARNING OBJECTIVES
  • 3. 2. CONTROL STATEMENTS INCLUDE Selection Statements • if • if-else • switch Iteration Statements • for • while • do-while Jump Statements • goto • break • continue • return
  • 4. Program Control Statements/Constructs Selection/Branching Conditional Type if if-else if-else- if switch Unconditional Type break continue goto Iteration/Looping for while do- while PROGRAM CONTROL STATEMENTS/CONSTRUCTS IN ‘C’
  • 6. To Specify Symbol Used less than < greater than > less than or equal to greater than or equal to <= >= To Specify Symbol Used Equal to == Not equal to != Logical AND && Logical OR || Negation ! RELATIONAL OPERATORS Equality and Logical Operators
  • 7.  If an expression, involving the relational operator, is true, it is given a value of 1. If an expression is false, it is given a value of 0. Similarly, if a numeric expression is used as a test expression, any non-zero value (including negative) will be considered as true, while a zero value will be considered as false.  Space can be given between operand and operator (relational or logical) but space is not allowed between any compound operator like <=, >=, ==, !=. It is also compiler error to reverse them.  a == b and a = b are not similar, as == is a test for equality, a = b is an assignment operator. Therefore, the equality operator has to be used carefully.  The relational operators have lower precedence than all arithmetic operators. POINTS TO NOTE
  • 8. The following declarations and initializations are given: int x=1, y=2, z=3; Then, The expression x>=y evaluates to 0 (false). The expression x+y evaluates to 3 (true). The expression x=y evaluates to 2 (true). A FEW EXAMPLES
  • 9. NOT operator (!) AND operator && OR operator || LOGICAL OPERATORS MAY BE MIXED WITHIN RELATIONAL EXPRESSIONS BUT ONE MUST ABIDE BY THEIR PRECEDENCE RULES WHICH IS AS FOLLOWS: © Oxford University Press 2013. All rights reserved.
  • 10. Operators Associativity () ++ (postfix) -- (postfix) left to right + (unary) - (unary) right to left ++ (prefix) -- (prefix) * / % left to right + - left to right < <= > >= left to right == != left to right && left to right || left to right ?: right to left = + = - = * = / = right to left , (comma operator) left to right OPERATOR SEMANTICS © Oxford University Press 2013. All rights reserved.
  • 11. Selection Statements The Conditional Operator The switch Statement CONDITIONAL EXECUTION AND SELECTION
  • 12. One-way decisions using if statement Two-way decisions using if-else statement Multi-way decisions Dangling else Problem SELECTION STATEMENTS
  • 13. Flowchart for if construct if(TestExpr) stmtT; T F ONE-WAY DECISIONS USING IF STATEMENT TestExpr stmtT
  • 14. Algorithm C Program 1. START #include <stdio.h> int main() { int a, b, c, max; printf(“nEnter 3 numbers”); scanf(“%d %d %d”, &a, &b, &c); max=a; if(b>max) max=b; if(c>max) max=c; printf(“Largest No is %d”, max); return 0; } 2. PRINT “ENTER THREE NUMBERS” 3. INPUT A, B, C 4. MAX=A 5. IF B>MAX THEN MAX=B 6. IF C>MAX THEN MAX=C 7. PRINT “LARGEST NUMBER IS”, MAX 8. STOP WRITE A PROGRAM THAT PRINTS THE LARGEST AMONG THREE NUMBERS. © Oxford University Press 2013. All rights reserved.
  • 15. Flowchart of if-else construct The form of a two-way decision is as follows: if(TestExpr) stmtT; else stmtF; TWO-WAY DECISIONS USING IF-ELSE STATEMENT © Oxford University Press 2013. All rights reserved. TestExpr stmtT stmtF
  • 16. Algorithm C Program 1. START #include <stdio.h> int main() { int a, b, c, max; printf(“nEnter 3 numbers”); scanf(“%d %d %d”, &a, &b, &c); max=a; if(b>max) max=b; if(c>max) max=c; printf(“Largest No is %d”, max); return 0; } 2. PRINT “ENTER THREE NUMBERS” 3. INPUT A, B, C 4. MAX=A 5. IF B>MAX THEN MAX=B 6. IF C>MAX THEN MAX=C 7. PRINT “LARGEST NUMBER IS”, MAX 8. STOP WRITE A PROGRAM THAT PRINTS THE LARGEST AMONG THREE NUMBERS. © Oxford University Press 2013. All rights reserved.
  • 17. if-else-if ladder if(TestExpr1) stmtT1; else if(TestExpr2) stmtT2; else if(TestExpr3) stmtT3; .. . else if(TestExprN) stmtTN; else stmtF; General format of switch statements switch(expr) { case constant1: stmtList1; break; case constant2: stmtList2; break; case constant3: stmtList3; break; …………………………. …………………………. default: stmtListn; } MULTI-WAY DECISIONS © Oxford University Press 2013. All rights reserved.
  • 18. FLOWCHART OF AN IF-ELSE-IF CONSTRUCT © Oxford University Press 2013. All rights reserved. TestExpr TestExpr2 TestExprN TestExpr3 stmtT2 stmtTN stmtT3 stmtTF stmtT1
  • 19. #include <stdio.h> int main() { int x; printf(“n ENTER THE NUMBER:”); scanf(“%d”, &x); if(x > 0) printf(“x is positive n”); else if(x == 0) printf(“x is zero n”); else printf(“x is negative n”); return 0; } THE FOLLOWING PROGRAM CHECKS WHETHER A NUMBER GIVEN BY THE USER IS ZERO, POSITIVE, OR NEGATIVE © Oxford University Press 2013. All rights reserved.
  • 20.  When any if statement is written under another if statement, this cluster is called a nested if.  The syntax for the nested is given here: Construct 1 Construct 2 if(TestExprA) if(TestExprB) stmtBT; else stmtBF; else stmtAF; if(TestExprA) if(TestExprB) stmtBT; else stmtBF; else if(TestExprC) stmtCT; else stmtCF; NESTED IF © Oxford University Press 2013. All rights reserved.
  • 21. A PROGRAM TO FIND THE LARGEST AMONG THREE NUMBERS USING THE NESTED LOOP #include <stdio.h> int main() { int a, b, c; printf(“nEnter the three numbers”); scanf(“%d %d %d”, &a, &b, &c); if(a > b) if(a > c) printf(“%d”, a); else printf(“%d”, c); else if(b > c) printf(“%d”, b); else printf(“%d”, c); return 0; }
  • 22.  This classic problem occurs when there is no matching else for each if. To avoid this problem, the simple C rule is that always pair an else to the most recent unpaired if in the current block. Consider the illustration shown here.  The else is automatically paired with the closest if. But, it may be needed to associate an else with the outer if also. DANGLING ELSE PROBLEM © Oxford University Press 2013. All rights reserved.
  • 23. Use of null else Use of braces to enclose the true action of the second if With null else With braces if(TestExprA) if(TestExprB) stmtBT; else ; else stmtAF; if(TestExprA) { if(TestExprB) stmtBT; } else stmtAF; SOLUTIONS TO DANGLING ELSE PROBLEM © Oxford University Press 2013. All rights reserved.
  • 24. An Example  It has the following simple format: expr1 ? expr2 : expr3 It executes by first evaluating expr1, which is normally a relational expression, and then evaluates either expr2, if the first result was true, or expr3, if the first result was false. #include <stdio.h> int main() { int a,b,c; printf(“n ENTER THE TWO NUMBERS:”); scanf(“%d %d”, &a, &b); c=a>b? a : b>a ? b :-1; if(c==-1) printf(“n BOTH NUMBERS ARE EQUAL”); else printf(“n LARGER NUMBER IS %d”,c); return 0; } 6. THE CONDITIONAL OPERATOR © Oxford University Press 2013. All rights reserved.
  • 25. The C switch construct The general format of a switch statement is switch(expr) { case constant1: stmtList1; break; case constant2: stmtList2; break; case constant3: stmtList3; break; …………………………. …………………………. default: stmtListn; } THE SWITCH STATEMENT © Oxford University Press 2013. All rights reserved.
  • 26. © Oxford University Press 2013. All rights reserved.
  • 27.  The switch differs from the else-if in that switch can test only for equality, whereas the if conditional expression can be of a test expression involving any type of relational operators and/or logical operators.  A switch statement is usually more efficient than nested ifs.  The switch statement can always be replaced with a series of else-if statements. SWITCH VS NESTED IF © Oxford University Press 2013. All rights reserved.
  • 28.  A loop allows one to execute a statement or block of statements repeatedly. There are mainly two types of iterations or loops – unbounded iteration or unbounded loop and bounded iteration or bounded loop.  A loop can either be a pre- test loop or be a post-test loop as illustrated in the diagram. ITERATION AND REPETITIVE EXECUTION © Oxford University Press 2013. All rights reserved.
  • 29. Expanded Syntax of “while” and its Flowchart Representation while statement is a pretest loop. The basic syntax of the while statement is shown below: “WHILE” CONSTRUCT © Oxford University Press 2013. All rights reserved.
  • 30. #include <stdio.h> int main() { int c; c=5; // Initialization while(c>0) { // Test Expression printf(“ n %d”,c); c=c-1; // Updating } return 0; } This loop contains all the parts of a while loop. When executed in a program, this loop will output 5 4 3 2 1 AN EXAMPLE © Oxford University Press 2013. All rights reserved.
  • 31. float x; x = 0.0; while(x != 1.1) { x = x + 0.1; printf(“1.1 minus %f equals %.20gn”, x, 1.1 -x); } The above loop never terminates on many computers, because 0.1 cannot be accurately represented using binary numbers. Never test floating point numbers for exact equality, especially in loops. The correct way to make the test is to see if the two numbers are ‘approximately equal’. TESTING FOR FLOATING-POINT ‘EQUALITY’ © Oxford University Press 2013. All rights reserved.
  • 32.  The general form of the for statement is as follows: for(initialization; TestExpr; updating) stmT; for construct flow chart “FOR” CONSTRUCT © Oxford University Press 2013. All rights reserved.
  • 33. #include <stdio.h> int main() { int n, s=0, r; printf(“n Enter the Number”); scanf(“%d”, &n); for(;n>0;n/=10) { r=n%10; s=s+r; } printf(“n Sum of digits %d”, s); return 0; } EXAMPLE © Oxford University Press 2013. All rights reserved.
  • 34. The C do-while loop The form of this loop construct is as follows: do { stmT; /* body of statements would be placed here*/ }while(TestExpr); 8.3 “DO-WHILE” CONSTRUCT © Oxford University Press 2013. All rights reserved.
  • 35. With a do-while statement, the body of the loop is executed first and the test expression is checked after the loop body is executed. Thus, the do-while statement always executes the loop body at least once. POINT TO NOTE © Oxford University Press 2013. All rights reserved.
  • 36. #include <stdio.h> int main() { int x = 1; int count = 0; do { scanf(“%d”, &x); if(x >= 0) count += 1; } while(x >= 0); return 0; } AN EXAMPLE © Oxford University Press 2013. All rights reserved.
  • 37. WHICH LOOP SHOULD BE USED??? © Oxford University Press 2013. All rights reserved.
  • 38. Some methods of controlling repetition in a program are:  Using Sentinel Values  Using Prime Read  Using Counter THERE ARE NO HARD-AND-FAST RULE REGARDING WHICH TYPE OF LOOP SHOULD BE USED
  • 39. The control is unconditionally transferred to the statement associated with the label specified in the goto statement. The form of a goto statement is goto label_name; The following program is used to find the factorial of a number. #include <stdio.h> int main() { int n, c; long int f=1; printf(“n Enter the number:”); scanf(“%d”,&n); if(n<0) goto end; for(c=1; c<=n; c++) f*=c; printf(“n FACTORIAL IS %ld”, f); end: return 0; } GOTO STATEMENT © Oxford University Press 2013. All rights reserved.
  • 40. “return” statements “break” statements “continue” statements 10. SPECIAL CONTROL STATEMENTS © Oxford University Press 2013. All rights reserved.
  • 41. break continue 1. It helps to make an early exit from the block where it appears. 1. It helps in avoiding the remaining statements in a current iteration of the loop and continuing with the next Iteration 2. It can be used in all control statements including switch construct. 2. It can be used only in loop constructs. “BREAK” AND “CONTINUE” STATEMENTS
  • 42.  A nested loop refers to a loop that is contained within another loop.  If the following output has to be obtained on the screen 1 2 2 3 3 3 4 4 4 4 then the corresponding program will be #include <stdio.h> int main() { int row, col; for(row=1;row<=4;++row) { for(col=1;col<=row;++col) printf(“%d t”, row); printf(“n”); } return 0; } NESTED LOOPS
  • 43.  Writing expressions like a<b<c or a==b==c etc.  Use of = instead of ==  Forgetting to use braces for compound statement  Dangling else  Use of semicolon in loop  Floating point equality COMMON PROGRAMMING ERRORS