0% found this document useful (0 votes)
158 views

Algorithms and Flowcharts

The document discusses algorithms, flowcharts, and the character set of the C programming language. It defines algorithms as ordered sequences of steps to solve a problem, and flowcharts as graphical representations of algorithm logic and control flow. It also outlines the basic symbols used in flowcharts and provides examples. Finally, it describes the character set of C including identifiers, keywords, constants, operators, and punctuation symbols.

Uploaded by

I LOVE You
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
158 views

Algorithms and Flowcharts

The document discusses algorithms, flowcharts, and the character set of the C programming language. It defines algorithms as ordered sequences of steps to solve a problem, and flowcharts as graphical representations of algorithm logic and control flow. It also outlines the basic symbols used in flowcharts and provides examples. Finally, it describes the character set of C including identifiers, keywords, constants, operators, and punctuation symbols.

Uploaded by

I LOVE You
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

ALGORITHMS AND

FLOWCHARTS
ALGORITHMS AND FLOWCHARTS

• A typical programming task can be divided into


two phases:
•Problem solving phase
• produce an ordered sequence of steps that describe
solution of problem
• this sequence of steps is called analgorithm
•Implementation phase
• implement the program in some programming language
Steps in Problem Solving

First produce a general algorithm (one can use


pseudocode )
Refine the algorithm successively to get step
by step detailedalgorithm that is very close to a
computer language.
Pseudocode is an artificial and informal
language that helps programmers develop
algorithms. Pseudocode is very similar to
everyday English.
Pseudocode & Algorithm

• Example 1: Write an algorithm to determine a student’s final

grade and indicate whether it is passing or failing. The final

grade is calculated as the average of four marks.


Pseudocode & Algorithm

Pseudocode:
1.Input a set of 4 marks
2.Calculate their average by summing and
dividing by 4
3.if average is below 50
Print “FAIL”
else
Print “PASS”
Pseudocode & Algorithm

•Detailed Algorithm
• Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
The Flowchart

(Dictionary) A schematic representation of a sequence


of operations, as in a manufacturing process or
computer program.
(Technical) A graphical representation of the sequence
of operations in an information system or program.
• Information system flowcharts show how data flows from
source documents through the computer to final distribution to
users.
• Program flowcharts show the sequence of instructions in a
single program or subroutine. Different symbols are used to
draw each type of flowchart.
The Flowchart

A Flowchart

• shows logic of an algorithm

• emphasizes individual steps and their interconnections

• e.g. control flow from one action to the next


Flowcharts

• Flowcharts is a graph used to depict or show a step by step


solution using symbols which represent a task.
• The symbols used consist of geometrical shapes that are
connected by flow lines.
• It is an alternative to pseudocoding; whereas a pseudocode
description is verbal, a flowchart is graphical in nature.

9
Flowchart Symbols
Basic
Flowchart Symbols
Terminal symbol - indicates the beginning and
end points of an algorithm.

Process symbol - shows an instruction other than


input, output or selection.

Input-output symbol - shows an input or an output


operation.

Disk storage I/O symbol - indicates input from or output to


disk storage.

Printer output symbol - shows hardcopy printer


output.

11
Flowchart Symbols cont…
Selection symbol - shows a selection process
for two-way selection.

Off-page connector - provides continuation of a logical


path on another page.

On-page connector - provides continuation


of logical path at another point in the same
page.

Flow lines - indicate the logical sequence of


execution steps in the algorithm.

12
Flowchart – sequence control structure

Statement 1

Statement 2

Statement 3

13
Flowchart – selection control structure

No Yes
Condition

else- then-
statement(s) statement(s)

14
Flowchart – repetition control structure

yes Loop
Condition
Statement(s)

no

15
Example

START
Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Input
M1,M2,M3,M4
Step 3: if (GRADE <50) then
Print “FAIL”
else
GRADE(M1+M2+M3+M4)/4 Print “PASS”
endif
N IS Y
GRADE<50

PRINT PRINT
“PASS” “FAIL”

STOP
Example 2

• Write an algorithm and draw a flowchart to convert the length in


feet to centimeter.
Pseudocode:
• Input the length in feet (Lft)
• Calculate the length in cm (Lcm) by multiplying LFT with 30
• Print length in cm (LCM)
Example 2
Flowchart
Algorithm
• Step 1: Input Lft
START
• Step 2: Lcm  Lft x 30
• Step 3: Print Lcm Input
Lft

