SlideShare a Scribd company logo
CONTROL STATEMENTS
IN C
By: Anupam Sharma
Assistant Professor
Faculty of Enggineering
Chandigarh Group of Colleges-Technical Campus
1. LEARNING OBJECTIVES
 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 about nested loops and their utility
 Learn the use of special control constructs such as goto, break,
continue, and return
2. CONTROL STATEMENTS INCLUDE
Selection
Statements
• if
• Nested if
•
• if-else
• If-else
ladder
• switch
Iteration
Statements
• for
• while
• do-while
• Nested
for/while
Jump
Statements
• goto
• break
• continue
• return
PROGRAM CONTROL
STATEMENTS/CONSTRUCTS IN ‘C’
Program Control
Statements/Constructs
Selection/Branching
Conditional
Type
if if-else
if-else-
ladder
switch
Unconditional
Type
break continue goto
Iteration/Looping
for while
do-
while
OPERATORS
Operators
<
>
==
<=
>=
!=&&
||
!=
!
RELATIONAL 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 !
Equality and Logical
Operators
POINTS TO NOTE
 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.
A FEW EXAMPLES
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).
LOGICAL OPERATORS MAY BE MIXED WITHIN RELATIONAL EXPRESSIONS
BUT ONE MUST ABIDE BY THEIR PRECEDENCE RULES WHICH IS AS
FOLLOWS:
NOT
operator(!) AND
operator&& OR
operator||
OPERATOR SEMANTICS
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
CONDITIONAL EXECUTION AND
SELECTION
 Selection Statements
 The Conditional Operator
 The switch Statement
SELECTION STATEMENTS
One-way decisions using if statement
Two-way decisions using if-else statement
Multi-way decisions
Dangling else Problem
ONE-WAY DECISIONS USING IF
STATEMENT
Flowchart for if construct
if(TestExpr)
statementT;
T F
TestExpr
statementT
WRITE A PROGRAM THAT PRINTS THE LARGEST
AMONG THREE NUMBERS USING IF.
Algorithm C Program
1. START #include <stdio.h>
int main()
{
int A, B, C;
printf("Enter the numbers A, B and C: ");
scanf("%d %d %d", &A, &B, &C);
if (A >= B && A >= C)
printf("%d is the largest number.", A);
if (B >= A && B >= C)
printf("%d is the largest number.", B);
if (C >= A && C >= B)
printf("%d is the largest number.", C);
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
TWO-WAY DECISIONS USING IF-ELSE
STATEMENT
The form of a two-way
decision is as follows:
if(TestExpr)
statement1;
else
statement2;
Flowchart of if-else construct
TestExpr
statement
1
statement
2
T
F
WRITE A PROGRAM CHECK WHETHER
AN INTEGER IS ODD OR EVEN
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number%2 == 0) // True if the remainder is 0
{
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0; }
MULTI-WAY DECISIONS
if(TestExpr1)
statementT1;
else if(TestExpr2)
statementT2;
else if(TestExpr3)
statementT3;
.. .
else if(TestExprN)
statementTN;
else
statementF;
if-else-if ladder
FLOWCHART OF AN IF-ELSE-IF
CONSTRUCT
TestExpr
TestExpr2
TestExprN
TestExpr3
statementT2
statem
entTN
statementT3 statem
entTF
statementT1
T
T
T
F
F
F
F
T
THE FOLLOWING PROGRAM CHECKS WHETHER A NUMBER
GIVEN BY THE USER IS ZERO, POSITIVE, OR NEGATIVE
#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;
}
NESTED IF
 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)
statement1;
else
statement2;}
else
statement3;
if(TestExprA)
{if(TestExprB)
statement1;
else
statement2;}
else
{ if(TestExprC)
statement3;
else
statement3;}
A PROGRAM TO FIND THE LARGEST AMONG THREE
NUMBERS USING THE NESTED IF ELSE
#include <stdio.h>
int main()
{
int A, B, C;
printf("Enter three numbers: ");
scanf("%d %d %d", &A, &B, &C);
if (A >= B) {
if (A >= C)
printf("%d is the largest number.", A);
else
printf("%d is the largest number.", C);
}
else { if (B >= C)
printf("%d is the largest number.", B);
else
printf("%d is the largest number.", C);
} return 0; }
DANGLING ELSE PROBLEM
 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.
SOLUTIONS TO DANGLING ELSE PROBLEM
 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)
statementBT;
else
;
else
statementAF;
if(TestExprA)
{
if(TestExprB)
statementBT;
}
else
statementAF;
6. THE CONDITIONAL
OPERATOR
 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.
