SlideShare ist ein Scribd-Unternehmen logo
1 von 31
CONTROL STRUCTURE in C
Flow of Control
• Unless specified otherwise, the order of statement
execution through a function is linear: one statement after
another in sequence
• Some programming statements allow us to:
– decide whether or not to execute a particular statement
– execute a statement over and over, repetitively
• These decisions are based on boolean expressions (or
conditions) that evaluate to true or false
• The order of statement execution is called
the flow of control
Conditional Statements
• A conditional statement lets us choose which statement
will be executed next
• Therefore they are sometimes called selection
statements
• Conditional statements give us the power to make basic
decisions
• The C conditional statements are the:
– if statement
– if-else statement
– switch statement
Logic of an if statement
condition
evaluated
statement
true
false
The if Statement
• The if statement has the following syntax:
if ( condition )
statement;
if is a C
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or
false.
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
Logic of an if-else statement
condition
evaluated
statement1
true false
statement2
The if-else Statement
• An else clause can be added to an if
statement to make an if-else statement
if ( condition )
statement1;
else
statement2;
• If the condition is true, statement1 is executed;
if the condition is false, statement2 is executed
• One or the other will be executed, but not both
Boolean Expressions
• A condition often uses one of C's equality operators or relational
operators, which all return boolean results:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
• Note the difference between the equality operator (==) and the
assignment operator (=)
Boolean Expressions in C
• C does not have a boolean data type.
• Therefore, C compares the values of variables and
expressions against 0 (zero) to determine if they are true or
false.
• If the value is 0 then the result is implicitly assumed to be
false.
• If the value is different from 0 then the result is implicitly
assumed to be true.
• C++ and Java have boolean data types.
Block Statements
• Several statements can be grouped together
into a block statement delimited by braces
• A block statement can be used wherever a
statement is called for in the C syntax rules
if (total > MAX)
{
printf ("Error!!n");
errorCount++;
}
Block Statements
• In an if-else statement, the if portion,
or the else portion, or both, could be block
statements
if (total > MAX)
{
printf("Error!!");
errorCount++;
}
else
{
printf ("Total: %d“, total);
current = total*2;
}
Nested if Statements
• The statement executed as a result of an if statement or
else clause could be another if statement
• These are called nested if statements
• An else clause is matched to the last unmatched if (no
matter what the indentation implies)
• Braces can be used to specify the if statement to which an
else clause belongs
The switch Statement
• The switch statement provides another way to
decide which statement to execute next
• The switch statement evaluates an expression, then
attempts to match the result to one of several
possible cases
• Each case contains a value and a list of statements
• The flow of control transfers to statement associated
with the first case value that matches
© 2004 Pearson Addison-Wesley. All rights reserved
The switch Statement
• Often a break statement is used as the last
statement in each case's statement list
• A break statement causes control to transfer to the
end of the switch statement
• If a break statement is not used, the flow of control
will continue into the next case
• Sometimes this may be appropriate, but often we
want to execute only the statements associated with
one case
The switch Statement
switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
default:
otherCount++;
break;
}
• An example of a switch statement:
The switch Statement
• A switch statement can have an optional default
case
• The default case has no associated value and simply
uses the reserved word default
• If the default case is present, control will transfer to
it if no other case value matches
• If there is no default case, and no other value
matches, control falls through to the statement after
the switch
The switch Statement
• The expression of a switch statement must result
in an integral type, meaning an integer (byte,
short, int,) or a char
• It cannot be a floating point value (float or
double)
• The implicit test condition in a switch statement is
equality
• You cannot perform relational checks with a
switch statement
The switch Statement
• The general syntax of a switch statement
is: switch ( expression )
{
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
switch
and
case
are
reserved
words
If expression
matches value2,
control jumps
to here
Repetition in Programs
• In most software, the statements in the
program may need to repeat for many times.
– e.g., calculate the value of n!.
– If n = 10000, it’s not elegant to write the code as
1*2*3*…*10000.
• LoopLoop is a control structure that repeats a group
of steps in a program.
– Loop bodyLoop body stands for the repeated statements.
• There are three C loop control statements:
– whilewhile, forfor, and do-whiledo-while. 5-19
Flow Diagram of Loop Choice Process
Copyright ©2004 Pearson Addison-Wesley.
All rights reserved.
5-20
e.g., calculate the value of n!
e.g., read the content in a file
Comparison of Loop Choices (1/2)
Kind When to Use C Structure
Counting loop We know how many loop
repetitions will be needed
in advance.
while, for
Sentinel-
controlled loop
Input of a list of data ended
by a special value
while, for
Endfile-
controlled loop
Input of a list of data from
a data file
while, for
5-21
Comparison of Loop Choices (2/2)
Kind When to Use C Structure
Input validation
loop
Repeated interactive input
of a value until a desired
value is entered.
do-while
General
conditional
loop
Repeated processing of
data until a desired
condition is met.
while, for
5-22
The while Statement in C
• The syntax of while statement in C:
while (loop repetition conditionloop repetition condition)
statement
• Loop repetition conditionLoop repetition condition is the condition
which controls the loop.
• The statement is repeated as long as the loop
repetition condition is truetrue.
• A loop is called an infinite loopinfinite loop if the loop
repetition condition is always true.
5-23
An Example of a while Loop
5-24
Statement
Loop repetition condition
Loop control variableLoop control variable is the variable whose value controls
loop repetition.
In this example, count_emp is the loop control variable.
Flowchart for a while Loop
5-25
Loop repetition condition
Statement
The for Statement in C
• The syntax of for statement in C:
for (initialization expressioninitialization expression;
loop repetition conditionloop repetition condition;
update expressionupdate expression)
statement
• The initialization expressioninitialization expression set the initial value of the
loop control variable.
• The loop repetition conditionloop repetition condition test the value of the
loop control variable.
• The update expressionupdate expression update the loop control
variable. 5-26
An Example of the for Loop
5-27
Loop repetition condition
Initialization Expression
Update Expression
count_emp is set to 0 initially.
count_emp should not exceed the value of number_emp.
count_emp is increased by one after each iteration.
Increment and Decrement Operators
• The statements of increment and decrement
are commonly used in the for loop.
• The increment (i.e., ++++) or decrement (i.e., ----)
operators are the frequently used operators
which take only one operand.
• The increment/decrement operators increase or
decrease the value of the single operand.
– e.g., for (int i = 0; i < 100; i++i++){ … }
– The variable i increase one after each iteration.
5-28
Comparison of Prefix and Postfix
Increments
Copyright ©2004 Pearson Addison-Wesley.
All rights reserved.
5-29
The value of the expression (that uses the ++/-- operators)
depends on the position of the operator.
The value
of j is
increased
The value
of j is not
increased
The do-while Statement in C
• The syntax of do-while statement in C:
do
statement
while (loop repetition conditionloop repetition condition);
• The statement is first executed.
• If the loop repetition conditionloop repetition condition is true, the
statement is repeated.
• Otherwise, the loop is exited.
5-30
An Example of the do-while Loop
/* Find even number input */
do{
printf(“Enter a value: ”);
scanf(“%d”, &num);
}while (num % 2 !=0)
5-31
This loop will repeat if the user
inputs odd number.

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c language
 
Control structures in C
Control structures in CControl structures in C
Control structures in C
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
File in C language
File in C languageFile in C language
File in C language
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
IF Statement
IF StatementIF Statement
IF Statement
 
Loops in c++ programming language
Loops in c++ programming language Loops in c++ programming language
Loops in c++ programming language
 
Loops Basics
Loops BasicsLoops Basics
Loops Basics
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentation
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++
 
Switch case in C++
Switch case in C++Switch case in C++
Switch case in C++
 
Presentation on C Switch Case Statements
Presentation on C Switch Case StatementsPresentation on C Switch Case Statements
Presentation on C Switch Case Statements
 
While loop
While loopWhile loop
While loop
 
Looping statement
Looping statementLooping statement
Looping statement
 
Break and continue
Break and continueBreak and continue
Break and continue
 
Control Structures
Control StructuresControl Structures
Control Structures
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Switch Case in C Programming
Switch Case in C ProgrammingSwitch Case in C Programming
Switch Case in C Programming
 

Andere mochten auch

Control Structure in C
Control Structure in CControl Structure in C
Control Structure in CNeel Shah
 
control structures in c if switch for
control structures in c if switch forcontrol structures in c if switch for
control structures in c if switch forgourav kottawar
 
C LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSC LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSBESTECH SOLUTIONS
 
'Quality Engineering: Build It Right The First Time' by Allan Woodcock, Shoba...
'Quality Engineering: Build It Right The First Time' by Allan Woodcock, Shoba...'Quality Engineering: Build It Right The First Time' by Allan Woodcock, Shoba...
'Quality Engineering: Build It Right The First Time' by Allan Woodcock, Shoba...TEST Huddle
 
Basic data structure and data operation
Basic data structure and data operationBasic data structure and data operation
Basic data structure and data operationMohsin Siddique
 
Introduction to Quality Engineering / Quality Control
Introduction to Quality Engineering / Quality ControlIntroduction to Quality Engineering / Quality Control
Introduction to Quality Engineering / Quality ControlAFAQAHMED JAMADAR
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual BasicTushar Jain
 
Data structure & its types
Data structure & its typesData structure & its types
Data structure & its typesRameesha Sadaqat
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its typesNavtar Sidhu Brar
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGAbhishek Dwivedi
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsAakash deep Singhal
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURESbca2010
 
Lecture18 structurein c.ppt
Lecture18 structurein c.pptLecture18 structurein c.ppt
Lecture18 structurein c.ppteShikshak
 

Andere mochten auch (16)

Control structure in c
Control structure in cControl structure in c
Control structure in c
 
Control Structure in C
Control Structure in CControl Structure in C
Control Structure in C
 
structure control system
structure control systemstructure control system
structure control system
 
control structures in c if switch for
control structures in c if switch forcontrol structures in c if switch for
control structures in c if switch for
 
C LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSC LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONS
 
'Quality Engineering: Build It Right The First Time' by Allan Woodcock, Shoba...
'Quality Engineering: Build It Right The First Time' by Allan Woodcock, Shoba...'Quality Engineering: Build It Right The First Time' by Allan Woodcock, Shoba...
'Quality Engineering: Build It Right The First Time' by Allan Woodcock, Shoba...
 
Basic data structure and data operation
Basic data structure and data operationBasic data structure and data operation
Basic data structure and data operation
 
Introduction to Quality Engineering / Quality Control
Introduction to Quality Engineering / Quality ControlIntroduction to Quality Engineering / Quality Control
Introduction to Quality Engineering / Quality Control
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual Basic
 
Data structure & its types
Data structure & its typesData structure & its types
Data structure & its types
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its types
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
Control statements
Control statementsControl statements
Control statements
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithms
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
 
Lecture18 structurein c.ppt
Lecture18 structurein c.pptLecture18 structurein c.ppt
Lecture18 structurein c.ppt
 

Ähnlich wie Control structure

Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJTANUJ ⠀
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxLikhil181
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptxssuserfb3c3e
 
whileloop-161225171903.pdf
whileloop-161225171903.pdfwhileloop-161225171903.pdf
whileloop-161225171903.pdfBasirKhan21
 
Unit II chapter 4 Loops in C
Unit II chapter 4 Loops in CUnit II chapter 4 Loops in C
Unit II chapter 4 Loops in CSowmya Jyothi
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsEng Teong Cheah
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptxSKUP1
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptxLECO9
 
Programming Fundamentals in C++ structures
Programming Fundamentals in  C++ structuresProgramming Fundamentals in  C++ structures
Programming Fundamentals in C++ structuresayshasafdarwaada
 
Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)Muhammad Tahir Bashir
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While LoopAbhishek Choksi
 

