SlideShare a Scribd company logo
1 of 46
Chapter 3:
Control Flow/ Structure
PREPARED BY: MS. SA SOKNGIM
Content
1. Decision Making
2. Loops
3. Break and Continue Statement
4. Switch… case Statement
5. goto and label Statement
1. Decision Making
 Decision making is used to
specify the order in which
statements are executed.
• Decision making in a C program using:
• if statement
• if…else statement
• if…else if…else statement
• nested if...else statement
• Switch case Statement
1.1 if statement
if (testExpression)
{
// statements
}
Example: if statement
// Program to display a number if user enters negative number
// If user enters positive number, that number won't be displayed
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Test expression is true if number is less than 0
if (number < 0) {
printf("You entered %d.n", number);
}
printf("The if statement is easy.");
return 0;
}
1.2 if...else statement
 The if...else statement executes some code if the test expression
is true (nonzero) and some other code if the test expression is
false (0).
Syntax of if...else
if (testExpression) {
// codes inside the body of if
}else {
// codes inside the body of else
}
Example: if...else statement
// Program to check whether an integer entered by the user is odd or even
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
1.3 if...else if....else Statement
 The if...else statement executes two different codes
depending upon whether the test expression is true or false.
Sometimes, a choice has to be made from more than 2
possibilities.
 The if...else if…else statement allows you to check for
multiple test expressions and execute different codes for
more than two conditions.
Syntax of if...else if....else statement.
if (testExpression1) {
// statements to be executed if testExpression1 is true
} else if(testExpression2) {
// statements to be executed if testExpression1 is false and
testExpression2 is true
} else if (testExpression 3) {
// statements to be executed if testExpression1 and
testExpression2 is false and testExpression3 is true
} else {
// statements to be executed if all test expressions are false
}
Example: if...else if....else statement
// Program to relate two integers
using =, > or <
#include <stdio.h>
int main(){
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1,
&number2);
//checks if two integers are
equal.
if(number1 == number2){
printf("Result: %d = %d“,
number1,number2);
}
//checks if number1 is greater than
number2.
else if (number1 > number2) {
printf("Result: %d > %d",
number1, number2);
}
// if both test expression is false
else {
printf("Result: %d < %d",
number1, number2);
}
return 0;
}
1.4 Nested if else statement
 Nested if else statement is same like if else
statement, where new block of if else statement is
defined in existing if or else block statement.
 Used when user want to check more than one
conditions at a time.
Syntax of Nested If else Statement
if(condition is true){
if(condition is true){
statement;
}else{
statement;
}
}else{
statement;
}
Example of Nested if else Statement
#include <stdio.h>
void main(){
char username;
int password;
printf("Username:");
scanf("%c",&username);
printf("Password:");
scanf("%d",&password);
if(username=='a'){
if(password==12345){
printf("Login successful");
}else{
printf("Password is incorrect, Try again.");
}
}else{
printf("Username is incorrect, Try again.");
}
}
2. Loops
 Loops are used in programming to repeat a specific block until some end
condition is met.
 There are three loops in C programming:
o for loop
o while loop
o do...while loop
o Nested loops
2.1 for Loop
 The syntax of a for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// codes
}
for loop Flowchart
Example: for loop
// Program to calculate the sum of
first n natural numbers
// Positive integers 1,2,3...n are
known as natural numbers
#include <stdio.h>
int main(){
int n, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
// for loop terminates when n is less
than count
for(count = 1; count <= n; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
2.2 while loop
 The syntax of a while loop is:
while (testExpression)
{
//codes
}
Example: while loop
/ Program to find factorial of
a number
// For a positive integer n,
factorial = 1*2*3...n
#include <stdio.h>
int main(){
int number;
long factorial;
printf("Enter an integer: ");
scanf("%d",&number);
factorial = 1;
// loop terminates when number is less
than or equal to 0
while (number > 0) {
// factorial = factorial*number;
factorial *= number;
--number;
}
printf("Factorial= %lld", factorial);
return 0;
}
2.3 do...while loop
 The do..while loop is similar to the while loop with one
important difference.
 The body of do...while loop is executed once, before
checking the test expression.
 The do...while loop is executed at least once.
do...while loop Syntax
The syntax of a do while loop is:
do
{
// codes
}
while (testExpression);
Example: do...while loop
// Program to add numbers until user enters zero
#include <stdio.h>
int main() {
double number, sum = 0;
// loop body is executed at least once
do{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
2.4 Nested loops
 C programming allows to use one loop inside another
loop.
 Syntax for loop
for ( init; condition; increment ) {
for ( init; condition; increment ) {
statement(s);
}
statement(s);
}
2.4 Nested loops (Con)
 Syntax while loop
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
2.4 Nested loops (Con)
 Syntax do while loop
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
Example of Nested Loops
#include <stdio.h>
int main()
{
int n, c, k;
printf("Enter number of rowsn");
scanf("%d",&n);
for ( c = 1 ; c <= n ; c++ ){
for( k = 1 ; k <= c ; k++ )
printf("*");
printf("n");
}
return 0;
}
3. Break And Continue Statement
 What is BREAK meant?
 What is CONTINUE meant?
3.1 Break Statement
 The break statement terminates the loop immediately when
it is encountered.
 The break statement is used with decision making
statement such as if...else.
 Syntax of break statement
break;
Flowchart Of Break Statement
How break statement works?
Example: break statement
// Program to calculate the sum
of maximum of 10 numbers
// Calculates sum until user
enters positive number
# include <stdio.h>
int main() {
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i) {
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If user enters negative
number, loop is terminated
if(number < 0.0) {
break;
}
// sum = sum + number;
sum += number;
}
printf("Sum = %.2lf",sum);
return 0;
}
3.2 Continue Statement
 The continue statement skips some statements inside the loop.
 The continue statement is used with decision making statement
such as if...else.
 Syntax of continue Statement
continue;
Flowchart of Continue Statement
How Continue Statement Works?
Example: continue statement
// Program to calculate sum of
maximum of 10 numbers
// Negative numbers are skipped
from calculation
# include <stdio.h>
int main(){
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i) {
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If user enters negative
number, loop is terminated
if(number < 0.0) {
continue;
}
// sum = sum + number;
sum += number;
}
printf("Sum = %.2lf",sum);
return 0;
}
4. Switch...Case Statement
 The if...else if…else statement allows you to execute a block code among
many alternatives. If you are checking on the value of a single variable in
if...else if…else statement, it is better to use switch statement.
 The switch statement is often faster than nested if...else (not always).
Also, the syntax of switch statement is cleaner and easy to understand.
Syntax of switch...case
switch (n){
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
Switch Statement Flowchart
Example: switch Statement
// Program to create a simple calculator
// Performs addition, subtraction, multiplication or division
depending the input from user
# include <stdio.h>
int main() {
char operator;
double firstNumber,secondNumber;
printf("Enter an operator (+, -, *,): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&firstNumber, &secondNumber);
switch(operator) {
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber+secondNumber);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber*secondNumber);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);
break;
// operator is doesn't match any case constant (+, -, *, /)
default:
printf("Error! operator is not correct");
}
return 0; }
5. goto Statement
 The goto statement is used to alter the normal sequence of a C
program.
Syntax of goto Statement
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
What is Label?
 The label is an identifier. When goto statement is encountered,
control of the program jumps to label: and starts executing the code.
Example: goto Statement
// Program to calculate the sum and average of maximum of 5
numbers
// If user enters negative number, the sum and average of
previously entered positive number is displayed
# include <stdio.h>
int main(){
const int maxInput = 5;
int i;
double number, average, sum=0.0;
for(i=1; i<=maxInput; ++i){
printf("%d. Enter a number: ", i);
scanf("%lf",&number);
// If user enters negative number, flow of program moves to label
jump
if(number < 0.0)
goto jump;
sum += number; // sum = sum+number;
}
jump:
average=sum/(i-1);
printf("Sum = %.2fn", sum);
printf("Average = %.2f", average);
return 0;
}
Example: goto Statement
C Programming: Control Structure

More Related Content

What's hot

Union in C programming
Union in C programmingUnion in C programming
Union in C programmingKamal Acharya
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C ProgrammingAnil Pokhrel
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareGagan Deep
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)Ritika Sharma
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++Nitin Jawla
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programmingHarshita Yadav
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming LanguageMahantesh Devoor
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++Ankur Pandey
 