Lcm  Lft x 30

Print
Lcm

STOP
Example 3

Write an algorithm and draw a flowchart that


will read the two sides of a rectangle and
calculate its area.
Pseudocode
•Input the width (W) and Length (L) of a
rectangle
•Calculate the area (A) by multiplying L with W
•Print A
Example 3

Algorithm
START
• Step 1: Input W,L
• Step 2: A  L x W Input
• Step 3: Print A W, L

ALxW

Print
A

STOP
Flowchart – example 1

Begin

Read birth date

Calculate
Age = current year – birth date

Display
age

End

21
Flowchart – example 2

Begin

Read age

YES Age > 55? NO

print “Pencen” print “Kerja lagi”

End

22
Flowchart – example 5

Begin

sum = 0
current_number = 1

NO
current_number <= 10? print sum

YES
End
sum = sum + current_number
current_number = current_number + 1

23
Exercises: Algorithm & Flowchart

1. 1.) Create an algorithm and a flowchart that will accept/read

two numbers and then display the bigger number.


Exercises: Algorithm & Flowchart

2.) Create an algorithm and a flowchart that will compute the area of
a circle.
Exercises: Algorithm & Flowchart

3.) Create an algorithm and a flowchart that will compute the sum

of two numbers. If the sum is below or equal to twenty, two

numbers will be entered again. If the sum is above 20, it will

display the sum.


Lab Activity: Algorithm & Flowchart

4) Create an algorithm and a flowchart that will output the largest

number among the three numbers.


Assignment 1

1. Create an algorithm and a flowchart that will output for g.c.d.

2. Create an algorithm and a flowchart that will output the factorial of a

given number.

3. Create an algorithm and a flowchart that will output the Fibonacci

series up to a given number.

4. Create an algorithm and a flowchart that will output all the prime

numbers between 2 numbers.


The Character set of ‘C’
 C language consist of some characters set, numbers
and
some special symbols. The character set of C consist
of all the alphabets of English language. C consist of
 Alphabets a to z, A to Z
 Numeric 0,1 to 9
 Special Symbols {,},[,],?,+,-,*,/,%,!,;,and more
 The words formed from the character set are building
blocks of C and are sometimes known as tokens.
These
tokens represent the individual entity of language. The
following different types of token are used in C
1) Identifiers 2)Keywords 3)Constants
4) Operators 5)Punctuation Symbols
Identifiers
 A 'C' program consist of two types of elements , user defined and
system defined. Identifiers is nothing but a name given to these
elements.

 An identifier is a word used by a programmer to name a variable ,


function, or label.

 identifiers consist of letters and digits, in any order, except that the
first character or label.

 Identifiers consist of letters and digits if any order, except that the
first character must be letter.

 Both Upper and lowercase letters can be used


Keywords
• Keywords are nothing but auto double int struct
system defined identifiers.
• Keywords are reserved break else long switch
words of the language.
• They have specific meaning case enum register typedef
in the language and cannot
be used by the programmer char extern return union
as variable or constant
names
const float short unsigne
• C is case senitive, it means d
these must be used as it is continue for signed void
• 32 Keywords in C
Programming default goto sizeof volatile

do if static while
Variables
• A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
• The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. There are following basic variable
types −
Type Description
• char Typically a single octet(one byte). This is an integer type.
• int The most natural size of integer for the machine.
• float A single-precision floating point value.
• double A double-precision floating point value.
• void Represents the absence of type.
Constants
• A constant is a value or an identifier whose value cannot be
altered in a program. For example: 1, 2.5,
• As mentioned, an identifier also can be defined as a constant. eg.
const double PI = 3.14
• Here, PI is a constant. Basically what it means is that, PI and
3.14 is same for this program.

Integer constants
• A integer constant is a numeric constant (associated with
number) without any fractional or exponential part. There are
three types of integer constants in C programming:
• decimal constant(base 10)
• octal constant(base 8)
• hexadecimal constant(base 16)
Constants

Floating-point constants
• A floating point constant is a numeric constant that has
either a fractional form or an exponent form. For example:
2.0,0.0000234,-0.22E-5

Character constants
• A character constant is a constant which uses single
quotation around characters. For example: 'a', 'l', 'm', 'F'