/*C program to find largest among three
numbers using ternary operator */
#include <stdio.h>
int main()
{ int A, B, C, largest;
printf("Enter three numbers: ");
scanf("%d %d %d", &A, &B, &C);
largest = A > B ? (A > C ? A : C) : (B > C ? B : C);
printf("%d is the largest number.", largest);
return 0;
}
Output: Enter three numbers : 2 8 1
8 is the largest number.
THE SWITCH STATEMENT
The general format of a
switch statement is
switch(expr)
{
case constant1: statementList1;
break;
case constant2: statementList2;
break;
case constant3: statementList3;
break;
………………………….
………………………….
default: statement Listn;
} The C switch construct
Example
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0; }
Output: Choice is 2
SWITCH VS NESTED IF
 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.
ITERATION AND REPETITIVE EXECUTION
 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.
 WHILE
 DO..WHILE
 FOR
 JUMP STATEMENTS
 BREAK
 CONTINUE
 GOTO
 RETURN
While
while statement is a pretest loop.
The basic syntax of the while
statement is shown below:
Example While
Output
AN EXAMPLE
#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 give output
5
4
3
2
1
TESTING FOR FLOATING-POINT
‘EQUALITY’
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’.
While
Do…While
Do…While
Do…Whil
e
POINT TO NOTE
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.
Difference
For Loop
For Loop
For Loop
For Loop
For Loop
For Loop
NESTED LOOPS
 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;
}
Break
Statement
It is an jump instruction and can be used inside the
switch and loop statements.
The execution of the break statements causes the control
transfer to the statement immediately after the loop.
Break
Statement
Break
Statement
Break
Statement
Break
Statement
Continue
Statement
It is a jump statement.
It is used only inside the loop.
Its execution does not exit from the loop but escape
the loop for that iteration and transfer the control
back to the loop for the new iteration.
Continue
Statement
Continue
Statement
Continue
Statement
“BREAK” AND “CONTINUE” STATEMENTS
Goto
Statement
It is used the alter the normal sequence of flow by transferring
the control to some other part of the program unconditionally.
It is followed by the label statement which determine the
instruction to be handled next after the execution of the goto
statement.
Goto
Statement
Goto
Statement
COMMON PROGRAMMING ERRORS
 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
Control statments in c

More Related Content

PPTX
Decision Making Statement in C ppt
PPTX
Control structures in java
PDF
Introduction to Python
PDF
Function lecture
PPTX
Decision making and branching in c programming
PPTX
Data Types In C
PPTX
Presentation on C Switch Case Statements
PPTX
Exception handling c++
Decision Making Statement in C ppt
Control structures in java
Introduction to Python
Function lecture
Decision making and branching in c programming
Data Types In C
Presentation on C Switch Case Statements
Exception handling c++

What's hot (20)

PPTX
C tokens
PPTX
Pointer in c
PDF
Operators in python
PPTX
Union in c language
PDF
Operators in java
PPTX
Unit 3. Input and Output
PPTX
Switch statement, break statement, go to statement
PPT
RECURSION IN C
PPT
constants, variables and datatypes in C
PDF
Classes and objects
PPTX
File in C language
PDF
Lesson 02 python keywords and identifiers
PPT
Introduction to Basic C programming 01
PDF
Code generation in Compiler Design
PPTX
Arithmetic Expression
PPTX
Operators and expressions in c language
PPTX
Data Type in C Programming
PPTX
Structures in c language
PPTX
Conditional Statement in C Language
C tokens
Pointer in c
Operators in python
Union in c language
Operators in java
Unit 3. Input and Output
Switch statement, break statement, go to statement
RECURSION IN C
constants, variables and datatypes in C
Classes and objects
File in C language
Lesson 02 python keywords and identifiers
Introduction to Basic C programming 01
Code generation in Compiler Design
Arithmetic Expression
Operators and expressions in c language
Data Type in C Programming
Structures in c language
Conditional Statement in C Language
Ad

Similar to Control statments in c (20)

