AD4BP

Lesson 3: Variables and Data Types

During programming we need to store data. This data is stored in variables. Variables are locations in memory for storing data. The memory is divided into blocks. It can be viewed as pigeon-holes. You can also think of it as PO Boxes. In post offices there are different boxes and each has an address. Similarly in memory, there is a numerical address for each location of memory (block). It is difficult for us to handle these numerical addresses in our programs. So we give a name to these locations. These names are variables. We call them variables because they can contain different values at different times.
The variable names in C may be started with a character or an underscore ( _ ). But avoid starting a name with underscore ( _ ). C has many libraries which contain variables and function names normally starting with underscore ( _ ). So your variable name starting with underscore ( _ ) may conflict with these variables or function names.

In a program every variable has
o Name
o Type
o Size
o Value

The variables having a name, type and size (type and size will be discussed later) are just empty boxes. They are useless until we put some value in them. To put some value in these boxes is known as assigning values to variables. In C language, we use assignment operator for this purpose.
In C language equal-to-sign (=) is used as assignment operator. Do not confuse the algebraic equal-to with the assignment operator. In Algebra X = 2 means the value of X is 2, whereas in C language X = 2 (where X is a variable name) means take the value 2 and put it in the memory location labeled as X, afterwards you can assign some other value to X, for example you can write X = 10, that means now the memory location X contains the value 10 and the previous value 2 is no more there.

Data Types
A variable must have a data type associated with it, for example it can have data types like integer, decimal numbers, characters etc. The variable of type Integer stores integer values and a character type variable stores character value. The primary difference between various data types is their size in memory. Different data types have different sizes in memory depending on the machine and compilers. There are very few data types in C language. These data types are reserved words of C language. The reserve words can not be used as a variable name. Let’s take a look into different data types that the C language provides us to deal with whole numbers, real numbers and character data.

Whole Numbers
The C language provides three data types to handle whole numbers.
o int
o short
o long

The data type int is used to store whole numbers (integers). The integer type has a space of 4 bytes (32 bits for windows operating system) in memory. And it is mentioned as ‘int’ which is a reserved word of C, so we can not use it as a variable name. In programming before using any variable name we have to declare that variable with its data type. If we are using an integer variable named as ‘i’, we have to declare it as

int i ;

The above line is known as declaration statement. The declaration statement int i ; reserves 4 bytes of memory and labels it as ‘i’. This happens at the execution time.

We noted that the integer occupies four bytes in memory. So if we have to store a small integer like 5, 10 or 20, C provides another data type for storing small whole numbers which is called short. The size of short is two bytes and it can store numbers in range of -32768 to 32767. So if we are going to use a variable for which we know that it will not increase from 32767, for example the age of different people, then we use the data type short for age.

short age = 5;

On the other side if we have a very large whole number that cannot be stored in an int then we use the data type long provided by C. So when we are going to deal with very big whole numbers in our program, we use long data type. We use it in program as:

long x = 300500200;

Real Numbers
The C language provides two data types to deal with real numbers (numbers with decimal points e.g. 1.35, 735.251). The real numbers are also known as floating point numbers.
o float
o double

To store real numbers, float data type is used. The float data type uses four bytes to store
a real number. Here is program that uses float data types.

float f = 325.32501

If we need to store a large real number which cannot be store in four bytes, then we use double data type. Normally the size of double is twice the size of float. In program we use it as:
double x = 345624.769123;


char Data Type
So far we have been looking on data types to store numbers, In programming we do need to store characters like a,b,c etc. For storing the character data C language provides char data type. By using char data type we can store characters in variables. While assigning a character value to a char type variable single quotes are used around the character as ‘a’.

/* This program uses short data type to store values */
#include
main()
{
char x;
x = ’a’;
cout << “The character value in x = “;
cout << x;
}

Arithmetic Operators
In C language we have the usual arithmetic operators for addition, subtraction, multiplication and division. C also provides a special arithmetic operator which is called modulus. All these operators are binary operators which means they operate on two operands. So we need two values for addition, subtraction, multiplication, division and modulus.
Addition +
Subtraction -
Multiplication *
Division /
Modulus %

There is one thing to note in division that when we use integer division (i.e. both operands are integers) yields an integer result. This means that if, for example, you are dividing 5 by 2 (5 / 2) it will give integer result as 2 instead of actual result 2.5. Thus in integer division the result is truncated to the whole number, the fractional part (after decimal) is ignored. If we want to get the correct result, then we should use float data type. The modulus operator returns the remainder after division. This operator can only be used with integer operands. The expression x % y returns the remainder after x is divided by y. For example, the result of 5 % 2 will be 1, 23 % 5 will be 3 and 107%10 will be 7.

Precedence of Operators
The arithmetic operators in an expression are evaluated according to their precedence. The precedence means which operator will be evaluated first and which will be evaluated after that and so on. In an expression, the parentheses ( ) are used to force the evaluation order. The operators in the parentheses ( ) are evaluated first. If there are nested parentheses then the inner most is evaluated first. The expressions are always evaluated from left to right. The operators *, / and % have the highest precedence after parentheses. These operators are evaluated before + and –
operators. Thus + and – operators has the lowest precedence. It means that if there are * and + operators in an expression then first the * will be evaluated and then its result will be added to other operand. If there are * and / operators in an expression (both have the same precedence) then the operator which occurs first from left will be evaluated first and then the next, except you force any operator to evaluate by putting parentheses around it.