Data types in C language
Data types in C languageData types in C language
Data types in C languagekashyap399
 

What's hot (20)

Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
File in C language
File in C languageFile in C language
File in C language
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Control structures in c
Control structures in cControl structures in c
Control structures in c
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Strings in C
Strings in CStrings in C
Strings in C
 
Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Character set of c
Character set of cCharacter set of c
Character set of c
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
 

Viewers also liked

Control Structures
Control StructuresControl Structures
Control StructuresGhaffar Khan
 
disjoint-set data structures
disjoint-set data structuresdisjoint-set data structures
disjoint-set data structuresskku_npc
 
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
 
8 statement-level control structure
8 statement-level control structure8 statement-level control structure
8 statement-level control structurejigeno
 
Chapter20 capital structure_decision
Chapter20 capital structure_decisionChapter20 capital structure_decision
Chapter20 capital structure_decisionAmit Fogla
 
Control Structure in C
Control Structure in CControl Structure in C
Control Structure in CNeel Shah
 
C LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSC LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSBESTECH SOLUTIONS
 
Classical model of decision making
Classical model of decision makingClassical model of decision making
Classical model of decision makingShashank Gupta
 
Managerial Decision Making
Managerial Decision MakingManagerial Decision Making
Managerial Decision Makingmandalina landy
 
Decision Making In Management
Decision Making In ManagementDecision Making In Management
Decision Making In ManagementVinesh Pathak
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGAbhishek Dwivedi
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in JavaRavi_Kant_Sahu
 
Lecture18 structurein c.ppt
Lecture18 structurein c.pptLecture18 structurein c.ppt
Lecture18 structurein c.ppteShikshak
 

Viewers also liked (17)

Control Structures
Control StructuresControl Structures
Control Structures
 
disjoint-set data structures
disjoint-set data structuresdisjoint-set data structures
disjoint-set data structures
 
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
 
8 statement-level control structure
8 statement-level control structure8 statement-level control structure
8 statement-level control structure
 
Decision models
Decision modelsDecision models
Decision models
 
Chapter20 capital structure_decision
Chapter20 capital structure_decisionChapter20 capital structure_decision
Chapter20 capital structure_decision
 
Control structure
Control structureControl structure
Control structure
 
Control Structure in C
Control Structure in CControl Structure in C
Control Structure in C
 
C LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSC LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONS
 
Classical model of decision making
Classical model of decision makingClassical model of decision making
Classical model of decision making
 
Control structure in c
Control structure in cControl structure in c
Control structure in c
 
Managerial Decision Making
Managerial Decision MakingManagerial Decision Making
Managerial Decision Making
 
Decision Making In Management
Decision Making In ManagementDecision Making In Management
Decision Making In Management
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Decision making
Decision makingDecision making
Decision making
 
Lecture18 structurein c.ppt
Lecture18 structurein c.pptLecture18 structurein c.ppt
Lecture18 structurein c.ppt
 

Similar to C Programming: Control Structure

C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptxDEEPAK948083
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02Suhail Akraam
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptxeaglesniper008
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.Haard Shah
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programmingnmahi96
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Branching statements
Branching statementsBranching statements
Branching statementsArunMK17
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitionsaltwirqi
 
Simple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderSimple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderMoni Adhikary
 
