C++ Programming: User Interaction and Working with
Variables (Lesson๎2)
In programming, input, as well as other data, is stored in variables. There
are several different types of variables that store different kinds of
information; when you tell the compiler you are declaring a variable, you
must include the data type, or just type, along with the name of the
variable. The most common basic types available to you are๎char๎(stores
single character),๎int๎(stores integers) and๎double๎(numbers with decimal
places). Here are some examples of declaring variables:
int whole_number;
char letter;
double number_with_decimals;
You use๎cin๎(pronunced โC inโ) to accept input and it is followed by an
insertion operator going in the other direction, >>, followed by the variable
into insert the value typed by the user.
Here is a sample program demonstrating using a variable:
#include
using namespace std;
int main()
{
int thisisanuber;
cout<> thisisanuber;
cout << โYou entered โ <<thisisanuber <<โ\nโ;
}
Shortcut operators:
These are shortcut operators for adding any value to a variable:
x +=5; // adds 5 to x
x -=5; // subtract 5 from x
x *=5; // divide x by 5
x++ // add 1 to x;
x-- // subtract 1 from x;
With these operations, you can make a small calculator in C++:
#include
using namespace std;
int main()
{
int first_argument;
int second_argument;