Ähnlich wie Control structure (20)

Control statements anil
Control statements anilControl statements anil
Control statements anil
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptx
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
whileloop-161225171903.pdf
whileloop-161225171903.pdfwhileloop-161225171903.pdf
whileloop-161225171903.pdf
 
Unit II chapter 4 Loops in C
Unit II chapter 4 Loops in CUnit II chapter 4 Loops in C
Unit II chapter 4 Loops in C
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Programming loop
Programming loopProgramming loop
Programming loop
 
Decision making and looping
Decision making and loopingDecision making and looping
Decision making and looping
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 
Programming Fundamentals in C++ structures
Programming Fundamentals in  C++ structuresProgramming Fundamentals in  C++ structures
Programming Fundamentals in C++ structures
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
 
Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
cpu.pdf
cpu.pdfcpu.pdf
cpu.pdf
 
DECISION MAKING.pptx
DECISION MAKING.pptxDECISION MAKING.pptx
DECISION MAKING.pptx
 
CONTROL STMTS.pptx
CONTROL STMTS.pptxCONTROL STMTS.pptx
CONTROL STMTS.pptx
 

Mehr von Samsil Arefin

Transmission Control Protocol and User Datagram protocol
Transmission Control Protocol and User Datagram protocolTransmission Control Protocol and User Datagram protocol
Transmission Control Protocol and User Datagram protocolSamsil Arefin
 
