SlideShare a Scribd company logo
1 of 37
Download to read offline
Flow Control
Lecture 5 – Tuesday 25th February 2019
Today’s Class
• Flow Control
• Control Structures
• Conditional Statements
Intro-Decisions in Your Code
• Programs execute top-down
• Decisions break the top-down flow
• The if statement tests a condition
• When the condition is true, program flow is
altered.
Flow Control
• In computer science, control flow (or flow
of control) is the order in which individual
statements, instructions or function calls of
an imperative program are executed or
evaluated. The emphasis on explicit control
flow distinguishes an imperative
programming language from a declarative
programming language. Wikipedia
Flow Control
• In a program statement may be executed
sequentially, selectively or iteratively.
• Every program language provides constructs to
support sequence, selection or iteration.
Types of Control Structures
Flow of control through any given function is
implemented with three basic types of control
structures:
• Sequential: default mode. ... Following a
recipe
• Selection: used for decisions, branching --
choosing between 2 or more alternative
paths. ... If, if/else, switch
• Repetition: used for looping, i.e. repeating
a piece of code multiple times in a
row….while, do/while, for
Useful tools
Some useful tools for building programs or
program segments
• pseudocode - helps "think" out a problem
or algorithm before trying to code it.
• flowcharting - graphical way to formulate
an algorithm or a program's flow.
• stepwise refinement (top-down design) of
algorithms
THE SEQUENCE CONSTRUCT
Statement 1
Statement 2
Statement 3
Example of Sequential Structure
#include <stdio.h>
int main()
{
puts("I'm a computer!");
puts("Thrilled to meet you!");
return(0);
}
View code
SELECTION
• The Selection construct means the execution
of statement(s) depending upon a
condition-test. If a condition evaluates to
true, a course-of-action (a set of statements)
is followed otherwise another course-of-
action (a different set of statements).
• This construct(selection construct) is also
called decision construct because it helps in
making decision about which set-of-
statements is to be executed.
THE SELECTION CONSTRUCT.
Condition ? Statement 1 Statement 2
Statement 1
Statement 2
ITERATION
• Iteration construct means repetition of set of
statements depending upon a condition
test. Till the time of condition is true. ( or false
depending upon the loop). A set of
statements are repeated again and again.
As soon as the condition become false (or
true), the repetition stops. The iteration
condition is also called ”Looping Construct”.
THE ITERATION CONSTRUCT
Condition ?
Statement 1
Statement 2
The Loop Body
True
False
Comparison Operator
THE SELECTION STATEMENT – if Statement
• An if statement tests a particular condition,
if the condition evaluated to true, a course
of action is followed, i.e., a statement or a
set of statement is executed. Otherwise if
the condition evaluated to false then the
course of action is ignored.
SYNTAX OF IF STATEMENT
• if (condition)
statement 1;
The statement may consist of single or
compound. If the condition evaluates non
zero value that is true then the statement 1
is executed otherwise if the condition
evaluates zero i.e., false then the statement
1 is ignored.
Example of if statement
Example 1:
if (age>18)
printf(“The person is eligible for vote”)
Example 2:
#include <stdio.h>
int main()
{
int a;
printf("Type an integer: ");
scanf("%d",&a);
if( a > 10 )
printf("%d is greater than 10.n",a);
return(0);
}
Notice the semi colon
Example of if statement
The need to evaluate the false condition would then give us the following code.
#include <stdio.h>
int main()
{
int a;
printf("Type an integer: ");
scanf("%d",&a);
if( a > 10 )
{
printf("You typed %d.n",a);
printf("%d is greater than 10.n",a);
}
if(a <= 10 )
{
printf("You typed %d.n",a);
printf("%d is less than or equal to 10.n",a);
}
return(0);
THE ELSE CLUASE
• An if statement can optionally include an else
clause. The else clause is included as follows:
if (expression)
statement1;
else
statement2;
• If expression evaluates to true, statement1 is
executed. If expression evaluates to false,
statement2 is executed.
• Both statement1 and statement2 can be
compound statements or blocks.
3/7/2019
Flow chart of if statement
if Condition ? Statement 1 Statement 2
Statement 1
Statement 2
els
e
tru
e
IF - ELSE FORMAT
if (condition)
{
Statement 1
Statement 2
}
else
{
Statement 1
Statement 2
}
Example of if-else
#include <stdio.h>
int main()
{
int a;
printf("Type an integer: ");
scanf("%d",&a);
if( a > 10 )
{
printf("You typed %d.n",a);
printf("%d is greater than 10.n",a);
}
else(a <= 10 )
{
printf("You typed %d.n",a);
printf("%d is less than or equal to 10.n",a);
}
return(0);
Run code
NESTED IFs
• A nested if is an if that has another if in its body or
in its else body. The nested if can have one of
the following three forms
Form 1 :
if (expression 1)
{
if (expression 2)
statement 1
else
statement 2
}
else
body of else
NESTED IF contd..
• Form 2:
if (expression 1)
{
if (expression 2)
statement 1
else
statement 2
……….
}
else
{
if (expression 2)
statement 1
else
statement 2
……….
}
NESTED IF contd..
• Form 3:
if (expression 1)
{
body of if
}
else
{
if (expression 2)
statement 1
else
statement 2
……….
}
THE if-else-if LADDER
• A common programming construct in C is
the if-else-if ladder, which is often also
called as the if-else-if ladder because of its
appearance. It takes the following general
form.
if (expression 1) statement 1;
else
if (expression 2) statement 2
else
if (expression 3) statement 3
……….
else
Statement 4;
Example
#include <stdio.h>
int main()
{
int a;
printf("Type an integer: ");
scanf("%d",&a);
if( a > 10 )
{
printf("You typed %d.n",a);
printf("%d is greater than 10.n",a);
}
else if( a < 10)
{
printf("You typed %d.n",a);
printf("%d is less than 10.n",a);
}
else
{
printf("You typed %d.n",a);
printf("%d is 10.n",a);
}
return(0);
}
Run code
THE ? : ALTERNATIVE TO if
• C has an operator that can be alternative to if
statement. The conditional operator ? :
• This operator can be used to replace the if
statement of C.
CONDITIONAL OPERATOR ? :
if (expression 2)
statement 1
else
statement 2
• The above form of if else statement can be
replaced as,
expression1?expression2:expression3;
CONDITIONAL OPERATOR ? :
• For example
char result;
int marks;
if (marks > 50)
{
result =‘p’;
}
Else
{
result =‘f’;
}
• This can be alternatively written as,
char result;
int marks;
Result = (marks > 50) ? ‘p’ : ‘f’;
COMPARISON OF if AND ? :
1. compared to if –else sequence, ?: offers more
concise, clean and compact code, but it is less
obvious as compared to if.
2. Another difference is that the conditional
operator ?: produces an expression, and hence a
single value can be assigned or incorporated into
a larger expression, where as if is more flexible. if
can have multiple statements multiple assignments
and expressions (in the form of compound
statement) in its body.
3. When ?: operator is used in its nested form it
becomes complex and difficult to understand.
Generally ?: is used to conceal (hide) the purpose
of the code.
Challenge- Group work
• What is the output of the following C
program fragment?
#include <stdio.h>
Int var =75
Int var2 =56
Int num;
num =sizeof(var)? (var2>23 ?)((var ==75) ? ‘A’ : 0) :0) :0;
Printf(“%d”, num);
Return o;
}
Multiple Decisions
• The C language lets you handle complex
decisions by stacking a bunch of if else
conditions.
• Sometimes that structure gets a bit weird.
• As an alternative you can employ the
switch-case structure which is another
decision making tool in the C-language.
Example
#include <stdio.h>
int main()
{
char a;
printf("Your choice (A,B,C): ");
scanf("%c",&a);
switch(a)
{
case 'A':
puts("Excellent choice!");
break;
case 'B':
puts("This is the most common choice.");
break;
case 'C':
puts("I question your decision.");
break;
default:
puts("That's not a valid choice.");
}
return(0);
}
Build and run the code lets see what it does
Challenge-Group Exercise
• Code a decision making structure
• Prompt for integer input
• For values1,2,or3, display the words “red”,
“green” or “blue.”
• Flag invalid input for any other values the
user inputs.
Solution
• Lets see
• 2
• 3
• 4
• Solutions
• Stick to one solution, groups of 5
(tengwau@must.ac.ug)
• THANKS FOR LISTENING
• Next iteration construct