COM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingCOM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingHemantha Kulathilake
 
CONTROL FLOW in C.pptx
CONTROL FLOW in C.pptxCONTROL FLOW in C.pptx
CONTROL FLOW in C.pptxSmitaAparadh
 
unit 2-Control Structures.pptx
unit 2-Control Structures.pptxunit 2-Control Structures.pptx
unit 2-Control Structures.pptxishaparte4
 
Control structuresin c
Control structuresin cControl structuresin c
Control structuresin cVikash Dhal
 

Similar to C Programming: Control Structure (20)

C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptx
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
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
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptx
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
Control statments in c
Control statments in cControl statments in c
Control statments in c
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Branching statements
Branching statementsBranching statements
Branching statements
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
Simple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderSimple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladder
 
3. control statement
3. control statement3. control statement
3. control statement
 
COM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingCOM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & Branching
 
CONTROL FLOW in C.pptx
CONTROL FLOW in C.pptxCONTROL FLOW in C.pptx
CONTROL FLOW in C.pptx
 
unit 2-Control Structures.pptx
unit 2-Control Structures.pptxunit 2-Control Structures.pptx
unit 2-Control Structures.pptx
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Control structuresin c
Control structuresin cControl structuresin c
Control structuresin c
 

More from Sokngim Sa

How to decompile apk
How to decompile apkHow to decompile apk
How to decompile apkSokngim Sa
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycleSokngim Sa
 
03 android application structure
03 android application structure03 android application structure
03 android application structureSokngim Sa
 
02 getting start with android app development
02 getting start with android app development02 getting start with android app development
02 getting start with android app developmentSokngim Sa
 
01 introduction to android
01 introduction to android01 introduction to android
01 introduction to androidSokngim Sa
 
Add eclipse project with git lab
Add eclipse project with git labAdd eclipse project with git lab
Add eclipse project with git labSokngim Sa
 
Transmitting network data using volley(14 09-16)
Transmitting network data using volley(14 09-16)Transmitting network data using volley(14 09-16)
Transmitting network data using volley(14 09-16)Sokngim Sa
 

More from Sokngim Sa (9)

06 UI Layout
06 UI Layout06 UI Layout
06 UI Layout
 
How to decompile apk
How to decompile apkHow to decompile apk
How to decompile apk
 
05 intent
05 intent05 intent
05 intent
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycle
 
03 android application structure
03 android application structure03 android application structure
03 android application structure
 
02 getting start with android app development
02 getting start with android app development02 getting start with android app development
02 getting start with android app development
 
01 introduction to android
01 introduction to android01 introduction to android
01 introduction to android
 
Add eclipse project with git lab
Add eclipse project with git labAdd eclipse project with git lab
Add eclipse project with git lab
 
Transmitting network data using volley(14 09-16)
Transmitting network data using volley(14 09-16)Transmitting network data using volley(14 09-16)
Transmitting network data using volley(14 09-16)
 

Recently uploaded

PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 

Recently uploaded (20)

Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 