Evolution Phylogenetic
Evolution PhylogeneticEvolution Phylogenetic
Evolution PhylogeneticSamsil Arefin
 
Evolution Phylogenetic
Evolution PhylogeneticEvolution Phylogenetic
Evolution PhylogeneticSamsil Arefin
 
Ego net facebook data analysis
Ego net facebook data analysisEgo net facebook data analysis
Ego net facebook data analysisSamsil Arefin
 
Augmented Reality (AR)
Augmented Reality (AR)Augmented Reality (AR)
Augmented Reality (AR)Samsil Arefin
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationSamsil Arefin
 
Strings in programming tutorial.
Strings  in programming tutorial.Strings  in programming tutorial.
Strings in programming tutorial.Samsil Arefin
 
Linked list searching deleting inserting
Linked list searching deleting insertingLinked list searching deleting inserting
Linked list searching deleting insertingSamsil Arefin
 
Program to sort the n names in an alphabetical order
Program to sort the n names in an alphabetical orderProgram to sort the n names in an alphabetical order
Program to sort the n names in an alphabetical orderSamsil Arefin
 
Linked list int_data_fdata
Linked list int_data_fdataLinked list int_data_fdata
Linked list int_data_fdataSamsil Arefin
 
Linked list Output tracing
Linked list Output tracingLinked list Output tracing
Linked list Output tracingSamsil Arefin
 