More Related Content

What's hot

What's hot (20)

If and select statement
If and select statementIf and select statement
If and select statement
 
Control Structure in C
Control Structure in CControl Structure in C
Control Structure in C
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 
C language control statements
C language  control statementsC language  control statements
C language control statements
 
Selection statements
Selection statementsSelection statements
Selection statements
 
Control structures i
Control structures i Control structures i
Control structures i
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
 
Control Statement programming
Control Statement programmingControl Statement programming
Control Statement programming
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C Programming
 
C programming decision making
C programming decision makingC programming decision making
C programming decision making
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Flow of control by deepak lakhlan
Flow of control by deepak lakhlanFlow of control by deepak lakhlan
Flow of control by deepak lakhlan
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Control structure in c
Control structure in cControl structure in c
Control structure in c
 
Control structures selection
Control structures   selectionControl structures   selection
Control structures selection
 
Controlstatment in c
Controlstatment in cControlstatment in c
Controlstatment in c
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Control statement
Control statementControl statement
Control statement
 

Similar to Introduction to computer programming (C)-CSC1205_Lec5_Flow control

C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
chintupro9
 
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYC UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
Rajeshkumar Reddy
 
Decision making and looping - c programming by YEASIN NEWAJ
Decision making and looping -  c programming by YEASIN NEWAJDecision making and looping -  c programming by YEASIN NEWAJ
Decision making and looping - c programming by YEASIN NEWAJ
YeasinNewaj
 

