SlideShare a Scribd company logo
For more Https://www.ThesisScientist.com
Unit 5
Controls & Loops
Control Statements
The control statements enable us to specify the order in which the various instructions in a program are to
be executed by the computer. They determine the flow of control in a program.
There are 4 types of control statements in C. They are:
a) Sequence control statements
b) Decision control statements or conditional statement
c) Case control statements
d) Repetition or loop control statements
Conditional Statements
C has two major decision making statements.
1. If_else statement
2. Switch statement
If_else Statement
The if_else statement is a powerful decision making tool. It allows the computer to evaluate the expression.
Depending on whether the value of expression is 'True' or 'False' certain group of statements are executed.
The syntax of if_else statement is:
if (condition is true)
statement 1;
else
statement 2;
The condition following the keyword is always enclosed in parenthesis. If the condition is true, statements
in then part are executed, i.e., statement1, otherwise statement2 in else part is executed. There may be a
number of statements in then and else parts.
e.g.:
/* magic number program * /
main( )
{
int magic = 223;
int guess;
printf ("Enter your guess for the number n");
scanf ("% d" &guess);
if (guess = = magic)
printf ("n Congratulation ! Right guess");
else
printf ("n wrong guess");
}
Nesting of if_else Statement
When a series of decisions are involved in the statement, we may have to use more than one if_else
statement in nested form. This can be described by the flowchart in the following figure:
Is
Condition
One True
Statement 1
Statement 2
Statement 3
Statement x
N
N
Y
Y
Is
Condition
One True
Is
Condition 2
True
Statement 1
Statement 2
Statement 3
Statement x
N
N
Y
Y
Figure 5.1: Flow Chart of if_else statement in Nested Form
e.g.: / * finding the largest of 3 numbers * /
main( )
{
float a = 5, b = 2, c = 7;
if (a > b)
{
if (a > c)
printf ("a is greatest");
else
printf ("c is greatest");
}
else
{
if (b > c) printf ("b is greatest");
else printf ("c is greatest");
}
}
else if Ladder
There is another way of putting ifs together when multipath decisions are involved. Multipath decision is a
chain of ifs in which statement associated with each else is an if.
It takes the following general form:
if (condition 1)
statement1;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
statement x;
The conditions in elseif ladder are evaluated from the top (of the ladder) downwards. As soon as the true
condition is found, associated statement is executed and control is transferred to statement x.
e.g.: main( )
{
int unit, custom;
float charges;
printf ("Enter Customer No. and Units Consumered: n");
scanf ("% d % d", & custnum, & unit);
if (unit < = 200)
charges = 0.5 *units;
else if (units < = 400)
charges = 100 + 0.65* (units - 200);
else if (units < = 600)
charges = 230 + 0.8 * (units - 600);
printf ("n n Customer No: % charges: %0.2f n" Custnum, Charges);
}
The Switch Statement
In multiway decision construct the complexity of a program increases with the increase in number of
alternatives. The program becomes difficult to read and follow. C has a built-in multiway decision
statement known as switch. The switch statement tests the value of a given variable or expression against a
list of case values and when a match is found a block of statement associated with that case is executed.
The general form is:
switch (expression)
{
case constant_1:
statements;
case constant_2:
statements;
default:
statements;
}
First, the integer expression following the keyword switch is evaluated. The value it gives is then matched,
one by one, against the constant values that follow the case statements. Whenever a match is formed, the
program executes the statements following the case, and all subsequent cases and default statements as
well.
/* Find whether number is even or odd */
main( )
{
int n, ch;
printf ("Enter the number: n");
scanf ("%d; &n);
if (n%2 = = 0)
ch = 1;
else
ch = 2;
switch (ch)
{
case 1:
printf ("number is even n");
break;
case 2:
printf ("Number is odd n");
}
}
Loops in C
Loops in C allow a set of instructions to be performed until a certain condition is reached. There are three
types of loops in C:
1. for loop
2. while loop
3. do-while loop
The for Loop
It is a very useful looping construct in C. It has three expressions. a) counter initialization
b) condition c) modification of counter.
Counter initialization
Loop terminated
fCheck the
Condition
Block of
statement
t
Modification
of counter
Counter initialization
Loop terminated
fCheck the
Condition
Block of
statement
t
Modification
of counter
Figure 5.2: Working of 'for' Loop
The general form of for loop is
for (initialization; condition; increment)
{
statement 1;
_______
_______
statement n;
}
The initialization is usually an assignment statement that is used to set the loop control variable. The
condition is a relational expression that determines when the loop will exit. The increment defines how loop
control variable will change each time the loop is repeated. These three sections are seperated by a
semicolon. The for loop will execute as long as the condition holds true. Once the condition becomes false,
program execution will resume on the statement following the block.
e.g.: /* program to print a message 5 times */
main( )
{
int i;
for (i = 1; i < = 5; i ++)
{
printf ("n In the loop % d times", i);
}
}
The While Loop
While is an entry controlled Loop statement. The basic format of the while statement is:
while (test condition)
{
body of Loop;
}
The test condition is evaluated and if the condition is true, the body of loop will be executed. That is why,
while Loop is an entry controlled statement.
Out of Loop
f
Condition
Block of
statement
t
Out of Loop
f
Condition
Block of
statement
t
Figure 5.3: The while Loop
e.g.:1 /* print the numbers 1 to 10 */
# include <stdio.h>
main( )
{
int n = 1;
while (n < = 10)
{
printf ("%d n", n);
n ++;
}
}
The Do-while Loop
The general form of do-while Loop is:
do
{
body of Loop;
}
while (test condition);
It first executes the body of the loop, then evaluates the test condition. If the condition is true, the body of
loop is executed again and again until the condition becomes false.
Out of Loop
false
Condition
Body of Loop
true
Out of Loop
false
Condition
Body of Loop
true
Figure 5.4: do-while Loop
Since the test condition is evaluated at the bottom of the loop, the do-while construct provides an exit
controlled loop. Thus, the body is executed at least once.
e.g.: /* Find the factorial of any number * /
# include <stdio.h>
main( )
{
int n, no, fact = 1;
printf ("Enter the number:");
scanf ("% d", & n);
no = n;
if (n < 0)
printf ("n factorial of negative number not possible:");
else
if (n = = 0)
printf ("Factorial of 0 is 1 n");
else
do
{
fact * = n;
n - -;
}
while (n > i)
printf ("factorial of % d = % d", no, fact);
}
The Continue Statement
The continue statement is used to bypass the remainder of the current pass through a loop. The loop does
not terminate when a continue statement is encountered. Rather, the remaining loop statements are skipped
and the computation proceeds directly to the next pass through the loop. The continue statement tells the
compiler to skip the following statements and continue with the next iteration. The continue statement can
be included within a while, a do-while or a for statement. It is written simply as continue; without any
embedded statements or expressions.
Some illustrations of loops that contain continue statements are given below. In each case, the processing of
the current value of x will be bypassed if the value of x is negative. Execution of a loop will then continue
with the next pass.
do-while Loop
do
{
scanf ("%f", &x);
if (x < 0)
{
printf ("Error-negative value for X");
continue;
};
The exit( ) Function
The exit( ) function is used for terminating the execution of C program. It is a standard library function and
uses header file stdlib.h.
The general form of exit( ) function is
exit (int status);
The difference between break and exit( ) is that former terminates the execution of loop in which it is
written while exit( ) terminates the execution of program itself.
The status (in the general form of exit( )) is a value returned to the operation system after the termination of
the program.
.
The goto Statement
C supports the goto statement to branch unconditionally from one point to another in the program. A goto
statement breaks the normal sequential execution of the program. The goto requires a label in order to
identify the place where the branch is to be made. A label is any valid variable name, and must be followed
by a colon. A label is placed immediately before the statement where the control is to be transferred.
The general forms of goto and label statements are shown below:
goto label; label:
. . . . . . . . statements;
label: . . . . . . . .
statement; goto label;
The label: can by anywhere in the program either before or after the goto label; statement.
During running of a program when a statement like goto begin; is met, the flow of control will jump to the
statement immediately following the label begin. The following program is written to evaluate the square
root of numbers read from the terminal. Due to the unconditional goto statement at the end, the control is
always transferred back to the input statement. It puts the computer in a permanent loop as infinite loop.
main( )
{
double x, y;
read: scanf ("%f", &x);
if (x < 0) goto read;
y = sqrt (x);
printf ("%f %f n", x, y);
goto read;
}

More Related Content

PPT
Control statements and functions in c
PPTX
Decision making and branching in c programming
PPTX
Decision statements in c language
PPT
Branching in C
PDF
Unit II chapter 4 Loops in C
PPTX
Selection Statements in C Programming
Control statements and functions in c
Decision making and branching in c programming
Decision statements in c language
Branching in C
Unit II chapter 4 Loops in C
Selection Statements in C Programming

What's hot (20)

PDF
C programming decision making
PPTX
Control and conditional statements
PPTX
Control structure of c
PPT
Decision Making and Branching in C
PDF
9. statements (conditional statements)
PPTX
Decision Making Statement in C ppt
PPTX
Control Flow Statements
PPTX
operators and control statements in c language
PPTX
Decision making statements in C programming
PPTX
Branching statements
PPTX
C decision making and looping.
PPTX
Control statements in c
PPTX
Control structure of c language
PPT
Control structure
PPT
Decision making and branching
PPT
The Three Basic Selection Structures in C++ Programming Concepts
PPTX
C Programming: Control Structure
PPT
Control structure C++
PPT
Structure in programming in c or c++ or c# or java
C programming decision making
Control and conditional statements
Control structure of c
Decision Making and Branching in C
9. statements (conditional statements)
Decision Making Statement in C ppt
Control Flow Statements
operators and control statements in c language
Decision making statements in C programming
Branching statements
C decision making and looping.
Control statements in c
Control structure of c language
Control structure
Decision making and branching
The Three Basic Selection Structures in C++ Programming Concepts
C Programming: Control Structure
Control structure C++
Structure in programming in c or c++ or c# or java
Ad

Similar to Controls & Loops in C (20)

PPTX
control_structures_c_language_regarding how to represent the loop in language...
PPTX
Control Structures in C
PDF
PROBLEM SOLVING USING NOW PPSC- UNIT -2.pdf
PDF
CS305PC_C++_UNIT 2.pdf jntuh third semester
PPT
C statements.ppt presentation in c language
PPT
Decision making in C(2020-2021) statements
PPTX
Basics of Control Statement in C Languages
PDF
Control statements-Computer programming
PPTX
Decision statements in c laguage
PPT
2. Control structures with for while and do while.ppt
PDF
Unit 2=Decision Control & Looping Statements.pdf
PPTX
CH-4 (1).pptx
PPTX
C Programming Unit-2
PPTX
Mca i pic u-3 handling input output and control statements
PPTX
C Programming Control Structures(if,if-else)
PPTX
Diploma ii cfpc u-3 handling input output and control statements
PPTX
Btech i pic u-3 handling input output and control statements
PPTX
handling input output and control statements
PDF
4_Decision Making and Branching in C Program.pdf
PPTX
Bsc cs pic u-3 handling input output and control statements
control_structures_c_language_regarding how to represent the loop in language...
Control Structures in C
PROBLEM SOLVING USING NOW PPSC- UNIT -2.pdf
CS305PC_C++_UNIT 2.pdf jntuh third semester
C statements.ppt presentation in c language
Decision making in C(2020-2021) statements
Basics of Control Statement in C Languages
Control statements-Computer programming
Decision statements in c laguage
2. Control structures with for while and do while.ppt
Unit 2=Decision Control & Looping Statements.pdf
CH-4 (1).pptx
C Programming Unit-2
Mca i pic u-3 handling input output and control statements
C Programming Control Structures(if,if-else)
Diploma ii cfpc u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statements
handling input output and control statements
4_Decision Making and Branching in C Program.pdf
Bsc cs pic u-3 handling input output and control statements
Ad

More from Thesis Scientist Private Limited (20)

PDF
HTML guide for beginners
PDF
Ransomware attacks 2017
PDF
How to write a Great Research Paper?
PDF
Research Process design
PDF
How to write a good Dissertation/ Thesis
PDF
How to write a Research Paper
PDF
Internet security tips for Businesses
PDF
How to deal with a Compulsive liar
PDF
Driverless car Google
PDF
Podcast tips beginners
PDF
Vastu for Career Success
PDF
Reliance jio broadband
PDF
Job Satisfaction definition
PDF
Mistakes in Advertising
PDF
Contributor in a sentence
PDF
Different Routing protocols
PDF
Ad hoc network routing protocols
PDF
Latest Thesis Topics for Fog computing
PDF
Latest Research Topics On Flying Ad-Hoc Networks (FANETs):
HTML guide for beginners
Ransomware attacks 2017
How to write a Great Research Paper?
Research Process design
How to write a good Dissertation/ Thesis
How to write a Research Paper
Internet security tips for Businesses
How to deal with a Compulsive liar
Driverless car Google
Podcast tips beginners
Vastu for Career Success
Reliance jio broadband
Job Satisfaction definition
Mistakes in Advertising
Contributor in a sentence
Different Routing protocols
Ad hoc network routing protocols
Latest Thesis Topics for Fog computing
Latest Research Topics On Flying Ad-Hoc Networks (FANETs):

Recently uploaded (20)

PDF
Digital Logic Computer Design lecture notes
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPT
Project quality management in manufacturing
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
OOP with Java - Java Introduction (Basics)
PPT
Mechanical Engineering MATERIALS Selection
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
additive manufacturing of ss316l using mig welding
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
web development for engineering and engineering
PDF
Well-logging-methods_new................
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
composite construction of structures.pdf
Digital Logic Computer Design lecture notes
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
CYBER-CRIMES AND SECURITY A guide to understanding
Project quality management in manufacturing
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
OOP with Java - Java Introduction (Basics)
Mechanical Engineering MATERIALS Selection
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Operating System & Kernel Study Guide-1 - converted.pdf
additive manufacturing of ss316l using mig welding
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
web development for engineering and engineering
Well-logging-methods_new................
Internet of Things (IOT) - A guide to understanding
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Foundation to blockchain - A guide to Blockchain Tech
composite construction of structures.pdf

Controls & Loops in C

  • 1. For more Https://www.ThesisScientist.com Unit 5 Controls & Loops Control Statements The control statements enable us to specify the order in which the various instructions in a program are to be executed by the computer. They determine the flow of control in a program. There are 4 types of control statements in C. They are: a) Sequence control statements b) Decision control statements or conditional statement c) Case control statements d) Repetition or loop control statements Conditional Statements C has two major decision making statements. 1. If_else statement 2. Switch statement If_else Statement The if_else statement is a powerful decision making tool. It allows the computer to evaluate the expression. Depending on whether the value of expression is 'True' or 'False' certain group of statements are executed. The syntax of if_else statement is: if (condition is true) statement 1; else statement 2; The condition following the keyword is always enclosed in parenthesis. If the condition is true, statements in then part are executed, i.e., statement1, otherwise statement2 in else part is executed. There may be a number of statements in then and else parts. e.g.: /* magic number program * / main( ) { int magic = 223; int guess;
  • 2. printf ("Enter your guess for the number n"); scanf ("% d" &guess); if (guess = = magic) printf ("n Congratulation ! Right guess"); else printf ("n wrong guess"); } Nesting of if_else Statement When a series of decisions are involved in the statement, we may have to use more than one if_else statement in nested form. This can be described by the flowchart in the following figure: Is Condition One True Statement 1 Statement 2 Statement 3 Statement x N N Y Y Is Condition One True Is Condition 2 True Statement 1 Statement 2 Statement 3 Statement x N N Y Y Figure 5.1: Flow Chart of if_else statement in Nested Form
  • 3. e.g.: / * finding the largest of 3 numbers * / main( ) { float a = 5, b = 2, c = 7; if (a > b) { if (a > c) printf ("a is greatest"); else printf ("c is greatest"); } else { if (b > c) printf ("b is greatest"); else printf ("c is greatest"); } } else if Ladder There is another way of putting ifs together when multipath decisions are involved. Multipath decision is a chain of ifs in which statement associated with each else is an if. It takes the following general form: if (condition 1) statement1; else if (condition 2) statement 2; else if (condition 3) statement 3; statement x; The conditions in elseif ladder are evaluated from the top (of the ladder) downwards. As soon as the true condition is found, associated statement is executed and control is transferred to statement x. e.g.: main( ) { int unit, custom; float charges; printf ("Enter Customer No. and Units Consumered: n"); scanf ("% d % d", & custnum, & unit); if (unit < = 200) charges = 0.5 *units; else if (units < = 400) charges = 100 + 0.65* (units - 200); else if (units < = 600) charges = 230 + 0.8 * (units - 600); printf ("n n Customer No: % charges: %0.2f n" Custnum, Charges); }
  • 4. The Switch Statement In multiway decision construct the complexity of a program increases with the increase in number of alternatives. The program becomes difficult to read and follow. C has a built-in multiway decision statement known as switch. The switch statement tests the value of a given variable or expression against a list of case values and when a match is found a block of statement associated with that case is executed. The general form is: switch (expression) { case constant_1: statements; case constant_2: statements; default: statements; } First, the integer expression following the keyword switch is evaluated. The value it gives is then matched, one by one, against the constant values that follow the case statements. Whenever a match is formed, the program executes the statements following the case, and all subsequent cases and default statements as well. /* Find whether number is even or odd */ main( ) { int n, ch; printf ("Enter the number: n"); scanf ("%d; &n); if (n%2 = = 0) ch = 1; else ch = 2; switch (ch) { case 1: printf ("number is even n"); break; case 2: printf ("Number is odd n"); } }
  • 5. Loops in C Loops in C allow a set of instructions to be performed until a certain condition is reached. There are three types of loops in C: 1. for loop 2. while loop 3. do-while loop The for Loop It is a very useful looping construct in C. It has three expressions. a) counter initialization b) condition c) modification of counter. Counter initialization Loop terminated fCheck the Condition Block of statement t Modification of counter Counter initialization Loop terminated fCheck the Condition Block of statement t Modification of counter Figure 5.2: Working of 'for' Loop The general form of for loop is for (initialization; condition; increment) { statement 1; _______ _______ statement n; }
  • 6. The initialization is usually an assignment statement that is used to set the loop control variable. The condition is a relational expression that determines when the loop will exit. The increment defines how loop control variable will change each time the loop is repeated. These three sections are seperated by a semicolon. The for loop will execute as long as the condition holds true. Once the condition becomes false, program execution will resume on the statement following the block. e.g.: /* program to print a message 5 times */ main( ) { int i; for (i = 1; i < = 5; i ++) { printf ("n In the loop % d times", i); } } The While Loop While is an entry controlled Loop statement. The basic format of the while statement is: while (test condition) { body of Loop; } The test condition is evaluated and if the condition is true, the body of loop will be executed. That is why, while Loop is an entry controlled statement. Out of Loop f Condition Block of statement t Out of Loop f Condition Block of statement t Figure 5.3: The while Loop e.g.:1 /* print the numbers 1 to 10 */
  • 7. # include <stdio.h> main( ) { int n = 1; while (n < = 10) { printf ("%d n", n); n ++; } } The Do-while Loop The general form of do-while Loop is: do { body of Loop; } while (test condition); It first executes the body of the loop, then evaluates the test condition. If the condition is true, the body of loop is executed again and again until the condition becomes false. Out of Loop false Condition Body of Loop true Out of Loop false Condition Body of Loop true Figure 5.4: do-while Loop Since the test condition is evaluated at the bottom of the loop, the do-while construct provides an exit controlled loop. Thus, the body is executed at least once.
  • 8. e.g.: /* Find the factorial of any number * / # include <stdio.h> main( ) { int n, no, fact = 1; printf ("Enter the number:"); scanf ("% d", & n); no = n; if (n < 0) printf ("n factorial of negative number not possible:"); else if (n = = 0) printf ("Factorial of 0 is 1 n"); else do { fact * = n; n - -; } while (n > i) printf ("factorial of % d = % d", no, fact); } The Continue Statement The continue statement is used to bypass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. Rather, the remaining loop statements are skipped and the computation proceeds directly to the next pass through the loop. The continue statement tells the compiler to skip the following statements and continue with the next iteration. The continue statement can be included within a while, a do-while or a for statement. It is written simply as continue; without any embedded statements or expressions. Some illustrations of loops that contain continue statements are given below. In each case, the processing of the current value of x will be bypassed if the value of x is negative. Execution of a loop will then continue with the next pass. do-while Loop do { scanf ("%f", &x); if (x < 0) {
  • 9. printf ("Error-negative value for X"); continue; }; The exit( ) Function The exit( ) function is used for terminating the execution of C program. It is a standard library function and uses header file stdlib.h. The general form of exit( ) function is exit (int status); The difference between break and exit( ) is that former terminates the execution of loop in which it is written while exit( ) terminates the execution of program itself. The status (in the general form of exit( )) is a value returned to the operation system after the termination of the program. . The goto Statement C supports the goto statement to branch unconditionally from one point to another in the program. A goto statement breaks the normal sequential execution of the program. The goto requires a label in order to identify the place where the branch is to be made. A label is any valid variable name, and must be followed by a colon. A label is placed immediately before the statement where the control is to be transferred. The general forms of goto and label statements are shown below: goto label; label: . . . . . . . . statements; label: . . . . . . . . statement; goto label; The label: can by anywhere in the program either before or after the goto label; statement. During running of a program when a statement like goto begin; is met, the flow of control will jump to the statement immediately following the label begin. The following program is written to evaluate the square root of numbers read from the terminal. Due to the unconditional goto statement at the end, the control is always transferred back to the input statement. It puts the computer in a permanent loop as infinite loop. main( ) { double x, y; read: scanf ("%f", &x); if (x < 0) goto read; y = sqrt (x); printf ("%f %f n", x, y);