0% found this document useful (0 votes)
24 views5 pages

CH 04

Uploaded by

Samson Girma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views5 pages

CH 04

Uploaded by

Samson Girma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

4.

VARIABLES, DATA TYPES & CONSTANTS

DEFINITION

A variable is a symbolic name for a memory location in which data can be stored and subsequently
recalled. Variables are used for holding data values so that they can be utilized in various
computations in a program. All variables have two important attributes:

• A type which is established when the variable is defined (e.g., integer,


real, character). Once defined, the type of a C++ variable cannot be changed.
• A value which can be changed by assigning a new value to the variable.
The kind of values a variable can assume depends on its type. For
example, an integer variable can only take integer values (e.g., 2, 100, -1,
etc).

The name of a variable is called an identifier. You can give a variable any name you want, as long as
it is a valid identifier.

VALID IDENTIFIERS

A valid identifier is a sequence of one or more letters, digits or underscores. The identifier must begin
with a letter. C++ does not allow identifiers to start with a number, punctuation marks, symbols or
spaces. Compiler specific keywords or external identifiers usually begin with an underscore. It also
possible to use an underscore at the beginning of your identifier, but it is not recommended.

For example: valid identifiers - my_var, _m, abc , A_


invalid identifiers - 1my_var, $a, !abc

The C++ language is a "case sensitive" language. This means that an identifier with capital letters is
not the same as with normal letters.

For example: myvar, Myvar, MyVar and MYVAR are four different variable identifiers.

The C++ language also uses a set of names that are reserved. It is not allowed to use these keywords
as variable identifiers (variable names). The standard reserved keywords are:

asm, auto, bool, break, case, catch, class, char, const,const_cast, continue, default, delete,
double, do, dynamic_cast, enum, else, explicit, extern, export, float, false, for, friend, goto
int, if, inline, long, mutable, namespace, new, operator, private, protected, public, register,
reinterpret_cast, return, short, switch, signed, sizeof, static, static_cast, struct, template, this,
throw, true, try, typedef, typeid, typename, union, unsigned, using, void, virtual, volatile,
while, wchar_t
DATA TYPES

There are three types of variables: numeric-integer, numeric-real and character.

• Numeric variables can either be of the type integer (int) or of the type real (float). Integer (int)
values are whole numbers (like 10 or -10.) Real (float) values can have a decimal point in
them. (Like 1.25 or -1.25.)
• Character variables are letters of the alphabet, ASCII characters or numbers (0-9). If you
declare a character variable you must always put the character between single quotes (like so
'a'). So remember a character between single quotes is not the same as a character with single
quotes.

FUNDAMENTAL DATA TYPES

When programming, we store the variables in our computer's memory, but the computer has to know
what kind of data we want to store in them, since it is not going to occupy the same amount of
memory to store a simple number than to store a single letter or a large number, and they are not
going to be interpreted the same way. The memory in our computers is organized in bytes. A byte is
the minimum amount of memory that we can manage in C++. A byte can store a relatively small
amount of data: one single character or a small integer (generally an integer between 0 and 255). In
addition, the computer can manipulate more complex data types that come from grouping several
bytes, such as long numbers or non-integer numbers.

Name Description Size* Range*


bool Boolean value. It can take one of two 1 true or false
values: true or false.
char Character or small integer. 1 signed: -128 to 127
unsigned: 0 to 255
short int Short Integer. 2 signed: -32768 to 32767
(short) unsigned: 0 to 65535
wchar_t Wide character. 2 1 wide character
int Integer. 4 signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
long int (long) Long integer. 4 signed: -2147483648 to 2147483647
unsigned: 0 to 94967295
float Floating point number. 4 3.4e +/- 38 (7 digits)
double Double precision floating point number. 8 1.7e +/- 308 (15 digits)
long double Long double precision floating point 8 1.7e +/- 308 (15 digits)
number.

DECLARING A VARIABLE

So we now know different data types and which rules an identifier must comply. But how do we
declare them. Declaring a variable is very easy. First you have to declare the data type. After the data
type you place the name of the variable. But remember choose the names wisely. It is easier if a
variable name reflects the use of that variable. For instance: if you name a float PI, you always know
what it means.

Now let's declare some variables, a variable MyIntegerVariable which is an integer number,
MyRealVariable which is a real number and MyCharacterVariable which is a character variable
respectively.
int MyIntegerVariable;
float MyRealVariable;
char MyCharacterVariable;

It is possible to declare more than one variable at the same time:

int Variable1, Variable2, Variable3;// declares Variable1, Variable2 & Variable3 as


integer
float x, y, z; // declares x, y & z as real number

SIGNED AND UNSIGNED VARIABLES

The difference between signed and unsigned variables is that signed variables can be either negative
or positive but unsigned variables can only be positive. By using an unsigned variable you can
increase the maximum positive range. When you declare a variable in the normal way it is
automatically a signed variable. To declare an unsigned variable you just put the word unsigned
before your variable declaration or signed for a signed variable although there is no reason to declare
a variable as signed since they already are.

unsigned int MyOnlyPositiveVar; // the variable accepts +ve numbers


signed int MyNegativeAndPositiveVar; // the variable accepts +ve & -ve numbers
int MyNegativeAndPositiveVar; //The same as the second example.