Similar to Introduction to computer programming (C)-CSC1205_Lec5_Flow control (20)

C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
 
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYC UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
2. Control structures with for while and do while.ppt
2. Control structures with for while and do while.ppt2. Control structures with for while and do while.ppt
2. Control structures with for while and do while.ppt
 
Decision making and looping - c programming by YEASIN NEWAJ
Decision making and looping -  c programming by YEASIN NEWAJDecision making and looping -  c programming by YEASIN NEWAJ
Decision making and looping - c programming by YEASIN NEWAJ
 
Control statements
Control statementsControl statements
Control statements
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Programming Fundamentals in C++ structures
Programming Fundamentals in  C++ structuresProgramming Fundamentals in  C++ structures
Programming Fundamentals in C++ structures
 
C sharp chap4
C sharp chap4C sharp chap4
C sharp chap4
 
CONTROL STMTS.pptx
CONTROL STMTS.pptxCONTROL STMTS.pptx
CONTROL STMTS.pptx
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
 
C Constructs (C Statements & Loop)
C Constructs (C Statements & Loop)C Constructs (C Statements & Loop)
C Constructs (C Statements & Loop)
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
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
 
Comp ppt (1)
Comp ppt (1)Comp ppt (1)
Comp ppt (1)
 
C fundamental
C fundamentalC fundamental
C fundamental
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

