You are on page 1of 4

1. Calculation of Average of Numbers A program to calculate the average of a set of N numbers is given in Fig.2.11.

AVERAGE OF n VALUES Program #define main( ! in" f($a" N 10 /* SYMBOLIC CONSTANT */

#$%n" & )%m* a+e,a-e* n%m.e, &

/* 'ECLARATION OF */ /* VARIABLES */ /* INITIALI0ATION */ /* OF VARIABLES */

)%m / 0 & #$%n" / 0 & 12i(e( #$%n" 3 N ! )#anf(45f4* 6n%m.e, & )%m / )%m 7 n%m.e, & #$%n" / #$%n" 7 1 & 8

8 Output

a+e,a-e / )%m/N & 9,in"f(4N / 5d S%m / 5f4* N* )%m & 9,in"f(4 A+e,a-e / 5f4* a+e,a-e &

1 :;< =;>? 1;=: ? <;>? =;0@ :;: =;:A @;:1 N / 10

S%m / <@;?BBBBB

A+e,a-e / <;@@0000

Fig. 2.11 Average of N numbers


The variable number is declared as float and therefore it can take both integer and real numbers. Since the symbolic constant N is assigned the value of 10 using the #define statement the program accepts ten values and calculates their sum using the while loop. The

variable count counts the number of values and as soon as it becomes 11 the while loop is e!ited and then the average is calculated. Notice that the actual value of sum is "#.# but the value displayed is "#.$%%%%%. &n fact the actual value that is displayed is 'uite dependent on the computer system. Such an inaccuracy is due to the (ay the floating point numbers are internally represented inside the computer. 2. Temperature Conversion Problem The program presented in Fig.2.12 converts the given temperature in fahrenheit to celsius using the follo(ing conversion formula) F * "2 + , ************ 1.#

FACRENCEIT D CELSIUS CONVERSION TABLE EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE Program #define #define #define FELOF FEMAG STEH 0 :A0 :A /* DDDDDDDDDDDDDDDDDDDDD */ /* SYMBOLIC CONSTANTS */ /* DDDDDDDDDDDDDDDDDDDDD */

main( ! "I9edef f($a" REAL & REAL fa2,en2ei"* #e()i%) &

/* TYHE 'EFINITION /* 'ECLARATION

*/ */

fa2,en2ei" / FELOF & /* INITIALI0ATION */ 9,in"f(4Fa2,en2ei" Ce()i%)JnJn4 & 12i(e( fa2,en2ei" 3/ FEMAG ! #e()i%) / ( fa2,en2ei" D <:;0 / 1;@ & 9,in"f(4 5A;1f 5?;:fJn4* fa2,en2ei"* #e()i%) & fa2,en2ei" / fa2,en2ei" 7 STEH & 8

Output Fa2,en2ei" 0;0 :A;0 A0;0 ?A;0 Ce()i%) D1?;?@ D<;@B 10;00 :<;@B

100;0 1:A;0 1A0;0 1?A;0 :00;0 ::A;0 :A0;0

<?;?@ A1;>? >A;A> ?B;== B<;<< 10?;:: 1:1;11

---------------------------------------------------------------

Fig. 2.12 Temperature conversion


The program prints a conversion table for reading temperature in celsius given the fahrenheit values. The minimum and ma!imum values and step si.e are defined as symbolic constants. These values can be changed by redefining the #define statements. An user*defined data type name R A! is used to declare the variables fahrenheit and celsius. The formation specifications /0.1f and /$.2 in the second printf statement produces t(o* column output as sho(n.

You might also like