Examples of Expressions

Tuesday, May 29, 2012
We have already seen the precedence of arithmetic operators. We have expressions for different calculations in algebraic form, and in our programs we write them in the form of C statements. Let’s discuss some more examples to get a better understanding.

We know about the quadratic equation in algebra, that is y = ax2 + bx + c. The quadratic equation in C will be written as y = a * x * x + b * x + c. In C, it is not an equation but an assignment statement. We can use parentheses in this statement, this will make the expression statement easy to read and understand. Thus we can rewrite it as y = a * (x * x) + (b * y) + c.

Note that we have no power operator in C, just use * to multiply the same value.

Here is another expression in algebra: x = ax + by + cz2. In C the above expression will be as:

x = a * x + b * y + c * z * z

The * operator will be evaluated before the + operator. We can rewrite the above statement with the use of parentheses. The same expressions can be written as:

x = (a * x) + (b * y) + c * ( z * z)

Lets have an other expression in algebra as x = a(x + b(y + cz2)). The parentheses in this equation forces the order of evaluation. This expression will be written in C as:

x = a * (x + b * (y + c * z * z))

While writing expressions in C we should keep in mind the precedence of the operators and the order of evaluation of the expressions (expressions are evaluated from left to right). Parentheses are used in complicated expressions. In algebra, there may be curly brackets { } and square brackets [ ] in an expression but in C we have only parentheses ( ). Using parentheses, we can make a complex expression easy to read and understand and can force the order of evaluation. We have to be very careful while using parentheses, as parentheses at wrong place can cause an incorrect result. For example a statement x = 2 + 4 * 3 results x = 14. As * operator is of higher precedence, 4 * 3 is evaluated first and then result 12 is added to 4 which gives the result 14. We can rewrite this statement, with the use of parentheses to show it clearly, that multiplication is performed first. Thus we can write it as x = 2 + (4 * 3). But the same statement with different parentheses like x = (2 + 4) * 3 will give the result 18, so we have to be careful while using parenthesis and the evaluation order of the expression.

Similarly the equation (b^2 – 4ac)/2a can be written as ( b * b – 4 * a * c) / ( 2 * a ). The same statement without using parentheses will be as b * b – 4 * a * c / 2 * a. This is wrong as it evaluates to b^2 – 4ac/2a (i.e. 4ac is divided by 2a instead of (b^2-4ac)).

For previous lesson click here: Sample Program
For next lesson click here: Use of Operators


the easiest way to learn programming
introduction to programming
Examples of Expressions

Sample Program

Monday, May 28, 2012
Problem statement:

Calculate the average age of a class of ten students. Prompt the user to enter the age of each student.

Solution:

Lets first sort out the problem. In the problem we will take the ages of ten students from the user. To store these ages we will use ten variables, one for each student’s age. We will take the ages of students in whole numbers (in years only, like 10, 12, 15 etc), so we will use the variables of data type int. The variables declaration statement in our program will be as follow:

int age1, age2, age3, age4, age5, age6, age7, age8, age9, age10;

We have declared all the ten variables in a single line by using comma separator (,). This is a short method to declare a number of variables of the same data type.

After this we will add all the ages to get the total age and store this total age in a variable. Then we will get the average age of the ten students by dividing this total age by 10. For the storage of total and average ages we need variables. For this purpose we use variable TotalAge for the total of ages and AverageAge for average of ages respectively.

int TotalAge, AverageAge;

We have declared AverageAge as int data type so it can store only whole numbers. The average age of the class can be in real numbers with decimal point (for example if total age is 173 then average age will be 17.3). But the division of integers will produce integer result only and the decimal portion is truncated. If we need the actual result then we should use real numbers (float or double) in our program.

Now we have declared variables for storing different values. In the next step we prompt the user to enter the age of first student. We simply show a text line on the screen by using the statement:

cout << “Please enter the age of first student : “; So on the screen the sentence “Please enter the age of first student:” will appear. Whenever we are requesting user to enter some information we need to be very clear i.e. write such sentences that are self explanatory and user understands them thoroughly and correctly. Now with the above sentence everyone can understand that age would be entered for the first student. As we are expecting only whole numbers i.e. age in years only i.e. 10, 12 etc, our program is not to expect ages as 13.5 or 12.3 or 12 years and 3 months etc. We can refine our sentence such, that the user understands precisely that the age would be entered in whole number only. After this we allow the user to enter the age. To, get the age, entered by the user into a variable, we use the statement: cin >> age1;

