SlideShare a Scribd company logo
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
 
Introduction to algorithms
Introduction to algorithmsIntroduction to algorithms
Introduction to algorithms
Madishetty Prathibha
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
tanmaymodi4
 
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
Tech
 
Pseudocode
PseudocodePseudocode
Pseudocode
grahamwell
 
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
Sowmya 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 Precedence
Muhammad 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 detail
gourav kottawar
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniques
fika sweety
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
Sowmya Jyothi
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
Rohit Shrivastava
 
1153 algorithms%20and%20flowcharts
1153 algorithms%20and%20flowcharts1153 algorithms%20and%20flowcharts
1153 algorithms%20and%20flowchartsDani Garnida
 
[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++
Muhammad Hammad Waseem
 

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 Sorting
Rishabh Mehan
 
Basic Programming Concept
Basic Programming ConceptBasic Programming Concept
Basic Programming Concept
Cma 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
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
Hemantha Kulathilake
 
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-examples
Gautam 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 Structure
Sokngim Sa
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
Suhail Akraam
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
Komal Kotak
 
Control structures(class 02)
Control structures(class 02)Control structures(class 02)
Control structures(class 02)
Vinoth Chandrasekaran
 
Decision Making and Branching
Decision Making and BranchingDecision Making and Branching
Decision Making and Branching
Munazza-Mah-Jabeen
 
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 statements
ArunMK17
 
control statement
control statement control statement
control statement
Kathmandu University
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptx
DEEPAK948083
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about C
Yi-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 C
sana shaikh
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
Green Ecosystem
 
Decisions in C or If condition
Decisions in C or If conditionDecisions in C or If condition
Decisions in C or If condition
yarkhosh
 
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
jacksnathalie
 

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 English
Hemantha Kulathilake
 
NLP_KASHK:POS Tagging
NLP_KASHK:POS TaggingNLP_KASHK:POS Tagging
NLP_KASHK:POS Tagging
Hemantha Kulathilake
 
NLP_KASHK:Markov Models
NLP_KASHK:Markov ModelsNLP_KASHK:Markov Models
NLP_KASHK:Markov Models
Hemantha Kulathilake
 
NLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram ModelsNLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram Models
Hemantha Kulathilake
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language Model
Hemantha Kulathilake
 
NLP_KASHK:N-Grams
NLP_KASHK:N-GramsNLP_KASHK:N-Grams
NLP_KASHK:N-Grams
Hemantha Kulathilake
 
NLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit DistanceNLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit Distance
Hemantha Kulathilake
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological Parsing
Hemantha Kulathilake
 
NLP_KASHK:Morphology
NLP_KASHK:MorphologyNLP_KASHK:Morphology
NLP_KASHK:Morphology
Hemantha Kulathilake
 
NLP_KASHK:Text Normalization
NLP_KASHK:Text NormalizationNLP_KASHK:Text Normalization
NLP_KASHK:Text Normalization
Hemantha Kulathilake
 
NLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State AutomataNLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State Automata
Hemantha Kulathilake
 
NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions
Hemantha Kulathilake
 
NLP_KASHK: Introduction
NLP_KASHK: Introduction NLP_KASHK: Introduction
NLP_KASHK: Introduction
Hemantha Kulathilake
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
Hemantha 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
 
COM1407: Input/ Output Functions
COM1407: Input/ Output FunctionsCOM1407: Input/ Output Functions
COM1407: Input/ Output Functions
Hemantha Kulathilake
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
Hemantha Kulathilake
 
COM1407: C Operators
COM1407: C OperatorsCOM1407: C Operators
COM1407: C Operators
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

"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 

Recently uploaded (20)

"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 

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