Tuesday 3 July 2012

Declaration Of Variables


After designing suitable variable names, we must declare them to the compiler. Declaration does two things:
I. It tells the compiler what the \ ariable name is.
2. It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.
Primary Type Declaration
A variable can be used to store a value of any data type. That is, the name has nothing to do with its type. The syntax for declaring a variable is as follows:
data-type vl,v2,....vn
vl, v2, ....vn are the names of variables. Variables are separated by commas. A declaration statement must end with a semicolon. For example, valid declarations are:
int count ;
int number, total;
double ratio;
int and double are the keywords to represent integer type and real type data values respectively. Table  shows various data types and their keyword equivalents.




The program segment given in Fig.  illustrates declaration of variables. main() is the beginning of the program. The opening brace signals the execution of the program. Declaration of variables is usually done immediately after the opening brace of the program. The variables can also be declared outside (either before or after) the main function. The importance of place of declaration will be dealt in detail later while discussing functions.

When an adjective (qualifier) short, long, or unsigned is used without a basic data type specifier. C compilers treat the data type as an int. If we want to declare a character variable as unsigned. then we must do so using both the terms like unsigned char.


User-Defined Type Declaration
C supports a feature known as "type definition" that allows users to define an identifier that would represent an existing data type. The user-defined data type identifier can later be used to declare variables . It takes the general form:
typedef type identifier;

Where type refers to an existing data type and "identifier" refers to the "new" name given to the data type. The existing data type may belong to any class of type, including the user-defined ones. Remember that the new type is 'new' only in name, but not the data type. typedef cannot create a new type. Some examples of type definition are:
typedef int units; typedef float marks;

Here, units symbolizes int and marks symbolizes float. They can be later used to declare vari­ables as follows:
units batchl, batch2;
marks namel[50], name2[50];

batch' and batch2 are inclared as int variable and name I [501 and name2[50] are declared as 50 element floating point array variables. The main advantage of typedef is that we can create meaning­ful data type names for increasing the readability of the program.


Wednesday 20 June 2012

C Data Types


Data Types :
C language is rich in its data types. Storage representations and machine instructions to handle constants differ from machine to machine. The variety of data types available allow the programmer to select the type appropriate to the needs of the application as well as the machine.
C supports three classes of data types:

1. Primary (or fundamental) data types
2. Derived data types
3. User-defined data types

The primary data types and their extensions are discussed in this section. The user-defined data types are defined in the next section while the derived data types such as arrays, functions, structures and pointers are discussed as and when they are encountered.

All C compilers support five fundamental data types, namely integer (int), character (char), floating point (float), double-precision floating point (double) and void. Many of them also offer extended data types such as long int and long double. Various data types and the terminology used to describe them are given in Fig. . The range of the basic four types are given in Table . We discuss briefly each one of them in this section.


Integer Types
Integers are whole numbers with a range of values supported by a particular machine. Generally, integers occupy one word of storage, and since the word sizes of machines vary (typically, 16 or 32 bits) the size of an integer that can be stored depends on the computer. If we use a 16 bit word length, the size of the integer value is limited to the range —32768 to -1-32767 (that is, —215 to + 215 - 1). A signed integer uses one bit for sign and 15 bits for the magnitude of the number. Similarly, a 32 bit word length can store an integer ranging from -2,147,483,648 to 2,147,483,647.

In order to provide some control over the range of numbers and storage space. C has three classes of integer storage, namely short int, int, and long int, in both signed and unsigned forms. C defines these types so that they can be organized from the smallest to the largest, as shown in Fig. . For example, short int represents fairly small integer values and requires half the amount of storage as a regular int number uses. Unlike signed integers, unsigned integers use all the bits for the magnitude of the number and are always positive. Therefore, for a 16 bit machine, the range of unsigned integer numbers will be from 0 to 65,535.


We declare long and unsigned integers to increase the range of values. The use of qualifier signed on integers is optional because the default declaration assumes a signed number. Table shows all the allowed combinations of basic types and qualifiers and their size and range on a 16-bit machine.