Lesson 2: First C Program

The best way to learn C is to start coding right away. So here is our very first program in C.
# include
main()
{
cout << "HELLO WORLD!"; } Let's see what the above snippet of code means. # include #include is a pre-processor directive. It is not part of our program; it is an instruction to the compiler. It tells the C compiler to include the contents of a file, in this case the system file iostream.h. The compiler knows that it is a system file, and therefore looks for it in a special place. The features of preprocessor will be discussed later. For the time being take this line on faith. You have to write this line. The sign # is known as HASH and also called SHARP.
is the name of the library definition file for all Input Output Streams. Your program will almost certainly want to send stuff to the screen and read things from the keyboard. iostream.h is the name of the file which has the code to do that work for you.

main()
The name main is special, in that the main is actually the one which is run when your program is used. A C program is made up of a large number of functions. Each of these is given a name by the programmer and they refer to each other as the program runs. C regards the name "main" as a special case and will run this function first. If you forget to have a main function, or mistype the name, the compiler will give you an error.

Notice that there are parentheses (“( )”, normal brackets) with main. Here the parentheses contain nothing. There may be something written inside the parentheses. It will be discussed in later lectures.

{}
Next, there is a curly bracket also called braces("{ }"). For every open brace there must be a matching close. Braces allows to group together pieces of a program. The body of main is enclosed in braces. Braces are very important in C; they enclose the blocks of the program.

cout
cout is known as out put stream in C and C++. Stream is a complicated thing, you will learn about it later. Think of a stream as a door. The data is transferred through stream, cout takes data from computer and sends it to the output. For the moment it is a screen of the monitor. hence we use cout for output.

<<
The sign << indicates the direction of data. Here it is towards cout and the function of cout is to show data on the screen.

“HELLO WORLD!”
The thing between the double quotes (“ ”) is known as character string. In C programming character strings are written in double quotes. Whatever is written after << and within quotation marks will be direct it to cout, cout will display it on the screen.

The semicolon (;) at the end of the above statement is very important. All C statements end with a semicolon (;). Missing of a semicolon (;) at the end of statement is a syntax error and compiler will report an error during compilation. If there is only a semicolon (;) on a line than it will be called a null statement. i.e. it does nothing. The extra semicolons may be put at the end but are useless and aimless

What is Programming?

Formally: "A program is a precise sequence of steps to solve a particular problem."
At its most basic level, programming a computer simply means telling it what to do. Without these instructions or programs computers are merely dumb machines. Computers are incredibly stupid. They do exactly what we tell them to do: no more, no less-- unlike human beings. Computers can't think by themselves. In this sense, they differ from human beings. For example, if someone asks you, “What is the time?”, “Time please?” or just, “Time?” you understand anyway that he is asking the time but computer is different. Instructions to the computer should be explicitly stated. Computer will tell you the time only if you ask it in the way you have programmed it. When you're programming, it helps to be able to "think'' as stupidly as the computer does, so that you are in the right frame of mind for specifying everything in minute detail, and not assuming that the right thing will happen by itself.

The Receipe of a good Program:
In order to design a program effectively and properly we must have a recipe to follow. In the book name ‘How to design programs’ by Matthias Felleisen and the co-worker, the idea of design recipe has been stated very elegenlty as “Learning to design programs is like learning to play soccer. A player must learn to trap a ball, to dribble with a ball, to pass, and to shoot a ball. Once the player knows those basic skills, the next goals are to learn to play a position, to play certain strategies, to choose among feasible strategies, and, on occasion, to create variations of a strategy because none fits.“ The author then continues to say that: “A programmer is also very much like an architect, a composers, or a writer. They are creative people who start with ideas in their heads and blank pieces of paper. They conceive of an idea, form a mental outline, and refine it on paper until their writings reflect their mental image as much as possible. As they bring their ideas to paper, they employ basic drawing, writing, and playing music to express certain style elements of a building, to describe a person's character, or to formulate portions of a melody. They can practice their trade because they have honed their basic skills for a long time and can use them on an instinctive level. Programmers also form outlines, translate them into first designs, and iteratively refine them until they truly match the initial idea. Indeed, the best programmers edit and rewrite their programs many times until they meet certain aesthetic standards. And just like soccer players, architects, composers, or writers, programmers must practice the basic skills of their trade for a long time before they can be truly creative. Design recipes are the equivalent of soccer ball handling techniques, writing techniques, arrangements, and drawing skills. “ Hence to design a program properly, we must:

o Analyze a problem statement, typically expressed as a word problem.
o Express its essence, abstractly and with examples.
o Formulate statements and comments in a precise language.
o Evaluate and revise the activities in light of checks and tests and
o Pay attention to detail.

All of these are activities are very useful for a programmer.

The above details are provided just for the sake of completeness and do not worry if the above sounds greek to you. it is natural. If, after going half of the course, you come back here then you will be in a perfect position to understand all of this. We have kept this boring detail to a limit. There were other topics like types of softwares, system software, application software, device drivers and the dry background of C programming language, which we have not included in this tutorial / guide. Our focus in this tutorial / guide is on programming C / C++.