Lecture 3 – Variables and Constants
Variables and Constants
While
writing a program you need some place to put your data on. For that we need
variables and constants.
Variable
A variable
is a named memory location, whose contents can be changed during the course of
the program. For example a, x, y, k.
There
are two types of variable in C.
1.
Numeric
a.
Integer
An integer variable is a
variable which has NO fractional
part. For example a=5, b=6 etc. We will be using two types of integer variable
during our course. int for integer and short for short integer. Integer takes
2-bytes whereas Short takes 1-byte in memory.
·
Integer can handle values from -32768 to 32767
·
Short can handle values from -128 to 127
b.
Floating
point
An floating point
variable is a variable which has fractional part. For example a=5.6, b=6.134,
PI=3.1416 etc. Float takes 4-bytes in memory.
2.
Character
Character variable is used to store characters in memory. A
single character can store only one character in memory. If we need to store
things like your name, we need to create a character array. Arrays are beyond
the scope of our current course, they will not be discussed.
Constant
Constant
is a literal which can be assigned a value during its declaration and its value
cannot be changed. For example you’re Date of birth, the value of PI, speed of
light etc.
Variable Declaration
Variable
declaration is the process of reserving space, for your variable in the memory.
You must declare a variable before you can use it. If you do not declare a
variable and try to use it, it would be a syntax error. Declare variables’ at
the start of main function. The general declaration syntax is
<datatype> <variablename>; e.g. à int a; or float b; or char
c;
We
can declare multiple variables of same data type like
int a, b, c; //
a, b and c all are of integer data type
int x, y, z; float k; // x, y, z are of type integer, and k
is a type of float
Rules for naming a variable
1.
Variable name must
a. start
with an alphabet or underscore
b. be
less than 31 characters
c. be
declared before it can be used
2.
Variable name cannot
a. start
with any digit
b. contain
any spaces
c. contain
any special character(s)
d. be
declared more than once
e. be
a reserved word
f.
be a keyword
Variable initialization
Assigning
first value to a variable is called variable initialization. A variable can be
assigned a value using the ‘=’ operator. For example
int
a; // variable declaration
a=5; // variable initialization
We
can use compound assignment operator to initialize multiple variables. E.g
a=b=c=5; // firstly c = 5
will be evaluated, then b=c and lastly a =b
We
can declare and initialize a variable at the same time. E.g.
int
z=0;
similarly
multiple variables can be declared and initialized at the same time. E.g.
int
a, b, c=5; // only c will be
initialized because no value is specified for a and b
int
a=5, b=10, c=15; // a will be
initialized with 5, b with 10 and c with 15
Comments
Post a Comment