Sie sind auf Seite 1von 43

UNIT -I

Algorithm/pseudo code

Algorithm can be defined as a well-defined computational procedure that takes single value or a set of values as inputs and
produces a single or multiple values as output. Thus it is a

sequence of steps which transforms an input into an output. A single problem may have multiple algorithms. Also, an algorithm is
always a language-free computational steps.

In order to compare algorithms, we must have some criteria to measure the efficiency of our algorithms. Suppose an algorithm
has m input data. The time and space used by the algorithm are the two main measures for the efficiency of the algorithm. The
time is measured by counting the number of key operations—in sorting and searching algorithms,

for example the number of comparisons, searches, etc. This is because key operations are so defined that the time for the other
operation is much less than or at the most equal to the time for key operations. The space is measured by counting the maximum
of memory needed by the algorithm.

The complexity of an algorithm is a function which gives the running time and / or storage space requirement of the algorithm in
terms of the size of the input data. Normally, the

complexity will refer to the running time of the algorithm

Algorithm to find the roots of quadratic equation for all the cases.

Step 1: Input A, B, C

Step 2: Set D = B * B – 4 * A * C

Step 3: If D > 0 then :

(a)Set X1 = (­B + SQRT(D))/ 2 * A

(b)Set X2 = (­B ­ SQRT(D))/ 2 * A

(c) Print X1, X2

Else if D = 0 then:

(a)Set X = ­B / 2 * A

1
(b)Print X

Else:

Print “Roots are imaginary”

End If

Step 4: Exit

Flow chart

A flowchart is the pictorial representation of an algorithm. The various steps in an

algorithm are drawn in the form of prescribed symbols. The flow of the algorithm is

maintained in a flowchart. The various symbols used in a flowchart are as below. The name

of the symbol is given inside the symbol itself.

2
The structure of a C program.

The basic structure of a C program is as follows:

#include

#include

.#include

int main()

statement 1;

statement 2;

statement n;

return value;

Any C program is a set of functions. One and the must among these is main(). Empty

Parenthesis after main() is necessary.

3
Every function contains one or more C statements or instructions which are enclosed within a pair of braces. Each instruction
should end with a;.

If the program uses library functions, i.e. functions which are defined elsewhere, theprogram must include that library file using a
#include preprocessor directive at the

beginning of the program. If the keyword ‘void’ is not preceded with the main(), the main() should have a return statement at the
end of program.

General characteristics of C

C is a middle level language. Its characteristics lie between those of problem oriented language such as Fortran, Basic, Pascal and
low level Languages. It is a procedural language. It is reliable, efficient, simple and easy to understand.The approach of
programming in C is bottom-up. The modularity feature of C language, i.e. breaking the

problem into modules called the function makes it easier to organize and maintain

Data types in C

OR about space requirements for variables of different data types:

The variety of data types available allow the programmer to application as well as the machine.

‘C’ supports the following four classes of data types:

1. Primary or fundamental data types

2. Derived data types

3. User-defined data types

4. Empty data types

Primary data types There are four fundamental data types, namely integer (int), character (char), floating point (float) double
floating point (double).

Derived data types Generally arrays, functions, structures and pointer will come under the category of derived data types.

4
User defined data types Type definition (type def ) enumerated data type (enum) are the user defined data types. (Structures and
unions also come under this category).

Integer types—these are whole numbers without any decimal portion. They can be signed

or unsigned. They are also classified as short and long integers depending on their value.

Floating point types—these are real numbers (with decimal portion) which are stored in 32

bits with 6 digits of precision. There are two types of such numbers in C. These are float and

double. The data type double offers more precision when compared to float data type.

Character type—A single character is defined as a char data type. They are stored in one

byte of internal storage. They can be signed or unsigned. Signed char can have values

between 0 and 255 while unsigned have –128 to 127 ranges.

User defined data types—Apart from the above, the programmers can define their own data types using the typedef keyword.

Difference between signed integer and unsigned integer in terms of memory and range:

1. Signed In memory it occupies these are Integers 16 bits. Ranging from ­32,678 to 32,677.

2. Unsigned In memory it occupies these are Integers 16 bits. Ranging from 0 to 65,535.

For a 16 bit machine, a signed integer uses one for sign and 15 bits for the magnitude of the number. Unlike signed integer,
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.