Lets have a look on the statement cin >> age1; cin is the counter part of the cout. Here cin is the input stream that gets data from the user and assigns it to the variable on its right side. We know that the sign >> indicates the direction of the flow of data. In our statement it means that data comes from user and is assigned to the variable age1, where age1 is a variable used for storing the age entered for student1. Similarly we get the ages of all the ten students and store them into respective variables. That means the age of first student in age1, the age of second student in age2 and so on up to 10 students. When cin statement is reached in a program, the program stops execution and expects some input from the user. So when cin >> age1; is executed, the program expects from the user to type the age of the student1. After entering the age, the user has to press the 'enter key'. Pressing 'enter key' conveys to the program that user has finished entering the input and cin assigns the input value to the variable on the right hand side which is age1 in this case. As we have seen earlier that in an assignment statement, we can have only one variable on left hand side of the assignment operator and on right hand side we can have an expression that evaluates to a single value. If we have an expression on the left hand side of assignment operator we get an error i.e. x = 2 + 4; is a correct statement but x + y = 3+ 5; is an incorrect statement as we can not have an expression on the left hand side. Similarly we can not have an expression after the >> sign with cin. So we can have one and only one variable after >> sign i.e cin >> x; is a correct statement and cin >> x + y; is an incorrect statement.

Next, we add all these values and store the result to the variable TotalAge. We use assignment operator for this purpose. On the right hand side of the assignment operator, we write the expression to add the ages and store the result in the variable, TotalAge on left hand side. For this purpose we write the statement as follow:

TotalAge = age1 + age2 + age3 + age4 + age5 + age6 + age7 + age8 + age9 + age10 ;

The expression on the right hand side uses many addition operators ( + ). As these operators have the same precedence, the expression is evaluated from left to right. Thus first age1 is added to age2 and then the result of this is added to age3 and then this result is added to age4 and so on.

Now we divide this TotalAge by 10 and get the average age. We store this average age in the variable i.e. AverageAge by writing the statement:

AverageAge = TotalAge / 10;

And at the end we display this average age on the screen by using the following statement:

cout << “ The average age of the students is : “ << AverageAge; Here the string enclosed in the quotation marks, will be printed on the screen as it is and the value of AverageAge will be printed on the screen. The complete coding of the program is given below.


A snapshot of the execution of the above program:


In the above output the total age of the students is 123 and the actual average should be 12.3 but as we are using integer data types so the decimal part is truncated and the whole number 12 is assigned to the variable AverageAge.

For previous lesson click here: Precedence of Operators
For next lesson click here: Examples of Expressions


the easiest way to learn programming
introduction to programming
Sample Program

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.

The following table explains the precedence of the arithmetic operators:

Operators Operations Precedence (Order of evaluation)
( ) Parentheses Evaluated first
*, /, or % Multiplication, Division, Modulus Evaluated second. If there are several, they are evaluated from left to right
+ or - Addition, Subtraction Evaluated last. If there are several, they are evaluated from left to right

Lets look some examples.

What is the result of 10 + 10 * 5 ?

The answer is 60 not 100. As * has higher precedence than + so 10 * 5 is evaluated first and then the answer 50 is added to 10 and we get the result 60. The answer will be 100 if we force the addition operation to be done first by putting 10 + 10 in parentheses. Thus the same expression rewritten as (10 + 10) * 5 will give the result 100. Note that how the parentheses affect the evaluation of an expression.

Similarly the expression 5 * 3 + 6 / 3 gives the answer 17, and not 7. The evaluation of this expression can be clarified by writing it with the use of parentheses as (5 * 3) + (6 / 3) which gives 15 + 2 = 17. Thus you should be careful while writing arithmetic expressions.

Tips
  • Use spaces in the coding to make it easy to read and understand
  • Reserved words can not be used as variable names
  • There is always a main( ) in a C program that is the starting point of execution
  • Write one statement per line
  • Type parentheses ’( )’ and braces ‘{ }’ in pairs
  • Use parentheses for clarification in arithmetic expressions
  • Don’t forget semicolon at the end of each statement
  • C Language is case sensitive so variable names x and X are two different variables

