Constants

Problem:

The equation for the volume of a cone is V = ( 1 / 3 ) * Pi * h * r * r , where V is volume, h is the height and r is the radius. Write an interactive program which prompts the user to enter a height and a radius, calculates and displays the volume.

Solution:


#include <iostream>

const float PI = 3.14159;

int main()
{
   float volume = 0;
   float height = 0;
   float radius = 0;
   
   cout << "Enter the height of the cone: ";
   cin >> height;
   
   cout << "Enter the radius of the cone: ";
   cin >> radius;
   
   volume = (1.0 / 3.0) * PI * height * radius * radius;
   
   cout << "The volume of the cone is: " << volume << endl;
   
   return 0;
}

The only thing new here is the constant variable declared, hey, wait, it's not inside of main!? Hold on a minute. One thing at a time.

A constant is a variable whose value never changes, and cannot be changed. It must have a value the moment that the function is called, and in this case, the function is main, so it must have a value prior to the start of the program. At no time during the duration of the function can this value be changed.

But it's not in main!? Yes, it is declared outside of main. It is what is called a global constant, meaning it can be used by any function called by main, but, as it is a constant, the value can never be changed by main or any called function. If placed inside main, or within another function, it is then known as a local constant, which can only be used by the function it is directly declared within. Variables work in similar ways, globally and locally, except their values are subject to being changed. PI is now a constant data type float.

Now, a brief tangent to a side note. If you were to include the library, cmath, which is a library of math functions such as powers, squareroots, logrithms, and trigonometric functions, some common constants are evidently imported along with this. While playing around with cmath, I got an error with my global constant PI. Turns out, cmath included its' own global constant PI for my program to access. Needless to say, it caused an error from me trying to "change the value" of the constant, when I tried to "re-declare" it at the beginning of my program. Suffice to say, its' PI was much more accurate than my 3.14159, and so it's probably safe to stay. You can play around with this if you wish. Just add:

#include <cmath>

to the header of your .cpp file. You'll immediately see upon compilation the following error:

Error   : parse error before `3.14159265358979323846'
volumeofcone.cpp line 4   const float PI = 3.14159;

Comment out your constant definition line (//const float PI = 3.14159;) and the program functionsproperly again.

Now it's time for a few programs on your own to practice.