You are on page 1of 16

C PROGRAMMING LAB MANUAL

What is C
C is a programming language developed at AT & Ts Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the more familiar languages of that time like PL/I, ALGOL, etc. No one pushed C. It wasnt made the official Bell Labs language. Thus, without any advertisement Cs reputation spread and its pool of users grew. Ritchie seems to have been rather surprised that so many programmers preferred C to older languages like FORTRAN or PL/I, or the newer ones like Pascal and APL. But, that's what happened. Possibly why C seems so popular is because it is reliable, simple and easy to use. Moreover, in an industry where newer languages, tools and technologies emerge and vanish day in and day out, a language that has survived for more than 3 decades has to be really
good

The First C Program


Armed with the knowledge about the types of variables, constants & keywords the next logical step is to combine them to form instructions. However, instead of this, we would write our first C program now. Once we have done that we would see in detail the instructions that it made use of. Before we begin with our first C program do remember the following rules that are applicable to all C programs: (a) Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements. (b)The statements in a program must appear in the same order in which we wish them to be executed; unless of course the logic of the problem demands a deliberate jump or transfer of control to a statement, which is out of sequence. (c)Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are

allowed within a variable, constant or keyword. (d)All statements are entered in small case letters. (e)C has no specific rules for the position at which a statement is to be written. Thats why it is often called a free-form language. (f)Every C statement must end with a ;. Thus ; acts as a statement terminator.

Compilation and Execution


Once you have written the program you need to type it and instruct the machine to execute it. To type your C program you need another program called Editor. Once the program has been typed it needs to be converted to machine language (0s and 1s) before the machine can execute it. To carry out this conversion we need another program called Compiler. Compiler vendors provide an Integrated Development Environment (IDE) which consists of an Editor as well as the Compiler. There are several such IDEs available in the market targeted towards different operating systems. For example, Turbo C, Turbo C++ and Microsoft C are some of the popular compilers that work under MS-DOS; Visual C++ and Borland C++ are the compilers that work under Windows, whereas gcc compiler works under Linux. Note that Turbo C++, Microsoft C++ and Borland C++ software also contain a C compiler bundled with them. If you are a beginner you would be better off using a simple compiler like Turbo C or Turbo C++. Once you have mastered the language elements you can then switch over to more sophisticated compilers like Visual C++ under Windows or gcc under Linux. Most of the programs in this book would work with all the compilers. Wherever there is a deviation I would point it out that time. Assuming that you are using a Turbo C or Turbo C++ compiler here are the steps that you need to follow to compile and execute your first C program Start the compiler at C> prompt. The compiler (TC.EXE is usually present in C:\TC\BIN directory). Select New from the File menu. Type the program. Save the program using F2 under a proper name (say Program1.c). Use Ctrl + F9 to compile and execute the program.

Use Alt + F5 to view the output. Note that on compiling the program its machine language equivalent is stored as an EXE file (Program1.EXE) on the disk. This file is called an executable file. If we copy this file to another machine we can execute it there without being required to recompile it. In fact the other machine need not even have a compiler to be able to execute the file. A word of caution! If you run this program in Turbo C++ compiler, you may get an error The function printf should have a prototype. To get rid of this error, perform the following steps and then recompile the program. Select Options menu and then select Compiler | C++ Options. In the dialog box that pops up, select CPP always in the Use C++ Compiler options. Again select Options menu and then select Environment | Editor. Make sure that the default extension is C rather than CPP.

The if Statement
Like most languages, C uses the keyword if to implement the decision control instruction. The general form of if statement looks like this: if ( this condition is true ) execute this statement ; The keyword if tells the compiler that what follows is a decision control instruction. The condition following the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is, is true, then the statement is executed. If the condition is not true then the statement is not executed; instead the program skips past it. But how do we express the condition itself in C? And how do we evaluate its truth or falsity? As a general rule, we express a condition using Cs relational operators. The relational operators allow us to compare two values to see whether they are equal to each other, unequal, or whether one is greater than the other. Heres how they look and how they are evaluated in C. this expression is true if x == y x is equal to y x != y x is not equal to y x < y x is less than y

x > y x is greater than y x <= y x is less than or equal to y x >= y x is greater than or equal to y

