Programming in C++: Variables, Mathematics and User Input

All variables must be declared in C++. Ideally, variables should be defined only in the functions that they are used. If you are writing a program with just a "main" function then you should declare your variables there.

For starters, we will consider two types of variables- integers (int) and floating point numbers (float). Integers have no decimal part, whereas floating point numbers can have decimal parts. The difference between these variables types is illustrated in the following program:

#include <iostream.h>

int main(void)
{
return 0;
}

Notice the common features of this program and the "hello world" program from yesterday. They both needed the #include<iostream.h> for output to the screen. They both included a main function, and the cout lines are of similar format. The variables should be declared at the beginning of main, and they must be declared before they are used.

What do you think the result of this program will be? Try it. What is the actual result?

You may assign the results from most algebraic expressions to variables. The normal operations of addition, subtraction, multiplication and division may be used, as well as other functions which will be discussed later. Order of operations will be followed, and you should use parentheses where appropriate.

In order to get input from a user you will need to use the cin command along with the extraction operator ">>". In order to have the user input an integer into the variable I, you would use the following statement.

cin>>i;

Input statements should be used in conjunction with output statements so that the user needs to know what needs to be input. This is shown in the following two expressions.

cout<<"Enter a number between 1 and 10:";
cin>>i;

The three concepts of variables, user input and mathematical expressions are illustrated in the following program.

#include <iostream.h>

int main(void)
{
float a;
float b;
float c;
c=3.14159;
cout<<"Enter a number: ";
cin>>a;
cout<<endl;
b=c*a*a;