String constants
• String constants are the constants which are enclosed in
a pair of double-quote marks. For example: "good" ,"x","
Earth is round\n"
• Convert 108 to a binary number.
• Solution: Given number is 108
• 108 = (1 * 81) + (0 * 80)
•=1*8+0*1
•=8+0
• = 8 (Decimal number)
• Now convert this decimal number into its equivalent binary
number.
• Ans: (1000)2
• hex number (4FA)16
• Step 1: 4 F A
• A 4 15 10
• =1024+240+10
• Ans: 1247
Escape Sequences

Sometimes, it is necessary to use characters which cannot be typed or has


special meaning in C programming. For example: newline(enter), tab, question
mark etc. In order to use these characters, escape sequence is used.
• For example: \n is used for newline. The backslash ( \ ) causes "escape" from
the normal way the characters are interpreted by the compiler.Escape
Sequences Character
• \b Backspace
• \f Form feed
• \n Newline
• \r Return
• \t Horizontal tab
• \v Vertical tab
• \\ Backslash
• \' Single quotation mark
• \" Double quotation mark
• \? Question mark
• \0 Null character
Parts of C program-
• # include <stdio.h> – This command is a preprocessor
directive in C  that includes all standard input-output files before
compiling any C program so as to make use of all those
functions in our C program.
•  int main() – This is the line from where the execution of the
program starts . The main() function starts the execution of any
C program.
• { (Opening bracket) – This indicates the beginning of any
function  in the program (Here it indicates the beginning of the
main function).
• /* some comments */ – Whatever is inside /*——-*/ are not
compiled and executed ; they are only written for user
understanding or for making the program interactive by
inserting a comment line. These are known as multiline
comments. Single line comments are represented with the help
of 2 forward slashes “//——”.
• printf(“Hello World”) –The printf() command is included in the C
stdio.h library, which helps to display the message on the
• getch() – This command helps to hold the screen .
• return 0 –This command terminates the C program and returns a null
value, that is, 0.
• } (Closing brackets)-  This indicates the end of the function . (Here it
indicates the end of the main function)

Basic C Program

#include <stdio.h>

int main()

// Our first basic program in C

printf("Hello World!\n\n");

return 0;

}
Steps to RUN
• Step 1: Open turbo C IDE(Integrated Development Environment),
click on File and then click on New
• 
• Step 2: Write a Hello World program that we created in the
previous article - C Hello World program.
• 
• Step 3: Click on Compile menu and then on Compile option, or
press the keys press Alt + F9 to compile the code.
• 
• Step 4: Click on Run or press Ctrl + F9 to run the code. Yes, C
programs are first compiled to generate the object code and
then that object code is Run.
• Step 5: Output is here.
Operators in C

• An operator is a symbol which operates on a value or a variable.


For example: + is an operator to perform addition.
• C programming has wide range of operators to perform various
operations. For better understanding of operators, these
operators can be classified as:
• Arithmetic Operators
• Increment and Decrement Operators
• Assignment Operators
• Relational Operators
• Logical Operators
• Conditional Operators
• Bitwise Operators
• Special Operators
1. Arithmetic Operators: 
These operators are used to perform arithmetic/mathematical
operations on operands. Examples: (+, -, *, /, %,++,–). Arithmetic
operators are of two types: 
a) Unary Operators: Operators that operate or work with a single
operand are unary operators. For example: Increment(++) and
Decrement(–) Operators
int val = 5;
++val; // 6
b) Binary Operators: Operators that operate or work with two
operands are binary operators. For example: Addition(+),
Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
c=a+b; // 9
2. Relational Operators:
These are used for the comparison of the values of two operands.
For example, checking if one operand is equal to the other
operand or not, an operand is greater than the other operand or
not, etc. Some of the relational operators are (==, >= , <= ).
int a = 3; int b = 5;
a < b; // operator to check if a is smaller than b
3. Logical Operators:
Logical Operators are used to combining two or more
conditions/constraints or to complement the evaluation of the
original condition in consideration. The result of the operation
of a logical operator is a Boolean value either true or false. 
Increment and Decrement Operators

1. C programming has two operators increment


++ and decrement -- to change the value of an
operand (constant or variable) by 1.
2. Increment ++ increases the value by 1
whereas decrement -- decreases the value by 1.
3. These two operators are unary operators,
meaning they only operate on a single operand.

eg. int a=10, b=100