Forms of if The if statement can take any of the following forms: (a) if ( condition ) do this ; (b) if ( condition ) { do this ; and this ; } (c) if ( condition ) do this ; else do this ; (d) if ( condition ) { do this ; and this ; } else { do this ; and this ; } (e) if ( condition ) do this ; else { if ( condition ) do this ; else { do this ; and this ;

} } (f) if ( condition ) { if ( condition ) do this ; else { do this ; and this ; } } else do this ; LOOPS The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control instruction. There are three methods by way of which we can repeat a part of a program. They are: (a) Using a for statement (b) Using a while statement (c) Using a do-while statement

The while Loop


It is often the case in programming that you want to do something a fixed number of times. Perhaps you want to calculate gross salaries of ten different persons, or you want to convert temperatures from centigrade to fahrenheit for 15 different cities The while loop is ideally suited for such cases

For Loop Statement


There are three parts that are separated by semi-colons in control block of the C forloop.

initialization_expression is executed before execution of

the loop starts. Theinitialization_expression is typically used to initialize a counter for the number of loop iterations. You can initialize a counter for the loop in this part.

The execution of the loop continues until

the loop_condition is false. This expression is checked at the beginning of each loop iteration.

The increment_expression, is usually used to increase (or

decrease) the loop counter. This part is executed at the end of each loop iteration

do while Loop Statement


The C do while loop statement consists of a block of code and a Boolean condition. First the code block is executed, and then the

condition is evaluated. If the condition is true, the code block is executed again until the condition becomes false. The flow chart of C do while loop is as follows:

Array
Array definition Array by definition is a variable that hold multiple elements which has the same data type. Declaring Arrays We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name. Here is the syntax:
1 data_type array_name[size];

For example, to declare an integer array which contains 100 elements we can do as follows:
1 int a[100];

There are some rules on array declaration. The data type can be any valid C data types including structure and union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer. We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1]. Initializing Arrays It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name. Here is an example of initializing an integer array.
1 int list[5] = {2,1,3,7,8};

Structure
In some programming contexts, you need to access multiple data types under a single name for easier data manipulation; for example you want to refer to address with multiple data like house number, street, zip code, country. C supports structure which allows you to wrap one or more variables with different data types. A structure can contain any valid data types like int, char, float even arrays or even other structures. Each variable in structure is called a structure member.

Defining structure To define a structure, you use struct keyword. Here is the common syntax of structure definition: struct struct_name{ structure_member }; The name of structure follows the rule of variable name. Here is an example of defining address structure:
1 struct address{ 2 unsigned int house_number; 3 char street_name[50]; 4 5 6 }; int zip_code; char country[50];

The address structure contains house number as an positive integer, street name as a string, zip code as an integer and country as a string. Declaring structure The above example only defines an address structure without creating any structure instance. To create or declare a structure instance, you can do it in two ways: The first way is to declare a structure followed by structure definition like this :
1 struct struct_name { 2 structure_member; 3 ... 4 } instance_1,instance_2 instance_n;

In the second way, you can declare the structure instance at a different location in your source code after structure definition. Here is structure declaration syntax :
1 struct struct_name instance_1,instance_2 instance_n;

Complex structure If a structure contains arrays or other structures, it is called complex structure. For example address structure is a structure. We can define a complex structure calledcustomer which contains address structure as follows:
1 struct customer{ 2 char name[50]; 3 structure address billing_addr; 4 structure address shipping_addr; 5 };

Accessing structure member To access structure members we can use dot operator (.) between structure name and structure member name as follows: structure_name.structure_member For example to access street name of structure address we do as follows:
1 struct address billing_addr; 2 billing_addr.country = "US";

If the structure contains another structure, we can use dot operator to access nested structure and use dot operator again to access variables of nested structure.
1 struct customer jack; 2 jack.billing_addr.country = "US";

PointerC pointer is a memory address. When you define a


variable for example:
1 int x = 10;

You specify variable name (x), its data type (integer in this example) and its value is 10. The variable x resides in memory with a specified memory address. To get the memory address of

variable x, you use operator & before it. This code snippet print memory address of x
1 printf("memory address of x is %d\n",&x);

and in my PC the output is


memory address of x is 1310588

