Introduction to Programming
Variables
What is a variable?
A variable is like a box that you can put something in and use it later.
For example, if you get some numbers from the user and you want to add them together,
you would keep each number in a variable. Then you could add the numbers together, and
store the result in yet another variable. Finally, you'd look in this last variable when
you tell the user what the result is.
Each variable must first be declared. To declare a variable, you just need a
type and a name, and a semicolon ; at the end. The name can be any
combinations of letters, numbers, and underscores _ and must not start with a number.
There can be no spaces in a variable name!
For example:
int a;
char b;
float my_variable;
int my_4th_variable;
Variable Types
int
One of the easiest types to understand and use is int. int is short for "integer"
and is another word for "whole number". When using printf to display the value of an int,
use the %d format code.
int a;
a = 5;
a = a * 2;
a = (a + 2) / 3;
printf("The value of a is %d\n", a);
float
Another type of number is float. float is short for "floating point" and is
a number which isn't necessarily a whole number. When using printf, use the %f format code.
float b;
b = 3.8;
b = b + 1.773;
b = (b * 1.05 - 6.1) / 3.33;
printf("The value of b is %f\n", b);
char
A different type of variable is char. char is short for "character" and can be
any letter, number, or any other single symbol that can be displayed on the screen. Use
the %c printf format code.
char c;
c = 'a';
printf("The value of c is %c\n", c);