0 ratings 0% found this document useful (0 votes) 21 views 25 pages Decision Making and Looping PDF
This chapter discusses decision making and looping in programming, focusing on the use of loops to execute code segments repeatedly. It introduces different types of loops, including entry-controlled (while) and exit-controlled (do...while) loops, as well as counter-controlled and sentinel-controlled loops. The chapter also explains the syntax and functionality of the for loop, providing examples of how to implement these looping structures in C programming.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save DECISION MAKING AND LOOPING PDF For Later Chapter
Decision Making
and Looping
6.1 INTRODUCTION
We have seen in the previous chapter that it is possible to execute a segment of a program repeatedly
by introducing a counter and later testing it using the if statement. While this method is quite satisfac~
tory for all practical purposes, we need to initialize and increment a counter and test its value at an
appropriate place in the program for the completion of the loop. For example, suppose we want to
calculate the sum of squares of all integers between 1 and 10, We can write a program using the if
statement as follows:
o| goto print;
ol else
pl | n= 10,
is a yto" Tabp; | end of loop
} |
print: = J
‘This program does the following things:
1. Initializes the variable n.
2. Computes the square of n and adds it to sum.
3. Tests the value of n to see whether it is equal to 10 or not. If it is equal to 10, then the program
prints the results.4, Hfmis tess than 10, then it ts incremented by one and the control goes back to compute
again. ql "
The program evaluates the statement
sum = sum + n*ns
10 times. That is, the loop is executed 10 times. This number can be decreased or increaseg ¢..,
ion appropriately in the statement if (n == 10). On such cath
modifying the relational expr
where the exact number of repetitions are known, there are more convenient methods oF loop
programs containing repetitive Peat
146] Programming in ANSI ©
These looping capabilities enable us to develop concis
without the use of goto statements,
In looping, a sequence of statements are executed until some conditions for termination of the
are satisfied. A program loop therefore consists of two segments, one known as the Pod of het?
and the other known as the control statement. The control statement tests certain conditions ang *
directs the repeated execution of the statements contained in the body of the loop fe
_ Depending on the position of the control statement in the loop, a control structure may be elas
either as the entry-controlled loop or as the exit-controlled loop. The flow charts in Fig. 6.1 ile
trate these structures. In the entry-controlled loop, the control conditions are tested before thestaty
the loop execution. If the conditions are not satisfied, then the body of the loop will not be executy
In the case of an exit-controlled loop, the test is performed at the end of the body of the loop ay
therefore the body is exectited unconditionally for the first time. The entry-controlled and exit,
trolled loops are also known as pre-test and post-test loops respectively.
Entry Entry
’ '
1 \
| test Body of
| condition >-False the loop,
2
~~ 4 ‘
True 1
| Body of | CA False
|| theteop | condition 2
J A
= A
° -— True |
, ’
(a) Entry contro! (b) Exit controt
Fig. 6.1 Loop control structuresa
carta Decision Making and Looping [147 =
uly stated ji
ee conn order to perform the desired number of loop
not do so then Sventually transfer the control out of the loop. In
rol sets up an infinite loop and the body is executed
‘The test conditions should be
executions. It is assumed that the
tase, due 10 Some reason it do
over and over again,
A looping process, in general, would i
A looping process, in general, woutd include the fattowine f
1, Setting and initialization ofa condition variable en
Execution of the statements in the loop.
Test for a specified value of :
3. Test for aspeciied vale ofthe condition variable for execution of
' ng oF updating the condition variab en Ne oP
e tes ay be eithes a ie.
The est may be elther to determine wheter the loop has beet
times or to determine whether a particular condition hee boone
The C language provides for three ieeeit at
1. The while statement.
2. The do statement,
3. The for statement.
We shall discuss the features and applications of
ps:
ied number of
constructs: ert i r
structs for performing loop operations. They are:
h of these statements in this chapter,
Sentinel Loops »
Based on the nature of control variable and the kind of value assigned to it for
testing the control expression, the loops may be classified into two general cat
egories:
1. Counter-controlled loops
2. Sentinel-controlled loops
When we know in advance exactly how many times the loop will be executed,
we use a counter-controlled loop. We use a control variable known as counter
The counter must be initialized, tested and updated properly for the desired loop
er of times we want to execute the loop may be a constant
operations, The numb’
‘A counter-controlled loop is sometimes
of a variable that is assigned a value
called definite repetition loop.
Ina sentinel-controlled loop, a special value called a sentinel value is used to
change the loop control expression from true to false. For example, when tead-
ing data we may indicate the "end of data” by a spec ial value, like 1 and 999.
The control variable is called sentinel variable. A sentinel-controlled loop is
often called indefinite repetition Joop because the number of repetitions is not
known before the loop begins executing.
‘TEMEN?
6.2: ‘THE WHILE STA
ewhile statement. We have used while in many of
g structures: in Cis th
mon ile statement is
The simplest of all the loopin
: ic format of the W
our earlier programs. The baTTT ea rey x.
148| Programming in ANSI C
white (test condition)
{
body of the loop
}
The while isan emtry-controlied loop statement, The fest-condition is evaluated and if the
tion is true, then the body of the loop is executed. After exveution of the body, the test-congi
once again evaluated and if itis true, the body is executed once again, This process of repet®
execution of the body continues until the test-condition finally becomes false and the control gy, 4
ferred out of the loop. On exit, the program continues with the statement immediately aller the bye
of the loop. i
The body of the loop may have one or more statements. The braces are needed only if the
contains two or more statements, However, it is a good practice to use braces even if the body te
only one statement.
We can rewrite the program loop discussed in Section 6.1 as follows:
|
f n= 15 /* Initialization */ |
while(n <= 10) /* Testing */ |
{ |
loop sum = sum +n * nz |
= n= ntl; /* Incrementing */ |
I
printf("sum = %d\n", sum);
The body of the loop is executed 10 times forn = 1, -, 10, each time adding the square of te
value of n, which is incremented inside the loop. The test condition may also be written as n< Ist
result would be the same, This is a typical example of counter-controlled loops. The variable nis
called counter or control variable.
Another example of while statement, which uses the keyboard input is shown below:
character
while (character != 'Y')
character = getchar();
HRAKKIKS
First the characteris initialized to * *. The while statement then begins by testin
is not equal to Y. Since the character was initialized to * 7
getchar();
is executed. Each tiie a letter is keyed in, the test is carried om
until the letter Y is pressed. When Y is pressed, the
whether charac
*, the test is true and the loop statemett
character
J
and the loop statement is exe
condition becomes false because chars“
il sce enc cal aDecision Making andooping [149°
XXxxxXX;. This is
haracter constant ty’ is called sentinel value and
which often referred to as the sentinel variable.
Example 61 A program to evaluate the equation
Lo yex!
when n Is a non-negative Integer, Is given In Fig, 6.2
initialized to 1 and then mul
equals Y, and the loop terminates, thus ttansferring the control to the stateme
typical example of sentine!-controlled loops. The ch
the variable character is the condition variable,
The variable y oe tiplicd by x, n times using the while loop. The loop
control variable count is initialized outside the loop and incremented inside the loop. When the value
ofcount becomes greater than n, the control exists the loop.
Program
main()
{
int count, n;
float x, ys
printf("Enter the values of x and nz ")s
scanf("sf Sd", &x, &n)
y= 1.05
count = 1; /* Initialisation */
/* LOOP BEGINS */
while ( count <= n) /* Testing */
{
y yeKs
count+s; /* Incrementing */
)
/* END OF LOOP */
printf("\nx = fs n= Sd; x to power n = %f\n",xsn,y)5
}
Output
Enter the values of x and n: 2.5 4
x = 2.500000; n = 4; x to power n = 39,062500
Enter the values of x and nn: 0.5 4
x = 0.500000; n = 4; x to power n = 0,062500
Fig. 6.2. Program to compute x to the power n using while loopigpenpseucen 2
The while loop construct that we have discussed in the previous section makes a test of con
hofare the loop is executed. Therefore, the body of the loop may not be executed atl if the ggg
is not satisfied at the very first attempt. On some occasions it might be necessary to execute th
s
of the loop before the test is performed. Such situations can be handled with the help ore
statement. This takes the form: 4
&
150] ‘Programming in ANSI C.
63 THE DO STATEMENT
body of the loop
}
while (test-condition);
On reaching the do statement, the program proceeds to evaluate the body of the loop fist. Atg,
end of the loop, the test-condition in the while statement is evaluated. If the condition is tue, g.
program continues to evaluate the body of the /oop once again. This process continues as long a5,
condition is true. When the condition becomes false. the loop will be terminated and the control pe
to the statement that appears immediately after the while statement.
ince the rest-condition is evaluated at the bottom of the loop. the do...while construct providess,
exit-controlled loop and therefore the body of the loop is always executed at least once.
A simple example of a do...while loop is:
do
printf ("Input_a nurber\n
Joop number = getnun ( );
while (nurber > 0);
This segment of a program reads a number from the keyboard until a zero or a negative numberis
keyed in, and assigned to the sentinel variable number.
The test conditions may have compound relations as well. For instance, the statement
while (number > 0 && number < 100);
in the above example would cause the loop to be executed as long as the number keyed in lies betweet *
O and 100.
/* Initializing */ al
Consider another example:
/* Incrementing */
Lhe,
uhje(sum < 40 {| I < 10); /* Testing */
printf ("xd d\n", I, sum);
ee et ta /S3?--06 b>Decision Making and Looping [151
‘The loop will be executed as long as one of the two relations is true.
Example 6.2} A program to print the multiplication table from 1 x 1 to 12 x 10 as
shown below is given in Fig, 6.3.
1 2 3 4
10
2 4 6 8 20
3 6 9 12 30
4 40
2 ; s aft, 8120
This program contains (wo do... while loops in nested form. The outer loop is controlled by the
variable row and executed 12 times, The inner loop is controlled by the variable column and is
executed 10 times, cach time the outer loop is executed. That is, the inner loop is executed a total of
120 times, each time printing a value in the table.
Program:
#define COLMAX 10
#define ROWMAX 12
main()
{
int row,column, ys
row = 15
printf(" MULTIPLICATION TABLE \n")s
printf ("---- \n");
do /tr...+ OUTER LOOP BEGINS
{
y = row * columns
printf("*4d", y)3
column = colunn + 1;
}
while (column
printf("\n")s
row = row + 15
= COLMAX); /*... INNER LOOP ENDS ...*/
We (row <= ROWMAX);/*. OUTER LOOP ENDS .....*/
printf ("—— \n")s
} Ne
3 SHAW COUT
yyw A SHEN
002 @* CUTIACK:S yy
wre a7petnue MULTIPLICATION TABLE
6 7 8 10 |
; i ; 7 0 12 14 16 18 20 |
: 6 9 12, 15 18 21 24 27 30 |
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50 |
6 12. 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70 |
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100 |
ll 22 33 44 #55 66 77 88 99 110 |
12 24 36 48 60 72 84 96 108 120 |
Fig. 6.3. Printing of a multiplication table using do...wwhile loop
Notice that the printf of the inner loop does not contain any néw line char:
printing of all row values in one line. The empty
the next row
+ (\mn). This allows
printf in the outer loop initiates a new line to prin
6.4 THE FOR STATEMED
Simple ‘for Loops
The for loop is anotherentry-controlled loop that provides
@ more concise loop control structure. Te
general form of the for loop is
for ( initialization
{
+ test-condition ; increment)
body of the loop
‘The execution of the for statement is
Initialization of the control variables is
and count = 0, The variables i
as follow
done first, using a
and count are known
fgnMent statements such ast
The value of the control y
relational expression, such
true, the body of the loop
continues with the statement that imme
» When the body of the loop is
after evaluating the last statemen
an assignment statement such
tested to seeawhether it
loo] eval
isfy the test-conditfon,
“a
Powe
is execute
as i
able is tested using the test.
asi< 10 that determines when th
otherwise the
as loop-control variable: ‘
The test-condition is?
¢ loop will exit, Ifthe condition
loop is terminated and the exectti®®
follows the loop.
luted, the control is transferred back to the for stater
in the loop, Now, the
iT and the new
atisfies the loop condition. Ifthe
Lhis process continue
control variable is incr cemented ust
alue of the control variable is ast
condition is satisfied, the body oft
8 Ul the value of the control variable failsDecision Making’and Loopitig [153
Consider the following segment ofa program:
for (x=0;
loop { oe
printf("%d", x)
printf ("\n"
is for loop i: cl . A :
aed within a 10 times and prints the digits 0 to.9 in one line. The three sections
encl ee ‘ses must be separated by semicolons. Note that there is no semicolon at the
end of the increment section, x = x+1,
The for statement allows for negative increments. For example, the loop discussed above can be
written as follows:
for (x= 93 x>=0;x=x1)
printf("sd", x);
printf("\n");
This loop is also executed 10 times, but the output would be from 9 to 0 instead of 0 to 9. Note that
braces are optional when the body of the loop contains only one statement.
Since the conditional test is always performed at the beginning of the loop, the body of the loop
may not be executed at all, if the condition fails at the start. For example,
for (x = 9; x <9; x = x-1)
sd", x)s
will never be executed because the test condition fails at the very beginning itself.
Let us again consider the problem of sum of squares of integers discussed in Section 6.1. This
problem can be coded using the for statement as follows:
print#((
sum
for (n = 13 n <= 10; n = m4)
{
sum = sum+ n*n5
}
printf ("sum = %d\n", sum) 5
The body of the loop
sum = sum + n*n3
is executed 10 times for n= 1, 2, +++ 10 each time incrementing the sum by the square of the value
pine f ue
One of the important points about the for loop is that all the three actions, namely initialization,
testing, and incrementing, are placed in the for statement itself, thus making me ee to Ms
Programmers ‘and users, in one place. The for statement and its equivalent of while and do statements
are shown in Table 6.1.rogramming in ANSI C
Table 6.1 Comparison of the Three Loops
while
n= 1;
while (n<=10)
t
n=ntl;
[ Example 6.3] The program in Fig. 6.4 uses a for loop to print the “Powers of 2° 5
eee iorthe power 0 to 20, both positive and negative. me
The program evaluates the value
p=2
successively by multiplying 2 by itself'n times.
Note that we have declared p as a Jong int and q as a double.
Fe re
Additio
The for loop in C has several capabilities that are not found in other loop constructs. For examp,
more than one variable can be initialized at a time in the for statement. The statements
p=;
for (n=0; n<17; +n)
can be rewritten as
for (p=1, n=0; n<17; +n)
Program
main()
{
long int p;
\n")s
printf(" 2 to power n n 2 to power -n\n")i
printf(" \n")i
p=;
for (n= 0; n< 21; ++n) /* LOOP BEGINS */Decision’ Making and Looping [135
{
if (n == 0)
pels
else
p=p* 2;
4 = 1.0/(double)p 5
printf("%101d %10d %20.121f\n", p, ns q)s
/* LOOP ENDS */
printf("-
Output
0 1.000000000000
1 0.500000000000
2 0.250000000000
3} 0. 125000000000
4 0.062500000000
5 0.031250000000
6 0015625000000
7 0.007812500000
8 0.003906250000
9 0.001953125000
10 0000976562500
u 0,000488281250
12 0.000244140625
13 0.000122070313
14 0.000061035156
15 0.000030517578
16 0000015258789
V7 0.000007629395
18 0..000003814697
19 0000001907349
0
Fig. 6.4 Program to print ‘Posver of 2 sable using, for loop
= | and n= | separated by a comma.
‘o have more than one part, For example,
ction has two parts P
t section may als
Notice that the initialization s
Like the initialization section, the ineremen'
the loop
for (n=1, m=50; n 0; x = x/2)
is perfectly valid,
Another unique aspect of for loo}
p is that one or more sections can be omitted, if necessary, cq,
sider the following statements:
printf("sd\n", m);
m= m5;
Both the initialization and increment sections are omitied in the for statement. The initializationbs
been done before the for statement and the control variable is incremented inside the Toop. In suck
cases, the sections are lefi blank". However, the semicolons separating the sections must remain lf
the test-condition is not present, the for statement sets Up an “infinite” loop. Such loops can be broke
using break or goto statements in the loop.
We can set up time delay loops using the
null statement as follows:
for ( j = 1000; j > 0; j-1)
This loop is executed 1000 times without producing any output; it simply causes a time delay. Nott
that the body of the loop contains only a semicolon, know
wn as a null statement, This can also &
written as
for (j=1000; j > 0; j = j-1)
This implies that the C compiler will not give an error me:
the end of a for statement. The semicolon wi
Produce some nonsense,
jstakedl
ige if we place a semicolon by raise
ill be considered as a null statement and the program™!
{
Nesting of for Loops
‘ . : ; xa
Nesting of loops, that is, one for statement within another for statement, is allowed in C. Fore
ple, two loops can be nested as follows:
ah| { < 10; 444) - a8
| |
| fi |
| er C5 5 15 5 te 53 44g) |
| | toner | outer
| [loop | loop
| ees =
| |
ee |
‘The nesting may continue
sible the *eader ain UP to any desired level. The loops should be properly indented so as to
ANSI Callows up to 1 ly determine which statements are contained within cach for statement.
(an allows up to 15 levels of nesting. However, some compilers permit more).
The program to print the multiplica i
r plication table discussed in Example 6.2 can be written more con-
cisely using nested for statements as follow: Canes came
for (row
{
15 row <= ROWMAX ; ++row)
for (column
{
3 column <= COLMAX ; +#column)
y = row * column;
}
The outer loop controls the rows while the inner loop controls the columns.
A class of n students take an annual examination in m subjects. A
program to read the marks obtained by each student in various sub-
jects and to compute and print the total marks obtained by each of
them is given in Fig. 6.5
The program uses two for loops, one for controlling the number of students and the other for control-
ling the number of subjects. Since both the number of students and the number of subjects are re-
quested by the program, the program may be used fora class of any size and any number of subjects.
The outer loop includes three parts:
(1) reading of roll-numbers o| ‘students, one after anothet
(2) inner loop, where the marks are read and totalled for each student, and
(3) printing of total marks and dec! ion of grades.158] Programming in ANSEC
Program
define FIRST 36
Adetine SECOND 240
main()
{
int ny my ty de
roll number, marks, totals
printh("Cnter number of students and subjects\n"),
scant (Mid id", bn, Bm) 5
printf('\n")
for (i = ty fee ng et)
printf("Enter roll number + ")s
scanf("d", troll number);
total © 0
printf("\nEnter marks of %d subjects for ROLL NO sd\q
m,roll_number) ;
Jose ms S++)
for (j *
{
scanf("sd", marks) s
total = total + marks;
}
printf("TOTAL MARKS = “d ", total);
if (total >= FIRST)
printf("( First Division )\n\n");
else if (total = SECOND)
printf("( Second Division )\n\n"
else
printf("( *** FAT L *** )\n\n");
}
Output
Enter number of students and subjects
36
Enter roll_number ; 8701
Enter marks of 6 subjects for ROL NO 8701
81 75 83 45 61 59
TOTAL MARKS = 404 ( First Division )
Enter roll_number ; 8702
Enter marks of 6 subjects for ROLL NO 8702
51 49 55 47 65 41
TOTAL MARKS = 308 ( Second Division )
Enter roll_number : 8704
Enter marks of 6 subjects for ROLL NO 8704
40 19 31 47 39 25
TOTAL MARKS = 201 CP RAL L tee )
Fig. 6.5 Mlustration of nested for loopsDecision Making and Looping [159
Selecting a Loop »)
Given a probler 0 3
Gu nee pom, the programmer's first concer is to decide the type of loop
pee . joose on es
use the following strategy: eof the three loop supported by C, we may
lyse
Analyse the problem and see whether it required a pre-test or post-test loop.
If it requires a post-test loop, then we
can use only one loop, do while.
# If it requires a pres
ecide whether i
Decide whether the loop termination requires counter-based control or sen-
tinel-based control.
loop, then we have two choices: for and while.
Use for loop if the counter-based control is necessary.
Use while loop if the sentinel-based control is required,
Note that both the counter-controlled and sentinel-controlled loops can be
implemented by all the three control structures.
6.5
J
APS IN LOOPS
Loops perform a set of operations repeatedly until the control variable fails to satisfy the test-condi-
tion, The number of times a loop is repeated is decided in advance and the test condition is written to
achieve this. Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to
leave the loop as soon as a certain condition occurs. For example, consider the case of searching for
particular name in a list containing, say, 100 names. A program loop written for reading and testing
the names 100 times must be terminated as soon as the desired name is found. C permits a jump from
jump out of a loop.
one statement to another within a loop as well as a
Jumping Out of a Loop
[An early exiting from a loop can be accomplished by using the break statement or the goto state-
ment. We have already seen the use of the break in the switeh statement and the goto in the if..else
construct, These statements can also be used within while, do, or for loops. They are illustrated in
Fig. 6.6 and Fig. 6.7. |
When a break statement is encountered inside a loop. the loop is immediately exited and the
program continues withthe statement immediately following the loop. When the loops are nested, the
break would only exit from the loop containing it. That is, the break will exit only a single loop.
Since a goto statement can transfer the control to any place in @ program, itis useful to provide
important use of goto is to exit from deeply nested loops when an
branching within a loop. Anothe
error occurs, A simple break statement would not work here.ing in ANSI.C
160] Programemin’ an ae
while ( {
f :
Aare if (condition)
if (condition) __— break;
oe break; Exit [
Exit Front cect
it Toop } while (
Toop } Li
a (»)
(a)
for )
for (--~) for ¢
{ {
for ¢-----)
F
if (error) i
ieee ecneaks if (condition)
Pelt , break;
from | Exit [ 5
loop) } from | .
L_, inner
Toop >
(c) (d)
Fig. 6.6 Exiting a loop with break statement
while ( ) for ( )
{
if (error)
goto stop; for ( )
if(condition) | Exit :
Fi l goto abc; from if(error)
ump | Naat ;
aenint | Toop exit | goto error
Joop | from
> abe: | anleen
loops)
A —> error;
stop: «——___
(a)
(b)
Fig. 6.7. Jumping within and exiting from the loops with goto statementDecision’ Making ‘Looping
grample 6.5) The program jn Fig. 6.8 i oe ie
Program, SMlustrates 4
rogram reads a list of positive eS a
1000 values. However, itwe wars e894 calculay
IN Use of the break statement in aC
if We want the progras toc:
se. The for loop is written to
than 1000, then We must enter a “negates ae calculate the average of any set of values less
ai ‘er the last value in the list, to mark the end of
Program
main()
{
int m;
float x, Sum, average;
rintt("
Printt ("this progran Computes the average of a
7 et of numbers\n");
PERE ieee values one after another\n" ;
TE(Enter a NEGATIVE number at the end.\n\n");
sum = 0;
ia (m= 15 m<= 1000 5 +m)
scanf("*f", ax);
if (x <0)
break;
sum += x ;
}
average = sum/(float) (m1);
printf("\n");
printf("Number of values = %
printf ("Sum
printf ("Average : average);
}
Output
This program computes the average of a set of numbers
Enter values one after another
Enter a NEGATIVE number at the end.
21 23 24 22 26 22
imber of values = 6
ow 138.000000
Average = 23.000000
Fig. 6.8 Use of break in a program
Each value, when it
a e number 1. If it is positive, the
s teste ee whether it is a positive number or no r
ad, is tested to see w pesoueee i peed :
value is added to the sums otherwise, the loop terminates. On exit, the average of the values read is
lue is added to the sum; 5
calculated and the results are printed out
[Example 6.4) 66] A program to evaluate the serieseee
a
162| Programming in ANSI.
ven in Fig. 69,
for-1 for (initialization; test condition; increment)
{
|
Fig. 6.10. Bypassing and continuing in loops
‘Example 6.7) The program in Fig. 6.11 illustrates the use of continue statement.
>
The program evaluates the square root of a series of numbers and prints the results. The pro
stops when the number 9999 is typed in. i
In case, the series contains any ne ative numbers, the process of evaluation of square roost
be bypassed for such numbers because the square root of a negative number is not defined: is
continue statement is used to achieve this. The program ing thatthe mut
is negative and keeps an account of negative numbe
, : nevativeit™
The final output includes the number of positive values evaluated and the number of negative!
encountered.
prints a message s
>»Program:
Finclude <
main() math ho
}
Output
int Count, ny,
double mens Meaatives
5 rs sqroot;
Printt ("Ent 9
Count = 9,” 2999 to sy
Negative 20 p
pal (count < - 100)
OP\n") ;
Printf ("Enter a numb
er:
Scant (*z1 48 tnunber);
if (number z= 9999) :
break; * EXIT FI
C 3 ROM 7
if (number < 0) me
{
Printf("Number ¥S negative\n\n");
negativer+ ;
Continue; /* sxip REST OF THE Loop */
sqroot = sqrt (number) ;
Printf("Number = =
“lf\n Square root = %1f\n\n",
number, sqroot);
Ccount++ ;
}
Printf("Number of items done
printf("\n\nNegative items =
printf("END OF DATA\n");
d\n", count);
Sd\n", negative);
Enter 9999 to STOP
Enter a number : 25.0
Number = 25.000000
Square root = 5.000000
Enter a number
Number
40.5
40.500000
Square root = 6.363961
Enter a number: -9
Number is negative
ber : 16
se
0
Square root = 4~00000'
Enter a number + -14.75166| Programming in ANSIC
Number is negative
Enter a number : 80
Number = 80.000000
Square root * 8.944272
Enter a number : 9999
Number of items done = 4
Negative items =2
END OF DATA
Fig. 6.1L Use of continue statement
Avoiding goto
As mentioned earlier, itis a good practice to avoid using gotos. There are many reasons for yj
When goto is used, many compilers generate a less efficient code. In addition, using many oft
makes a program logic complicated and renders the program unreadable. It is possible to avoid ujy
goto by careful program design, In case any goto is absolutely necessary
The following goto jumps would cause problems and therefore must b
it should be documenig
voided.
Concise Test Expressions
We often use test expressions in theif, for, while and do st
with zero for making branching decisions. Since
need not make explicit comparisons with zero, Fo:
zero, and false when x is zero. Applying!
using any relational operators
if (expression ==0)
is equivalent to
if{lexpression)
Similarly,
if (expres
is equivalent to
if (expression)
‘atements that are evaluated and compare
every integer expression has a true/false value,
Finstance, the expression x is true wheneverxisn
operator, we ean write concise test expressions witht
ion!
0)
For example,
if (M%5==0 KK n%5==0)
ame as if)DB
BR BB B BB
wz
wz
wh
pares forget to place the semicolon at the end of do ....while statement.
ig as colon after the control expression in a while or for statement is not
a syntax error but it is most likely a logic error.
ising as rather 5 7 . ;
Using commas rather than semicolon in the header of a for statement is an error.
Do not forget to place the increment statement in the body of a while or
do...while loop.
Itis a common error to use wi
that the loop is ev:
Tong relational operator in test expressions. Ensure
aluated exactly the required number of times.
Avoid a common error using = in place of = = operator.
Do not change the control variable in both the for statement and the body of the
loop. It is a logic error,
Do not compare floating-point values for equality.
Avoid using while and for statements for implementing exit-controlled (post-
test) loops. Use do...while statement. Similarly, do not use do...while for
pre-test loops.
When performing an operation on a variable repeatedly in the body of a loop,
make sure that the variable is initialized properly before entering the loop.
Although it is legally allowed to place the initialization, testing and increment
sections outside the header of a for statement, avoid them as far as possible.
Although it is permissible to use arithmetic expressions in initialization and in-
crement section, be aware of round offand truncation errors during their evalua-
tion.
Although statements preceding a for and statements in the body can be placed in
the for header, avoid doing so as it makes the program more difficult to read.
The use of break and continue statements in any of the loops is considered
unstructured programming. Try to eliminate the use of these jump statements, as
far as possible. /
Avoid the use of goto anywhere in the program.
Indent the statements in the body of loops properly to enhance readability and
understandability. a :
Use of blank spaces before and after the loops and terminating remarks are highly
recommended.ammirig in ANSI C:
CASK, STUDIES
1. Table of Binomial Coefficients
Problem: Binomial coefficients are used in the study of binomial distributions and Teliabip
multicomponent redundant systems, It is given by Ny oy
m
Bmx) =()
A table of binomial coefficients is required to determine the binomial coefficient for any set Of may
x,
Problem Analysis: Vhe binomial coefficient can be recursively calculated as follows:
Bom,o) = 1
Bom,x) = Bim,x. |
sm>e x
max4t
x
«7 12,3,
Purther,
Boo) = 1
That is, the binomial coefficient is one when either x is zero oF m is zero. ‘The program in Fig. 6;
Prints the table of inom coefficients for m= 10, The program employs one do loop and one
Joop.
Program
define MAX 10
main()
{
int m, x, binom;
printf(" m x");
for (m= 03 m<= 10 5 +m)
printf("%4d", m)
printf("\n-~~
printf("s2d ", m);
% = 05 binom = 1;
while (x <= m)
{
if(m == 0 || x <= 9)
Printf("%4d", binom);
else ;
{
binom = binom *
Printf("4d",
(m= x + 1)/x5
binom) ;
X= x41;}
printf(*\n);
prom pimdels
while (m <= Max)
printf (*—~
m 0 1 2 3 4°65 6 7 @ 9 10
o 1
Led 1
202 past
3913 3 4
Bom 4 6 0h J
5p oditnt5}, 10104 454
6 1 6 15 2 15 6 1
7 1 7 21 35 35 2107 1
@ 1 8 2 56 70 5 2 4% 1}
9 1 9 36 B84 126 12% 2 2 9 3
10 1 10 45120 210 262 210 120 45 10 3
Fig. 6.12 Program to print binomial coefficient table
2. Histogram
Problem: In an organization, the employees are grouped according to their basic pay for t
ofcenain perks. The pay-range and the number of employees in each group are as follows:
Group Pay-Range Number of Employees
1 750 ~ 1500 12
2 1501 ~ 3000 23
3 3001 - 4500 35
4 4501 - 6000 20
above 6000 HW
5
draw a histogram to highlight the group sizes.
Problem Analysis: Given the size of groups, itis required to dra
‘atious groups. For each bar, its group number and size are 10 bi /
*rogam in Fig, 6.13 reads the number of employees belonging to each group and draws a histogram.
the program uses four for loops and 1wo if....else statements.
bars representing the sizes of
Program:
ddefine NS
main()*
{
int value[N]s
int i, J, Ms %