Now you want to access memory address of variable x you have to use pointer. After that you can access and modify the content of memory address which pointer point to. In this case the memory address of x is 1310588 and its content is 10. To declare pointer you use asterisk notation (*) after pointer's data type and before pointer name as follows:
1 int *px;

Now if you want pointer px to points to memory address of variable x, you can use address-of operator (&) as follows:
1 int *px = &x;

After that you can change the content of variable x for example you can increase, decrease x value :
1 2 3 4 *px += 10; printf("value of x is %d\n",x); *px -= 5; printf("value of x is %d\n",x);

and the output indicates that x variable has been change via pointer px.
value of x is 20 value of x is 15

It is noted that the operator (*) is used to dereference and return content of memory address.

In some programming contexts, you need a pointer which you can only change memory address of it but value or change the value of it but memory address.

Function
In programming, a big task is divided into smaller ones to enable programmers to develop on a solid foundation that others have done instead of starting over from scratch. In order to do so,function is invented in programming world. Proper functions hide its operation details from the external programs using them and expose only the interface and its usage. The C has been designed in such a way that make functions easy to use and efficient. A C program typically consists of many small functions. C functions are reside in a separated file and loaded together with the source files of the program. C provides a lot of built-in functions to do various tasks ranging from file I/O, string manipulation, network interface etc. In this section, you will find the tutorials on how to create your own function in C.
Introducing to C function

A function is a unit of code that designed to accomplish a particular task.


Passing Arguments to Function

C supports a wide range of mechanisms to allow you to program functions effectively.


C Recursive Function

Recursive function is a function which contains a call to itself. Define function Function is a block of source code which does one or some tasks with specified purpose. Benefit of using function

C programming language supports function to provide One of major advantage of function is it can be executed as

modularity to the software.

many time as necessary from different points in your program so it helps you avoid duplication of work.

By using function, you can divide complex tasks into

smaller manageable tasks and test them independently before using them together.

In software development, function allows sharing

responsibility between team members in software development team. The whole team can define a set of standard function interface and implement it effectively.

Structure of function

Function header
The general form of function header is:
1 return_type function_name(parameter_list)

Function header consists of three parts:

Data type of return value of function; it can be any legal

data type such as int, char, pointer if the function does not return a value, the return type has to be specified by keyword void.

Function name; function name is a sequence of letters and

digits, the first of which is a letter, and where an underscore counts as a letter. The name of a function should meaningful and express what it does, for example bubble_sort,

And a parameter list; parameter passed to function have to

be separated by a semicolon, and each parameter has to indicate it data type and parameter name. Function does not require formal parameter so if you dont pass any parameter to function you can use keyword void. Here are some examples of function header:
1 /* sort the array of integer a with the 2 specified size and return nothing */ 3 void sort(int a[], int size); 4 5 /* authenticate user by username and password and return true 6 if user is authenticated */ 7 bool authenticate(char*username,char*password)

Function body
Function body is the place you write your own source code. All variables declare in function body and parameters in parameter list are local to function or in other word have function scope.

Return statement
Return statement returns a value to where it was called. A copy of return value being return is made automatically. A function can have multiple return statements. If the void keyword used, the function dont need a return statement or using return; the syntax of return statement is return expression; Using function

How to use the function


Before using a function we should declare the function so the compiler has information of function to check and use it correctly. The function implementation has to match the function declaration for all part return data type, function name and parameter list. When you pass the parameter to function, they have to match data type, the order of parameter.

Passing Arguments to Function


In order to write correct function you should know how to pass arguments to it. C supports a wide range of mechanisms to allow you to program functions effectively.

Pass by value With this mechanism, all arguments you pass to function are copied into copy versions and your function work in that copy versions. So parameters does not affects after the function finished. Pass by pointer In some programming contexts, you want to change arguments you pass to function. In this case, you can use pass by pointer mechanism. Remember that a pointer is a memory address of a variable. So when you pass a pointer to a function, the function makes a copy of it and changes the content of that memory address, after function finish the parameter is changed with the changes in function body. Pass an array to function C allows you pass an array to a function, in this case the array is not copied. The name of array is a pointer which points to the first entry of it. And this pointer is passed to the function when you pass an array to a function.

You might also like