Floating Point Types
Floating point (or real) numbers are stored in 32 bits (on all 16 bit and 32 bit machines), with 6 digits of precision. Floating point numbers are defined in C by the keyword float. When the accuracy provided by a float number is not sufficient, the type double can be used to define the number. A double data type number uses 64 bits giving a precision of 14 digits. These are known as douhle precision numbers. Remember that double type represents the same data type that float represents, but with a greater precision. To extend the precision further, we may use long double which uses 80 bits. The relationship among floating types is illustrated in Fig. .





Viod Types 

The void type has no values. This is usually used to specify the type of function. The type of a function is said to be void when it dose not return any value to the calling function. It can also play the role of a generic type, meaning that it can represent any of the other standard types .

Character Types 

A single character can be defined as a character (char) type data. Character are usually stored in 8 bits (one byte) of internal storage. The qualifier signed or unsigned may be explicitly applied to char. While unsigned chars have value between 0 and 255. signed chars have values from - 128 to 127





Thursday 14 June 2012

Variables

C Variables :
A variable is a data name that may be used to store a data value. Unlike constants that remain unchanged during the execution of a program. a variable may take different values at different times during execution. In Chapter 1, we used several variables. For instance, we used the variable amount in Sample Program 3 to store the value of money at the end of each year (after adding the interest earned during that year).
A variable name can be chosen by the programmer in a meaningful way so as to reflect its function or nature in the program. Some examples of such names are:

Average
height
Total
Counter_ 1
class_strength
As mentioned earlier, variable names may consist of letters, digits, and the underscore(_) charac-ter, subject to the following conditions:

1. They must begin with a letter. Some systems permit underscore as the first character.
2. Standard recognizes a length of 31 characters. However, length should not be normally more than eight characters, since only the first eight characters are treated as significant by many compilers.
3. Uppercase and lowercase are significant. That is, the varible Total is not the same as total or TOTAL.
4. It should not be a keyword.
5. White space is not allowed.
Some examples of valid variable names are:


John                       Value                       T_raise

Delhi                          xl                       ph_value

mark                         suml                        distance

Invalid examples include:

123 (area)
25th
Further examples of variable names and their con-ectness are given in Table .


If only the first eight characters are recognized by a compiler, then the two names
average_height 
average_weight


mean the same thing to the computer. Such names can be rewritten as
avg_height and avg_weight or
ht_average and wt_average


without changing their meanings.



Monday 4 June 2012

Constants

C Constants :
Constants in C refer to fixed values that do not change during the execution of program. C suports several types of constants as illustrated .





An integer constant refers to a sequence of digits. There are three types of integers, namely, decimal integer, octal integer and hexadecimal integer.
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional — or + sign. Valid examples of decimal integer constants are:


123 — 321 0 654321 +78


Embedded spaces, commas, and non-digit characters are not permitted between digits. For exam¬ple,


15 750 20,000 S1000


are illegal numbers. Note that  C supports unary plus which was not defined earlier.
An octal integer constant consists of any combination of digits from the set 0 through 7, with a leading (). Some examples of octal integer are:


037 0 0435 0551

A sequence of digits preceded by Ox or OX is considered as hexadecimal integer. They may also include alphabets A through F or a through f. The letter A through F represent the numbers 10 through 15. Following are the examples of valid hex integers.

OX' Ox9F OXbcd Ox

We rarely use octal and hexadecimal numbers in programming.
The lamest integer value that can be stored is machine-dependent. It is 32767 on 16-bit machines and 2.147.483.647 on 32-bit machines. It is also possible to store larger integer constants on these machines by appending qualifiers such as U,L and LIL to the constants. For examples:

56789U or 56789u (unsigned integer)
987612347UL or 98761234111 (unsigned long integer)
9876543L or 98765431 (long integer)
The concept of unsigned and lone integers are discussed in detail in Section 2.7.

Example Representation of integer constants on a 16-bit computer.

The program in Fig. illustrates the use of integer constants on a 16-bit machine. The output in Fig. shows that the integer values larger than 32767 are not properly stored on a 16-bit machine. However. when they are qualified as long integer (by appending L), the values are correctly stored.


Real Constants :