Fundamentals of-electric-circuit
Fundamentals of-electric-circuitFundamentals of-electric-circuit
Fundamentals of-electric-circuitSamsil Arefin
 
Data structure lecture 1
Data structure   lecture 1Data structure   lecture 1
Data structure lecture 1Samsil Arefin
 
Structure in programming in c or c++ or c# or java
Structure in programming  in c or c++ or c# or javaStructure in programming  in c or c++ or c# or java
Structure in programming in c or c++ or c# or javaSamsil Arefin
 

Mehr von Samsil Arefin (20)

Transmission Control Protocol and User Datagram protocol
Transmission Control Protocol and User Datagram protocolTransmission Control Protocol and User Datagram protocol
Transmission Control Protocol and User Datagram protocol
 
Evolution Phylogenetic
Evolution PhylogeneticEvolution Phylogenetic
Evolution Phylogenetic
 
Evolution Phylogenetic
Evolution PhylogeneticEvolution Phylogenetic
Evolution Phylogenetic
 
Ego net facebook data analysis
Ego net facebook data analysisEgo net facebook data analysis
Ego net facebook data analysis
 
Augmented Reality (AR)
Augmented Reality (AR)Augmented Reality (AR)
Augmented Reality (AR)
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
Strings in programming tutorial.
Strings  in programming tutorial.Strings  in programming tutorial.
Strings in programming tutorial.
 
Linked list searching deleting inserting
Linked list searching deleting insertingLinked list searching deleting inserting
Linked list searching deleting inserting
 
Number theory
Number theoryNumber theory
Number theory
 
Program to sort the n names in an alphabetical order
Program to sort the n names in an alphabetical orderProgram to sort the n names in an alphabetical order
Program to sort the n names in an alphabetical order
 
Linked list int_data_fdata
Linked list int_data_fdataLinked list int_data_fdata
Linked list int_data_fdata
 
Linked list Output tracing
Linked list Output tracingLinked list Output tracing
Linked list Output tracing
 