Signed integers are declared as signed int and unsigned integers are declared as unsigned int. Both of these two contain integer
storage classes of 3 types, namely, short int, int, long int.

5
Constants

Constants refer to fixed values, which do not change during the execution of a program.

There are many types of constants in C as shown below:

6
Operators

What is meant by operator precedence? What are the relative Precedence of thearithmetic operators ?

Each operator in ‘C’ has a precedence associated with it. This Precedence is used to determine how an expression involving more
than one operator is evaluated. There are distinct levels of precedence and an operator may belong to one of these levels. The
relative precedence of arithmetic operators can be given from two distinct levels, they are

HIGH PRIORITY: * , / , %

LOW PRIORITY: +, –

7
The basic evaluation procedure includes two left to right passes during the first pass , the high priority operators are applied as
they are Encountered during the second pass, the low priority operators are applied as they are encountered.

What are unary operator? Explain example for each.

The unary operators are the operators which require only one operand to perform the

operation.

The unary operators are

(1) ! –logical not

Eg: a !a

T F

F T

(2) Short hand assignment operators:

Eg: a+ = works as a = a+1

a– =1 works as a = a­1

a*=1 works as a = a*1

a/=1 works as a = a/1

(3) Increment and decreament operators:

Eg: let m = 5 and result be stored in y.

m = 5

m++; //m = m+1//

resultant m = 6

8
m = 5;

–m; //m=m–1//

Resultant m = 4.

(4) Bitwise left shift operator, bitwise right shift operator

(a) suppose a =4

A<<2 . if left shifts the binary bits twice.

So a = 00010000

(b) suppose a>>2 . if right shifts the binary bits twice. so a = 00000001

(5) size of operator.

Eg: suppose a is declared as integer. The size of a is

Int a;

x = size of (a);

x = 2.

Explain the following and illustrate it with an example each.

(i) Increment and decrement operator

9
(ii) Conditional operator

(iii) Bitwise operator

(iv) Assignment operator

The increment operator is represented like ++. This operator is to add 1 to the value of the

associated variable. For example, ++m means m = m + 1. There are two forms of this operator. These are ++m and m++. The
difference is better understood with the following

example:

m = 10;

n = ++m; // n will get 11 and m will also be 11

m = 10;

n = m++; // n will get 10 but after this assignment, m = 11

The decrement operator is represented like - -. This operator will subtract 1 from the value of the

associated variable. For example, - -m means m = m – 1. There are two forms of this operator.

These are —m and m—. The difference is better understood with the following example:

m = 10;

n = - -m; // n will get 0 and m will also be 9

m = 10;

n = m- -; // n will get 10 but after this assignment, m = 9

(ii) Conditional operator A ternary operator pair “?:” is available in C to construct conditional expressions of the form:

expr 1 ? expr2 : expr3;

Here, expr1 is evaluated first. If it is nonzero (or true), then expr2 is evaluated and this

becomes the result of the expression. However, if expr1 is false, expr3 is evaluated and it

10
becomes the value of the expression. Look at the example below:

a = 10;

b = 15;

c = (a > b) ? a : b;

In the able “a > b” is evaluated. If it is true, c will get the value stored in a, otherwise c will

get the value of b. In the above, since a < b, c will get the value of b.

(iii) Bitwise operator

These are special operators, which can be used for manipulation of data at a bot level.

These operators are used for testing the bits, or shifting them left or right. They can be

applied only on integers. The various bitwise operators are:

(iv) Assignment operator

They are used to assign the result of an expression to a variable. We have the usual operator which is “=”. The statement “a =
10;” means, the variable a will get a value 10 stored in it.

Another form of the assignment operator is the shorthand arithmetic operator. This takes the form “a += 1”. This is equivalent to
write as “a = a + 1”. Like this, we have -=, *=, /= and %=.

Type casting

How can the value of an expression be converted to a different data Types?

11
The conversion of data from one form to another form is called type conversion.

Automatic type conversion:

If the operands are different types, the ‘lower’ type is automatically converted to the ‘higher’ type . The result is of the higher
type.

Ex: int female;

float male, ratio;

ratio= female/male;

Casting of values:

The values of an expression can be converted into different data types by casting the value.

Consider the following example:

Since female and male are declared as integers in program the decimal part of the result of the division would be lost and the ratio
would represent a wrong figure. This problem can solved by converting one of the variables locally to floating point.

int female, male;

float ratio;

ratio=(float)female/male;