Introduction to computer programming (C)-CSC1205_Lec5_Flow control

  • 1. Flow Control Lecture 5 – Tuesday 25th February 2019
  • 2. Today’s Class • Flow Control • Control Structures • Conditional Statements
  • 3. Intro-Decisions in Your Code • Programs execute top-down • Decisions break the top-down flow • The if statement tests a condition • When the condition is true, program flow is altered.
  • 4. Flow Control • In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an imperative programming language from a declarative programming language. Wikipedia
  • 5. Flow Control • In a program statement may be executed sequentially, selectively or iteratively. • Every program language provides constructs to support sequence, selection or iteration.
  • 6. Types of Control Structures Flow of control through any given function is implemented with three basic types of control structures: • Sequential: default mode. ... Following a recipe • Selection: used for decisions, branching -- choosing between 2 or more alternative paths. ... If, if/else, switch • Repetition: used for looping, i.e. repeating a piece of code multiple times in a row….while, do/while, for
  • 7. Useful tools Some useful tools for building programs or program segments • pseudocode - helps "think" out a problem or algorithm before trying to code it. • flowcharting - graphical way to formulate an algorithm or a program's flow. • stepwise refinement (top-down design) of algorithms
  • 8. THE SEQUENCE CONSTRUCT Statement 1 Statement 2 Statement 3
  • 9. Example of Sequential Structure #include <stdio.h> int main() { puts("I'm a computer!"); puts("Thrilled to meet you!"); return(0); } View code
  • 10. SELECTION • The Selection construct means the execution of statement(s) depending upon a condition-test. If a condition evaluates to true, a course-of-action (a set of statements) is followed otherwise another course-of- action (a different set of statements). • This construct(selection construct) is also called decision construct because it helps in making decision about which set-of- statements is to be executed.
  • 11. THE SELECTION CONSTRUCT. Condition ? Statement 1 Statement 2 Statement 1 Statement 2
  • 12. ITERATION • Iteration construct means repetition of set of statements depending upon a condition test. Till the time of condition is true. ( or false depending upon the loop). A set of statements are repeated again and again. As soon as the condition become false (or true), the repetition stops. The iteration condition is also called ”Looping Construct”.
  • 13. THE ITERATION CONSTRUCT Condition ? Statement 1 Statement 2 The Loop Body True False
  • 15. THE SELECTION STATEMENT – if Statement • An if statement tests a particular condition, if the condition evaluated to true, a course of action is followed, i.e., a statement or a set of statement is executed. Otherwise if the condition evaluated to false then the course of action is ignored.
  • 16. SYNTAX OF IF STATEMENT • if (condition) statement 1; The statement may consist of single or compound. If the condition evaluates non zero value that is true then the statement 1 is executed otherwise if the condition evaluates zero i.e., false then the statement 1 is ignored.
  • 17. Example of if statement Example 1: if (age>18) printf(“The person is eligible for vote”) Example 2: #include <stdio.h> int main() { int a; printf("Type an integer: "); scanf("%d",&a); if( a > 10 ) printf("%d is greater than 10.n",a); return(0); } Notice the semi colon
  • 18. Example of if statement The need to evaluate the false condition would then give us the following code. #include <stdio.h> int main() { int a; printf("Type an integer: "); scanf("%d",&a); if( a > 10 ) { printf("You typed %d.n",a); printf("%d is greater than 10.n",a); } if(a <= 10 ) { printf("You typed %d.n",a); printf("%d is less than or equal to 10.n",a); } return(0);
  • 19. THE ELSE CLUASE • An if statement can optionally include an else clause. The else clause is included as follows: if (expression) statement1; else statement2; • If expression evaluates to true, statement1 is executed. If expression evaluates to false, statement2 is executed. • Both statement1 and statement2 can be compound statements or blocks. 3/7/2019
  • 20. Flow chart of if statement if Condition ? Statement 1 Statement 2 Statement 1 Statement 2 els e tru e
  • 21. IF - ELSE FORMAT if (condition) { Statement 1 Statement 2 } else { Statement 1 Statement 2 }
  • 22. Example of if-else #include <stdio.h> int main() { int a; printf("Type an integer: "); scanf("%d",&a); if( a > 10 ) { printf("You typed %d.n",a); printf("%d is greater than 10.n",a); } else(a <= 10 ) { printf("You typed %d.n",a); printf("%d is less than or equal to 10.n",a); } return(0); Run code
  • 23. NESTED IFs • A nested if is an if that has another if in its body or in its else body. The nested if can have one of the following three forms Form 1 : if (expression 1) { if (expression 2) statement 1 else statement 2 } else body of else
  • 24. NESTED IF contd.. • Form 2: if (expression 1) { if (expression 2) statement 1 else statement 2 ………. } else { if (expression 2) statement 1 else statement 2 ………. }
  • 25. NESTED IF contd.. • Form 3: if (expression 1) { body of if } else { if (expression 2) statement 1 else statement 2 ………. }
  • 26. THE if-else-if LADDER • A common programming construct in C is the if-else-if ladder, which is often also called as the if-else-if ladder because of its appearance. It takes the following general form. if (expression 1) statement 1; else if (expression 2) statement 2 else if (expression 3) statement 3 ………. else Statement 4;
  • 27. Example #include <stdio.h> int main() { int a; printf("Type an integer: "); scanf("%d",&a); if( a > 10 ) { printf("You typed %d.n",a); printf("%d is greater than 10.n",a); } else if( a < 10) { printf("You typed %d.n",a); printf("%d is less than 10.n",a); } else { printf("You typed %d.n",a); printf("%d is 10.n",a); } return(0); } Run code
  • 28. THE ? : ALTERNATIVE TO if • C has an operator that can be alternative to if statement. The conditional operator ? : • This operator can be used to replace the if statement of C.
  • 29. CONDITIONAL OPERATOR ? : if (expression 2) statement 1 else statement 2 • The above form of if else statement can be replaced as, expression1?expression2:expression3;
  • 30. CONDITIONAL OPERATOR ? : • For example char result; int marks; if (marks > 50) { result =‘p’; } Else { result =‘f’; } • This can be alternatively written as, char result; int marks; Result = (marks > 50) ? ‘p’ : ‘f’;
  • 31. COMPARISON OF if AND ? : 1. compared to if –else sequence, ?: offers more concise, clean and compact code, but it is less obvious as compared to if. 2. Another difference is that the conditional operator ?: produces an expression, and hence a single value can be assigned or incorporated into a larger expression, where as if is more flexible. if can have multiple statements multiple assignments and expressions (in the form of compound statement) in its body. 3. When ?: operator is used in its nested form it becomes complex and difficult to understand. Generally ?: is used to conceal (hide) the purpose of the code.
  • 32. Challenge- Group work • What is the output of the following C program fragment? #include <stdio.h> Int var =75 Int var2 =56 Int num; num =sizeof(var)? (var2>23 ?)((var ==75) ? ‘A’ : 0) :0) :0; Printf(“%d”, num); Return o; }
  • 33. Multiple Decisions • The C language lets you handle complex decisions by stacking a bunch of if else conditions. • Sometimes that structure gets a bit weird. • As an alternative you can employ the switch-case structure which is another decision making tool in the C-language.
  • 34. Example #include <stdio.h> int main() { char a; printf("Your choice (A,B,C): "); scanf("%c",&a); switch(a) { case 'A': puts("Excellent choice!"); break; case 'B': puts("This is the most common choice."); break; case 'C': puts("I question your decision."); break; default: puts("That's not a valid choice."); } return(0); } Build and run the code lets see what it does
  • 35. Challenge-Group Exercise • Code a decision making structure • Prompt for integer input • For values1,2,or3, display the words “red”, “green” or “blue.” • Flag invalid input for any other values the user inputs.
  • 36. Solution • Lets see • 2 • 3 • 4 • Solutions • Stick to one solution, groups of 5 (tengwau@must.ac.ug)
  • 37. • THANKS FOR LISTENING • Next iteration construct