For previous lesson click here: Arithmetic Operators
For next lesson click here: Sample Program


the easiest way to learn programming
introduction to programming
Precedence of Operators

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.

Arithmetic OperationArithmetic OperatorAlgebraic ExpressionC Expression
Addition+x + yx + y
Subtraction-x - yx - y
Multiplication*xyx * y
Division/x ÷ y, x / yx / y
Modulus%x mod yx % y

Addition, subtraction and multiplication are same as we use in algebra.
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.

Sample Program 2
This is a sample program that uses the arithmetic operators. It displays the result of arithmetic operations on the screen. To make the result more visible we have used end line character (endl) with cout. So the statement:

cout << endl;

Simply ends the current line on the screen and the next cout statement displayed at the next line on the screen.

Code of The Program(Operation with integers)

Output of the program

Code of The Program(Operation with decimal numbers)

Output of the program

see everything clearly
// A Sample Program that uses Arithmetic Operators.

#include

main ()
{
//declaration of variables
int a;
int b;
int c;

float x;
float y;
float z;

// assigning values to variables
a = 23;
b = 5;
x = 12.5;
y = 2.25;

// processing and display with integer values
cout << "Operations with integers" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; //addition c = a + b; cout << "a + b = " << c << endl; //subtraction c = a - b; cout << "a - b = " << c << endl; //multiplication c = a * b; cout << "a * b = " << c << endl; // division c = a / b; cout << "a / b = " << c << endl; //modulus c = a % b; cout << "a % b = " << c << endl; // processing and display with decimal values cout << "Operations with decimal numbers" << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; //addition z = x + y; cout << "x + y = " << z << endl; //subtraction z = x - y; cout << "x - y = " << z << endl; //multiplication z = x * y; cout << "x * y = " << z << endl; //division z = x / y; cout << "x / y = " << z << endl; } Output of the program
Operations with integers

a = 23
b = 5
a + b = 28
a - b = 18
a * b = 115
a / b = 4
a % b = 3

Operations with decimal numbers

x = 12.5
y = 2.25
x + y = 14.75
x - y = 10.25
x * y = 28.125
x / y = 5.55556

For previous lesson click here: Data Types
For next lesson click here: Precedence of Operators


the easiest way to learn programming
introduction to programming
Arithmetic Operators

Data Types

A variable must have a data type like integer, decimal numbers, characters etc. The variable of type Integer stores integers and a character type variable stores characters. The primary difference between data types is their size in memory. Different data types have different size in memory depending on the machine and compilers. These also affect the way they are displayed. The ‘cout’ knows how to display a digit and a character. There are 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.
  • int
  • short
  • long
int Data Type:
The data type int is used to store whole numbers (integers). The integer type has a space of 4 bytes (32 bits) 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. When we declare a variable in this way, it reserves some space in memory depending on the size of data type and labels it with the variable name. The declaration statement int i ; reserves 4 bytes of memory and labels it as ‘i’. This happens at the execution time.
Sample Program 1
Let’s consider a simple example to explain int data type. In this example we take two integers, add them and display the answer on the screen.

The code of the program is written below.


The first three lines are the same, we have discussed already in our first program. Now as we need to use variables in our program. So we first declare three variables x, y and z with their data type integer as following.

int x;
int y;
int z;

These three declarations can also be written on one line. C provides us the comma separator (,). The above three lines can be written in a single line as below

int x, y, z;

As we know that semicolon (;) indicates the end of the statement. So we can write many statements on a single line. In this way we can also write the above declarations in the following form

int x; int y; int z;

For good programming practice, write a single statement on a single line.

Now we assign values to variables x and y by using assignment operator. The lines x = 5; and y = 10 assign the values 5 and 10 to the variables x and y, respectively. These statements put the values 5 and 10 to the memory locations labeled as x and y.

The next statement z = x + y; evaluates the expression on right hand side. It takes values stored in variables x and y (which are 5 and 10 respectively), adds them and by using the assignment operator (=), puts the value of the result, which is 15 in this case, to the memory location labeled as z.

Here a thing to be noted is that the values of x and y remains the same after this operation. In arithmetic operations the values of variables used in expression on the right hand side are not affected. They remain the same. But a statement like x = x + 1; is an exceptional case. In this case the value of x is changed.

The next line cout << “ x = “ ; is simple. It just displays ‘ x = ‘ on the screen. Now we want to display the value of x after ‘x =’. For this we write the statement cout << x ; Here comes the affect of data type on cout. The previous statement cout << “x = “ ; has a character string after << sign and cout simply displays the string. In the statement cout << x; there is a variable name x. Now cout will not display ‘x’ but the value of x. The cout interprets that x is a variable of integer type, it goes to the location x in the memory and takes its value and displays it in integer form, on the screen. The next line cout << ”y =”; displays ‘ y = ‘ on the screen. And line cout << y; displays the value of y on the screen. Thus we see that when we write something in quotation marks it is displayed as it is but when we use a variable name it displays the value of the variable not name of the variable. The next two lines cout << “z = x + y = ”; and cout << z; are written to display ‘z = x + y = ’ and the value of z that is 15. Now when we execute the program after compiling, we get the following output


short Data Type:

We noted that the integer has four bytes in memory. So if we have to store a small integer like 5, 10 or 20 it will occupy four bytes. The 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. We can write the above sample program by using short instead of int.



long Data Type:
stored in 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.

  • float
  • double

float Data Type:
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.


Here is the output of the above program.


double Data Type:
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:

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’.


The output will be as:

For previous lesson click here: Assignment Operator
For next lesson click here: Arithmetic Operators


the easiest way to learn programming
introduction to programming
Data Types

Assignment Operator

The equal-to-sign (=) is used as assignment operator in C language. 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.

Assignment operator is a binary operator (a binary operator has two operands). It must have variable on left hand side and expression (that evaluates to a single value) on right hand side. This operator takes the value on right hand side and stores it to the location labeled as the variable on left hand side, e.g. X = 5, X = 10 + 5, and X = X +1. In C language the statement X = X + 1 means that add 1 to the value of X and then store the result in X variable. If the value of X is 10 then after the execution of this statement the value of X becomes 11. This is a common practice for incrementing the value of the variable by one in C language. Similarly you can use the statement X = X - 1 for decrementing the value of the variable by one. The statement X = X + 1 in algebra is not valid except when X is infinity. So do not confuse assignment operator (=) with equal sign (=) in algebra. Remember that assignment operator must have a variable name on left hand side unlike algebra in which you can use expression on both sides of equal sign (=). For example, in algebra, X +5 = Y + 7 is correct but incorrect in C language. The compiler will not understand it and will give error.

For previous lesson click here: Variables
For next lesson click here: Data Types


the easiest way to learn programming
introduction to programming
Assignment Operator

Variables

We store every kind of data 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 think of it as PO Boxes also. 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:
  • Name
  • Type
  • Size
  • 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.

For previous lesson click here: Our First Program,c++ First program
For next lesson click here: Assignment Operator


the easiest way to learn programming
introduction to programming
Variables

Our First Program,c++ First program

Sunday, May 27, 2012
Let’s write our first program in C and understand the basics of C program by explaining it line by line.

# include

main()

{
cout << "hello!"; }


The first line is # include

This is preprocessor directive. 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.

The next line contains main().

There is a main() in every C program. It occurs once in a program. When we write a program and it compiles successfully, it converts into an executable program (file). Then we execute it by typing the command or by double clicking in graphical interface. The system then loads the program into memory. Now the question arises from where the execution should start. In C programs the execution always starts from the main(). In large programs there may be many modules. But the starting point of the program will always be the main function.

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 next lectures.

Next, there is a curly bracket also called braces("{ }"). Here is a thing to remember that brackets (parentheses ( ) and braces { }) always occur in pairs. The body of main is enclosed in braces. Braces are very important in C; they enclose the blocks of the program.

The next line in the program,

cout << “hello!”;

is a statement in C language. There are many things in this line to be discussed. Let’s see them one by one.

The word ‘cout’ is known as stream in C and C++. Stream is a complicated thing, you will learn about it later. Think a stream as a door. The data is transferred through stream, cout takes data from computer and sends it to the output that is the screen of the monitor. So 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. The thing between the double quoutes (“ ”) is known as character string. In C programming character strings are written in double quotes. Whatever will be written in quotation marks the sign << will direct it towards cout which will show it on the screen. There is a semicolon (;) at the end of the statement. This is very important. All C statements end with semicolon (;). Missing of a semicolon (;) at the end of statement is a syntax error and compiler will report an error during compilation. The only semicolon (;) on a line is a null statement. It does nothing. The extra semicolons may be put at the end but are useless and aimless. Do not put semicolon (;) at a wrong place, it may cause a problem during the execution of the program or may cause a logical error. In this program we give a fixed character string to cout and the program prints it to the screen as: hello!

For previous lesson click here: IDE (Integrated Development Environment)
For next lesson click here: Variables


the easiest way to learn programming
introduction to programming
Our First Program,c++ First program

IDE (Integrated Development Environment)

Saturday, May 26, 2012
There are many IDEs provided by different vendors. These IDEs contain editor, compilers, debugger, linker and loader. The benefit of an IDE is that we have all these things at the same place. We write program, compile it and run it at the same place (i.e. in an IDE). But the difficulty is that in an IDE the things become complex. There are many buttons/menus provided to perform different tasks. We have to take care of all aspects while working in an IDE. The IDE we are going to use in our course is Dev C++, which is a product of Bloodshed Software and is available on the internet for free down load at the site (http://www.bloodshed.net).

For previous lesson click here: Steps involved in writing and executing a program
For next lesson click here: Our First Program,c++ First program


the easiest way to learn programming
introduction to programming
IDE (Integrated Development Environment)

Steps involved in writing and executing a program

The following figure represents a graphical explanation of all the steps involved in
writing and executing a program.

For previous lesson click here: Tools Of Trade
For next lesson click here: IDE (Integrated Development Environment)


the easiest way to learn programming
introduction to programming
Steps involved in writing and executing a program

Tools Of Trade

As programmer we need different tools to develop a program. These tools are needed for the life cycle of programs.
editors:
First of all we need a tool for writing the code of a program. For this purpose we used Editors in which we write our code. We can use word processor too for this, but word processors have many other features like bold the text, italic, coloring the text etc, so when we save a file written in a word processor, lot of other information including the text is saved on the disk. For programming purposes we don’t need these things we only need simple text. Text editors are such editors which save only the text which we type. So for programming we will be using a text editor.
Compiler and Interpreter:
As we write the code in English and we know that computers can understand only 0s and 1s. So we need a translator which translates the code of our program into machine language. There are two kinds of translators which are known as Interpreter and Compilers. These translators translate our program which is written in C-Language into Machine language. Interpreters translates the program line by line meaning it reads one line of program and translates it, then it reads second line, translate it and so on. The benefit of it is that we get the errors as we go along and it is very easy to correct the errors. The drawback of the interpreter is that the program executes slowly as the interpreter translates the program line by line. Another drawback is that as interpreters are reading the program line by line so they cannot get the overall picture of the program hence cannot optimize the program making it efficient.
Compilers also translate the English like language (Code written in C) into a language (Machine language) which computers can understand. The Compiler read the whole program and translates it into machine language completely. The difference between interpreter and compiler is that compiler will stop translating if it finds an error and there will be no executable code generated whereas Interpreter will execute all the lines before error and will stop at the line which contains the error. So Compiler needs syntactically correct program to produce an executable code. We will be using compiler in our course.
Debugger:
Another important tool is Debugger. Every programmer should be familiar with it. Debugger is used to debug the program i.e. to correct the logical errors. Using debugger we can control our program while it is running. We can stop the execution of our program at some point and can check the values in different variables, can change these values etc. In this way we can trace the logical errors in our program and can see whether our program is producing the correct results. This tool is very powerful, so it is complex too.
Linker:
Most of the time our program is using different routines and functions. So our program standalone cannot be executed, it also needs the executable code of those routines/functions which we are using in our program. Linker is a tool which performs this job, it checks our program and includes all those routines or functions which we are using in our program to make a standalone executable code and this process is called Linking.
Loader:
After a executable program is linked and saved on the disk and it is ready for
execution. We need another process which loads the program into memory and then
instruct the processor to start the execution of the program from the first instruction (the starting point of every C program is from the main function). This processor is known as loader. Linker and loaders are the part of development environment. These are part of system software.

For previous lesson click here: History of C Language
For next lesson click here: Steps involved in writing and executing a program


the easiest way to learn programming
introduction to programming
Tools Of Trade

History of C Language

The C language was developed in late 60’s and early 70’s, in Bell Laboratories. In those days BCPL and B languages were developed at Bell Laboratories. The BCPL language was developed in 1967 by Martin Richards as a language for writing operating systems software and compilers. In 1970 Ken Thompson used B language to create early versions of the UNIX operating system at Bell Laboratories. Thus both the languages were being used to develop various system software even compilers. Both BCPL and B were ‘type less’ languages, every data item occupied one ‘word’ in memory and the burden of treating a data item as a whole number or real number, for example was the responsibility of the programmer.

Dennis Ritchie developed a general purpose language, called C language, by using different features of BCPL and B languages. C uses many important concepts of BCPL and B while adding data typing and other features. In the start C became widely known as the development language of the UNIX operating system, and the UNIX operating system was written by using this C language. The C language is so powerful that the compiler of C and other various operating systems are written in C. C language has almost unlimited powers to do with computers. You can program to turn on or off any device of computer. You can do a lot to hard disk and other peripherals. It is very easy to write a program in C that stops the running of computer. So be careful while programming in C.

The C language and UNIX operating system widely spread in educational and research institutions. There was C and UNIX everywhere. Due to the wide spread of C, different researchers started to add their features in the language. And thus different variations in C came into existence. Many universities developed their own C by adding different features to the C language developed by Ritchie. These variations led to the need of a standard version of C. In 1983 a technical committee was created under the American National Standards Committee on Computer and Information Processing to provide an unambiguous and machine-independent definition of the language. In 1989 the standard was approved. ANSI cooperated with the International Standard Organization (ISO) to standardize C worldwide.

There were revolutions in computer industry, there came new features and languages. So immediately after C came the C++. Stroustrup wrote the C++. First its name was ‘C with objects’ and then eventually became C++. It is an object oriented language having all powers of C. The development environment which we are going to use for programming is actually the environment of C++. It has objects, methods and many others thing. But we will avoid object oriented features in our course.

For previous lesson click here: types of system softwares
For next lesson click here: Tools Of Trade


the easiest way to learn programming
introduction to programming
History of C Language

types of system softwares

o Operating system
o Device drivers
o Utilities

Operating system:
An operating system (sometimes abbreviated as "OS") is the program that manages all the other programs in a computer. It is a integrated collection of routines that service the sequencing and processing of programs by a computer. Note: An operating system may provide many services, such as resource allocation, scheduling, input/output control, and data management.
Definition of Operating system:
“Operating system is the software responsible for controlling the allocation and usage of hardware sources such as memory, central processing unit (CPU) time, disk space, and peripheral devices. The operating system is the foundation on which applications, such as word processing and spreadsheet programs, are built. (Microsoft)”

Device drivers:
The device driver software is used to communicate between the devices and the computer. We have monitor, keyboard and mouse attached to almost all PC’s; if we look at the properties of these devices we will see that the operating system has
installed special software to control these devices. This piece of software is called device driver software. When we attach a new device with the computer, we need software to communicate with this device. These kinds of software are known as device drivers e.g. CD Rom driver, Sound Card driver and Modem driver. Normally manufacturer of the device provide the device driver software with the device. For scanners to work properly with the computers we install the device driver of the scanner. Nowadays if you have seen a scanner, it comes with TWAIN Drivers. TWAIN stands for Technology Without An Interesting Name.

Utility Software:
Utility software is a program that performs a very specific task, usually related to managing system resources. You would have noticed a utility of Disk Compression. Whenever you write a file and save it to the disk, Compression Utility compresses the file (reduce the file size) and write it to the disk and when you request this file from the disk, the compression utility uncompressed the file and shows its contents. Similarly there is another utility, Disk Defragmentation which is used to defragment the disk. The data is stored on the disks in chunks, so if we are using several files and are making changes to these files then the different portions of file are saved on different locations on the disk. These chunks are linked and the operating system knows how to read the contents of file from the disk combining all the chunks. Similarly when we delete a file then the place where that file was stored on the disk is emptied and is available now to store other files. As the time goes on, we have a lot of empty and used pieces on the disk. In such situation we say that the disk is fragmented now. If we remove this fragmentation the chunks of data on the disk will be stored close to each other and thus reading of data will be faster. For the purpose of removing fragmentation on the disk the Defragmentation utility is used.

The compilers and interpreters also belong to the System Software category.

For previous lesson click here: Software Categories
For next lesson click here: History of C Language


the easiest way to learn programming
introduction to programming
types of system softwares

Software Categories

Software is categorized into two main categories:
o System Software
o Application Software

System Software:
The system software controls the computer. It communicates with computer’s hardware (key board, mouse, modem, sound card etc) and controls different aspects of operations. Sub categories of system software are:
o Operating system
o Device drivers
o Utilities

Application software:
A program or group of programs designed for end users. For example a program for Accounting, Payroll, Inventory Control System, and guided system for planes. GPS
lobal positioning system), another application software, is being used in vehicles,which through satellite determines the geographical position of the vehicle.

For previous lesson click here: Program design recipe
For next lesson click here: types of system softwares


the easiest way to learn programming
introduction to programming
Software Categories

Program design recipe

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 continue 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 that are useful, not only for a programmer but also for a businessman, a lawyer, a journalist, a scientist, an engineer, and many others.
Let us take an example to demonstrate the use of design recipe:
Suppose we have to develop a payroll system of a company. The company has permanent staff, contractual staff, hourly based employees and per unit making employees. Moreover, there are different deductions and benefits for permanent employees and there is a bonus for per unit making employees and overtime for contractual employees.
We need to analyze the above problem statement. The company has four categories of employees; i.e.; Permanent staff, Contractual staff, hourly based employees and per unit making employees. Further, permanent staff has benefits and deductions depending upon their designation. Bonus will be given to per unit making employees if they make more than 10 pieces a day. Contractual employee will get overtime if they stay after office hours.
Now divide the problem into small segments and calculations. Also include examples in all segments. In this problem, we should take an employee with his details from each category. Let’s say, Mr. Ahmad is a permanent employee working as Finance Manager. His salary is Rs/$20000 and benefits of medical, car allowance and house rent are Rs/$4000 and there is a deduction of Rs/$1200. Similarly, we should consider employees from other categories. This will help us in checking and testing the program later on.
The next step is to formulate these statements in a precise language, i.e. we can use the pseudo code and flowcharting. which will be then used to develop the program using computer language.
Then the program should be evaluated by testing and checking. If there are some changes identified, we revise the activities and repeat the process. Thus repeating the cycle, we achieve a refined solution.

Points to remember
Hence the major points to keep in mind are:
o Don’t assume on the part of the users
o User Interface should be friendly
o Don’t forget to comment the code
o PAY ATTENTION TO DETAIL
o Program, program and program, not just writing code, but the whole process of design and development.

For previous lesson click here: Comment the code liberally
For next lesson click here: Software Categories


the easiest way to learn programming
introduction to programming
Program design recipe

Comment the code liberally

Always comment the code liberally. The comment statements do not affect the performance of the program as these are ignored by the compiler and do not take any memory in the computer. Comments are used to explain the functioning of the programs. It helps the other programmers as well as the creator of the program to understand the code.


For previous lesson click here: Understand the fact that computers are stupid
For next lesson click here: Program design recipe


the easiest way to learn programming
introduction to programming
Comment the code liberally

Understand the fact that computers are stupid

Computers are incredibly stupid. They do exactly what you 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.

For previous lesson click here: Think about Good user interface
For next lesson click here: Comment the code liberally


the easiest way to learn programming
introduction to programming
Understand the fact that computers are stupid

Think about Good user interface

As programmers, we assume that computer users know a lot of things, this is a big mistake. So never assume that the user of your program is computer literate. Always provide an easy to understand and easy to use interface that is self explanatory.

For previous lesson click here: Think about the reusability
For next lesson click here: Understand the fact that computers are stupid


the easiest way to learn programming
introduction to programming
Think about Good user interface

Think about the reusability

When ever you are writing a program, always keep in mind that it could be reused at some other time. Also, try to write in a way that it can be used to solve some other related problem.

For previous lesson click here: Paying attention to detail
For next lesson click here: Think about Good user interface


the easiest way to learn programming
introduction to programming
Think about the reusability

Paying attention to detail

In programming, the details matter. This is a very important skill. A good programmer always analyzes the problem statement very carefully and in detail. You should pay attention to all the aspects of the problem. You can't be vague. You can't describe your program 3/4th of the way, then say, "You know what I mean?'', and have the compiler figure out the rest.
Furthermore you should pay attention to the calculations involved in the program, its flow, and most importantly, the logic of the program. Sometimes, a grammatically correct sentence does not make any sense. For example, here is a verse from poem "Through the Looking Glass" written by Lewis Carol:
“Twas brillig, and the slithy toves
Did gyre and gimble in the wabe “
The grammar is correct but there is no meaning. Similarly, the sentence, "Mr. ABC sleeps thirty hours every day", is grammatically correct but it is illogical.
So it may happen that a program is grammatically correct. It compiles and runs but produces incorrect or absurd results and does not solve the problem. It is very important to pay attention to the logic of the program.

For previous lesson click here: What skills are needed
For next lesson click here: Think about the reusability


the easiest way to learn programming
introduction to programming
Paying attention to detail

What skills are needed

Programming is an important activity as people life and living depends on the programs one make. Hence while programming one should
o Paying attention to detail
o Think about the reusability
o Think about good user interface
o Understand the fact the computers are stupid
o Comment the code liberally


For previous lesson click here: Why Programming is important
For next lesson click here: Paying attention to detail


the easiest way to learn programming
introduction to programming
What skills are needed

Why Programming is important

The question most of the people ask is why should we learn to program when there are so many application software and code generators available to do the task for us. Well the answer is as give by the Matthias Felleisen in the book ‘How to design programs’
“The answer consists of two parts. First, it is indeed true that traditional forms of programming are useful for just a few people. But, programming as we the authors understand it is useful for everyone: the administrative secretary who uses spreadsheets as well as the high-tech programmer. In other words, we have a broader notion of programming in mind than the traditional one. We explain our notion in a moment. Second, we teach our idea of programming with a technology that is based on the principle of minimal intrusion. Hence, our notion of programming teaches problem-analysis and problem-solving skills without imposing the overhead of traditional programming notations and tools.”
Hence learning to program is important because it develops analytical and problem solving abilities. It is a creative activity and provides us a mean to express abstract ideas. Thus programming is fun and is much more than a vocational skill. By designing programs, we learn many skills that are important for all professions. These skills can be summarized as:
o Critical reading
o Analytical thinking
o Creative synthesis


For previous lesson click here: what is programming
For next lesson click here: What skills are needed


the easiest way to learn programming
introduction to programming
Why Programming is important

What is programming

Definition: "A program is a precise sequence of steps to solve a particular problem.” It means that when we say that we have a program, it actually means that we know about a complete set activities to be performed in a particular order. The purpose of these activities is to solve a given problem. Alan Perlis, a professor at Yale University, says: "It goes against the grain of modern education to teach children to program. What fun is there in making plans, acquiring discipline in organizing thoughts, devoting attention to detail and learning to be self-critical? " It is a sarcastic statement about modern education, and it means that the modern education is not developing critical skills like planning, organizing and paying attention to detail. Practically, in our day to day lives we are constantly planning, organizing and paying attention to fine details (if we want our plans to succeed). And it is also fun to do these activities. For example, for a picnic trip we plan where to go, what to wear, what to take for lunch, organize travel details and have a good time while doing so. When we talk about computer programming then as Mr. Steve Summit puts it “At its most basic level, programming a computer simply means telling it what to do, and this vapid-sounding definition is not even a joke. There are no other truly fundamental aspects of computer programming; everything else we talk about will simply be the details of a particular, usually artificial, mechanism for telling a computer what to do. Sometimes these mechanisms are chosen because they have been found to be convenient for programmers (people) to use; other times they have been chosen because they're easy for the computer to understand. The first hard thing about programming is to learn, become comfortable with, and accept these artificial mechanisms, whether they make ``sense'' to you or not.

For next lesson click here: Why Programming is important


the easiest way to learn programming
introduction to programming
what is programming

 

introduction to programming Copyright © 2011-2012 | Powered by Blogger