The result will be converted into float. The process of such a local conversion is known as casting of value. The general form is:

(data type name) expression.

State the rules that applied while evaluating expression in automatic type conversion

(a) if one of the operands is long double, the other will be converted o long double and the result will be long double

(b) if one of the operands is double, the other will be converted to double and the result will be a double

(c) if one of the operands is float, the other will be converted to float and the result will be float

(d) if one of the operands is unsigned long int, the other will be converted to unsigned long int and the result will be unsigned
long int

12
(e) if one of the operands is long int, the other will be converted to long int and the result will be long int

(f) if one of the operands is unsigned int, the other will be converted to unsigned int and the result will be unsigned int

(g) All short and char are automatically converted to int

What is the purpose of break statement?

Some times it is convenient to be able to exit from a loop other than by testing at the top or bottom. The ‘break’ statement
provides an early exit from ‘for’, ‘while’ and ‘do-while’ loops. This can be explained as follows. Generally, looping job is
executed until the given condition of loop statement is false. When the condition is false the loop is terminated. If we give
‘‘break’’ statement, the job

will be terminated in the middle, irrespective to the given condition in looping.

For Example,

Void main ( )

Int i;

For (i=1; i<=20; i++)

Printf ("%d", i);

If (i==5) 

Break;

13
}

This will print the numbers from 1 to 5 but not 1 to 20.

Suppose a break statement is included within the innermost of several nested control statements. What happens when
break statement is executed?

If a ‘‘break’’ statement included within the innermost of several nested control statements, are executed, the ‘‘break’’ would only
exit from the loop counting it. That is ‘‘break’’ will exit only a single loop and the statements which are in the next outer loops of
the program are executed. But it does not come to the end of program.

This can be seen with following example.

For (­­­­­­­­­­­­)

Statement(s);

For (­­­­­­­­­­­­)

Statement (s);

If (condition)

Break;

Statement(s);

Here, the break is in the inner ‘‘for’’ loop. When it is executed, it comes to outer ‘‘for’’ loop.

UNIT-II

14
What do you mean by functions? Give the structure of the functions and explain

about the arguments and their return values.

A C program has always a main module (called main) where the execution of the program begins and ends. If a program is very
big and if we write all the statements of that big program in main itself, the program may become tool complex and large. As a
result, the

task of debugging and maintaining will become very difficult. On the other hand, if we split the program into several functional
portions, these are easier. These subprograms are called functions.

The structure of a function is:

Function name (Argument declaration)

local variables declaration;

Executable statements;

Return value;

Arguments—the arguments are valid variable names separated by commas. The argument

variables receive values from a calling function. Thus they provide as the link between the

main program and the function.

Actual argument—these are the arguments, which are specified in the function call.

For example, consider, a = gcd (x, y). Here x and y are called the actual arguments

Formal arguments—these are the arguments used in the function declaration. For

example, consider int gcd (int m, int n). Here m and n are called the formal arguments

Return values—a function may or may not send a value back to the calling function. This

15
value which is sent to the calling function is the return value of the function. It is achieved

through the return keyword. There can be only one value in a return statement.

Explain in detail about pass by value and pass by reference. Explain with a sample

program.

Pass by value – this is default way of passing parameter to a function. When the called

function changes the value of such a variable, it does not get reflected back in the calling

function.

Pass by reference – here the parameter is passed as a pointer. This will allow the called

function to alter the value of the variable.

In the example below, the argument a is passed by value and b is passed by reference:

main()

int a = 10;

int b = 20;

printf(“\nBefore the call: a = %d, b = %d”, a, b);

change(a, &b);

printf(“\nAfter the call: a = %d, b = %d”, a, b);

change(int x, int *y)

16
x = 50;

*y = 60;

Global and local variables

Global variable—the variables, which are declared outside all the functions (including

the main) is, called as global variable. They are available to all the functions.

Local variable—the variables, which are declared within a function, are called local

variables. They can be used only within the function in which it is declared.

(iii) Automatic and static variables

Automatic variable—they are created when the function block is entered and removed

when the function is terminated. By default, all the variables are automatic variables.

Static variables—they are variables, which are declared local to a function. However

they are available even outside the function in which they are declared.

UNIT­III

Arrays

In what way array is different from an ordinary variable?

An array is a collective name given to a group of similar elements whereas a variable is any entity that may change during
program execution.