++a = 11
--b = 99
#include <stdio.h>
int main()
{
int x = 10,y = 20;
printf("----INCREMENT OPERATOR EXAMPLE---- \n");
printf("Value of x : %d \n", x); //Original Value
printf("Value of x : %d \n", x++); // Using increment Operator
printf("Value of x : %d \n", x); //Incremented value
printf("----DECREMENT OPERATOR EXAMPLE---- \n");
printf("Value of y : %d \n", y); //Original Value
printf("Value of y : %d \n", y--); // using decrement Operator
printf("Value of y : %d \n", y); //decremented value
return 0;
}
C Assignment Operators

• An assignment operator is used for assigning a


value to a variable. The most common
assignment operator is =
• Operator Example Same as
•= a=b a=b
• += a += b a = a+b
• -= a -= b a = a-b
• *= a *= b a = a*b
• /= a /= b a = a/b
• %= a %= b a = a%b
C Relational Operators
• A relational operator checks the relationship between two
operands. If the relation is true, it returns 1; if the relation
is false, it returns value 0.
• Relational operators are used in decision making and
loops.
Operator Meaning of OperatorExample
• == Equal to 5 == 3 returns 0
•> Greater than 5 > 3 returns 1
•< Less than 5 < 3 returns 0
• != Not equal to 5 != 3 returns 1
• >= Greater than or equal to 5 >= 3 returns 1
• <= Less than or equal to 5 <= 3 return 0
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
printf("Line 1 - a is equal to b\n" );
} else {
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b ) {
printf("Line 2 - a is less than b\n" );
} else {
printf("Line 2 - a is not less than b\n" );
}
Logical Operators
Logical Operators are used to combining two or more conditions/constraints
or to complement the evaluation of the original condition in consideration.
The result of the operation of a logical operator is a Boolean value
either true or false. 
Operator Description Example

&& Called Logical AND operator. If both the operands (A && B) is false.
are non-zero, then the condition becomes true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


operands is non-zero, then the condition becomes
true.

! Called Logical NOT Operator. It is used to reverse the !(A && B) is true.
logical state of its operand. If a condition is true,
then Logical NOT operator will make it false.
Example

#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf("Line 1 - Condition is true\n" );
}
if ( a || b ) {
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
b = 10;

if ( a && b ) {
printf("Line 3 - Condition is true\n" );
} else {
printf("Line 3 - Condition is not true\n" );
}

if ( !(a && b) ) {
printf("Line 4 - Condition is true\n" );
}

}
Conditional or Ternary Operator (?:) in C

• The conditional operator is kind of similar to


the if-else statement as it does follow the same
algorithm as of if-else statement but the
conditional operator takes less space and helps
to write the if-else statements in the shortest
way possible.
• Syntax: 
The conditional operator is of the form  
variable = Expression1 ? Expression2 :
Expression3
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Special operators

 1. The Comma Operator


 The comma operator can be used to link the related
expressions together. A comma-linked list of expressions is
evaluated left to right and the value of right-most expression
is the value of the combined expression. For example, the
statement
 value = (x=10, y=5, x+y);
 first assigns the value 10 to x, then assigns 5 to y, and finally
assigns 15 to value. Since comma operator has the lowest
precedence of all operators, the parentheses are necessary.

58
Data Types

C has a concept of 'data types' which are used to define a variable


before its use. The definition of a variable will assign storage for the
variable and define the type of data that will be held in the location.
The value of a variable can be changed any time.
C has the following basic built-in datatypes.
int
float
double
char
Data Types
1. int - data type
int is used to define integer numbers.
{
int Count;
Count = 5;
}
2. float - data type
float is used to define floating point numbers.
{
float Miles;
Miles = 5.6;
}
3. double - data type
double is used to define BIG floating point numbers. It reserves twice the
storage for the number
{
double Atoms;
Atoms = 2500000;
}
UNIT-II
DESIGNING STRUCTURED
PROGRAMS IN C
CONTROL STATEMENTS
1. LEARNING OBJECTIVES
Understanding meaning of a statement and statement block

Learn about decision type control constructs in C and the way


these are used

Learn about looping type control constructs in C and the


technique of putting them to use

Learn the use of special control constructs such as goto,


break, continue, and return

Learn about nested loops and their utility


2. CONTROL STATEMENTS INCLUDE
PROGRAM CONTROL STATEMENTS/
CONSTRUCTS IN ‘C’
OPERATORS
RELATIONAL Equality and Logical
OPERATORS Operators

To Specify Symbol To Specify Symbol Used


Used
less than < Equal to ==

greater than > Not equal to !=

less than or <= Logical AND &&