Integer numbers are inadequate to represent quantities that very continuously, such as distances, height, temperatures, price and so on. These quantities are represented by numbers containing  frictional parts like I 7.548. Such numbers are called real (or floating poini) constants. Further ex¬amples of real constants are:
0.0083 -0.75 435.36 +247.0
These numbers are shown in decimal notation, having a whole number followed by a decimal point and the fractional part. It is possible to omit digits before the decimal point, or digits after the decimal point. That is,
215. .95 -.71 +.5
are all valid real numbers.
A real number may also be expressed in exponential (or scientific) notation. For example, the value 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiply by 102. The general form is:
mantissa C exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer number with an optional plus or minus sign. The letter e separating the mantissa and the exponent can be written in either lowercase or uppercase. Since the exponent causes the decimal point to "float-, this notation is said to represent a real number in floating poin(lin-m. Examples of legal floating-point constants are:
0.65e4 I 2e-2 I .5e+5 3.18E3 -1.2E-1
Embedded white space is not allowed.
Exponential notation is useful for representing numbers that are either very large or very small in magnitude. For example, 7500000000 may be written as 7.5E9 or 75E8. Similarly, -0.000000368 is equivalent to -3.68E-7.

Floating-point constants are normally represented as double-precision quantities. However, the suffixes f or F may be used to force single-precision and I or L to extend double precision further. Some examples of valid and invalid numeric constants are given in Table .