An array is a variable that is capable of holding many values where as an ordinary variable can hold a single value at a time. For
example, an array initialization would be Int number [8];

for which there are 8 storage locations reserved where 8 different values can be stored belonging to the same type.

An ordinary variable initialization would be

17
Int number; & only one storage location is reserved and can hold only one value at a time.

What conditions must be satisfied by the entire elements of any given Array?

Elements of an array can be initialized at the time & place of their declaration. Consider an array with it’s elements.

Int a [4] = {1,2,3,4};

In the above example, 4 elements are stored in array ‘a’ The array elements are stored in continuous memory locations.

The array elements are read from ‘0’ i.e a [0], is assigned the value ‘1’, similarily a [1] is arranged the value ‘2’,a [2] is assigned
‘3’.

The condition that needs to be satisfied is that, all the elements of the array must be of the same data type under which the array
is declared

What are subscripts? How are they written? What restrictions apply to the Values that can be assigned to subscripts?

Subscript of an array is an integer expression, integer constant or integer variable like ‘i’ ,‘n’ etc that refers to different elements
in

the array. Consider a statement int a[5];

here, array subscripts start at 0 in c-language. Therefore the elements are a [0], a [1],………a [4].

The values that can be assigned to the subscripts always must start from ‘0’ and it ends at “size of array-1” for example consider
the array int a[5]

here the range of subscripts starts from ‘0’ and it ends at ‘4’.

What advantages is there in defining an array size in terms of a symbolic constant rather than a fixed integer quantity?

The advantage of defining the size of an array using symbolic constant instead of fixed numbers is that, by defining the symbolic
constant at the beginning of the program, it allows us to know the maximum size of the array and in future if we want to change
the

size of the array, it can be easily done by modifying the definition of the symbolic constant which gets reflected throughout the
program.

Pointers

What is a pointer? List out the reasons for using pointers.

18
Pointer is a variable which holds the address of another variable, i.e. a pointer is, therefore,nothing but a variable that contains an
address which is a location of another variable inmemory. Since a pointer is a variable, its value is also stored in the memory in
another location.

Example: variable value address

quantity 179 5000

p 5000 5048

Let us assign the address of ‘quantity’ to a variable ‘p’ which is called a “pointer”.

Reasons for using pointers are as follows:

1. A pointer enables us to access a variable that is defined outside the function.

2. Pointers are more efficient in handling the data tables.

3. Pointers reduce the length and complexity of a program.

4. They increase the execution speed.

5. The use of a pointer array to character strings results in saving a data storage space in

memory.

Explain the effect of the following statements:

i. int a, *b = &a - variable is declared as an integer variable. Variable b is declared as a pointer variable which is assigned
to the address of the variable a

(ii) int p, *p – this will give an error while compiling since the same variable name cannot be used as a normal and pointer
variable

(iii) char *s – this will create a pointer to string variable and name it as s. The variable s points to a string

(iv) a=(float*)&X – this will take the address of the variable X and assign it to the variable a. The contents of the variable is
casted with float. Hence the contents of variable a is a float

How to use pointer variables in expressions? Explain through examples.

19
Pointer variables can be used in expressions in place of ordinary variables. For this purpose, we need to prefix the pointer
variable with an asterisk. For example, consider the following.

int i = 100;

int *p = &i;

Now we can use *p wherever we would use i. For example, suppose that we want to multiply the value of i by 2 to compute the
value of another variable j. Then, the following two expressions are the same.

int j = i * 2;

int j = *p * 2;

Note that we have simply substituted i with *p. Similarly, we can have the following equivalent if conditions.

if (i > 100)

printf ("Hello");

if (*p > 100)

printf ("Hello");

Write a ‘C’ program to illustrate the use of pointers in arithmetic operations.

/ Program of addition of two variables using pointer.*/

#include

#include

main()

int var1,var2,result;

var1=20;

20
var2=30;

add(&var1 ,&var2,&result);

printf("Result of addition is %d ",result);

void add( int *a , int *b, int *c)

*c= *a+*b;

UNIT­IV

STRUCTURES

What is a structure? How it is declared? How it is initialized?

Structures help to organize complex data in a more meaningful manner. It creates a format, which may be used to declare many
other variables in that format. For example, we want a single collection to hold an integer and a character variable. This is
possible only through a structure. It is declared as below. We will define a structure, which will define details of a book—title of
the book, author of the book, price of the book and the number of pages it has. Look at the declaration given as follows:

struct book

char title[20];

char author[15];

int pages;

float price;

21
};

It can be initialized as below:

static struct book mybook = {“Data Structure”, “tenenbaum”, 500, 200.0};

How are structure elements stored in memory?

1. Members of structure themselves are not variables. So, they do not occupy any memory

until they are associated with structure objects.

2. When an object is created, a memory is created equal to the total memory occupied by

all its members individually.

3. The elements are stored in consecutive memory blocks in main memory.

Explain the advantages of structure type over the array type variable.

1. An array type variable can store only homogeneous data i.e. it can store only values of data

types according to which the variable is declared. For example, an integer array can store

only integer numbers. This limitation is not there in a structure variable. A structure

variable can host many data types at the same time.

2. An array type is subjected to lower and upper bounds limitations. If we try to read or write

past these bounds, we will get error. This is not a limitation in structure variable.

3. A structure variable can host an array variable also.

When are array of structures used? Declare a variable as array of structure and initialize it.

Consider a simple example. While analyzing the marks obtained by a class of students, we may use a template to describe student
name and marks obtained in various subjects and then declare all the students as structure variables. In such cases, we may
declare an array

of structures, each element of the array representing a structure variable.

22
struct marks

int marks1;

int marks2;

int marks3;

};

main()

static struct marks MRITS[2] ={{78, 76, 87}, {67, 87, 76}};

What is a structure within structure? Give an example.

A Structure within a structure means nesting of structures. This means one structure is defined within another structure. The
example is given below:

struct employee;

char name[20];

int empno;

struct salary

int basic;

23
int DA;

};

Distinguish between an array of structures and array within a structure. Give an example of each.

Array of structures is nothing but many structures with the same fields. It is a collection of similar data types.

Grouping structure variables into one array is referred to as an array of structures.

Examples: struct student

int marks 1;

int marks 2;

int marks 3;

}st;

If we declare a structure such that the fields has an array type declaration then array within a structure is defined. It enables the
user to have decreased number of variables.

Example: struct student

int marks[3];

}st;

Example for array of structures

24
struct student

int rno;

char name[30];

float marks;

} s[10];

Here s[10] represents array of structures. It consists of 10 student structures. The elements in

the structure can be accessed as

s[i]. rno

s[i].name

s[i].marks

Array index starts from 0 and ends at size–1.

(b). Write a C program using structure to create a library catalogue with the following

fields: Access number, Author’s name, Title of book, Year of publication,Publisher’s name, Price.

#include

Struct library

Int acno; 

Char aname[20];

Char tbook[40];

25
Int year;

Char pname[40];

Float price;

};

main()

Struct library s[50];

Int n;

Printf(“enter the number of entries”);

Scanf(“%d”,&n);

Printf(“enter the book details”);

For(I=0; I<=n; i++)

Scanf(“%d%s%s%d%s%f”,&s[i].acno,s[i].aname,s[i].tboo

k,&s[i].year,&s[i].pname,s[i].price);

Printf(“\n Library catalogue\n”);

Printf(“Access number\t author number\t title of book\t

year of put\t pub name \t price \n”);

26
For(i=1; i<=n; i++)

Printf(“%d\t%s\t%s\t%d\t%s\t%f\n”,s[i].acno,s[i].aname,s[i].

tbook,s[i].year,s[i].pname,s[i].price);

Define the structure to represent a date. Use your structure that accept two different dates in the format mmdd of the
year and do the following: Write a C program to display the month names of both dates.

struct mydate

int yyyy;

int mmdd;

};

main()

struct mydate date1, date2;

int month1, month2;

char *months[] = {“”,”Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”,”Jul”,

“Aug”,”Sep”,”Oct”,”Nov”,”Dec”};

printf(“\nEnter first date (mmdd) “);

27
scanf(“%4d”,&date1.mmdd);

printf(“\nEnter second date (mmdd) “);

scanf(“%4d”,&date2.mmdd);

month1 = date1.mmdd / 100; // take month alone

month2 = date2.mmdd / 100; // take month alone

printf(“\nFirst month is %s”,months[month1]);

printf(“\nSecond month is %s”,months[month2]);

Explain the different ways of passing structure as arguments in functions.

Structure variable can be passed to the function using one of the following ways.

1. By passing individual member of the structure.

2. By passing the entire structure variable.