equal to >=
greater than or Logical OR ||
equal to
Negation !
POINTS TO NOTE
If an expression, involving the relational operator, is true, it is given a value of
1. If an expression is false, it is given a value of 0. Similarly, if a numeric
expression is used as a test expression, any non-zero value (including
negative) will be considered as true, while a zero value will be considered as
false.

Space can be given between operand and operator (relational or logical) but
space is not allowed between any compound operator like <=, >=, ==, !=. It is
also compiler error to reverse them.

a == b and a = b are not similar, as == is a test for equality, a = b is an


assignment operator. Therefore, the equality operator has to be used
carefully.

The relational operators have lower precedence than all arithmetic


operators.
A FEW EXAMPLES
The following declarations and
initializations are given:
int x=1, y=2, z=3;
Then,
The expression x>=y evaluates to 0
(false).
The expression x+y evaluates to 3 (true).
The expression x=y evaluates to 2 (true).

© Oxford University Press 2013. All rights reserved.


Decision making statements

One-way decisions using if statement

Two-way decisions using if-else statement

Multi-way decisions

Dangling else Problem


ONE-WAY DECISIONS USING IF STATEMENT
Flowchart for if construct
Syntax:
if(TestExpr)
stmtT; T F
TestExpr

stmtT
Example
#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}
TWO-WAY DECISIONS USING IF-ELSE
STATEMENT
The form of a two-way decision is Flowchart of if-else construct
as follows:

if(TestExpr)
TestEx
stmtT; yes pr No
else
stmtF;

stmtT stmtF
Example
C Program to Check Number is Multiple of 7 or not
#include<stdio.h>
int main()
{
int number;

printf("Enter a number: ");


scanf("%d",&number);

if(number%7==0)
{
printf("%d is multiple of 7.",number);
}
else
{
printf("%d is not multiple of 7.",number);
}

return 0;
}
MULTI-WAY DECISIONS

if(TestExpr1)
switch(expr)
stmtT1;
{
else if(TestExpr2) case constant1: stmtList1;
stmtT2; break;
else if(TestExpr3) case constant2: stmtList2;
stmtT3; break;
.. . case constant3: stmtList3;
else if(TestExprN) break;
stmtTN; ………………………….
………………………….
else
default: stmtListn;
stmtF;
}
if-else-if ladder General format of switch
statements
Example
#include<stdio.h>
int main()
{
float number;

printf("Enter a number: ");


scanf("%f",&number);

if(number>0)
{
printf("%.2f is a positive number",number);
}
else if(number<0)
{
printf("%.2f is a negative number",number);
}
else
{
printf("Number is zero");
}
FLOWCHART OF AN IF-ELSE-IF
CONSTRUCT
TestExp
r
TestExpr
2
TestExpr
stmtT 3
1 TestExpr
stmtT
2 N
stmtT
3 stmtT
stmtT F
N
THE FOLLOWING PROGRAM CHECKS WHETHER A
NUMBER GIVEN BY THE USER IS ZERO, POSITIVE, OR
NEGATIVE
#include <stdio.h>
int main()
{
int x;
printf(“\n ENTER THE NUMBER:”);
scanf(“%d”, &x);
if(x > 0)
printf(“x is positive \n”);
else if(x == 0)
printf(“x is zero \n”);
else
printf(“x is negative \n”);
return 0;
}
NESTED IF
• When any if statement is Construct 1 Construct 2
written under another if
statement, this cluster is called if(TestExprA) if(TestExprA)
a nested if.
if(TestExprB) if(TestExprB)
• The syntax for the nested is stmtBT; stmtBT;
given here: else else
stmtBF; stmtBF;
else else
stmtAF;
if(TestExprC)
stmtCT;
else
stmtCF;
A PROGRAM TO FIND THE LARGEST AMONG
THREE NUMBERS USING THE NESTED LOOP
#include <stdio.h>
int main()
{
int a, b, c;
printf(“\nEnter the three numbers”)
;
scanf(“%d %d %d”, &a, &b, &c);
if(a > b)
if(a > c)
printf(“%d”, a);
else
printf(“%d”, c);
else
if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
return 0;
}
6. THE CONDITIONAL OPERATOR
• It has the following simple #include <stdio.h>
format: int main()
{
int a,b,c;
expr1 ? expr2 : expr3 printf(“\n ENTER THE TWO
NUMBERS:”);
scanf(“%d %d”, &a, &b);
It executes by first evaluating c=a>b? a : b>a ? b :-1;
if(c==-1)
expr1, which is normally a printf(“\n BOTH NUMBERS ARE
relational expression, and then EQUAL”);
evaluates either expr2, if the else
first result was true, or expr3, if printf(“\n LARGER NUMBER IS %d”,c);
the first result was false. return 0;
}

An Example
THE SWITCH STATEMENT
The general format of a switch
statement is
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}

