Let’s walk through the steps to create a simple C++ program that will calculate a circle’s area using the formula area = pi x r2
First we’ll set up our preprocessor directives, and an empty main function.
#include <iostream>
using namespace std;
int main() {
}
Next we will need to define variables that will be used by the program. In C/C++ we must define the type of data we are using, along with the variable name. The data type is specified first, then the variable name.
If we define a variable outside of a function, then it is a global variable, and that should be avoided. Instead, define them inside of the function.
double radius;
double area;
For simplicity sake, we will define the variable’s value, instead of reading it in at this time.
radius = 20;
For multiplication, like with almost every language, we use the * (star/asterisk) .
area = radius * radius * 3.14159;
And finally print this data out.
cout << "The area of the circle is: " << area;
With the final program looking like:
#include <iostream>
using namespace std;
int main() {
double radius;
double area;
radius = 20;
area = radius * radius * 3.14159;
cout << "The area of the circle is: " << area;
return 0;
}
A Simple C++ Program was originally found on Access 2 Learn