Starting+Out+With+C+++From+Control+Structures+through+Objects+(6th+Ed)+Tony+Gaddis+(P1)

Page 140

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH 109

i

3.6 Named Constants

3 4

5 6

II This program calculates the area of a circle. II The formula for the area of a circle is PI times II the radius squared . PI is 3.14159. iinclude <iostream> II needed for pow function #include <cmath> using names pace std;

7

8

int main()

9

{

10 11

canst double PI = 3.14159; double area, radius;

az

12

Ri

cout « "This program calculates the area of a circle.\n"; cout « "What is the radius of the circle? "; cin » radius ; area = PI * pow(radius, 2.0); cout « "The area is " « area « endl; return 0; )

an

13 14 15 16 17 18 19

Yo

1 2

us uf

Program 3-13

Ha

canst int SIZE ~ 21; char name [SIZE J i

ss

Earlier in ch is chapter you saw how to create a char array for the purpose of holding a C-string. It is a common practice to use a named constant to indicate the array's size. H ere is an example:

ad

This practice can make the program easier to maintain. When we sto re the size of the array in a named constant, we can use the named constant rather than a literal number in any statement that must refer to the size of (he array. Then, if we ever need to change the array's size, we need only to change the ini tialization value of the named constant.

m

If You Plan to Continue in Computer Science: The #define Directive

m

The older C-style method of creating named constants is with the 'define preprocessor directive. Although it is preferable (Q use the const modifier, there are programs with the ' define directive still in use. In addition, Chapter 13 teaches ocher uses of the ' define directive, so it is important to understand .

uh a

In Chapter 2 you learned that the 'include directive causes the preprocessor to include rhe contents of another file in you r program. Program 3-14 shows how the preprocessor can be used to create a named conStant.

Program 3-14

M

1 II This program calculates the area of a circle. 2 II The formula for the area of a circle is PI times 3 II the radius squared. PI is 3.1459. 4 5

*include <iostream> finclude <cmath> II needed for pow function (program continues)

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.