C Programming: Control Structure

  • 1. Chapter 3: Control Flow/ Structure PREPARED BY: MS. SA SOKNGIM
  • 2. Content 1. Decision Making 2. Loops 3. Break and Continue Statement 4. Switch… case Statement 5. goto and label Statement
  • 3. 1. Decision Making  Decision making is used to specify the order in which statements are executed. • Decision making in a C program using: • if statement • if…else statement • if…else if…else statement • nested if...else statement • Switch case Statement
  • 4. 1.1 if statement if (testExpression) { // statements }
  • 5. Example: if statement // Program to display a number if user enters negative number // If user enters positive number, that number won't be displayed #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); // Test expression is true if number is less than 0 if (number < 0) { printf("You entered %d.n", number); } printf("The if statement is easy."); return 0; }
  • 6. 1.2 if...else statement  The if...else statement executes some code if the test expression is true (nonzero) and some other code if the test expression is false (0). Syntax of if...else if (testExpression) { // codes inside the body of if }else { // codes inside the body of else }
  • 7. Example: if...else statement // Program to check whether an integer entered by the user is odd or even #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d",&number); // True if remainder is 0 if( number%2 == 0 ) printf("%d is an even integer.",number); else printf("%d is an odd integer.",number); return 0; }
  • 8. 1.3 if...else if....else Statement  The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.  The if...else if…else statement allows you to check for multiple test expressions and execute different codes for more than two conditions.
  • 9. Syntax of if...else if....else statement. if (testExpression1) { // statements to be executed if testExpression1 is true } else if(testExpression2) { // statements to be executed if testExpression1 is false and testExpression2 is true } else if (testExpression 3) { // statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true } else { // statements to be executed if all test expressions are false }
  • 10. Example: if...else if....else statement // Program to relate two integers using =, > or < #include <stdio.h> int main(){ int number1, number2; printf("Enter two integers: "); scanf("%d %d", &number1, &number2); //checks if two integers are equal. if(number1 == number2){ printf("Result: %d = %d“, number1,number2); } //checks if number1 is greater than number2. else if (number1 > number2) { printf("Result: %d > %d", number1, number2); } // if both test expression is false else { printf("Result: %d < %d", number1, number2); } return 0; }
  • 11. 1.4 Nested if else statement  Nested if else statement is same like if else statement, where new block of if else statement is defined in existing if or else block statement.  Used when user want to check more than one conditions at a time.
  • 12. Syntax of Nested If else Statement if(condition is true){ if(condition is true){ statement; }else{ statement; } }else{ statement; }
  • 13. Example of Nested if else Statement #include <stdio.h> void main(){ char username; int password; printf("Username:"); scanf("%c",&username); printf("Password:"); scanf("%d",&password); if(username=='a'){ if(password==12345){ printf("Login successful"); }else{ printf("Password is incorrect, Try again."); } }else{ printf("Username is incorrect, Try again."); } }
  • 14. 2. Loops  Loops are used in programming to repeat a specific block until some end condition is met.  There are three loops in C programming: o for loop o while loop o do...while loop o Nested loops
  • 15. 2.1 for Loop  The syntax of a for loop is: for (initializationStatement; testExpression; updateStatement) { // codes }
  • 17. Example: for loop // Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include <stdio.h> int main(){ int n, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &n); // for loop terminates when n is less than count for(count = 1; count <= n; ++count) { sum += count; } printf("Sum = %d", sum); return 0; }
  • 18. 2.2 while loop  The syntax of a while loop is: while (testExpression) { //codes }
  • 19. Example: while loop / Program to find factorial of a number // For a positive integer n, factorial = 1*2*3...n #include <stdio.h> int main(){ int number; long factorial; printf("Enter an integer: "); scanf("%d",&number); factorial = 1; // loop terminates when number is less than or equal to 0 while (number > 0) { // factorial = factorial*number; factorial *= number; --number; } printf("Factorial= %lld", factorial); return 0; }
  • 20. 2.3 do...while loop  The do..while loop is similar to the while loop with one important difference.  The body of do...while loop is executed once, before checking the test expression.  The do...while loop is executed at least once.
  • 21. do...while loop Syntax The syntax of a do while loop is: do { // codes } while (testExpression);
  • 22. Example: do...while loop // Program to add numbers until user enters zero #include <stdio.h> int main() { double number, sum = 0; // loop body is executed at least once do{ printf("Enter a number: "); scanf("%lf", &number); sum += number; }while(number != 0.0); printf("Sum = %.2lf",sum); return 0; }
  • 23. 2.4 Nested loops  C programming allows to use one loop inside another loop.  Syntax for loop for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); }
  • 24. 2.4 Nested loops (Con)  Syntax while loop while(condition) { while(condition) { statement(s); } statement(s); }
  • 25. 2.4 Nested loops (Con)  Syntax do while loop do { statement(s); do { statement(s); }while( condition ); }while( condition );
  • 26. Example of Nested Loops #include <stdio.h> int main() { int n, c, k; printf("Enter number of rowsn"); scanf("%d",&n); for ( c = 1 ; c <= n ; c++ ){ for( k = 1 ; k <= c ; k++ ) printf("*"); printf("n"); } return 0; }
  • 27. 3. Break And Continue Statement  What is BREAK meant?  What is CONTINUE meant?
  • 28. 3.1 Break Statement  The break statement terminates the loop immediately when it is encountered.  The break statement is used with decision making statement such as if...else.  Syntax of break statement break;
  • 29. Flowchart Of Break Statement
  • 31. Example: break statement // Program to calculate the sum of maximum of 10 numbers // Calculates sum until user enters positive number # include <stdio.h> int main() { int i; double number, sum = 0.0; for(i=1; i <= 10; ++i) { printf("Enter a n%d: ",i); scanf("%lf",&number); // If user enters negative number, loop is terminated if(number < 0.0) { break; } // sum = sum + number; sum += number; } printf("Sum = %.2lf",sum); return 0; }
  • 32. 3.2 Continue Statement  The continue statement skips some statements inside the loop.  The continue statement is used with decision making statement such as if...else.  Syntax of continue Statement continue;
  • 35. Example: continue statement // Program to calculate sum of maximum of 10 numbers // Negative numbers are skipped from calculation # include <stdio.h> int main(){ int i; double number, sum = 0.0; for(i=1; i <= 10; ++i) { printf("Enter a n%d: ",i); scanf("%lf",&number); // If user enters negative number, loop is terminated if(number < 0.0) { continue; } // sum = sum + number; sum += number; } printf("Sum = %.2lf",sum); return 0; }
  • 36. 4. Switch...Case Statement  The if...else if…else statement allows you to execute a block code among many alternatives. If you are checking on the value of a single variable in if...else if…else statement, it is better to use switch statement.  The switch statement is often faster than nested if...else (not always). Also, the syntax of switch statement is cleaner and easy to understand.
  • 37. Syntax of switch...case switch (n){ case constant1: // code to be executed if n is equal to constant1; break; case constant2: // code to be executed if n is equal to constant2; break; . . . default: // code to be executed if n doesn't match any constant }
  • 39. Example: switch Statement // Program to create a simple calculator // Performs addition, subtraction, multiplication or division depending the input from user # include <stdio.h> int main() { char operator; double firstNumber,secondNumber; printf("Enter an operator (+, -, *,): "); scanf("%c", &operator); printf("Enter two operands: "); scanf("%lf %lf",&firstNumber, &secondNumber);
  • 40. switch(operator) { case '+': printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber+secondNumber); break; case '-': printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-secondNumber); break; case '*': printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber*secondNumber); break; case '/': printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber); break; // operator is doesn't match any case constant (+, -, *, /) default: printf("Error! operator is not correct"); } return 0; }
  • 41. 5. goto Statement  The goto statement is used to alter the normal sequence of a C program.
  • 42. Syntax of goto Statement goto label; ... .. ... ... .. ... ... .. ... label: statement;
  • 43. What is Label?  The label is an identifier. When goto statement is encountered, control of the program jumps to label: and starts executing the code.
  • 44. Example: goto Statement // Program to calculate the sum and average of maximum of 5 numbers // If user enters negative number, the sum and average of previously entered positive number is displayed # include <stdio.h> int main(){ const int maxInput = 5; int i; double number, average, sum=0.0; for(i=1; i<=maxInput; ++i){ printf("%d. Enter a number: ", i); scanf("%lf",&number);
  • 45. // If user enters negative number, flow of program moves to label jump if(number < 0.0) goto jump; sum += number; // sum = sum+number; } jump: average=sum/(i-1); printf("Sum = %.2fn", sum); printf("Average = %.2f", average); return 0; } Example: goto Statement