Lesson 2 - Variables and Constants
Lesson 2 - Variables and Constants
Declaring variables
Before you can use a variable you must declare it. When you declare a variable you
choose its data type and give it a name. Here is an example of how to declare a variable
of the data type integer with the name i.
int i;
Using variables
You set the value of a variable using a =. Here is an example of how to set the value of an
int called i to 5.
int i;
i = 5;
You can set the value of a variable at the same time as you declare it. This is called
initialization.
int i = 5;
A char is a letter, number or any special character. You must put char values inside single
quotes.
char c = 'a';
A variable can also be signed or unsigned. Signed means that it can have negative
numbers and unsigned means it can't but unsigned gives a variable a greater positive
range. You simply put the words signed or unsigned in front of a variable declaration to
use them.
unsigned int i;
Putting short or long in front of a variable gives it a smaller or bigger range respectively.
short int i;
Using signed, unsigned, short and long without a variable type will use int by default.
signed s;
unsigned u;
short sh;
long l;
A string is a type of variable that can store words and sentences. There are 2 kinds of
strings. The first kind is a string pointer. You declare it as a *char. The * means that it
points to the first char of the string.
char *s;
s = "Hello";
The second kind is an array of characters which you must give a size when you declare it.
You have to use the strcpy command to put values in it. You must also include the string
header file to be able to use the strcpy command.
#include<string>
...
char t[10];
strcpy(t,"Hello");
The cin command is used for reading in values that are entered by the user. When you
read a value you must store it inside a variable. Here is an example of how to read an int
into a variable.
int age;
cout << "Enter your age: ";
cin >> age;