The C switch construct


SWITCH VS NESTED IF

The switch differs from the else-if in that


switch can test only for equality, whereas the if
conditional expression can be of a test
expression involving any type of relational
operators and/or logical operators.

A switch statement is usually more efficient


than nested ifs.

The switch statement can always be replaced


with a series of else-if statements.
ITERATION AND REPETITIVE
EXECUTION
• A loop allows one to execute a
statement or block of
statements repeatedly. There
are mainly two types of
iterations or loopsunbounded

iteration or unbounded loop and
bounded iteration or bounded
loop.
• A loop can either be apre-test
loop or be a post-test loop as
.
illustrated in the diagram
“WHILE” CONSTRUCT
while statement is a pretest
loop. The basic syntax of the
Expanded Syntax of “while” and its
while statement is shown
Flowchart Representation
below:
AN EXAMPLE
#include <stdio.h> This loop contains all the
int main() parts of a while loop. When
executed in a program, this
{ loop will output
int c;
c=5; // Initialization 5
4
while(c>0) 3
{ // Test Expression 2
printf(“ \n %d”,c); 1
c=c-1; // Updating
}
return 0;
}
TESTING FOR FLOATING-POINT ‘EQUALITY’
float x;
x = 0.0;
while(x != 1.1)
{
x = x + 0.1;
printf(“1.1 minus %f equals %.20g\n”, x, 1.1 -x);
}
The above loop never terminates on many computers, because 0.1
cannot be accurately represented using binary numbers.
Never test floating point numbers for exact equality, especially in
loops.
The correct way to make the test is to see if the two numbers are
‘approximately equal’.
“FOR” CONSTRUCT
• The general form of the for statement is as follows:
for(initialization; TestExpr; updating)
stmT;
for construct
flow chart
EXAMPLE
#include <stdio.h>
int main()
{
int n, s=0, r;
printf(“\n Enter the Number”);
scanf(“%d”, &n);
for(;n>0;n/=10)
{
r=n%10;
s=s+r;
}
printf(“\n Sum of digits %d”, s);
return 0;
}
8.3 “DO-WHILE” CONSTRUCT

The C do-while loop


The form of this loop
construct is as
follows:
do
{
stmT; /* body of
statements would be
placed here*/
}while(TestExpr);
POINT TO NOTE

With a do-while statement, the body of the loop


is executed first and the test expression is
checked after the loop body is executed. Thus,
the do-while statement always executes the loop
body at least once.
AN EXAMPLE
#include <stdio.h>
int main()
{
int x = 1;
int count = 0;
do {
scanf(“%d”, &x);
if(x >= 0) count += 1;
} while(x >= 0);
return 0;
}
WHICH LOOP SHOULD BE USED???
THERE ARE NO HARD-AND-FAST RULE
REGARDING WHICH TYPE OF LOOP SHOULD BE USED

Some methods of controlling repetition in a program are:

Using Sentinel Values

Using Prime Read

Using Counter
GOTO STATEMENT
The following program is used to
The control is find the factorial of a number.
unconditionally transferred #include <stdio.h>
to the statement associated int main()
with the label specified in the {
int n, c;
goto statement. The form of long int f=1;
a goto statement is printf(“\n Enter the number:”);
scanf(“%d”,&n);
if(n<0)
goto label_name; goto end;
for(c=1; c<=n; c++)
f*=c;
printf(“\n FACTORIAL IS %ld”, f);
end:
return 0;
}
10. SPECIAL CONTROL STATEMENTS

“return” statements

“break” statements

“continue” statements
“BREAK” AND “CONTINUE” STATEMENTS
NESTED LOOPS
A nested loop refers to a loop #include <stdio.h>
that is contained within int main()
another loop.
{
If the following output has to
be obtained on the screen int row, col;
1 for(row=1;row<=4;++row)
22 {
333 for(col=1;col<=row;++col)
4444 printf(“%d \t”, row);
then the corresponding printf(“\n”);
program will be }
return 0;
}

You might also like