Stack
StackStack
Stack
 
Sorting
SortingSorting
Sorting
 
Fundamentals of-electric-circuit
Fundamentals of-electric-circuitFundamentals of-electric-circuit
Fundamentals of-electric-circuit
 
Cyber security
Cyber securityCyber security
Cyber security
 
C programming
C programmingC programming
C programming
 
Data structure lecture 1
Data structure   lecture 1Data structure   lecture 1
Data structure lecture 1
 
Structure and union
Structure and unionStructure and union
Structure and union
 
Structure in programming in c or c++ or c# or java
Structure in programming  in c or c++ or c# or javaStructure in programming  in c or c++ or c# or java
Structure in programming in c or c++ or c# or java
 

Kürzlich hochgeladen

KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosVictor Morales
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfalene1
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
CS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdfCS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdfBalamuruganV28
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Erbil Polytechnic University
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.elesangwon
 
70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical trainingGladiatorsKasper
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communicationpanditadesh123
 
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...Stork
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Coursebim.edu.pl
 
Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Communityprachaibot
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHSneha Padhiar
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxRomil Mishra
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxStephen Sitton
 
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmComputer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmDeepika Walanjkar
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
A brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision ProA brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision ProRay Yuan Liu
 
Secure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech LabsSecure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech Labsamber724300
 
Immutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfImmutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfDrew Moseley
 

Kürzlich hochgeladen (20)

KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitos
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
CS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdfCS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdf
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
 
70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communication
 
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Course
 
Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Community
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptx
 
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmComputer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
A brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision ProA brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision Pro
 
Secure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech LabsSecure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech Labs
 
Immutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfImmutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdf
 