Following program demonstrates the way of passing individual member of the structure.

/*** Passing individual structure elements ****/

main()

struct book

char name[25];

char name[25];

28
int callno;

};

stuct book b1={"Lets us C","YPK",101};

display(b1.name,b1.author,b1.callno);

void display (char *s, char *t ,int n)

printf("\n%s %s %d",s,t,n);

Write a C program to illustrate the method of sending an entire structure as a parameter to a function.

#include

#include

struct book

char bname[20];

float price;

};

//prototype

void display(struct book);

29
int main()

struct book b1={" C Primer", 250.00};

display (b1);

return 0;

Void display (struct book b2)

Puts(b2.bname);

puts(b2.price);

UNIT­V

FILES

Explain the way of defining, opening and closing a file. Also explain the different modes of operation. OR

Define a file and elaborately discuss about reading, opening and closing of a file.

If we want to store data in a file in the secondary memory, we must specify certain things about

the file, to the operating system. They include:

1. Filename.

2. Data structure.

3. Purpose.

30
Filename is a string of characters that make up a valid filename for the operating system. It may contain two parts, a primary
name and an optional period with the extension. Examples:

Input.data, store, PROG.C, Student c and Text.out

Data structure of a file is defined as FILE in the library of standard I/O function definitions.

Therefore, all files should be declared as type FILE before they are used. FILE is a defined data type.

When we open a file, we must specify what we want to do with the file. For example, we may write data to the file or read the
already existing data.

Following is the general format for declaring and opening a file:

FILE *fp;

fp = fopen(“ filename”, “ mode”);

The first statement declares the variable fp as a “pointer to the data type FILE”. As stated earlier. FILE is a structure that is
defined in the I/O library. The second statement opens the file

named filename and assigns an identifier to the FILE type pointer fp. This pointer which contains all the information about the
file is subsequently used as a communication link between the

system and the program.

The second statement also specifies the purpose of opening this file. The mode does this job.

Mode can be one of the following:

r open the file for reading only.

w open the file for writing only.

a open the file for appending (or adding) data to it.

Note that both the filename and mode are specified as strings. They should be enclosed in double quotation marks.

When trying to open a file, one of the following things may happen:

1. When the mode is ‘writing’ a file with the specified name is created if the file does not exist. The contents are deleted, if the
file already exists.

31
2. When the purpose is ‘appending’, the file is opened with the current contents safe. A file with the specified name is created if
the file does not exist.

3. If the purpose is ‘reading’, and if it exists, then the file is opened with the current contents safe; otherwise an error occurs.

Consider the following statements:

FILE *p1, *p2;

p1 = fopen(“data”, “r”);

p2 = fopen(“results”, “w”);

The file data is opened for reading and results is opened for writing. In case, the results file already exists, its contents are
deleted and the file is opened as a new file. If data file does not

exist, an error will occur.

Many recent compilers include additional modes of operation. They include:

r+ The existing file is opened to the beginning for both reading and writing.

w+ Same as w except both for reading and writing.

a+ Same as a except both for reading and writing.

We can open and use a number of files at a time. This number however depends on the system we use.

32
Explain the command line arguments. What are the syntactic constructs followed in ‘C’.

Command line argument is the parameter supplied to a program when the program is invoked.This parameter may represent a file
name the program should process. For example, if we want to execute a program to copy the contents of a file named X_FILE to

another one name Y_FILE then we may use a command line like

c>program X_FILE Y_FILE

Program is the file name where the executable code of the program is stored. This eliminates the need for the program to request
the user to enter the file names during execution.

The ‘main’ function can take two arguments called argc, argv and information contained in the command line is passed on to the
program to these arguments, when ‘main’ is called up by the system. The variable argv is an argument vector and represents an
array of

characters pointers that point to the command line arguments. argc is an argument counter that counts the number of arguments
on the command line. The size of this array is equal to the value of argc. In order to access the command line arguments, we must
declare the

33
‘main’ function and its parameters as follows:

main(argc,argv)

int argc;

char *arg[ ];

……….

……….

Generally arg[0] represents the program name.

Write a C program to read data from the keyboard, write it to a file called INPUT, again read the same data from the
INPUT file, and display it on the screen.

#include

main()

Char ch;

FILE *fp;

clrscr();

