SlideShare a Scribd company logo
1 of 39
COM1407
Computer Programming
Lecture 06
Program Control Structures – Decision
Making & Branching
K.A.S.H. Kulathilake
B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK)
Rajarata University of Sri Lanka
Department of Physical Sciences
1
Objectives
• At the end of this lecture students should be able
to;
▫ Define the operation of if, if-else, nested if-else,
switch and conditional operator.
▫ Justify the control flow of the program under the
aforementioned C language constructs.
▫ Apply taught concepts for writing programs.
2
Decision Making with C
• The C programming language also provides
several decision-making constructs, which are:
▫ The if statement
▫ The switch statement
▫ The conditional operator
3
if Statement
• The general format of the ‘if’ statement is as follows:
if ( expression )
Program statement
or
if ( expression )
{
block of statements;
}
• Similarly, in the program statement
if ( count > COUNT_LIMIT )
printf ("Count limit exceededn");
• The printf statement is executed only if the value of count is greater
than the value of COUNT_LIMIT; otherwise, it is ignored.
4
if Statement (Cont…)
int main (void)
{
int number;
printf ("Type in your number: ");
scanf ("%i", &number);
if ( number < 0 )
{
number = -number;
}
printf ("The absolute value is %in", number);
return 0;
}
5
If entered number is < 0 the
controller passes in to the if
block and negate the value of
number. Then continue with
the printf statement.
If entered number is >= 0
the controller ignores the if
block and directly passes to
printf statement.
It is no need to specify the
scope using {} of the if block
if it has single statement.
if-else Construct
• The general format of the ‘if-else’ statement is as follows;
if (expression)
{
program statement 1;
}
else
{
program statement 2;
}
• The if-else is actually just an extension of the general
format of the if statement.
• If the result of the evaluation of expression is TRUE,
program statement 1, which immediately follows, is
executed; otherwise, program statement 2 is executed.
6
if-else Construct (Cont…)
• Similarly, in the program statement:
if ( count > COUNT_LIMIT )
printf ("Count limit exceededn");
else
printf ("Count limit is not exceededn");
• Count limit exceeded message is printed
only if the value of count is greater than the
value of COUNT_LIMIT; otherwise, it executes
the statement within the else block which is
Count limit is not exceeded.
7
if-else Construct (Cont…)
#include <stdio.h>
int main (void)
{
int number_to_test, remainder;
printf ("Enter your number to be tested.: ");
scanf ("%i", &number_to_test);
remainder = number_to_test % 2;
if ( remainder == 0 )
printf ("The number is even.n");
if ( remainder != 0 )
printf ("The number is odd.n");
return 0;
}
8
Compound Relational Test
• A compound relational test is simply one or more simple relational
tests joined by either the logical AND or the logical OR operator.
• These operators are represented by the character pairs && and ||,
respectively.
• As an example, the C statement
if ( grade >= 70 && grade <= 79 )
++grades_70_to_79;
• increments the value of grades_70_to_79 only if the value of grade
is greater than or equal to 70 and less than or equal to 79.
• In the same way, the statement
if ( index < 0 || index > 99 )
printf ("Error - index out of rangen");
• causes execution of the printf statement if index is less than 0 or
greater than 99.
9
Compound Relational Test (Cont…)
• The compound operators can be used to form
extremely complex expressions in C.
• The C language grants the programmer ultimate
flexibility in forming expressions.
• This flexibility is a capability that is often
abused.
• Simpler expressions are almost always easier to
read and debug.
10
Compound Relational Test (Cont…)
• When forming compound relational expressions,
liberally use parentheses to aid readability of the
expression and to avoid getting into trouble because
of a mistaken assumption about the precedence of
the operators in the expression.
• You can also use blank spaces to aid in the
expression’s readability.
• An extra blank space around the && and ||
operators visually sets these operators apart from
the expressions that are being joined by these
operators.
11
Compound Relational Test (Cont…)
• Candidate Selection ?
#include <stdio.h>
int main (void)
{
int appointmentNo,age,score;
printf ("Enter the appointment number : ");
scanf ("%i", &appointmentNo);
printf ("Enter age : ");
scanf ("%i", &age);
printf ("Enter score : ");
scanf ("%i", &score);
if ( (appointmentNo <= 30 && age >= 18) || score >= 40 )
printf ("Ticket issued.n");
else
printf ("You are not eligible.n");
return 0;
}
12
Nested if Statement
• In the general format of the if statement, remember that if the
result of evaluating the expression inside the parentheses is
TRUE, the statement that immediately follows is executed.
• It is perfectly valid that this program statement be another if
statement, as in the following statement:
if ( score >= 40 )
if ( age >= 18 )
printf (“Issue Ticketn");
• If the value of score is >=40, the following statement is
executed, which is another if statement.
• This if statement compares the value of age >= 18.
• If the two values are equal, the message “Issue Ticket” is
displayed at the terminal.
13
Nested if Statement (Cont…)
• What happen if we add an else clause
if ( score >= 40 )
if ( age >= 18 )
printf ("Issue Ticketn");
else
printf ("Not in agen");
• In this example else clause belongs to the closest
if statement.
14
Nested if Statement (Cont…)
#include <stdio.h>
int main (void)
{
int age,score;
printf ("Enter age : ");
scanf ("%i", &age);
printf ("Enter score : ");
scanf ("%i", &score);
if ( score >= 40 )
if ( age >= 18 )
printf ("Issue Ticketn");
else
printf ("Not in agen");
return 0;
}
15
What happen when you
enter following details?
Score = 40 and age 18
Score =20 and age 18
Score = 40 and age 10
Nested if Statement (Cont…)
• Another approach:
if ( score >= 40 )
{
if ( age >= 18 )
{
printf ("Issue Ticketn");
}
}
else
{
printf ("Not in agen");
}
• In this example else clause belongs to the outer if
statement.
16
Nested if Statement (Cont…)
#include <stdio.h>
int main (void)
{
int age,score;
printf ("Enter age : ");
scanf ("%i", &age);
printf ("Enter score : ");
scanf ("%i", &score);
if ( score >= 40 )
{
if ( age >= 18 )
{
printf ("Issue Ticketn");
}
}
else
{
printf ("Not in agen");
}
return 0;
}
17
What happen when you
enter following details?
Score = 40 and age 18
Score =20 and age 18
Score = 40 and age 10
Nested if Statement (Cont…)
• Complete version
#include <stdio.h>
int main (void)
{
int age,score;
printf ("Enter age : ");
scanf ("%i", &age);
printf ("Enter score : ");
scanf ("%i", &score);
if ( score >= 40 )
if ( age >= 18 )
printf ("Issue Ticketn");
else
printf ("Not in agen");
else
printf("Not scoredn");
return 0;
}
18
What happen when you
enter following details?
Score = 40 and age 18
Score =20 and age 18
Score = 40 and age 10
The else-if Statement
• Without if- else-if approach
if ( expression 1 )
program statement 1
else
if ( expression 2 )
program statement 2
else
program statement 3
19
Suppose you want to make three different decisions based on the value of an
input number. E.g. if the input number < 0, you execute program statement 1,
if the input number == 0, you execute program statement 2 and if the input
number > 0, you execute program statement 3.
if (input < 0 )
print (“-”);
else
if ( input == 0 )
print (“0”);
else
print (“+”);
The else-if Statement (Cont…)
20
• With if- else-if approach
if ( expression 1 )
program statement 1
else if ( expression 2 )
program statement 2
else
program statement 3
if (input < 0 )
print (“-”);
else if ( input == 0 )
print (“0”);
else
print (“+”);
This method of formatting improves the readability of the statement and makes it
clearer that a three-way decision is being made.
The else-if Statement (Cont…)
#include <stdio.h>
int main (void)
{
char c;
printf ("Enter a single character:n");
scanf ("%c", &c);
if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
printf ("It's an alphabetic character.n");
else if ( c >= '0' && c <= '9' )
printf ("It's a digit.n");
else
printf ("It's a special character.n");
return 0;
}
21
The else-if Statement (Cont…)
#include <stdio.h>
int main (void)
{
float value1, value2;
char operator;
printf ("Type in your expression.n");
scanf ("%f %c %f", &value1, &operator, &value2);
if ( operator == '+' )
printf ("%.2fn", value1 + value2);
else if ( operator == '-' )
printf ("%.2fn", value1 - value2);
else if ( operator == '*' )
printf ("%.2fn", value1 * value2);
else if ( operator == '/' )
printf ("%.2fn", value1 / value2);
return 0;
}
22
The else-if Statement (Cont…)
#include <stdio.h>
int main (void)
{
float value1, value2;
char operator;
printf ("Type in your expression.n");
scanf ("%f %c %f", &value1, &operator, &value2);
if ( operator == '+' )
printf ("%.2fn", value1 + value2);
else if ( operator == '-' )
printf ("%.2fn", value1 - value2);
else if ( operator == '*' )
printf ("%.2fn", value1 * value2);
else if ( operator == '/' )
if ( value2 == 0 )
printf ("Division by zero.n");
else
printf ("%.2fn", value1 / value2);
else
printf ("Unknown operator.n");
return 0;
}
23
switch Statement
• Within the type of if-else statement chain the
value of a variable is successively compared
against different values.
• It is so commonly used when developing
programs that a special program statement
exists in the C language for performing precisely
this function.
• The name of the statement is the switch
statement.
24
switch Statement (Cont…)
• The general format of switch statement is as
follows;
25
switch Statement (Cont…)
• The expression enclosed within parentheses is
successively compared against the values value1,
value2, ..., valuen, which must be simple
constants or constant expressions.
• If a case is found whose value is equal to the
value of expression, the program statements that
follow the case are executed.
• Note that when more than one such program
statement is included, they do not have to be
enclosed within braces.
26
switch Statement (Cont…)
• The break statement signals the end of a
particular case and causes execution of the
switch statement to be terminated.
• Remember to include the break statement at the
end of every case.
• Forgetting to do so for a particular case causes
program execution to continue into the next case
whenever that case gets executed.
27
switch Statement (Cont…)
• The special optional case called default is
executed if the value of expression does not
match any of the case values.
• This is conceptually equivalent to the “fall
through” else that you used in the previous if-
else-if example.
28
switch Statement (Cont…)
#include <stdio.h>
int main (void)
{
float value1, value2;
char operator;
printf ("Type in your expression.n");
scanf ("%f %c %f", &value1, &operator, &value2);
switch (operator)
{
case '+':
printf ("%.2fn", value1 + value2);
break;
case '-':
printf ("%.2fn", value1 - value2);
break;
29
switch Statement (Cont…)
case '*':
printf ("%.2fn", value1 * value2);
break;
case '/':
if ( value2 == 0 )
printf ("Division by zero.n");
else
printf ("%.2fn", value1 / value2);
break;
default:
printf ("Unknown operator.n");
break;
}
return 0;
}
30
switch Statement (Cont…)
• It is a good programming habit to remember to
include the break at the end of every case.
• When writing a switch statement, bear in mind that
no two case values can be the same.
• However, you can associate more than one case
value with a particular set of program statements.
• This is done simply by listing the multiple case
values (with the keyword case before the value and
the colon after the value in each case) before the
common statements that are to be executed.
31
switch Statement (Cont…)
32
The Conditional Operator
• The conditional operator is a ternary operator;
that is, it takes three operands.
• The two symbols that are used to denote this
operator are the question mark (?) and the colon
(:).
• The first operand is placed before the ?, the
second between the ? and the :, and the third
after the :.
33
The Conditional Operator (Cont…)
• The general format of the conditional operator is:
condition ? expression1 : expression2
• Where condition is an expression, usually a relational
expression, that is evaluated first whenever the
conditional operator is encountered.
• If the result of the evaluation of condition is TRUE (that
is, nonzero), then expression1 is evaluated and the result
of the evaluation becomes the result of the operation.
• If condition evaluates FALSE (that is, zero), then
expression2 is evaluated and its result becomes the
result of the operation.
34
The Conditional Operator (Cont…)
• The conditional operator is most often used to
assign one of two values to a variable depending
upon some condition.
• For example, suppose you have an integer
variable x and another integer variable s.
• If you want to assign –1 to s if x were less than
zero, and the value of x2 to s otherwise, the
following statement could be written:
s = ( x < 0 ) ? -1 : x * x;
35
The Conditional Operator (Cont…)
• Examples
• State what happen in following statements;
maxValue = ( a > b ) ? a : b;
sign = ( number < 0 ) ? -1 : (( number == 0 ) ? 0 : 1);
printf ("Sign = %in",
( number < 0 ) ? –1 : ( number == 0 ) ? 0 : 1);
36
Objective Re-cap
• Now you should be able to:
▫ Define the operation of if, if-else, nested if-else,
switch and conditional operator.
▫ Justify the control flow of the program under the
aforementioned C language constructs.
▫ Apply taught concepts for writing programs.
37
References
• Chapter 06 - Programming in C, 3rd Edition,
Stephen G. Kochan
38
Next: Program Control Structures – Repetition and Loops
39

More Related Content

What's hot

Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements Tarun Sharma
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
Best Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesBest Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesTech
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++Neeru Mittal
 
Algorithmsandflowcharts2
Algorithmsandflowcharts2Algorithmsandflowcharts2
Algorithmsandflowcharts2Darlene Interno
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of PrecedenceMuhammad Hammad Waseem
 
Variables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detailVariables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detailgourav kottawar
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniquesfika sweety
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiSowmya Jyothi
 
1153 algorithms%20and%20flowcharts
1153 algorithms%20and%20flowcharts1153 algorithms%20and%20flowcharts
1153 algorithms%20and%20flowchartsDani Garnida
 

What's hot (20)

Flow chart programming
Flow chart programmingFlow chart programming
Flow chart programming
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
Introduction to algorithms
Introduction to algorithmsIntroduction to algorithms
Introduction to algorithms
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
Best Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesBest Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing Techniques
 
Ch3 selection
Ch3 selectionCh3 selection
Ch3 selection
 
Algorithms
AlgorithmsAlgorithms
Algorithms
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
 
Algorithmsandflowcharts2
Algorithmsandflowcharts2Algorithmsandflowcharts2
Algorithmsandflowcharts2
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
 
Variables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detailVariables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detail
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniques
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
 
Flow chart
Flow chartFlow chart
Flow chart
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
1153 algorithms%20and%20flowcharts
1153 algorithms%20and%20flowcharts1153 algorithms%20and%20flowcharts
1153 algorithms%20and%20flowcharts
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
Program sba
Program sbaProgram sba
Program sba
 

Viewers also liked

Algorithms presentation on Path Matrix, Bell Number and Sorting
Algorithms presentation on Path Matrix, Bell Number and SortingAlgorithms presentation on Path Matrix, Bell Number and Sorting
Algorithms presentation on Path Matrix, Bell Number and SortingRishabh Mehan
 
Basic Programming Concept
Basic Programming ConceptBasic Programming Concept
Basic Programming ConceptCma Mohd
 
Programming process and flowchart
Programming process and flowchartProgramming process and flowchart
Programming process and flowcharthermiraguilar
 
Pseudocode-Flowchart
Pseudocode-FlowchartPseudocode-Flowchart
Pseudocode-Flowchartlotlot
 
Pseudocode flowcharts
Pseudocode flowchartsPseudocode flowcharts
Pseudocode flowchartsnicky_walters
 
Algorithm and pseudo codes
Algorithm and pseudo codesAlgorithm and pseudo codes
Algorithm and pseudo codeshermiraguilar
 
Flowchart pseudocode-examples
Flowchart pseudocode-examplesFlowchart pseudocode-examples
Flowchart pseudocode-examplesGautam Roy
 
Lect 1. introduction to programming languages
Lect 1. introduction to programming languagesLect 1. introduction to programming languages
Lect 1. introduction to programming languagesVarun Garg
 

Viewers also liked (9)

Algorithms presentation on Path Matrix, Bell Number and Sorting
Algorithms presentation on Path Matrix, Bell Number and SortingAlgorithms presentation on Path Matrix, Bell Number and Sorting
Algorithms presentation on Path Matrix, Bell Number and Sorting
 
Basic Programming Concept
Basic Programming ConceptBasic Programming Concept
Basic Programming Concept
 
Programming process and flowchart
Programming process and flowchartProgramming process and flowchart
Programming process and flowchart
 
Pseudocode-Flowchart
Pseudocode-FlowchartPseudocode-Flowchart
Pseudocode-Flowchart
 
Pseudocode flowcharts
Pseudocode flowchartsPseudocode flowcharts
Pseudocode flowcharts
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
Algorithm and pseudo codes
Algorithm and pseudo codesAlgorithm and pseudo codes
Algorithm and pseudo codes
 
Flowchart pseudocode-examples
Flowchart pseudocode-examplesFlowchart pseudocode-examples
Flowchart pseudocode-examples
 
Lect 1. introduction to programming languages
Lect 1. introduction to programming languagesLect 1. introduction to programming languages
Lect 1. introduction to programming languages
 

Similar to COM1407: Program Control Structures – Decision Making & Branching

Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions imtiazalijoono
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02Suhail Akraam
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 
Branching statements
Branching statementsBranching statements
Branching statementsArunMK17
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptxDEEPAK948083
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about CYi-Hsiu Hsu
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.Haard Shah
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.comGreen Ecosystem
 
Decisions in C or If condition
Decisions in C or If conditionDecisions in C or If condition
Decisions in C or If conditionyarkhosh
 
E1 – FundamentalsPlease refer to announcements for details about.docx
E1 – FundamentalsPlease refer to announcements for details about.docxE1 – FundamentalsPlease refer to announcements for details about.docx
E1 – FundamentalsPlease refer to announcements for details about.docxjacksnathalie
 

Similar to COM1407: Program Control Structures – Decision Making & Branching (20)

Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
Control structures(class 02)
Control structures(class 02)Control structures(class 02)
Control structures(class 02)
 
Decision Making and Branching
Decision Making and BranchingDecision Making and Branching
Decision Making and Branching
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Branching statements
Branching statementsBranching statements
Branching statements
 
control statement
control statement control statement
control statement
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptx
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about C
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 
Decisions in C or If condition
Decisions in C or If conditionDecisions in C or If condition
Decisions in C or If condition
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
E1 – FundamentalsPlease refer to announcements for details about.docx
E1 – FundamentalsPlease refer to announcements for details about.docxE1 – FundamentalsPlease refer to announcements for details about.docx
E1 – FundamentalsPlease refer to announcements for details about.docx
 

More from Hemantha Kulathilake

NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar Hemantha Kulathilake
 
NLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishNLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishHemantha Kulathilake
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelHemantha Kulathilake
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingHemantha Kulathilake
 
COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation Hemantha Kulathilake
 

More from Hemantha Kulathilake (20)

NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar
 
NLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishNLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for English
 
NLP_KASHK:POS Tagging
NLP_KASHK:POS TaggingNLP_KASHK:POS Tagging
NLP_KASHK:POS Tagging
 
NLP_KASHK:Markov Models
NLP_KASHK:Markov ModelsNLP_KASHK:Markov Models
NLP_KASHK:Markov Models
 
NLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram ModelsNLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram Models
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language Model
 
NLP_KASHK:N-Grams
NLP_KASHK:N-GramsNLP_KASHK:N-Grams
NLP_KASHK:N-Grams
 
NLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit DistanceNLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit Distance
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological Parsing
 
NLP_KASHK:Morphology
NLP_KASHK:MorphologyNLP_KASHK:Morphology
NLP_KASHK:Morphology
 
NLP_KASHK:Text Normalization
NLP_KASHK:Text NormalizationNLP_KASHK:Text Normalization
NLP_KASHK:Text Normalization
 
NLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State AutomataNLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State Automata
 
NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions
 
NLP_KASHK: Introduction
NLP_KASHK: Introduction NLP_KASHK: Introduction
NLP_KASHK: Introduction
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation
 
COM1407: Input/ Output Functions
COM1407: Input/ Output FunctionsCOM1407: Input/ Output Functions
COM1407: Input/ Output Functions
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
COM1407: C Operators
COM1407: C OperatorsCOM1407: C Operators
COM1407: C Operators
 

Recently uploaded

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 

Recently uploaded (20)

YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 

COM1407: Program Control Structures – Decision Making & Branching

  • 1. COM1407 Computer Programming Lecture 06 Program Control Structures – Decision Making & Branching K.A.S.H. Kulathilake B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK) Rajarata University of Sri Lanka Department of Physical Sciences 1
  • 2. Objectives • At the end of this lecture students should be able to; ▫ Define the operation of if, if-else, nested if-else, switch and conditional operator. ▫ Justify the control flow of the program under the aforementioned C language constructs. ▫ Apply taught concepts for writing programs. 2
  • 3. Decision Making with C • The C programming language also provides several decision-making constructs, which are: ▫ The if statement ▫ The switch statement ▫ The conditional operator 3
  • 4. if Statement • The general format of the ‘if’ statement is as follows: if ( expression ) Program statement or if ( expression ) { block of statements; } • Similarly, in the program statement if ( count > COUNT_LIMIT ) printf ("Count limit exceededn"); • The printf statement is executed only if the value of count is greater than the value of COUNT_LIMIT; otherwise, it is ignored. 4
  • 5. if Statement (Cont…) int main (void) { int number; printf ("Type in your number: "); scanf ("%i", &number); if ( number < 0 ) { number = -number; } printf ("The absolute value is %in", number); return 0; } 5 If entered number is < 0 the controller passes in to the if block and negate the value of number. Then continue with the printf statement. If entered number is >= 0 the controller ignores the if block and directly passes to printf statement. It is no need to specify the scope using {} of the if block if it has single statement.
  • 6. if-else Construct • The general format of the ‘if-else’ statement is as follows; if (expression) { program statement 1; } else { program statement 2; } • The if-else is actually just an extension of the general format of the if statement. • If the result of the evaluation of expression is TRUE, program statement 1, which immediately follows, is executed; otherwise, program statement 2 is executed. 6
  • 7. if-else Construct (Cont…) • Similarly, in the program statement: if ( count > COUNT_LIMIT ) printf ("Count limit exceededn"); else printf ("Count limit is not exceededn"); • Count limit exceeded message is printed only if the value of count is greater than the value of COUNT_LIMIT; otherwise, it executes the statement within the else block which is Count limit is not exceeded. 7
  • 8. if-else Construct (Cont…) #include <stdio.h> int main (void) { int number_to_test, remainder; printf ("Enter your number to be tested.: "); scanf ("%i", &number_to_test); remainder = number_to_test % 2; if ( remainder == 0 ) printf ("The number is even.n"); if ( remainder != 0 ) printf ("The number is odd.n"); return 0; } 8
  • 9. Compound Relational Test • A compound relational test is simply one or more simple relational tests joined by either the logical AND or the logical OR operator. • These operators are represented by the character pairs && and ||, respectively. • As an example, the C statement if ( grade >= 70 && grade <= 79 ) ++grades_70_to_79; • increments the value of grades_70_to_79 only if the value of grade is greater than or equal to 70 and less than or equal to 79. • In the same way, the statement if ( index < 0 || index > 99 ) printf ("Error - index out of rangen"); • causes execution of the printf statement if index is less than 0 or greater than 99. 9
  • 10. Compound Relational Test (Cont…) • The compound operators can be used to form extremely complex expressions in C. • The C language grants the programmer ultimate flexibility in forming expressions. • This flexibility is a capability that is often abused. • Simpler expressions are almost always easier to read and debug. 10
  • 11. Compound Relational Test (Cont…) • When forming compound relational expressions, liberally use parentheses to aid readability of the expression and to avoid getting into trouble because of a mistaken assumption about the precedence of the operators in the expression. • You can also use blank spaces to aid in the expression’s readability. • An extra blank space around the && and || operators visually sets these operators apart from the expressions that are being joined by these operators. 11
  • 12. Compound Relational Test (Cont…) • Candidate Selection ? #include <stdio.h> int main (void) { int appointmentNo,age,score; printf ("Enter the appointment number : "); scanf ("%i", &appointmentNo); printf ("Enter age : "); scanf ("%i", &age); printf ("Enter score : "); scanf ("%i", &score); if ( (appointmentNo <= 30 && age >= 18) || score >= 40 ) printf ("Ticket issued.n"); else printf ("You are not eligible.n"); return 0; } 12
  • 13. Nested if Statement • In the general format of the if statement, remember that if the result of evaluating the expression inside the parentheses is TRUE, the statement that immediately follows is executed. • It is perfectly valid that this program statement be another if statement, as in the following statement: if ( score >= 40 ) if ( age >= 18 ) printf (“Issue Ticketn"); • If the value of score is >=40, the following statement is executed, which is another if statement. • This if statement compares the value of age >= 18. • If the two values are equal, the message “Issue Ticket” is displayed at the terminal. 13
  • 14. Nested if Statement (Cont…) • What happen if we add an else clause if ( score >= 40 ) if ( age >= 18 ) printf ("Issue Ticketn"); else printf ("Not in agen"); • In this example else clause belongs to the closest if statement. 14
  • 15. Nested if Statement (Cont…) #include <stdio.h> int main (void) { int age,score; printf ("Enter age : "); scanf ("%i", &age); printf ("Enter score : "); scanf ("%i", &score); if ( score >= 40 ) if ( age >= 18 ) printf ("Issue Ticketn"); else printf ("Not in agen"); return 0; } 15 What happen when you enter following details? Score = 40 and age 18 Score =20 and age 18 Score = 40 and age 10
  • 16. Nested if Statement (Cont…) • Another approach: if ( score >= 40 ) { if ( age >= 18 ) { printf ("Issue Ticketn"); } } else { printf ("Not in agen"); } • In this example else clause belongs to the outer if statement. 16
  • 17. Nested if Statement (Cont…) #include <stdio.h> int main (void) { int age,score; printf ("Enter age : "); scanf ("%i", &age); printf ("Enter score : "); scanf ("%i", &score); if ( score >= 40 ) { if ( age >= 18 ) { printf ("Issue Ticketn"); } } else { printf ("Not in agen"); } return 0; } 17 What happen when you enter following details? Score = 40 and age 18 Score =20 and age 18 Score = 40 and age 10
  • 18. Nested if Statement (Cont…) • Complete version #include <stdio.h> int main (void) { int age,score; printf ("Enter age : "); scanf ("%i", &age); printf ("Enter score : "); scanf ("%i", &score); if ( score >= 40 ) if ( age >= 18 ) printf ("Issue Ticketn"); else printf ("Not in agen"); else printf("Not scoredn"); return 0; } 18 What happen when you enter following details? Score = 40 and age 18 Score =20 and age 18 Score = 40 and age 10
  • 19. The else-if Statement • Without if- else-if approach if ( expression 1 ) program statement 1 else if ( expression 2 ) program statement 2 else program statement 3 19 Suppose you want to make three different decisions based on the value of an input number. E.g. if the input number < 0, you execute program statement 1, if the input number == 0, you execute program statement 2 and if the input number > 0, you execute program statement 3. if (input < 0 ) print (“-”); else if ( input == 0 ) print (“0”); else print (“+”);
  • 20. The else-if Statement (Cont…) 20 • With if- else-if approach if ( expression 1 ) program statement 1 else if ( expression 2 ) program statement 2 else program statement 3 if (input < 0 ) print (“-”); else if ( input == 0 ) print (“0”); else print (“+”); This method of formatting improves the readability of the statement and makes it clearer that a three-way decision is being made.
  • 21. The else-if Statement (Cont…) #include <stdio.h> int main (void) { char c; printf ("Enter a single character:n"); scanf ("%c", &c); if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) printf ("It's an alphabetic character.n"); else if ( c >= '0' && c <= '9' ) printf ("It's a digit.n"); else printf ("It's a special character.n"); return 0; } 21
  • 22. The else-if Statement (Cont…) #include <stdio.h> int main (void) { float value1, value2; char operator; printf ("Type in your expression.n"); scanf ("%f %c %f", &value1, &operator, &value2); if ( operator == '+' ) printf ("%.2fn", value1 + value2); else if ( operator == '-' ) printf ("%.2fn", value1 - value2); else if ( operator == '*' ) printf ("%.2fn", value1 * value2); else if ( operator == '/' ) printf ("%.2fn", value1 / value2); return 0; } 22
  • 23. The else-if Statement (Cont…) #include <stdio.h> int main (void) { float value1, value2; char operator; printf ("Type in your expression.n"); scanf ("%f %c %f", &value1, &operator, &value2); if ( operator == '+' ) printf ("%.2fn", value1 + value2); else if ( operator == '-' ) printf ("%.2fn", value1 - value2); else if ( operator == '*' ) printf ("%.2fn", value1 * value2); else if ( operator == '/' ) if ( value2 == 0 ) printf ("Division by zero.n"); else printf ("%.2fn", value1 / value2); else printf ("Unknown operator.n"); return 0; } 23
  • 24. switch Statement • Within the type of if-else statement chain the value of a variable is successively compared against different values. • It is so commonly used when developing programs that a special program statement exists in the C language for performing precisely this function. • The name of the statement is the switch statement. 24
  • 25. switch Statement (Cont…) • The general format of switch statement is as follows; 25
  • 26. switch Statement (Cont…) • The expression enclosed within parentheses is successively compared against the values value1, value2, ..., valuen, which must be simple constants or constant expressions. • If a case is found whose value is equal to the value of expression, the program statements that follow the case are executed. • Note that when more than one such program statement is included, they do not have to be enclosed within braces. 26
  • 27. switch Statement (Cont…) • The break statement signals the end of a particular case and causes execution of the switch statement to be terminated. • Remember to include the break statement at the end of every case. • Forgetting to do so for a particular case causes program execution to continue into the next case whenever that case gets executed. 27
  • 28. switch Statement (Cont…) • The special optional case called default is executed if the value of expression does not match any of the case values. • This is conceptually equivalent to the “fall through” else that you used in the previous if- else-if example. 28
  • 29. switch Statement (Cont…) #include <stdio.h> int main (void) { float value1, value2; char operator; printf ("Type in your expression.n"); scanf ("%f %c %f", &value1, &operator, &value2); switch (operator) { case '+': printf ("%.2fn", value1 + value2); break; case '-': printf ("%.2fn", value1 - value2); break; 29
  • 30. switch Statement (Cont…) case '*': printf ("%.2fn", value1 * value2); break; case '/': if ( value2 == 0 ) printf ("Division by zero.n"); else printf ("%.2fn", value1 / value2); break; default: printf ("Unknown operator.n"); break; } return 0; } 30
  • 31. switch Statement (Cont…) • It is a good programming habit to remember to include the break at the end of every case. • When writing a switch statement, bear in mind that no two case values can be the same. • However, you can associate more than one case value with a particular set of program statements. • This is done simply by listing the multiple case values (with the keyword case before the value and the colon after the value in each case) before the common statements that are to be executed. 31
  • 33. The Conditional Operator • The conditional operator is a ternary operator; that is, it takes three operands. • The two symbols that are used to denote this operator are the question mark (?) and the colon (:). • The first operand is placed before the ?, the second between the ? and the :, and the third after the :. 33
  • 34. The Conditional Operator (Cont…) • The general format of the conditional operator is: condition ? expression1 : expression2 • Where condition is an expression, usually a relational expression, that is evaluated first whenever the conditional operator is encountered. • If the result of the evaluation of condition is TRUE (that is, nonzero), then expression1 is evaluated and the result of the evaluation becomes the result of the operation. • If condition evaluates FALSE (that is, zero), then expression2 is evaluated and its result becomes the result of the operation. 34
  • 35. The Conditional Operator (Cont…) • The conditional operator is most often used to assign one of two values to a variable depending upon some condition. • For example, suppose you have an integer variable x and another integer variable s. • If you want to assign –1 to s if x were less than zero, and the value of x2 to s otherwise, the following statement could be written: s = ( x < 0 ) ? -1 : x * x; 35
  • 36. The Conditional Operator (Cont…) • Examples • State what happen in following statements; maxValue = ( a > b ) ? a : b; sign = ( number < 0 ) ? -1 : (( number == 0 ) ? 0 : 1); printf ("Sign = %in", ( number < 0 ) ? –1 : ( number == 0 ) ? 0 : 1); 36
  • 37. Objective Re-cap • Now you should be able to: ▫ Define the operation of if, if-else, nested if-else, switch and conditional operator. ▫ Justify the control flow of the program under the aforementioned C language constructs. ▫ Apply taught concepts for writing programs. 37
  • 38. References • Chapter 06 - Programming in C, 3rd Edition, Stephen G. Kochan 38
  • 39. Next: Program Control Structures – Repetition and Loops 39