Control structure

  • 2. Flow of Control • Unless specified otherwise, the order of statement execution through a function is linear: one statement after another in sequence • Some programming statements allow us to: – decide whether or not to execute a particular statement – execute a statement over and over, repetitively • These decisions are based on boolean expressions (or conditions) that evaluate to true or false • The order of statement execution is called the flow of control
  • 3. Conditional Statements • A conditional statement lets us choose which statement will be executed next • Therefore they are sometimes called selection statements • Conditional statements give us the power to make basic decisions • The C conditional statements are the: – if statement – if-else statement – switch statement
  • 4. Logic of an if statement condition evaluated statement true false
  • 5. The if Statement • The if statement has the following syntax: if ( condition ) statement; if is a C reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped.
  • 6. Logic of an if-else statement condition evaluated statement1 true false statement2
  • 7. The if-else Statement • An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; • If the condition is true, statement1 is executed; if the condition is false, statement2 is executed • One or the other will be executed, but not both
  • 8. Boolean Expressions • A condition often uses one of C's equality operators or relational operators, which all return boolean results: == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to • Note the difference between the equality operator (==) and the assignment operator (=)
  • 9. Boolean Expressions in C • C does not have a boolean data type. • Therefore, C compares the values of variables and expressions against 0 (zero) to determine if they are true or false. • If the value is 0 then the result is implicitly assumed to be false. • If the value is different from 0 then the result is implicitly assumed to be true. • C++ and Java have boolean data types.
  • 10. Block Statements • Several statements can be grouped together into a block statement delimited by braces • A block statement can be used wherever a statement is called for in the C syntax rules if (total > MAX) { printf ("Error!!n"); errorCount++; }
  • 11. Block Statements • In an if-else statement, the if portion, or the else portion, or both, could be block statements if (total > MAX) { printf("Error!!"); errorCount++; } else { printf ("Total: %d“, total); current = total*2; }
  • 12. Nested if Statements • The statement executed as a result of an if statement or else clause could be another if statement • These are called nested if statements • An else clause is matched to the last unmatched if (no matter what the indentation implies) • Braces can be used to specify the if statement to which an else clause belongs
  • 13. The switch Statement • The switch statement provides another way to decide which statement to execute next • The switch statement evaluates an expression, then attempts to match the result to one of several possible cases • Each case contains a value and a list of statements • The flow of control transfers to statement associated with the first case value that matches © 2004 Pearson Addison-Wesley. All rights reserved
  • 14. The switch Statement • Often a break statement is used as the last statement in each case's statement list • A break statement causes control to transfer to the end of the switch statement • If a break statement is not used, the flow of control will continue into the next case • Sometimes this may be appropriate, but often we want to execute only the statements associated with one case
  • 15. The switch Statement switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: otherCount++; break; } • An example of a switch statement:
  • 16. The switch Statement • A switch statement can have an optional default case • The default case has no associated value and simply uses the reserved word default • If the default case is present, control will transfer to it if no other case value matches • If there is no default case, and no other value matches, control falls through to the statement after the switch
  • 17. The switch Statement • The expression of a switch statement must result in an integral type, meaning an integer (byte, short, int,) or a char • It cannot be a floating point value (float or double) • The implicit test condition in a switch statement is equality • You cannot perform relational checks with a switch statement
  • 18. The switch Statement • The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } switch and case are reserved words If expression matches value2, control jumps to here
  • 19. Repetition in Programs • In most software, the statements in the program may need to repeat for many times. – e.g., calculate the value of n!. – If n = 10000, it’s not elegant to write the code as 1*2*3*…*10000. • LoopLoop is a control structure that repeats a group of steps in a program. – Loop bodyLoop body stands for the repeated statements. • There are three C loop control statements: – whilewhile, forfor, and do-whiledo-while. 5-19
  • 20. Flow Diagram of Loop Choice Process Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-20 e.g., calculate the value of n! e.g., read the content in a file
  • 21. Comparison of Loop Choices (1/2) Kind When to Use C Structure Counting loop We know how many loop repetitions will be needed in advance. while, for Sentinel- controlled loop Input of a list of data ended by a special value while, for Endfile- controlled loop Input of a list of data from a data file while, for 5-21
  • 22. Comparison of Loop Choices (2/2) Kind When to Use C Structure Input validation loop Repeated interactive input of a value until a desired value is entered. do-while General conditional loop Repeated processing of data until a desired condition is met. while, for 5-22
  • 23. The while Statement in C • The syntax of while statement in C: while (loop repetition conditionloop repetition condition) statement • Loop repetition conditionLoop repetition condition is the condition which controls the loop. • The statement is repeated as long as the loop repetition condition is truetrue. • A loop is called an infinite loopinfinite loop if the loop repetition condition is always true. 5-23
  • 24. An Example of a while Loop 5-24 Statement Loop repetition condition Loop control variableLoop control variable is the variable whose value controls loop repetition. In this example, count_emp is the loop control variable.
  • 25. Flowchart for a while Loop 5-25 Loop repetition condition Statement
  • 26. The for Statement in C • The syntax of for statement in C: for (initialization expressioninitialization expression; loop repetition conditionloop repetition condition; update expressionupdate expression) statement • The initialization expressioninitialization expression set the initial value of the loop control variable. • The loop repetition conditionloop repetition condition test the value of the loop control variable. • The update expressionupdate expression update the loop control variable. 5-26
  • 27. An Example of the for Loop 5-27 Loop repetition condition Initialization Expression Update Expression count_emp is set to 0 initially. count_emp should not exceed the value of number_emp. count_emp is increased by one after each iteration.
  • 28. Increment and Decrement Operators • The statements of increment and decrement are commonly used in the for loop. • The increment (i.e., ++++) or decrement (i.e., ----) operators are the frequently used operators which take only one operand. • The increment/decrement operators increase or decrease the value of the single operand. – e.g., for (int i = 0; i < 100; i++i++){ … } – The variable i increase one after each iteration. 5-28
  • 29. Comparison of Prefix and Postfix Increments Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-29 The value of the expression (that uses the ++/-- operators) depends on the position of the operator. The value of j is increased The value of j is not increased
  • 30. The do-while Statement in C • The syntax of do-while statement in C: do statement while (loop repetition conditionloop repetition condition); • The statement is first executed. • If the loop repetition conditionloop repetition condition is true, the statement is repeated. • Otherwise, the loop is exited. 5-30
  • 31. An Example of the do-while Loop /* Find even number input */ do{ printf(“Enter a value: ”); scanf(“%d”, &num); }while (num % 2 !=0) 5-31 This loop will repeat if the user inputs odd number.