Fp=fopen[(“Input”,‘‘w”);

If(fp==NULL)

34
Printf(“file is not opened”);

exit(0);

While((ch=getchar())!=EOF)

putc(ch,fp);

fclose(fp);

fp=fopen(“Input”,‘‘r”);

while((ch=getc(fp)!=EOF)

printf(“%c”,ch)

Distinguish between getchar and scanf functions for reading strings.

35
Getchar:-Reading a single character can be done by using the function getchar.

Syntax:­ variable_name = getchar ( );

Variable_name is a valid ‘c’ name that has been declared as char type. When this statement is encountered, the computer waits
until a key is pressed and then assigns this character as a value to getchar function. Since getchar is used on the right hand side of
an assignment

statement, the character value of getchar is in turn assigned to the variable_name on the left. The getchar function may be called
successively to read the characters contained in a line of text. Getchar accepts space character.

Scanf (“control strings”,arg1, arg2, ………… argn);

The control string specifies the field format in which the data is to be entered and the arguments arg 1, arg 2, arg n specify the
address of locations where the data is stored.

Scanf does not accept space character.

UNIT VI

SEARCHING AND SORTING

Write and explain linear search procedure with a suitable example.

Sequential search is the traditional mechanism of searching for information. It is very simple to understand, but can be very poor
in performance when the data gets larger. The process of searching for information in this method is done element by element.
Each

element is taken from the pool of numbers and compared for the desired number. Thus the search is done sequentially from the
first to the last. The general algorithm is as below:

Step 1: Start with the number = 1

Step 2: If there are still more numbers in the list

Compare the current number with the number to be searched

Else Item is not found in the list, stop

Step 3: If a match is found The required number is found, stop

Else Get the next number in the list and proceed to step 2

36
Consider the list – 12, 34, 45, 3, 19 and 20. We need to look for the number 3. The steps are:

Pass 1 : Compare 12 and 3. They are not same. Proceed to next step

Pass 2 : Compare 34 and 3. They are not same. Proceed to next step

Pass 3 : Compare 45 and 3. They are not same. Proceed to next step

Pass 4 : Compare 3 and 3. They are same. Stop

Formulate recursive algorithm for binary search with its timing analysis.

Step 1: If (bottom > top)

Element not in the list, stop

Step 2: middle = integer((bottom + top) / 2)

Step 3: If number = list[middle]

Element is at middle position, Stop

Step 4: If number < list[middle]

Repeat algorithm between bottom and (middle – 1)

Else

Repeat algorithm between (middle + 1) and top

In the above algorithm, Step 4 calls the same algorithm recursively—each time, the value of top and bottom changes.

Complexity (timing analysis)—Note that each time the algorithm executes, the number of comparisons to be made is reduced
by half. Thus, to locate a number, we may require at most f(N) comparisons where f(N) = (log2N + 1). Here N is the number of
elements in the

list to be searched

Explain the algorithm for exchange sort with a suitable example.

37
BUBBLE SORT

The idea of bubble sort is to repeat by moving the smallest element to the lowest index position in the list. Example:-

15 18 3 9 12

The first pass takes i = 1 and j = 2, 3, 4, 5. The value 15 is compared with 18

and net changed 15>3, now values interchanged 3, 18,15, 9, 12.

Since 3<9 and 3<12, so elements are not changed

After the first pass, list is 3, 18, 15, 9 ,12

In the second pass i = 2 and j = 3, 4, 5

Values 18>15, so interchanged 3, 15, 18, 9,12

Since 15>9, so interchanged 3, 9, 18, 15, 12

Since 9<12, no change is required 3, 9, 18, 15, 12

In the third pass i = 3 and j= 4, 5.

Since 18>15, so interchanged 3, 9, 15, 18, 12

Since 15>12, so interchanged 3, 9, 12, 18, 15

In the fourth pass, i = 4 and j = 5

Since 18>15, so interchanged 3, 9, 12, 15, 18

Efficiency of bubble sort:

No. of comparison in first pass = n–1

No. of comparisons in second pass = n-2 and so on.

The total no. of comparisons

(n-1)+(n-2)+(n-3)+………….+2+1=n(n+1)/2 = O(n2)

38
Compare sort and exchange sort.

Sorting refers to the operation of arranging records in some given order. Sorting can either be internal or external. When sorting is
done keeping the records in the main memory, it is called internal sorting. When sorting is done by keeping the records in
external files on

storage devices like disks, tapes, etc., it is called external sorting.

We have different sorting algorithms to sort the data They are:

Bubble sort(or) Exchange sort

Merge sort Good for external file sorting

Heap sort As efficient as quick sort in an average

case and far superior to quick sort in work case.

Explain quick sort with algorithm.

This method, invented by Hoare, is considered to be a very faster method to sort the elements. The method is also called partition
exchange sorting. The method is based on divide-and-conquer technique, i.e., the entire list is divided into various partitions and

sorting is again and again applied on the partitions.

In this method, the list is divided into two based on an element called the pivot element. Usually, the first element is considered to
be the pivot element. Now, move the pivot element into its correct position in the list. The elements to the left of the pivot are less
than

the pivot while the elements to the right of the pivot are greater than the pivot. The process is reapplied to each of these partitions.
This process proceeds till we get the sorted list of elements. Let us understand this by an example.

Consider the list—74, 39, 35, 32, 97, 84.

(1) We will take 74 as the pivot and move it to position so that the new list becomes – 39, 35, 32, 74, 97, 84. Note that the
elements to the left are lesser than 74. Also, these elements (39, 35 and 32) are yet to be sorted. Similarly, the elements 97 and 84,
which are right to the pivot, are yet to be sorted.

(2) Now take the partitioned list—39, 35, 32. Let us take 39 as the pivot. Moving it to the correct position gives—35, 32, 39. The
partition to the left is 35, 32. There is no right partition. Reapply the process on the partition, we get 32, 35. Thus, we have 32, 35,

39. (3) Apply the process to the right partition of 74 which is 97, 84. Taking 97 as the pivot and positioning it, we get 84, 97.

39
(4) Assembling all the elements from each partition, we get the sorted

List.

UNIT-VII

Define a data structure. What are the different types of data structures? Explain each of them with suitable example.

Data structure is the Mathematical or logical organization of data

Data structure operations are

1. Insertion

2. Deletion

3. Search

40
4. Sorting

5. Traversing

There are two types of data structures:

1. Linear data structure:

If there exists a linear relationship between elements present in data structure, then the data structure is known as linear data
structure.

These are mainly arrays, stacks, and queues.

ARRAYS: An array is a group of related data items that share a common name.

ex:­salary[10];

In this example ‘salary’ represent a set of salaries of a group of employees. A particular number is indicated by writing a number
called Index number of subscript in brackets after the array name.

The example salary[10] represent the salary of the tenth employee.

STACKS: It is a linear data structure in which insertion and deletion takes place from only one end called top of the stack.

Example: Insert 10, 2, 15, 9, 6 with size = 4.

Fig. Set 1.6.(a)

In Fig. Set 1.6(a) the “arrow” mark indicates the current element that is inserted. If we try to

insert ‘6’ we come across overflow condition, i.e, overflow = size–1.

Delete the elements from above stack will be

Fig. Set 1.6 (b)

_#"_ ________ __________

If we try to delete after top Fig. set 1.6 (b) = –1, we come across under flow.

Stack is also known an LIFO (LAST-IN-FIRST-OUT) or pile or push down list.

41
QUEUES: It is a non linear data structure in which insertion takes place at the rear end and the

deletion takes place at the front end.

Example: Insert 10, 33 with size = 5.

Fig. set 1.6 (c)

Here the first arrow on the right side in queue I represents the front and the arrow on the down

represents the rear side.

If we want to insert elements more than the given size, then the condition is called overflow

condition, i.e. rear = size–1.

Deletion of elements from above queue will be:

Fig. Set 1.6 (d)

After deleting 10, if we try to delete another element it will come across under flow condition, i.e. rear

= –1 and front = 0.

2. NON LINEAR DATA STRUCTURES:

If there exists random relationship between the elements of a data structure, then that data structure is

called non-linear data structure.

Trees and Graphs are known as non-linear data structures.

________ __________ _#""

TREE: A tree is either empty or it may have a special node or a set of branches. Each branch in

turn represents a tree.

Example: Fig. set 1.6 (e)

42
2

Fig. set 1.6(e)

GRAPHS: Set of vertices and set of edges combined together is known as graph. It is denoted by

(G (V, E)).

Example: Fig. set 1.6(f)

32

Fig. set 1.6(f)

V = {1, 2, 3, 4}

E = {(1,2), (1,3), (3,4), (2,4), (2,3)}

43

Das könnte Ihnen auch gefallen