22
C PROGRAMMING LAB MANUAL What is C C is a programming language developed at AT & T’s 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 wasn’t made the ‘official’ Bell Labs language. Thus, without any advertisement C’s 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

c Programming Lab Manual

Embed Size (px)

Citation preview

Page 1: c Programming Lab Manual

C PROGRAMMING LAB MANUAL

What is C

C is a programming language developed at AT & T’s BellLaboratories of USA in 1972. It was designed and written by aman named Dennis Ritchie. In the late seventies C began toreplace the more familiar languages of that time like PL/I,ALGOL, etc. No one pushed C. It wasn’t made the ‘official’ BellLabs language. Thus, without any advertisement C’s reputationspread and its pool of users grew. Ritchie seems to have beenrather surprised that so many programmers preferred C to olderlanguages like FORTRAN or PL/I, or the newer ones like Pascaland APL. But, that's what happened.Possibly why C seems so popular is because it is reliable, simpleand easy to use. Moreover, in an industry where newer languages,tools and technologies emerge and vanish day in and day out, alanguage that has survived for more than 3 decades has to be reallygood

The First C ProgramArmed with the knowledge about the types of variables, constants& keywords the next logical step is to combine them to forminstructions. However, instead of this, we would write our first Cprogram now. Once we have done that we would see in detail theinstructions that it made use of.Before we begin with our first C program do remember thefollowing rules that are applicable to all C programs:(a) Each instruction in a C program is written as a separatestatement. Therefore a complete C program would compriseof a series of statements.

(b)The statements in a program must appear in the same order inwhich we wish them to be executed; unless of course the logicof the problem demands a deliberate ‘jump’ or transfer ofcontrol to a statement, which is out of sequence.(c)Blank spaces may be inserted between two words to improve

Page 2: c Programming Lab Manual

the readability of the statement. However, no blank spaces areallowed 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 isto be written. That’s why it is often called a free-formlanguage.(f)Every C statement must end with a ;. Thus ; acts as astatement terminator.

Compilation and ExecutionOnce you have written the program you need to type it and instructthe machine to execute it. To type your C program you needanother program called Editor. Once the program has been typed itneeds to be converted to machine language (0s and 1s) before themachine can execute it. To carry out this conversion we needanother program called Compiler. Compiler vendors provide anIntegrated Development Environment (IDE) which consists of anEditor as well as the Compiler.There are several such IDEs available in the market targetedtowards different operating systems. For example, Turbo C, TurboC++ and Microsoft C are some of the popular compilers that workunder MS-DOS; Visual C++ and Borland C++ are the compilersthat work under Windows, whereas gcc compiler works underLinux. Note that Turbo C++, Microsoft C++ and Borland C++software also contain a C compiler bundled with them. If you are abeginner you would be better off using a simple compiler likeTurbo C or Turbo C++. Once you have mastered the languageelements you can then switch over to more sophisticated compilerslike Visual C++ under Windows or gcc under Linux. Most of theprograms 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++ compilerhere are the steps that you need to follow to compile and executeyour first C program…Start the compiler at C> prompt. The compiler (TC.EXE isusually present in C:\TC\BIN directory).Select New from the File menu.Type the program.Save the program using F2 under a proper name (sayProgram1.c).

Page 3: c Programming Lab Manual

Use Ctrl + F9 to compile and execute the program.Use Alt + F5 to view the output.Note that on compiling the program its machine languageequivalent is stored as an EXE file (Program1.EXE) on the disk.This file is called an executable file. If we copy this file to anothermachine we can execute it there without being required torecompile it. In fact the other machine need not even have acompiler 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 shouldhave a prototype”. To get rid of this error, perform the followingsteps 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 StatementLike most languages, C uses the keyword if to implement thedecision control instruction. The general form of if statement lookslike this:if ( this condition is true )execute this statement ;The keyword if tells the compiler that what follows is a decisioncontrol instruction. The condition following the keyword if isalways enclosed within a pair of parentheses. If the condition,whatever it is, is true, then the statement is executed. If thecondition is not true then the statement is not executed; instead theprogram skips past it. But how do we express the condition itselfin C? And how do we evaluate its truth or falsity? As a generalrule, we express a condition using C’s ‘relational’ operators. Therelational operators allow us to compare two values to see whetherthey are equal to each other, unequal, or whether one is greaterthan the other. Here’s how they look and how they are evaluated inC.this expression is true ifx == y x is equal to yx != y x is not equal to y

Page 4: c Programming Lab Manual

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

Forms of ifThe 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 ;elsedo 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 ;}}

Page 5: c Programming Lab Manual

(f) if ( condition ){if ( condition )do this ;

else{do this ;and this ;}}elsedo this ;

LOOPS

The versatility of the computer lies in its ability to perform a set ofinstructions repeatedly. This involves repeating some portion ofthe program either a specified number of times or until a particularcondition is being satisfied. This repetitive operation is donethrough 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 LoopIt is often the case in programming that you want to do somethinga fixed number of times. Perhaps you want to calculate grosssalaries of ten different persons, or you want to converttemperatures from centigrade to fahrenheit for 15 different citiesThe while loop is ideally suited for such cases

Page 6: c Programming Lab Manual

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.

Page 7: c Programming Lab Manual

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

Page 8: c Programming Lab Manual

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.

Page 9: c Programming Lab Manual

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       int zip_code;5       char country[50];6     };

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

Page 10: c Programming Lab Manual

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 x1 printf("memory address of x is %d\n",&x);

and in my PC the output is

Page 11: c Programming Lab Manual

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 *px += 10;2 printf("value of x is %d\n",x);3 *px -= 5;4 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

Page 12: c Programming Lab Manual

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

Page 13: c Programming Lab Manual

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 modularity to the software.

One of major advantage of function is it can be

executed as 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.

Page 14: c Programming Lab Manual

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 don’t 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 the2 specified size and return nothing */

3 void sort(int a[], int size);4  5 /* authenticate user by username and password and return true6 if user is authenticated */

7 bool authenticate(char*username,char*password)

Page 15: c Programming Lab Manual

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 don’t

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

Page 16: c Programming Lab Manual

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.