Single Character Constants
A single character constant (or simply character constant) contains a single character enclosed within a pair of single quote marks. Example of character constants are:
'5'
Note that the character constant '5' is not the same as the number 5. The last constant is a blank
space.
Character constants have integer values known as ASCII values. For example. the statement
printf("%d", ' a ) ;
would print the number 97. the ASCII value of the letter a. Similarly, the statement

printf("%c", '97');
would output the letter 'a'. ASCII values for all characters are given in Appendix II.
Since each character constant represents an integer value, it is also possible to perform arithmetic operations on character constants.
String Constants
A string constant is a sequence of characters enclosed in double quotes. The characters may be letters, numbers, special characters and blank space. Examples are:
"Hello!" "1987" "WELL DONE" "?...!" "5+3" "X"
Remember that a character constant (e.g., 'X') is not equivalent to the single character string constant (e.g., "X"). Further, a single character string constant does not have an equivalent integer value while a character constant has an integer value. Character strings are often used in programs to build meaningful programs.
Backslash Character Constants
C supports some special backslash character constants that are used in output functions. For example, the symbol `s\n' stands for newline character. A list of such backslash character constants is given in Table. Note that each one of them represents one character, although they consist of two characters. These characters combinations are known as escape sequences.





Saturday 26 May 2012

Keywords And Identifiers

C Programming Keywords Identifiers :
Every C word is classified as either a keyword or an identifier. All keywords have fixed meanings and these meanings cannot be changed. Keywords serve as basic building blocks for program state¬ments. The list of all keywords of ANSI C are listed in Table 2.3. All keywords must be written in lowercase. Some compilers may use additional keywords that must be identified from the C manual.


Identifiers refer to the names of variables, functions and arrays. These are user-defined names and consist of a sequence of letters and digits, with a letter as a first character. Both uppercase and lowercase letters are permitted, although lowercase letters are commonly used. The underscore character is also permitted in identifiers. It is usually used as a link between two words in long identifiers.


Thursday 17 May 2012

C Tokens

C Programming:
In a passage of text, individual words and punctuation marks are called tokens. Similarly, in a c program the smallest individual units are known as C tokens. C has six types of tokens as shown in Fig. C programs are written using these tokens and the syntax of the language.

C Tokens

Friday 11 May 2012

Character Set


Character Set: 
The characters that can be used to form words, numbers and expressions depend upon the computer on which the program is run. However, a subset of characters is available that can be used on most personal, micro, mini and mainframe computers. The characters in C are grouped into the following categories:
1. Letters
2. Digits
3. Special characters
4. White spaces
The entire character set is given in Table .
The compiler ignores white spaces unless they are a part of a string constant. White spaces may h, used to separate words, but are prohibited between the characters of keywords and identifiers.

Character Set

Trigraph Characters:
Many non-English keyboards do not support all the characters mentioned in Table . Trigraph- sequences to provide a way to enter certain characters that are not available on some keyboards. Each trigraph sequence consists of three characters (two question marks followed by another character) as shown in Table .


Trigraph Characters





Sunday 6 May 2012

MS-Dos System

The program can be created using any word processing software in non-document mode. The file name

should end with the characters ".c" like program.c, pay.c, etc. Then the command

MSC pay . c


under MS-DOS operating system would load the program stored in the file pay.c and generate the object code. This code is stored in another file under name pay.obj. In case any language errors are found, the compilation is not completed. The program should then be corrected and compiled again.
The linking is done by the command


LINK pay .obj


which generates the executable code with the filename pay.exe. Now the command

pay

would execute the program and give the results.

Friday 27 April 2012

Unix System


Creating the program

Once we load the UNIX operating system into the memory, the computer is ready to receive program. The program must be entered into a file. The file name can consist of letters, digits and special characters, followed by a dot and a letter c. Examples of valid file names are:

hello.c
program. c 
ebg 1 . c

The file is created with the help of a text editor, either ed or vi. The command for calling the editor and creating the file is

ed filename

 If the file existed before, it is loaded. If it does not yet exist, the file has to be created so that ready to receive the new program. Any corrections in the program are done under the editor. ITN name of your system's editor may be different. Check your system manual.)


When the editing is over, the file is saved on disk. It can then be referenced any time later by its file name. The program that is entered into the file is known as the source program3 since it represents the original form of the program.

Compiling and Linking

Let us assume that the source program has been created in a file named ebgl.c. Now the program is ready for compilation. The compilation command to achieve this task under UNIX is

cc ebgl c

The source program instructions are now translated into a form that is suitable for execution by the computer. The translation is done after examining each instruction for its correctness. If everything is
alright, the compilation proceeds silently and the translated program is stored on another file with the 'name ebgl.o. This program is known as object code.
Linking is the process of putting together other program files and functions that are required by the program. For example, if the program is using exp() function, then the object code of this function should be brought from the math library of the system and linked to the main program. Under UNIX, the linking is automatically done (if no errors are detected) when the cc command is used.
If any mistakes in the syntax and semantics of the language are discovered, they are listed out and the compilation process ends right there. The errors should be corrected in the source program with the help of the editor and the compilation is done again.
The compiled and linked program is called the executable object code and is stored automatically in another file named a.out.
Note that some systems use different compilation command for linking mathematical functions.
cc filename - I m


is the command under UNIPLUS SYSTEM V operating system.
Executing the Program
Execution is a simple task. The command
a. out


would load the executable object code into the computer memory and execute the instructions. During execution, the program may request for sonic data to be entered through the keyboard. Sometimes the program does not produce the desired results. Perhaps, something is wrong with the program logic or data. Then it would be necessary to correct the source program or the data. In case the source pro¬gram is modified, the entire process of compiling, linking and executing the program should be re¬peated.
Creating Your Own Executable File
Note that the linker always assigns the same name a.out. When we compile another program, this file will be overwritten by the executable object code of the new program. If we want to prevent from happening, we should rename the file immediately by using the command.
my a.out name


We may also achieve this by specifying an option in the cc command as follows:
cc —o name source-file


This will store the executable object code in the file name and prevent the old file a.out from being destroyed.
Multiple Source Files


To compile and link multiple source program files, we must append all the files names to the a command.
cc filename-lc filename-n.c
These files will be separately compiled into object files called
filename-i


and then linked to produce an executable program file a.out as shown in Fig..
It is also possible to compile each file separately and link them later. For example. the commands cc
-c modl.c

cc -c mod2.c
will compile the source files 'nod 1 .c and mod2.c into objects files mod], and mod2.o. They can be linked together by the command
cc modl.o mod2.o
we may also combine the source files and object files as follows:
cc modl.c mod2.o


Only mod I .c is compiled and then linked with the object file mod2.o. This approach is useful when one of the multiple source files need lobe changed and recompiled or an already existing object files is to be used along with the program to be compiled.






Sunday 22 April 2012

Executing C Program

C Programming :

Executing a program written in C involves a series of steps. These are:
1.    Creating the program
2.    Compiling the program
3.    Linking the program with functions that are needed from the C library4.    Executing the program.
Illustrates the process of creating, compiling and executing a C program. Although these steps remain the same irrespective of the operating system, system commands for implementing the steps and conventions for namingfi/es may differ on different systems.
An operating system is a program that controls the entire operation of a computer system. All input/out operations are channeled through the operating system. The operating system, which is an interface between the hardware and the user, handles the execution of user programs.
The two most popular operating systems today are UNIX (for minicomputers) and MS-DOS (for microcomputers). We shall discuss briefly the procedure to be followed in executing C program, under both these operating systems in the following sections.

Sunday 15 April 2012

C Programming Style

C Programming :

Unlike some other programming languages (COBOL. FORTRAN, etc.,) C is afree-form_language. That is, the C compiler does not care, where on the line we begin typing. While this may be a licence for bad programming, we should try to use this fact to our advantage in developing readable pro¬grams. Although several alternative styles are possible, we should select one style and use it with total consistency.
First of all, we must develop the habit of writing programs in lowercase letters. C program state¬ments are written in lowercase letters. Uppercase letters are used only for symbolic constants.
Braces group program statements together and mark the beginning and the end of functions. A proper indentation of braces and statements would make a program easier to read and debug. Note how the braces are aligned and the statements are indented in the program of Fig.
Since C is a free-form language, we can group statements together on one line. The statements


may be written in one line like
main( ) {printf("Hello C")};

However, this style make the program more difficult to understand and should not be used In this book, each statement is written on a separate line.

The generous use of comments inside a program cannot be overemphasized. Judiciously inserted comments not only increase the readability but also help to understand the program logic. This is very important for debugging and testing the program.


Wednesday 11 April 2012

C Programming - Sample - 5 - Basic Structure Of C Programs

BASIC STRUCTURE OF C PROGRAMS :

The examples discussed so far illustrate that a C program can be viewed as a group of building blocks called functions. A function is a subroutine that may include one or more statements designed to perform a specific task. To write a C program, we first create functions and then put them together. A C program may contain one or more sections shown in Fig.




The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later. The link section provides instructions to the compiler to link functions from the system library. The definition section defines all symbolic constants.
There are sonic variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined functions.

Every C program must have one main( ) function section. This section contains two parts, declara¬tion part and executable part. The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between the opening and the closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function section is the logical end of the program. All statements in the declaration and executable parts end with a semicolon.

The subprogram section contains all the user-defined functions that are called in the main function. User-defined functions are generally placed immediately after the main function, although they may appear in any order.

All sections, except the main function section may be absent when they are not required.

Friday 6 April 2012

C Programming - Sample - 4 - USE OF MATH FUNCTIONS

USE OF MATH FUNCTIONS :
We often use standard mathematical functions such as cos, sin, exp. etc. We shall see now the use of a mathematical function in a program. The standard mathematical functions are defined and kept as a part of C math library. If we want to use any of these mathematical functions, we must add an #include instruction in the program. Like #define, it is also a compiler directive that instructs the compiler to link the specified mathematical functions from the library. The instruction is of the form

#include <math.h>

math.h is the filename containing the required function. Figure illustrates the use of cosine func¬tion. The program calculates cosine values for angles 0, 10, 20 180 and prints out the results with headings.

Another #include instruction that is often required is

//include <stdio.h>

stdio.h refers to the standard 1/0 header file containing standard input and output functions




As mentioned earlier, C programs are divided into modules or functions. Some functions are written by users like us and many others are stored in the C library. Library functions are grouped category-wise and stored in different files known as header files. If we want to access the functions stored in the library, it is necessary to tell the compiler about the files to be accessed.

This is achieved by using the preprocessor directive #include as follows: 

#include < filename >

filename is the name of the library file that contains the required function defini¬tion. Preprocessor directives are placed at the beginning of a program. '



Thursday 29 March 2012

C Programming - Sample - 3 - Use Of Subroutines

USE OF SUBROUTINES:

So far, we have used only printf function that has been provided for us by the C system. The program shown in Fig. uses a user defined function. A function defined by the user is equivalent to a subroutine in FORTRAN or subprogram in BASIC.

Figure presents a very simple program that uses a mul ( ) function. The program will print the following output.


Multiplication of 5 and 10 is 50


The mul ( 1 function multiplies the values of x and y and the result is returned to the main ( ) function when it is called in the statement

c = mul (a, b);
The mul ( ) has two arguments x and y that are declared as integers. The values of a and b are passed on to x and y respectively when the function mul ( ) is called.

Thursday 22 March 2012

C Programming - Sample - 2 - Interest Calculation

Interest Calculation Programming

The program in Fig. calculates the value of money at the end of each year of investment, assuming an interest rate of 11 percent and prints the year, and the corresponding amount, in two columns. The output is shown in Fig.  for a period of 10 years with an initial investment of 5000.00. The pro¬gram uses the following formula: 

Value at the end of year = Value at start of year (1 + interest rate) 

In the program, the variable value represents the value of money at the end of the year while amount represents the value of money at the start of the year. The statement

amount = value 

makes the value at the end of the current year as the value at start of the next year.


Interest Calculation


 Let us consider the new features introduced in this program. The second and third lines begin with #detine instructions. A #define instruction defines value to a symbolic constant for use in the pro-gram. Whenever a symbolic name is encountered, the compiler substitutes the value associated with the name automatically. To change the value, we have to simply change the definition. In this exam-ple, we have defined two symbolic constants PERIOD and PRINCIPAL and assigned values 10 and 5000.00 respectively. These values remain constant throughout the execution of the program.

Investment Program Output


The #Define Directive:
A #define is a preprocessor compiler directive and not a statement. Therefore #define lines should not end with a semicolon. Symbolic constants are generally written in uppercase so that they are easily distinguished from lowercase variable names. #define instructions are usually placed at the beginning before the main() function. Symbolic constants are not declared in declaration section.

We must note that the defined constants are not variables. We may not change their values within the program by using an assignment statement. For example, the statement

PRINCIPAL = 10000.00;
is illegal.
The declaration section declares year as integer and amount, value and inrate as floating point numbers. Note all the floating-point variables are declared in one statement. They can also be declared as

fl oat amount ;

fl oat value; 
float inrate;


When two or more variables are declared in one statement, they are separated by a comma.
All computations and printing are accomplished in a while loop, while is a mechanism for evalu¬ating repeatedly a statement or a group of statements. In this case as long as the value of year is less than or equal to the value of PERIOD, the four statements that follow while are executed. Note that these four statements are grouped by braces. We exit the loop when year becomes greater than PERIOD. The concept and types of loops .
C supports the basic four arithmetic operators (—, +, /) along with several others.



Thursday 15 March 2012

C Programming - Sample - 2 - Adding Two Numbers


ADDING TWO NUMBERS

Consider another program, which performs addition on two numbers and displays the result. The complete program is shown :

 

This program when executed will produce the following output:

100
106.10

The first two lines of the program are comment lines. It is a good practice to use comment lines in the beginning to give information such as name of the program, author, date, etc. Comment characters are also used in other lines to indicate line numbers.
The words number and amount are variable names that are used to store numeric data. The numeric data may be either in integer form or in real form. In C, all variables should be declared to tell the compiler what the variable names are and what type of data they hold. The variables must be declared before they are used. In lines 5 and 6, the declarations

int number; fl 
oat amount ;

tell the compiler that number is an integer (int is the abbreviation for integer) and amount is a floating (float) point number. Declaration statements must appear at the beginning of the functions as shown in Fig. All declaration statements end with a semicolon .

The words such as int and float are called the keywords and cannot be used as variable names. 

Data is stored in a variable by assigning a data value to it. This is done in lines 8 and 10. In line- 8. an integer value 100 is assigned to the integer variable number and in line-10, the result of addi¬tion of two real numbers 30.75 and 75.35 is assigned to the floating point variable amount. The statements
number = 100;
amount = 30.75 + 75.35;
are called the assignment statements. Every assignment statement must have a semicolon at the end. The next statement is an output statement that prints the value of number. The print statement
printf ("%d \ n", number);
contains two arguments. The first argument "%d" tells the compiler that the value of the second argument number should be printed as a decimal integer. Note that these arguments are separated by a comma. The newline character \n causes the next output to appear on a new line. The last statement of the program
printf("%5.2f", amount);

prints out the value of amount in floating point format. The format specification %5.2f tells the compiler that the output must be infloating point, with five places in all and two places to the right of the decimal point.


Tuesday 13 March 2012

C Programming - Sample - 1


Printing A Message:



main( )
1"       .pri nting beg i ns.
pri ntf ("I see, I remember") ; /*          ....printing          ends.....................*/


This program when executed will produce the following output:

I see, I remember

Let us have a close look at the program. The first line informs the system that the name of the program is main and the execution begins at this line. The main( ) is a special function used by the C system to tell the computer where the program starts. Every program must have exactly one main function. If we use more than one main function, the compiler cannot tell which one marks the begin¬ning of the program.
The empty pair of parentheses immediately following main indicates that the function main has no arguments (or parameters).

The opening brace "{ " in the second line marks the beginning of the function main and the closing brace "}" in the last line indicates the end of the function. In this case, the closing brace also marks the end of the program. All the statements between these two braces form the ftinction body. The function body contains a set of instructions to perform the given task.

In this case, the function body contains three statements out of which only the printf line is an executable statement. The lines beginning with /* and ending with */ are known as comment lines. These are used in a program to enhance its readability and understanding. Comment lines are not executable statements and therefore anything between /* and */ is ignored by the compiler. In gen¬eral, a comment can be inserted wherever blank spaces can occur--at the beginning, middle or end of a line—"but never in the middle of a word ".

Although comments can appear anywhere, they cannot be nested in C. That means, we cannot have comments inside comments. Once the compiler finds an opening token, it ignores everything until it finds a closing token. The comment line is not valid and therefore results in an error. Since comments do not affect the execution speed and the size of a compiled program, we should use them liberally in our programs. They help the programmers and other users in understanding the various functions and operations of a program and serve as an aid to debugging and testing. We shall see the use of comment lines more in the examples that follow.

Let us now look at the printf( function, the only executable statement of the program.
printf ("I see, I remember"); 


printf is a predefined standard C function for printing output. Predefined means that it is a function that has already been written and compiled. and linked together with our program at the time of linking. The concepts of compilation and linking are explained later in this chapter. The printf func¬tion causes everything between the starting and the ending quotation marks to be printed out In this case, the output will be:


I see, I remember 


Note that the print line ends with a semicolon. Ever), statement in C .thould end with a semicolon ( mark.
Suppose we want to print the above quotation in two lines as

I see,
 I remember !

This can be achieved by adding another printf function as shown below:


printf(I see, \n"); 
Iprintf( .I remember !

The information contained between the parentheses is called the argument of the function. This argument of the first printf function is" I see, \n" and the second is "I remetnber!". These arguments are simply strings of characters to be printed out

Notice that the argument of the first printf contains a combination of two characters \ and n at the end of the string. This combination is collectively catled the newline character. A new line character instructs the computer logo to the next (new) line. It is 'similar in concept to the carriage return key on a typewriter. After printing the character comma t.) the presence of the newline character VI causes the string "I remember!" to be printed on the next line. No space is allowed between I and n.

It we omit the newline character from the first printf statement, then the output vsi I again be a single line as shown below.


see J remember ! 

This is similar to the output of the progrimi in Fig I 2 However. note that there is no space between . and I

It is also possible to produce two ot nut/ e lines ot output by one printf statement with the use newline character at appropriate pla,s lttr eydmple, the statement printf ("I see, \n I remember I");


will output


I see, I remember! 


while the statement


Printf( "I\n.. see,\n_ _ _ I\n_ _ ... remember !"); 


will print out
 I 
.. see
 ... remember !

NOTE: Sonic authors i,commend the inclusion of the statement

#include <stdio.h>

at the beginning of all programs that use any input/output library functions. However, this is not necessary for the functions priori and scal#'which have been defined as a part of the C language. See Chapter 4 for more on input and output functions.
Before we proceed to discuss further examples, we must note one important point. C does make a distinction between uppercase and lowercase letters. For example, printf and PRINTF are not the same. In C. everything is written in lowercase letters. However, uppercase letters are used for sym¬bolic names representing constants. We may also use uppercase letters in output strings like "I SEE" and -I REMEMBER"
The above example that printed I see, I remember is one of the simplest programs. Figure  highlights the general format of such simple programs. All C programs need a main function.

The main Function

The main is a part of every C program. C permits different forms of main state¬ment. Following forms are allowed.
main()
int main()
void main()
main(void)
void main(void)
int main(void)
The empty pair of parentheses indicates that the function has no arguments. This may be explicitly indicated by using the keyword void inside the parentheses. We may also specify the keyword int or void before the word main. The key¬word void means that the function does not return any information to the operat¬ing system and int means that the function returns an integer value to the operating system. When int is specified, the last statement in the program must be "return 0". For the sake of simplicity, we use the first form in our programs.


Sunday 11 March 2012

Importance Of C

C Importance:

1967
1970
1972
The increasing popularity of C is probably due to its many desirable qualities. It is a robust language whose rich set of built-in functions and operators can be used to write any complex program. The C compiler combines the capabilities of an assembly language with the features of a high-level lan-guage and therefore it is well suited for writing both system software and business packages. In tact. many of the C compilers available in the market are written in C.

Programs written in C are efficient and fast. This is due to its variety of data types 111`1 powerful operators. It is many times faster than BASIC. For example, a program to increment variable iffiin to 15000 takes about one second in C while it takes more than 50 secondsitt interpreter BASIC, There are only 32 keywords and its strength lies in its built-in functions. Several standard func¬:ions are available which can be used for developing programs.

C is highly portable. This means that C programs written for one computer can be run on another with little or no modification. Portability is important if we plan to use a new computer with a differ- nit operating system.

C language is well suited for structured programming, thus requiring the user to think of a problem in terms of function modules or blocks. A proper collection of these modules would make a complete program. This modular structure makes program debugging, testing and maintenance easier.

Another important feature of C is its ability to extend itself. A C program is basically a collection of functions that are supported by the C library. We can continuously add our own functions to C library. With the availability of a large number of functions, the programming task becomes simple.

Before discussing specific features of C, we shall look at some sample C programs, and analyze and understand how they work.

History Of C


'C' seems a strange name for a programming language. But this strange sounding language is one of the most popular computer languages today because it is a structured, high-level. machine independ­ent language. It allows software developers to develop programs without worrying about the hard­ware platforms where they will be implemented.

The root of all modern languages is ALGOL, introduced in the early 1960s. ALGOL was the first computer language to use a block structure. Although it never became popular in USA, it was widely used in Europe. ALGOL gave the concept of structured programming to the computer science com­munity. Computer scientists like Corrado Bohm, Guiseppe Jacopini and Edsger Dijkstra popularized this concept during 1960s. Subsequently. several languages were announced.

In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language) primarily for writing system software. In 1970, Ken Thompson created a language using many features of BCPL and called it simply B. B was used to create early versions of UNIX operat­ing system at Bell Laboratories. Both BCPL and B were "typeless" system programming languages.

C was evolved from ALGOL, BCPL and B by Dennis Ritchie at Bell Laboratories in 1972. C uses many concepts from these languages and added the concept of data types and other powerful features. Since it was developed along with the UNIX operating system, it is strongly associated with UNIX. This operating system, which was also developed at Bell Laboratories, was coded almost entirely in C. UNIX is one of the most popular network operating systems in use today and the heart of the Internet data superhighway.
For many years. C was used mainly in academic environments, but eventually with the release of many C compilers for commercial use and the increasing popularity of UNIX, it began to gain wide­spread support among computer professionals. Today, C is running under a variety of operating sys­tem and hardware platforms.

During 1970s, C had evolved into what is now known as -traditional C". The language became more popular after publication of the book 'The C Programming Language' by Brian Kerningham and Dennis Ritchie in 1978. The book was so popular that the language came to be known as "K&R C among the programming community. The rapid growth of C led to the development of different versions of the language that were similar but often incompatible. This posed a serious problem for system developers.