PPTX
unit2 C-ProgrammingChapter 2 Control statements.pptx
PPTX
C-Programming Control statements.pptx
PPTX
C-Programming Control statements.pptx
PDF
Module 2 - Control Structures c programming.pptm.pdf
PDF
Unit 2=Decision Control & Looping Statements.pdf
PPTX
C decision making and looping.
PPTX
Decision Making and Branching
PPTX
18CSS101J PROGRAMMING FOR PROBLEM SOLVING
PPTX
COM1407: Program Control Structures – Decision Making & Branching
PPTX
Basics of Control Statement in C Languages
PPTX
C Programming: Control Structure
PPTX
6 Control Structures-1.pptxAAAAAAAAAAAAAAAAAAAAA
PDF
Unit ii chapter 2 Decision making and Branching in C
PDF
Workbook_2_Problem_Solving_and_programming.pdf
PPTX
Control structure of c
PPTX
C programming Control Structure.pptx
PDF
ICP - Lecture 7 and 8
PDF
3-Conditional-if-else-switch btech computer in c.pdf
PDF
Selection & Making Decisions in c
PPTX
C programming
unit2 C-ProgrammingChapter 2 Control statements.pptx
C-Programming Control statements.pptx
C-Programming Control statements.pptx
Module 2 - Control Structures c programming.pptm.pdf
Unit 2=Decision Control & Looping Statements.pdf
C decision making and looping.
Decision Making and Branching
18CSS101J PROGRAMMING FOR PROBLEM SOLVING
COM1407: Program Control Structures – Decision Making & Branching
Basics of Control Statement in C Languages
C Programming: Control Structure
6 Control Structures-1.pptxAAAAAAAAAAAAAAAAAAAAA
Unit ii chapter 2 Decision making and Branching in C
Workbook_2_Problem_Solving_and_programming.pdf
Control structure of c
C programming Control Structure.pptx
ICP - Lecture 7 and 8
3-Conditional-if-else-switch btech computer in c.pdf
Selection & Making Decisions in c
C programming
Ad

More from CGC Technical campus,Mohali (20)

PPTX
Gender Issues CS.pptx
PPTX
Intellectual Property Rights.pptx
PPTX
Cyber Safety ppt.pptx
PPTX
Python Modules .pptx
PPT
Dynamic allocation
PPTX
Operators in c by anupam
PPTX
PPT
Fundamentals of-computer
PPT
PPTX
Structure in C language
PPTX
Function in c program
PPTX
PPTX
Data processing and Report writing in Research(Section E)
PPTX
data analysis and report wring in research (Section d)
PPTX
Section C(Analytical and descriptive surveys... )
Gender Issues CS.pptx
Intellectual Property Rights.pptx
Cyber Safety ppt.pptx
Python Modules .pptx
Dynamic allocation
Operators in c by anupam
Fundamentals of-computer
Structure in C language
Function in c program
Data processing and Report writing in Research(Section E)
data analysis and report wring in research (Section d)
Section C(Analytical and descriptive surveys... )

Recently uploaded (20)

PDF
Hazard Identification & Risk Assessment .pdf
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
advance database management system book.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Complications of Minimal Access Surgery at WLH
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Hazard Identification & Risk Assessment .pdf
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
Paper A Mock Exam 9_ Attempt review.pdf.
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
advance database management system book.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
A powerpoint presentation on the Revised K-10 Science Shaping Paper
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Computing-Curriculum for Schools in Ghana
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
Supply Chain Operations Speaking Notes -ICLT Program
Complications of Minimal Access Surgery at WLH
Weekly quiz Compilation Jan -July 25.pdf
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
Final Presentation General Medicine 03-08-2024.pptx
A systematic review of self-coping strategies used by university students to ...
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape

Control statments in c

  • 1. CONTROL STATEMENTS IN C By: Anupam Sharma Assistant Professor Faculty of Enggineering Chandigarh Group of Colleges-Technical Campus
  • 2. 1. LEARNING OBJECTIVES  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 about nested loops and their utility  Learn the use of special control constructs such as goto, break, continue, and return
  • 3. 2. CONTROL STATEMENTS INCLUDE Selection Statements • if • Nested if • • if-else • If-else ladder • switch Iteration Statements • for • while • do-while • Nested for/while Jump Statements • goto • break • continue • return
  • 4. PROGRAM CONTROL STATEMENTS/CONSTRUCTS IN ‘C’ Program Control Statements/Constructs Selection/Branching Conditional Type if if-else if-else- ladder switch Unconditional Type break continue goto Iteration/Looping for while do- while
  • 6. RELATIONAL 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 ! Equality and Logical Operators
  • 7. POINTS TO NOTE  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.
  • 8. A FEW EXAMPLES 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).
  • 9. LOGICAL OPERATORS MAY BE MIXED WITHIN RELATIONAL EXPRESSIONS BUT ONE MUST ABIDE BY THEIR PRECEDENCE RULES WHICH IS AS FOLLOWS: NOT operator(!) AND operator&& OR operator||
  • 10. OPERATOR SEMANTICS 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
  • 11. CONDITIONAL EXECUTION AND SELECTION  Selection Statements  The Conditional Operator  The switch Statement
  • 12. SELECTION STATEMENTS One-way decisions using if statement Two-way decisions using if-else statement Multi-way decisions Dangling else Problem
  • 13. ONE-WAY DECISIONS USING IF STATEMENT Flowchart for if construct if(TestExpr) statementT; T F TestExpr statementT
  • 14. WRITE A PROGRAM THAT PRINTS THE LARGEST AMONG THREE NUMBERS USING IF. Algorithm C Program 1. START #include <stdio.h> int main() { int A, B, C; printf("Enter the numbers A, B and C: "); scanf("%d %d %d", &A, &B, &C); if (A >= B && A >= C) printf("%d is the largest number.", A); if (B >= A && B >= C) printf("%d is the largest number.", B); if (C >= A && C >= B) printf("%d is the largest number.", C); 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
  • 15. TWO-WAY DECISIONS USING IF-ELSE STATEMENT The form of a two-way decision is as follows: if(TestExpr) statement1; else statement2; Flowchart of if-else construct TestExpr statement 1 statement 2 T F
  • 16. WRITE A PROGRAM CHECK WHETHER AN INTEGER IS ODD OR EVEN #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); if (number%2 == 0) // True if the remainder is 0 { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; }
  • 17. MULTI-WAY DECISIONS if(TestExpr1) statementT1; else if(TestExpr2) statementT2; else if(TestExpr3) statementT3; .. . else if(TestExprN) statementTN; else statementF; if-else-if ladder
  • 18. FLOWCHART OF AN IF-ELSE-IF CONSTRUCT TestExpr TestExpr2 TestExprN TestExpr3 statementT2 statem entTN statementT3 statem entTF statementT1 T T T F F F F T
  • 19. THE FOLLOWING PROGRAM CHECKS WHETHER A NUMBER GIVEN BY THE USER IS ZERO, POSITIVE, OR NEGATIVE #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; }
  • 20. NESTED IF  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) statement1; else statement2;} else statement3; if(TestExprA) {if(TestExprB) statement1; else statement2;} else { if(TestExprC) statement3; else statement3;}
  • 21. A PROGRAM TO FIND THE LARGEST AMONG THREE NUMBERS USING THE NESTED IF ELSE #include <stdio.h> int main() { int A, B, C; printf("Enter three numbers: "); scanf("%d %d %d", &A, &B, &C); if (A >= B) { if (A >= C) printf("%d is the largest number.", A); else printf("%d is the largest number.", C); } else { if (B >= C) printf("%d is the largest number.", B); else printf("%d is the largest number.", C); } return 0; }
  • 22. DANGLING ELSE PROBLEM  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.
  • 23. SOLUTIONS TO DANGLING ELSE PROBLEM  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) statementBT; else ; else statementAF; if(TestExprA) { if(TestExprB) statementBT; } else statementAF;
  • 24. 6. THE CONDITIONAL OPERATOR  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. /*C program to find largest among three numbers using ternary operator */ #include <stdio.h> int main() { int A, B, C, largest; printf("Enter three numbers: "); scanf("%d %d %d", &A, &B, &C); largest = A > B ? (A > C ? A : C) : (B > C ? B : C); printf("%d is the largest number.", largest); return 0; } Output: Enter three numbers : 2 8 1 8 is the largest number.
  • 25. THE SWITCH STATEMENT The general format of a switch statement is switch(expr) { case constant1: statementList1; break; case constant2: statementList2; break; case constant3: statementList3; break; …………………………. …………………………. default: statement Listn; } The C switch construct
  • 26. Example #include <stdio.h> int main() { int x = 2; switch (x) { case 1: printf("Choice is 1"); break; case 2: printf("Choice is 2"); break; case 3: printf("Choice is 3"); break; default: printf("Choice other than 1, 2 and 3"); break; } return 0; } Output: Choice is 2
  • 27. SWITCH VS NESTED IF  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.
  • 28. ITERATION AND REPETITIVE EXECUTION  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.  WHILE  DO..WHILE  FOR  JUMP STATEMENTS  BREAK  CONTINUE  GOTO  RETURN
  • 29. While while statement is a pretest loop. The basic syntax of the while statement is shown below:
  • 32. AN EXAMPLE #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 give output 5 4 3 2 1
  • 33. TESTING FOR FLOATING-POINT ‘EQUALITY’ 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’.
  • 34. While
  • 37. Do…Whil e POINT TO NOTE 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.
  • 45. NESTED LOOPS  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; }
  • 46. Break Statement It is an jump instruction and can be used inside the switch and loop statements. The execution of the break statements causes the control transfer to the statement immediately after the loop.
  • 51. Continue Statement It is a jump statement. It is used only inside the loop. Its execution does not exit from the loop but escape the loop for that iteration and transfer the control back to the loop for the new iteration.
  • 56. Goto Statement It is used the alter the normal sequence of flow by transferring the control to some other part of the program unconditionally. It is followed by the label statement which determine the instruction to be handled next after the execution of the goto statement.
  • 59. COMMON PROGRAMMING ERRORS  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