An exception to this general rule is the char type, which exists by itself and is considered a different
fundamental data type from signed char and unsigned char, thought to store characters. You should
use either signed or unsigned if you intend to store numerical values in a char-sized variable.

SCOPE OF VARIABLES

All the variables that we intend to use in a program must have been declared with its type specifier in
an earlier point in the code. Variable can be either of global or local scope. A global variable is a
variable declared in the main body of the source code, outside all functions, while a local variable is
one declared within the body of a function or a block. Global variables can be referred from anywhere
in the code, even inside functions, whenever it is after its declaration.

Example

#include <isostream.h>
using namespace std;

int Integer;
char character; Global variable
char string [20];

int main ()
{

float PI; Local variable

cin >> PI;


Integer = PI*2; Instructions
}
INITIALIZATION OF VARIABLES

When declaring a regular local variable, its value is by default undetermined. But you may want a
variable to store a concrete value at the same moment that it is declared. In order to do that, you can
initialize the variable. There are two ways to do this in C++:

The first one, known as c-like, is done by appending an equal sign followed by the value to which the
variable will be initialized:

type identifier = initial_value ;

For example, if we want to declare an int variable called a initialized with a value of 0 at the moment
in which it is declared, we could write:

int a = 0;

The other way to initialize variables, known as constructor initialization, is done by enclosing the
initial value between parentheses (()):

type identifier (initial_value) ;

For example:

int a (0);

Both ways of initializing variables are valid and equivalent in C++.

CONSTANTS

The difference between variables and constants is that variables can change their value at any time but
constants can never change their value. The constants value is locked for the duration of the program.
Constants can be very useful; PI for instance is a good example to declare as a constant.

DEFINING A CONSTANTS (#define)

With the pre-processor directive "define" it is possible to define your own constants.
The format of the pre-processor directive #define is:

#define identifier value

Example: To define PI as a constant we can say

#define PI 3.14159

DEFINING A CONSTANTS (const)

With the const prefix you can declare constants with a specific type in the same way as you would do
with a variable:

const type identifier = initial_value;

Example: To define PI as a constant we can say

const float PI = 3.14159;


Example 4.1: Let us try to see all of the above concepts in one civil engineering application.

Purpose: To calculate are of a circle.


Algorithm:
1. Accept radius of the circle from the user.
2. Calculate the area as .
3. Print out the result to the user.

From the above algorithm we see that we need three variables which all are real numbers. The code
looks like this

1 #include <iostream>
2 using namespace std;
3 #define PI 3.14159 // declaring PI as global variable and initializing it to 3.14
4
5 int main()
6 {
7 float area; // declares a local variable for calculating the area
8 float radius; // declares a local variable for accepting the radius
9 cout << "Welcome, this program calculates area of a circle given radius of a circle \n"; //greeting
10 cout << "Please enter the radius of the circle \n"; // notifies the user to give the program radius
11 cin >> radius; // reads radius form the user and saves it to radius variable
12 area = PI*radius*radius; // calculates area of the circle
13 cout << "The area of the circle equals " << area << " unit square \n"; // displays the output
14 }

Let us try to explain each line indicated by its line number on the left.

line 1. This line uses the preprocessor directive #include to include the contents of the header file iostream in the
program. iostream is a standard C++ header file and contains definitions for input and output.
line 2. This is an advanced feature of C++. It is used to specify that names used in the program (such as cout) are
defined in the standard C and C++ libraries. This is used to avoid problems with other libraries which may
also use these names.
line 3. Declare PI as real number variable with initial value of 3.14. All words after “//” are comments and are
ignored by the C++ compiler.
line 4. Blank lines are also ignored by the C++ compiler.
line 5. This line defines a function called main. A function may have zero or more parameters; these always
appear after the function name, between a pair of brackets. The word void appearing between the brackets
indicates that main has no parameters. A function may also have a return type; this always appears before
the function name. The return type for main is int (i.e., an integer number). All C++ programs must have
exactly one main function. Program execution always begins from main.
line 6. This brace marks the beginning of the body of main.
line 7. Declare area as real number variable for storing the value of the area of the circle after calculation
line 8. Declare radius as real number variable for accepting radius of the circle from the user
line 9. This line is a statement. A statement is a computation step which may produce a value. The end of a
statement is always marked with a semicolon (;). This statement causes the string “Welcome,...." to be sent
to the cout output stream. The last character in this string (\n) is a newline character which is similar to a
carriage return on a type writer. cout is the standard output stream in C++ (standard output usually means
your computer monitor screen) The symbol << is an output operator which takes an output stream as its left
operand and an expression as its right operand, and causes the value of the latter to be sent to the former. In
this case, the effect is that the string "Welcome,…" is sent to cout, causing it to be printed on the computer
monitor screen.
line 10. Same as line 9
line 11. This line reads the input value typed by the user and copies it to radius. The input operator >> takes an
input stream as its left operand (cin is the standard C++ input stream which corresponds to data entered via
the keyboard) and a variable (to which the input data is copied) as its right operand.
line 12. This line is a statement. It computes the area of the circle based on the given information.
line 13. This line outputs the result on your computer monitor.
line 14. This brace marks the end of the body of main.

You might also like