You are on page 1of 83

UNIT I

Algorithm:- Step by step representation to performing any task is called algorithm. Algorithm & flowchart for making a tea: Begin Boil water. Put tea power in the kettle. Pour boiled water in the kettle. Wait for three minutes. Boil milk. Put boiled milk in a cup. Add sugar to the cup. Empty the kettle in the cup. Stir the cup with a spoon.

End

Begin

Boil Water

Put tea power in the kettle

Pour boiled water in the kettle Wait for 3 minutes Boil milk Put boiled milk in a cup Add sugar to the cup Empty the kettle Stir the cup with a spoon

End

Steps to write an algorithm: It is the step by step method of performing any task. When we breakup a big task into smaller steps what we actually do is to create an algorithm. The steps in an algorithm can be divided in three basic categories. They are 1. Sequence 2. Selection 3. Iteration Sequence: A Sequence is a series of steps that we can follow in any algorithm without any break i.e., Unconditionally. Begin Take a utensil. Take the utensil to the water tap. Open the tap. Fill the utensil with water. Close the tap. Put the utensil on the gas or in the oven. Start the gas or the oven. Wait until the water boils. Switch off the gas or the oven. End Selection: Selection involves makes a choice from multiple, available options. A selection statement generally takes the form of 1. If 2. Then 3. End-if Eg: 1. If the guest wants tea. 2. Then give him tea. 3. Offer biscuits. 4. End-if Begin 1. If the guest wants tea 2. Then make tea. 3. End-if 4. Offer biscuits End. Offer biscuits to all guests Begin 1. If the guest wants tea 2. Then make tea; 3. offer biscuits 4. End-if End Offer biscuits only to guests who want tea 2

I. Compound conditions: We combine two or more conditions in to a single compound condition (using the words like and and/or or to join sentences. 1. Compound conditions with and: 1. If it is a weekday 2. and it is 7 am or more 3. and you are feeling ok 4. Then 5. Take breakfast 6. Go to work 7. End-if 2. Compound conditions with or: 1. If it is a weekday 2. or work is pending 3. or boss is angry 4. Then 5. Take breakfast 6. Go to work 7. End-if II. Nested condition:- Putting a if with in another if forms a nested condition. Eg 1. 1. If you are feeling ok 2. Then go to work 3. Else 4. If you have fever 5. Then go to the doctor 6. Else 7. Just relax 8. End-if 9. End-if Eg 2. 1. If a>b 2. Then If a>c 3. Then choose a 4. Else choose c 5. End-if 6. Else if b>c 7. Then choose b 8. Else choose a 9. End-if 10. End-if Selecting the largest of three numbers using nested conditions 3

III Testing and debugging: We are checking to see if our algorithm gives the desired result, Hence we testing the algorithm. A set of values of a, b and c that we use for testing (e.g. a=18, b=24,c=49) is called as a test case as we test our algorithm for a possibility (or case) at a given time. A group of test cases makes up the test data. If for any one of such conditions, our algorithm gives an incorrect result, we say that is a bug in the algorithm- it is another name for an error. The process of removing a bug from an algorithm is called as debugging. IV Indentation and Algorithm maintenance: For every if statement there is a end-if statement, for every Begin statement there is an end statement, writing end-if is exactly below if, end is exactly below begin & start some sentences at beginning and some after leaving some spaces is called indentation. Writing algorithms in indentation is very easy to understand & make changes very easily. Writing the algorithms in indented form is called good maintenance of algorithms. Iteration: A sequence of steps which are used repeatedly is called iteration. (a) 1. Repeat (b) 1. Do 2. Wait for two minutes. 2. Wait for two minutes. minutes. 3. Until I arrive 3. While I do not arrive 4. Go to Movie 4. Go to Movie (c) 1. While I do not arrive 2. Wait for two 3. End-while 4. Go to Movie

Repeat-Until & Do-While (cases a & b) are essentially, first it do the steps then check for the condition, While- End while(case) is differ from above, Because first checks the condition then do the steps.

Flowchart:- Representation of algorithm in graphical form is called Flowchart.

Flowchart Symbols & its uses


S. NO Symbols 1. Name Rounded Rectangle Purpose Terminal Usage of symbol in flowchart It is used to start and stop

2.

Parallelogram

Data

It is used for input or output data It is used to process the data

3.

Rectangle

Process

4.

Rhombus

Decision

It is used to give condition

5.

Arrows

Flow of control

It is used to give flow of given data

6.

Hexagon

Preparation

It is used for loops like For, While, Do While It is used for connecting lines It is used for junctions

7.

Circle

Connector

8.

Crossed Circle

Summing Junction

9.

------

Dotted Lines

Flow of data

It is used to give Flow of data in loops It is used for Predefined process like Macros

10.

Double Sided Rectangle

Predefined Process

Flowchart for Process of Compiling & Running a C Program


System Ready

Program Code

Enter Program Source Program Edit Source Program

C Compiler

Compile Source Program

Syntax Errors ?

Yes

System Library

No Object Code Link with System Library Executable Object Code

Input Data

Execute Object Code Logic and Data Errors Data Error Logic Error

? No Errors CORRECT OUTPUT Stop

C Tokens
Tokens Keywords (Reserved words) int, if Identifiers Symbols fact, avg Numeric Integer Real Constants Strings abc, A Character Single Character A, 1 Multi Character ABC, $123 Operators +,^ Special {, #

1.05, 2.4e2 Decimal Binary Octal (0-9) (0,1) (0-7) 89, 187 01, 110 05, 017

Hexa Decimal (0-9, A-F) 1A, FF

Data Types
Data Types User defined typedef, enum int Derived Structure, union Integers long short Primary(fundamental) Real Numbers float double long double Empty null Characters char Range (in 2 pow) -215 to 215-1 -215 to 215-1 0 to 216-1 -231 to 231-1 -231 to 231-1 0 to 232-1 -27 to 27-1 -27 to 27-1 0 to 28-1

Data Type Size(bytes) Size(bits) Range int 2 16 -32,768 to 32,767 signed int 2 16 -32,768 to 32,767 unsigned int 2 16 0 to 65,535 long 4 32 -2,147,483,648 to 2,147,483,647 signed long 4 32 -2,147,483,648 to 2,147,483,647 unsigned long 4 32 0 to 4,294,967,295 short 1 8 -128 to 127 signed long 1 8 -128 to 127 unsigned long 1 8 0 to 255 float 4 32 3.4E-38 to 3.4E+38 double 8 64 1.7E-308 to 1.7E+308 long double 10 80 3.4E-4932 to 1.1E+4932 char 1 8 -128 to 127 signed char 1 8 -128 to 127 unsigned char 1 8 0 to 255

-27 to 27-1 -27 to 27-1 0 to 28-1

First Program
Let's be polite and start by saluting the world! Type the following program into your favorite editor:

#include < stdio.h> void main() { printf("\nHello World\n"); } Save the code in the file hello.c, then compile it by typing: gcc hello.c This creates an executable file a.out, which is then executed simply by typing its name. The result is that the characters `` Hello World'' are printed out, preceded by an empty line. A C program contains functions and variables. The functions specify the tasks to be performed by the program. The ``main'' function establishes the overall logic of the code. It is normally kept short and calls different functions to perform the necessary sub-tasks. All C codes must have a ``main'' function. Our hello.c code calls printf, an output function from the I/O (input/output) library (defined in the file stdio.h). The original C language did not have any built-in I/O statements whatsoever. Nor did it have much arithmetic functionality. The original language was really not intended for ''scientific'' or ''technical'' computation.. These functions are now performed by standard libraries, which are now part of ANSI C. The K & R textbook lists the content of these and other standard libraries in an appendix. The printf line prints the message ``Hello World'' on ``stdout'' (the output stream corresponding to the X-terminal window in which you run the code); ``\n'' prints a ``new line'' character, which brings the cursor onto the next line. By construction, printf never inserts this character on its own: the following program would produce the same result: #include < stdio.h> void main() { printf("\n"); printf("Hello World"); printf("\n"); } Try leaving out the ``\n'' lines and see what happens. The first statement ``#include < stdio.h>'' includes a specification of the C I/O library. All variables in C must be explicitly defined before use: the ``.h'' files are by convention ``header files'' which contain definitions of variables and functions necessary for the functioning of a program, whether it be in a user-written section of code, or as part of the standard C libaries. The directive ``#include'' tells the C compiler to insert the contents of the specified file at that point in the code. The ``< ...>'' notation instructs the compiler to look for the file in certain ``standard'' system directories. 8

The void preceeding ``main'' indicates that main is of ``void'' type--that is, it has no type associated with it, meaning that it cannot return a result on execution. The ``;'' denotes the end of a statement. Blocks of statements are put in braces {...}, as in the definition of functions. All C statements are defined in free format, i.e., with no specified layout or column assignment. Whitespace (tabs or spaces) is never significant, except inside quotes as part of a character string. The following program would produce exactly the same result as our earlier example: #include < stdio.h> void main() { printf("\nHello World\n"); } The reasons for arranging your programs in lines and indenting to show structure should be obvious! The following program, sine.c, computes a table of the sine function for angles between 0 and 360 degrees. /************************/ /* Table of */ /* Sine Function */ /************************/ #include < stdio.h> #include < math.h> void main() { int angle_degree; double angle_radian, pi, value; printf ("\nCompute a table of the sine function\n\n"); pi = 4.0*atan(1.0); printf ( " Value of PI = %f \n\n", pi ); printf ( " angle Sine \n" ); angle_degree=0; /* initial angle value */ while ( angle_degree <= 360 ) /* loop until angle_degree > 360 */ { angle_radian = pi * angle_degree/180.0 ; value = sin(angle_radian); printf ( " %3d %f \n ", angle_degree, value ); angle_degree = angle_degree + 10; /* increment the loop index } }

*/

The code starts with a series of comments indicating its the purpose, as well as its author. It is considered good programming style to identify and document your work (although, sadly, most people only do this as an afterthought). Comments can be written anywhere in the code: any characters between /* and */ are ignored by the compiler and can be used to make the code easier to understand. The use of variable names that are meaningful within the context of the problem is also a good idea. 9

The #include statements now also include the header file for the standard mathematics library math.h. This statement is needed to define the calls to the trigonometric functions atan and sin. Note also that the compilation must include the mathematics library explicitly by typing
gcc sine.c -lm

Variable names are arbitrary (with some compiler-defined maximum length, typically 32 characters). C uses the following standard variable types: int -> integer variable short -> short integer long -> long integer float -> single precision real (floating point) variable double -> double precision real (floating point) variable char -> character variable (single byte) The compilers checks for consistency in the types of all variables used in any code. This feature is intended to prevent mistakes, in particular in mistyping variable names. Calculations done in the math library routines are usually done in double precision arithmetic (64 bits on most workstations). The actual number of bytes used in the internal storage of these data types depends on the machine being used. The printf function can be instructed to print integers, floats and strings properly. The general syntax is printf( "format", variables ); where "format" specifies the converstion specification and variables is a list of quantities to print. Some useful formats are %.nd %m.nf integer (optional n = number of columns; if 0, pad with zeroes) float or double (optional m = number of columns, n = number of decimal places) %ns string (optional n = number of columns) %c character \n \t to introduce new line or tab \gring the bell (``beep'') on the terminal Operators (+, -, *, /, %) (<, <=, >, >=, ==, !=) (&&, ||, !) (=) (a=a+b => a+=b Shorthand notation) (++, --) (a++, a-- => Post & ++a, a++ Pre) (&, |, ^, >>, <<,~) (Combination of ? : => c= a>b ? a+b : a-b) (,(comma), sizeof())

1. 2. 3. 4. 5. 6. 7. 8.

Arithmetic operators Relational Operators Logical Operators Assignment Operator Increment/Decrement Operators Bitwise Operators Conditional Operator Special Operators

10

Truth Tables
Logical Operators
Logical AND A 0 0 non zero non zero B 0 non zero 0 non zero A&&B 0 0 0 1 A 0 0 non zero non zero B 0 non zero 0 non zero A||B 0 1 1 1 Logical OR

Logical NOT A 0 non zero !A 1 0

Bitwise Operators
Bitwise AND A 0 0 1 1 B A&B 0 0 1 0 0 0 1 1 Bitwise OR A 0 0 1 1 B A|B 0 0 1 1 0 1 1 1

Bitwise Ex-OR A^B=AB+AB

Bitwise NOT Ones Complement

A 0 0 1 1

B A^B 0 0 1 1 0 1 1 0

A ~A 0 1 1 0

11

Operator Precedence & Associativity


Operator ( ) [ ] + ++ -! ~ * & Sizeof (type) * / % + << >> < <= > >= == != & ^ | && || ?: = *= /= %= += -= &= ^= |= <<= >>= , Description Function Call Array element reference Unary Plus Unary minus Increment Decrement Logical negation (Logical not) Ones compliment (Bitwise not) Pointer reference (indirection) Address Size of an object Type cast (conversion) Multiplication Division Modulus Addition Subtraction Left shift Right shift Less than Less than or equal to Greater than Greater than or equal to Equality (Relational equal to) Inequality (Relational not equal to) Bitwise AND Bitwise EX-OR Bitwise OR Logical AND Logical OR Conditional Operator (Conditional expression) Assignment operators Comma operator Associativity Rank Left to right 1

Right to left

Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left Left to right

3 4 5 6 7 8 9 10 11 12 13 14 15

12

Input Formats
Integer Numbers: int a,b,c,x,y,p,q,r; printf(Enter three integer numbers); scanf(%d %*d %d,&a,&b,&c); printf(%d %d %d,a,b,c); printf(Enter 2 4-digit numbers); scanf(%2d %4d,&x,&y); printf(%d %d,x,y); printf(Enter 2 2-digit numbers); scanf(%d %d,&a,&x); printf(%d %d,a,x); printf(Enter 9-digit number); scanf(%3d %4d %3d&p,&q,&r); printf(%d %d %d,p,q,r); printf(Enter 2 3-digit numbers); scanf(%d %d,&x,&y); printf(%d %d,x,y); Real Numbers: float x,y; double p,q; printf(Enter two values); scanf(%f %e,&x,&y); printf(%f %f,x,y); scanf(%lf %lf,&p,&q); printf(%lf %e,&p,&q);

1 1 6789 67 44 4321

2 3 4321 89 66 44

3 -3577

123456789 66 1234 123 89 456 123

567

12.3456 17.5e-2 12.345600 0.175000 4.142857142857 18.5678901234567890 4.142857142857 1.856789012346e+001

Strings: char name1[15],name2[15],name3[15],char address[80]; printf(Enter a name); scanf(%15c,name1); 123456789012345 printf(%15s,name1); 123456789012345r printf(Enter a name); scanf(%s,name2); New York printf(%15s,name2); New printf(Enter a name); scanf(%15s,name1); London printf(%s,name1); York printf(Enter a name); scanf(%15c,name1); 123456789012 printf(%15s,name1); 123456789012 r printf(Enter a name); scanf(%s,name2); New-York 13

printf(%15s,name2); printf(Enter a name); scanf(%15s,name1); printf(%s,name1); printf(Enter address); scanf(%[a-z],address); printf(%s,address); scanf(%[^\n],address); printf(%s,address); Integer Numbers: int m=12345; long n=987654 printf(%d,m); printf(%10d,m); printf(%010d,m); printf(%-10d,m); printf(%3d,m); printf(%-3d,m); printf(%d,-m); printf(%10d,-m); printf(%3d,-m); printf(%10d,n); Real Numbers: float y=98.7654 printf(%f,y); printf(%7.4f,y); printf(%7.2f,y); printf(%-7.2f,y); printf(%*.*f,7,2,y); rintf(%07.2f,y); printf(%10.2e,y); printf(%12.4e,y); printf(%-10.2e,y); printf(%e,y); printf(%f,-y); Strings: char x=A ;
A N 0 0 9 9 8 9 9 8 8 . . 9 . 9 9 . . 8 8 . 7 7 8 7 8 8 8 8 8 7 7 0 1 1 1 0 2 2 2 2 0 3 3 3 3 0 4 4 4 4

New-York London London new delhi 110002 (It accepts a to z values) new delhi new delhi 110002 (It accepts up to new line) new delhi 110002

Output Formats

5 1 0 5 5 5 5 1 2 3 4 5 1 2 2 3 3 4 4 5 5

5 9 8 7 6 5 4

6 6 . 7 . . 8 7 e 6 6

5
7

4
7

7 7 e 6 + 5 5

7 7 + 5 0 4 4 0 e 0 e 0 0 + 1 + 4 0 0 1 1 0 0 1

9 9 9-

9 . . 8

char
I

name[20]=ANIL KUMAR GUPTA;


L K U M A R G U P T A

printf(%c %3c %5c %3c %c); 14

printf(%s, name); printf(%20s,name);


printf(%20.10s,name);
A N I L K U A N N N I I I L L K U M A R G U P T A L K U M A R M N A I R L G K U U P M T A A R

printf(%-20.10s,name); A

printf(%.5,name); printf(%5s,name);

A A

Decision Making & branching


Decision Making & branching

if simple if if- else nested if

switch if-else ladder

goto

Conditional Operator (Combination of ? : => c= a>b ? a+b : a-b)

Syntax of if statement: if (Condition) { Statement 1; Statement 2; } if (Condition) Statement 1; is conditio n is True conditio n Statement 1 Statement 2 True Statement 1 Syntax of if-else statement: if (Condition) is conditio n Statement 1 Statement 2

15

True

Statement 1; Statement 2; } else { Statement 3; Statement 4; } Syntax of nested if statement:

false Statement 3 Statement 4

is condition 1

16

if (Condition 1) {

True

Statement 1 Statement 2

if (Condition 1) { Statement 1; Statement 2; } else { Statement 3;

is condition 2 False Statement 3 Statement 4

True

17

Statement 4; } } Syntax of if-else ladder statement: if (Condition 1) { Statement 1; } else if (Condition 2) { Statement 2; } else if (Condition 3) { Statement 3; } else { Statement 4; } is condition 1 True Statement 1 Syntax of switch statement: switch(expression) { case 1: statement 1; break; case 2: statement 2; break; case 3: statement 3; break; case 4: statement 4; break; default: statement 5; }

False

is condition 2 True Statement 2

False

is condition 3 True Statement 3

False

Statement 4

Syntax of goto statement: main() { double x, y; read: scanf(%lf,&x); if(X<0) goto read; y=sqrt(x); printf(%lf,x,y); goto read;

goto label; label: statement; Forward jump

label: statement; goto label; Backward jump

} Syntax of conditional operator: 18

If(x<0) Conditional expression ? expression1 : expression 2 else Flag=(x<0)? 0: 1 flag=1; flag=0;

Decision Making & Looping


Decision Making & looping

While

Do-while

For

Syntax of while Loop: while (test condition) { body of the loop }

Nested loops Syntax of do-while Loop: do { body of the loop } while (test condition);

Test Condition ? True Body of the loop

False

Body of the loop False

Test Condition ? True

Syntax of for Loop: for(initialization ; test-condition; increment) { body of the loop } Nested loops: while (condition 1) { outer loop while (condition 2) { inner loop do { do { 19 for(i=1;i<10;i++) { for(j=0;j<5;j++) {

} } Nested while loop

}while(condition 1); }while(condition 2); Nested do-while loop

} } Nested for loop

Most real programs contain some construct that loops within the program, performing repetitive actions on a stream of data or a region of memory. There are several ways to loop in C. Two of the most common are the while loop: while (expression) { ...block of statements to execute... } and the for loop: for (expression_1; expression_2; expression_3) { ...block of statements to execute... } The while loop continues to loop until the conditional expression becomes false. The condition is tested upon entering the loop. Any logical construction (see below for a list) can be used in this context. The for loop is a special case, and is equivalent to the following while loop: expression_1; while (expression_2) { ...block of statements... expression_3; } For instance, the following structure is often encountered: i = initial_i; while (i <= i_max) { ...block of statements... i = i + i_increment; } This structure may be rewritten in the easier syntax of the for loop as: for (i = initial_i; i <= i_max; i = i + i_increment) { ...block of statements... } Infinite loops are possible (e.g. for(;;)), but not too good for your computer budget! C permits you to write an infinite loop, and provides the break statement to ``breakout '' of the loop. For example, consider the following (admittedly not-so-clean) re-write of the previous loop: angle_degree = 0; for ( ; ; ) { ...block of statements... angle_degree = angle_degree + 10; 20

if (angle_degree == 360) break; } The conditional if simply asks whether angle_degree is equal to 360 or not; if yes, the loop is stopped. QUIZ QUESTIONS 1. ________ is a method of representing step by step procedure for solving a problem? a)Algorithm b)Flowchart c)both d)none [ ] 2. _________ is a diagrammatic representation of an algorithm.? a)Flowchart b)Pipeline c)Program d)none 3.__________ symbol is used to represent decision ? a)Rhombus b)Rectangle c)Circle d)none 4. _________ symbol is used to represent connector? a)Rhombus b)Rectangle c)Circle d)none 5. C follows ____________approach? a)Top-Down b)Bottom-Up c)both d)none [ [ [ [ ] ] ] ]

6. _________ is used to convert the code of high level language to m/c level language? a)Compiler b)Interpreter c)Assembler d)both a&b 7. _________ preprocessor directive is used for including header files and other files? a)#include b)#define c)both d)none [ ] 8. What are the steps involved in execution of a C program? 9. What is the expression of an algorithm in a programming language? 10.Give the programming development steps? 11.What is a process of collecting ,organizing and maintaining a complete information about the program? 12. What are the C Tokens? 13. Which one we used to refer the names of variables, functions and arrays? 14. Difference between variable and constant? 15. Types of data types in C? 16. What is the range of values for int data type? 17. Values can be assigned to variables by using which operator? 18. Giving values to variables through keyboard can be done by using which function? 19. What is an Operator? 20. Types of operators? 21

21. Which operator gives the net result true if the condition have the value true, otherwise gives the result false? 22. What is the another name for conditional operator? 23. What is an expression? 24.What are control statement? 25. What is a bi directional conditional control statement? 26. What is an unidirectional control statement ? 27. If the label : is placed after the go to label ; some statement will be skipped? 28. Which operator is used to increment the value of the variable by1 ? 29. Which operator is used to performs operations only at bit level? 30. What is the need of switch Switch Statement? 31. Which statement is used to end the particular case and exit from the switch statement? 32. What are the loop statements? 33. Difference between while loop and do-while loop? 34. Which symbol is used to give the process in flowcharts? 35. sizeof (long int) is __________ 36. a=15 , b=10 , c= - - a b , d=b--+++a printf(%d,(c>d)? 1:0); ________________ 37. printf(%06d,9876) = ____________ 38. name[20] = NEWDELHI 110001 printf(%7s,name)_____________________ 39. a=5, printf(%d%d%d,a++,a,++a); _____________________ 40. 14 % -3 =________________________ 41. \b used for _______________ 42. Each case statement in switch() is separated by which statement? 43.#define N 5 m 10 is this a valid statement? 44.How many times statements are executed in dowhile loop(minimum) ?

22

Review Questions 1. What is the purpose of if statement? Describe the different forms of if statement. ? 2. What is the purpose of while and do-while statement? What is the minimum number of times while and do-while statement will be executed? 3. In what respect for statement is different from while and do-while statement? 4. What is the role of control variable in for statements. 5. Describe switch statement. What is the difference between if and switch statement? 6. How break and continue statements work in repetitive statement? 7. What is the difference between a while and do- while loop? 8. How a for loop can be different with do while loop. 9. Write a program to find the sum of the following series: 1. S=l+3+5+. n 2. 5=1+2+4+.n 3. S=l+x2+x4+x6+xn. 4. s=x+x2/2!+x4!+x6/6!.......xn/n25. 10. Write a program to generate the following pattern i) 1 23 456 7 8 9 10 ii) A B C D E E D C B A ABCD DCBA ABC CBA AB BA A A 11 In a company an employ is paid as follows: Salary (i) Less then 2000 (ii) Greater then equal to 2000 but less then 4000 (iii) Greater then equal to 4000 but less then (iv) Greater then 8000 Find the net salary of an employee. 12 The rate of interest offered by a bank on fixed deposite is i. Period < 6 Months 5% ii. Period < 12 Months 6% iii. Between 1 year to 3 years 8% iv. Between 3 year to 5 years 9% v. Above 5 years or more 10% 13.What is the difference between conditional and unconditional goto statements? 14.What are breaking control statements? 23 DA 10% 25% 30% 40% HRA 5% 15% 25% 30%

15.What are conditional statement ? Explian in detail in C

UNIT II
Arrays:

Arrays of any type can be formed in C. The syntax is simple:


type name[dim];

In C, arrays starts at position 0. The elements of the array occupy adjacent locations in memory. C treats the name of the array as if it were a pointer to the first element--this is important in understanding how to do arithmetic with arrays. Thus, if v is an array, *v is the same thing as v[0], *(v+1) is the same thing as v[1], and so on:

Pointer use for an array

Consider the following code, which illustrates the use of pointers: #define SIZE 3 void main() { float x[SIZE]; float *fp; int i; for (i = 0; i < SIZE; i++) x[i] = 0.5*(float)i; for (i = 0; i < SIZE; i++) printf(" %d %f \n", i, x[i]); fp = x; for (i = 0; i < SIZE; i++) printf(" %d %f \n", i, *(fp+i)); }

24

(The expression ``i++'' is C shorthand for ``i = i + 1''.) Since x[i] means the element of the array x, and fp = x points to the start of the x array, then *(fp+i) is the content of the memory address i locations beyond fp, that is, x[i].
i-th

STRINGS :
A string constant , such as "I am a string" is an array of characters. It is represented internally in C by the ASCII characters in the string, i.e., ``I'', blank, ``a'', ``m'',... for the above string, and terminated by the special null character ``\0'' so programs can find the end of the string. String constants are often used in making the output of code intelligible using printf ; printf("Hello, world\n"); printf("The value of a is: %f\n", a); String constants can be associated with variables. C provides the char type variable, which can contain one character--1 byte--at a time. A character string is stored in an array of character type, one ASCII character per location. Never forget that, since strings are conventionally terminated by the null character ``\0'', we require one extra storage location in the array!

C does not provide any operator which manipulate entire strings at once. Strings are manipulated either via pointers or via special routines available from the standard string library string.h. Using character pointers is relatively easy since the name of an array is a just a pointer to its first element. Consider the following code: void main() { char text_1[100], text_2[100], text_3[100]; char *ta, *tb; int i; char message[] = "Hello, I am a string; what are you?"; printf("Original message: %s\n", message); i=0; while ( (text_1[i] = message[i]) != '\0' ) i++; printf("Text_1: %s\n", text_1); ta=message; tb=text_2; while ( ( *tb++ = *ta++ ) != '\0' ) ; printf("Text_2: %s\n", text_2); } 25

The standard ``string'' library contains many useful functions to manipulate strings; a description of this library can be found in an appendix of the K & R textbook. Some of the most useful functions are: char *strcpy(s,ct) char *strncpy(s,ct,n) char *strncat(s,ct) char *strncat(s,ct,n) int strcmp(cs,ct) char *strchr(cs,c) size_t strlen(cs)
-> -> -> ->

copy ct into s, including ``\0''; return s copy n charcater of ct into s, return s concatenate ct to end of s; return s concatenate n character of ct to end of s, terminate with ``\0''; return s compare cs and ct; return 0 if cs=ct, <0 if cs0 if cs>ct return pointer to first occurence of c in cs or NULL if not encountered return length of cs

->

->

->

(s and t are char*, cs and ct are const char*, c is an char converted to type int, and n is an int.)

Consider the following code which uses some of these functions: #include < string.h> void main() { char line[100], *sub_text; strcpy(line,"hello, I am a string;"); printf("Line: %s\n", line); strcat(line," what are you?"); printf("Line: %s\n", line); printf("Length of line: %d\n", (int)strlen(line)); if ( (sub_text = strchr ( line, 'W' ) )!= NULL ) printf("String starting with \"W\" ->%s\n", sub_text); if ( ( sub_text = strchr ( line, 'w' ) )!= NULL ) printf("String starting with \"w\" ->%s\n", sub_text); if ( ( sub_text = strchr ( sub_text, 'u' ) )!= NULL ) printf("String starting with \"w\" ->%s\n", sub_text); } 26

String Functions
String1= String2= V G E O R O Y D \0 \0

1. strcat(s1,s2): The content of string1 is concatenated with string2, string2 can not be changed strcat(String1,String2) String1= String2= V G E O R O Y D \0 G O O D \0

2. strcpy(s1,s2): The content of string2 is copied in to string1, string2 can not be changed strcpy (String1,String2) String1= String2= G G O O O O D D \0 \0

3. strcmp(s1,s2): Returns the ASCII values string2 is subtracted from the ASCII values of string1,if the result is zero the given strings are equal. String1= String2= T T H H E E I R R E \0 \0

x= strcmp(String1,String2) here x=-9 i.e. ASCII I ASCII R

4. strlen(s1): Returns the length of the given string String1= G O O D \0

x=strlen(string1) x=4 i.e. without the null character. 5. atoi(s1): string is converted in to integer & Returns a integer value number=12345 x=atoi(number) 27

6. itoa(i): integer value is converted in to string & Returns a string char str[20] str=itoa(123)

Storage Classes:
Storage classes gives the information about the 1. Scope of the variable. 2. Life time of the variable. 3. Where the variable will get the storage. 4. The default initial value of the variable. There are 4 types of storage classes. 1. Automatic 2. Register 3. Static 4. External. 1. Automatic: Keyword for this storage class is auto. The scope of the variable is local.That means life time of the variable is within the block or function. It will get the storage in RAM. The default initial value is garbage value.

2. Register:
Keyword is register. The scope of the register variable is local that means lifetime is within the block or function. It will get the storage in register. The default initial value is garbage value. Register access time is less when compared to the memory access time.

3. Static:
Keyword is static. The scope of the static variable is local & gloabal. That means lifetime is within the block or function (if it is local) & throughout the program (if it is global). It will get the storage in RAM. The default initial value is Zero.

4. External:
Keyword is extern. The scope of the extern variable is gloabal. That means lifetime is throughout the program. It will get the storage in RAM. The default initial value is Zero.

Storage Class
Auto Static Extern Register

Scope
Local Global Global Local

Default Value
Garbage Zero Zero Garbage

Storage Place
RAM RAM RAM Register 28

Functions:
Functions are easy to use; they allow complicated programs to be parcelled up into small blocks, each of which is easier to write, read, and maintain. We have already encountered the function main and made use of I/O and mathematical routines from the standard libraries. Now let's look at some other library functions, and how to write and use our own.

Calling a Function:
The call to a function in C simply entails referencing its name with the appropriate arguments. The C compiler checks for compatibility between the arguments in the calling sequence and the definition of the function. Library functions are generally not available to us in source form. Argument type checking is accomplished through the use of header files (like stdio.h) which contain all the necessary information. For example, as we saw earlier, in order to use the standard mathematical library you must include math.h via the statement at the top of the file containing your code. The most commonly used header files are #include < math.h> < stdio.h> -> defining I/O routines < ctype.h> -> defining character manipulation routines < string.h> -> defining string manipulation routines < math.h> -> defining mathematical routines < stdlib.h> -> defining number conversion, storage allocation and similar tasks < stdarg.h> -> defining libraries to handle routines with variable numbers of arguments < time.h> -> defining time-manipulation routines In addition, the following header files exist < assert.h> -> defining diagnostic routines < setjmp.h> -> defining non-local function calls < signal.h> -> defining signal handlers < limits.h> -> defining constants of the int type < float.h> -> defining constants of the float type

29

EXAMPLE OF FUNCTION:
Function acos(x) asin(x) atan(x) atan2(x, y) cos(x) sin(x) tan(x) cosh(x) sinh(x) tanh(x) Meaning Arc cosine of x Arc sine of x Arc tangent of x Arc tangent of x/y Cosine of x Sine of x Tangent of x Hyperbolic cosine of x Hyperbolic sine of x Hyperbolic tangent of x Function ceil(x) exp(x) fabs(x) floor(x) fmod(x, y) log(x) log10(x) pow(x, y) sqrt(x) Meaning x rounded up to the nearest integer e to the power of x Absolute value of x x rounded down to the nearest integer Reminder of x/y Natural log of x, x>0 Base 10 log of x, x>0 x to the power y(xy) Square root of x, x>0

A function has the following layout: return-type function-name ( argument-list-if-necessary ) { ...local-declarations... ...statements... return return-value; } If return-type is omitted, C defaults to int. The return-value must be of the declared type. A function may simply perform a task without returning any value, in which case it has the following layout: void function-name ( argument-list-if-necessary ) { ...local-declarations... ...statements... } As an example of function calls, consider the following code: #include < stdio.h> #include < string.h> void main() { int n; char string[50]; strcpy(string, "Hello World"); n = n_char(string); printf("Length of string = %d\n", n); } int n_char(char string[]) { int n; n = strlen(string); if (n > 50) printf("String is longer than 50 characters\n"); return n; 30

} Arguments are always passed by value in C function calls. This means that local ``copies'' of the values of the arguments are passed to the routines. Any change made to the arguments internally in the function is made only to the local copies of the arguments. In order to change (or define) an argument in the argument list, this argument must be passed as an address, thereby forcing C to change the ``real'' argument in the calling routine. As an example, consider exchanging two numbers between variables. First let's illustrate what happen if the variables are passed by value: #include < stdio.h> void exchange(int a, int b); void main() { int a, b; a = 5; b = 7; printf("From main: a = %d, b = %d\n", a, b); exchange(a, b); printf("Back in main: "); printf("a = %d, b = %d\n", a, b); } void exchange(int a, int b) { int temp; temp = a; a = b; b = temp; printf(" From function exchange: "); printf("a = %d, b = %d\n", a, b); } Run this code and observe that a and b are NOT exchanged! Only the copies of the arguments are exchanged. The RIGHT way to do this is of course to use pointers: #include < stdio.h> void exchange ( int *a, int *b ); void main() { int a, b; a = 5; b = 7; printf("From main: a = %d, b = %d\n", a, b); exchange(&a, &b); printf("Back in main: "); printf("a = %d, b = %d\n", a, b); } void exchange ( int *a, int *b ) { 31

int temp; temp = *a; *a = *b; *b = temp; printf(" From function exchange: "); printf("a = %d, b = %d\n", *a, *b); } The rule of thumb here is that

You use regular variables if the function does not change the values of those arguments You MUST use pointers if the function changes the values of those arguments QUIZ QUESTIONS

1. Array is collection of____________ 2. Array elements are stored in _________________ 3. A character array always ends with ________________ 4. If you declare array without static , the elements it will be set to ___________ 5. Declaring the name and the type of the array and setting the no of elements in the array is known as ____________________the array. 6. All array subscripts begin with __________________ 7. Array is a data structure which can hold multiple variable of _______________ 8. A number with in square brackets that differentiates one element of an arraqy from another is called ________________________ 9. An array having more than one subscript is called _________________ 10. the string will always terminate with _______________________ 11. We can initialize an array using___________________________ 12. The second subscript in 2Dimentional array designate_______________________ 13. sizeof( ) indicates ________________ 14. Total no of characters in the array is always _______________more than the string length. 15. s1 = welcome to, s2 = GIET ,strcat(s1,s2) is _________________ 16. Memory space allocated for an integer array of eight elements is _________________ 17. The main( ) function is ______________ 32

18. s1[10]=welcome l = strlen(s1) then l = ___________________ 19. s1[10] = their,s2[10] = there ,x=strcmp(s1,s2) then x = _______________ 20. x = z-1, then x = _______________ 21. It is necessary to declare the type of a function in the program if ________________ 22. Recursion is a process in which the function calls_______________ 23. By default function returns __________________ 24. The meaning of keyword void before the function name means____________________ 25. If a storage class not mentioned in the declaration then default storage class is ________ 26. Actual parameters are ___________________ 27. What is a function __________________ 28. The keyword return is used in __________________ 29. Formal Arguments are _____________________ 30. Recursive function is ____________________ 31. Header file includes _____________________ 32. Identifier storage class determines ____________________ 33. call by value method refers to _____________________ 34. Call by reference method used to __________________ 35. Preprocessor allows ________________ 36. #endif indicates _________________

33

Review Questions 1. What is an array? How it differs from the ordinary variable? 2. What are subscripts? How are they written? What restrictions apply to the values that can be assigned to subscripts ? 3. How arrays are usually processed of two matrices? 4. Write a program to print the multiplication of two matrices? 5. Write a program to find the Sum of elements above and below the main Diagonal of Matrix. 6. Write a program to print the Upper and Lower Triangular Elements of the Main Diagonal of a Matrix. 7. What do you mean by function prototyping? Write down the advantages of function prototypes in C 8. What is a function? State the advantages of using functions. 9. What is recursion? What advantage is there in its use? 10. Differentiate between recursion and iteration. 11Write a program to read a string and check whether it is a palindrome string or not Palindrome is string that reads the same from left to right and vice versa. 12. Write a program to find the number of vowels in the given line text. 13. Write about String built-in functions. 14. What are Storage Classes? Give the classification of storage classes. 34

15. What is the difference between one dimension and two dimensional arrays. 16. Write a program to add two matrices using static statement and global variables.

UNIT III Pointers:


The C language allows the programmer to ``peek and poke'' directly into memory locations. This gives great flexibility and power to the language, but it also one of the great hurdles that the beginner must overcome in using the language. All variables in a program reside in memory; the statements float x; x = 6.5; request that the compiler reserve 4 bytes of memory (on a 32-bit computer) for the floating-point variable x, then put the ``value'' 6.5 in it. Sometimes we want to know where a variable resides in memory. The address (location in memory) of any variable is obtained by placing the operator ``&'' before its name. Therefore &x is the address of x. C allows us to go one stage further and define a variable, called a pointer, that contains the address of (i.e. ``points to'') other variables. For example: float x; float* px; x = 6.5; px = &x; defines px to be a pointer to objects of type float, and sets it equal to the address of x:

35

Pointer use for a variable The content of the memory location referenced by a pointer is obtained using the ``*'' operator (this is called dereferencing the pointer). Thus, *px refers to the value of x. C allows us to perform arithmetic operations using pointers, but beware that the ``unit'' in pointer arithmetic is the size (in bytes) of the object to which the pointer points. For example, if px is a pointer to a variable x of type float, then the expression px + 1 refers not to the next bit or byte in memory but to the location of the next float after x (4 bytes away on most workstations); if x were of type double, then px + 1 would refer to a location 8 bytes (the size of a double)away, and so on. Only if x is of type char will px + 1 actually refer to the next byte in memory.

Thus, in char* pc; float* px; float x; x = 6.5; px = &x; pc = (char*) px; (the (char*) in the last line is a ``cast'', which converts one data type to another), px and pc both point to the same location in memory--the address of x--but px + 1 and pc + 1 point to different memory locations. Consider the following simple code. void main() { float x, y; /* x and y are of float type */ float *fp, *fp2; /* fp and fp2 are pointers to float */ x = 6.5; /* x now contains the value 6.5 */ printf("Value of x is %f, address of x %ld\n", x, &x); /* print contents and address of x */ fp = &x; /* fp now points to location of x */ printf("Value in memory location fp is %f\n", *fp); /* print the contents of fp */ *fp = 9.2; /* change content of memory location*/ printf("New value of x is %f = %f \n", *fp, x); *fp = *fp + 1.5; /* perform arithmetic */ printf("Final value of x is %f = %f \n", *fp, x); y = *fp; /* transfer values */ 36

fp2 = fp; printf("Transferred value into y = %f and fp2 = %f \n", y, *fp2); } Run this code to see the results of these different operations. Note that, while the value of a pointer (if you print it out with printf) is typically a large integer, denoting some particular memory location in the computer, pointers are not integers--they are a completely different data type.

Command-line arguments:
It is standard practice in UNIX for information to be passed from the command line directly into a program through the use of one or more command-line arguments, or switches. Switches are typically used to modify the behavior of a program, or to set the values of some internal parameters. You have already encountered several of these--for example, the "ls" command lists the files in your current directory, but when the switch -l is added, "ls -l" produces a so-called ``long'' listing instead. Similarly, "ls -l -a" produces a long listing, including ``hidden'' files, the command "tail -20" prints out the last 20 lines of a file (instead of the default 10), and so on. Conceptually, switches behave very much like arguments to functions within C, and they are passed to a C program from the operating system in precisely the same way as arguments are passed between functions. Up to now, the main() statements in our programs have had nothing between the parentheses. However, UNIX actually makes available to the program (whether the programmer chooses to use the information or not) two arguments to main: an array of character strings, conventionally called argv, and an integer, usually called argc, which specifies the number of strings in that array. The full statement of the first line of the program is main(int argc, char** argv) (The syntax char** argv declares argv to be a pointer to a pointer to a character, that is, a pointer to a character array (a character string)--in other words, an array of character strings. You could also write this as char* argv[]. Don't worry too much about the details of the syntax, however--the use of the array will be made clearer below.) When you run a program, the array argv contains, in order, all the information on the command line when you entered the command (strings are delineated by whitespace), including the command itself. The integer argc gives the total number of strings, and is therefore equal to equal to the number of arguments plus one. For example, if you typed a.out -i 2 -g -x 3 4 the program would receive argc = 7 argv[0] = "a.out" argv[1] = "-i" argv[2] = "2" argv[3] = "-g" argv[4] = "-x" argv[5] = "3" 37

argv[6] = "4" Note that the arguments, even the numeric ones, are all strings at this point. It is the programmer's job to decode them and decide what to do with them. The following program simply prints out its own name and arguments: #include < stdio.h> main(int argc, char **argv) { int i; printf("argc = %d\n", argc); for (i = 0; i < argc; i++) printf("argv[%d] = \"%s\"\n", i, argv[i]); } UNIX programmers have certain conventions about how to interpret the argument list. They are by no means mandatory, but it will make your program easier for others to use and understand if you stick to them. First, switches and key terms are always preceded by a ``-'' character. This makes them easy to recognize as you loop through the argument list. Then, depending on the switch, the next arguments may contain information to be interpreted as integers, floats, or just kept as character strings. With these conventions, the most common way to ``parse'' the argument list is with a for loop and a switch statement, as follows:
#include < stdio.h> #include < stdlib.h> main(int argc, char** argv) { int a_value = 0; float b_value = 0.0; char* c_value = NULL; int d1_value = 0, d2_value = 0; int i; for(i = 1; i < argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 'a': a_value = atoi(argv[++i]); break; case 'b': b_value = atof(argv[++i]); break; case 'c': c_value = argv[++i]; break; case 'd': d1_value = atoi(argv[++i]); d2_value = atoi(argv[++i]); break; } } } printf("a = %d\n", a_value); printf("b = %f\n", b_value); if (c_value != NULL) printf("c = \"%s\"\n", c_value); printf("d1 = %d, d2 = %d\n", d1_value, d2_value);

38

Note that argv[i][j] means the j-th character of the i-th character string. The if statement checks for a leading ``-'' (character 0), then the switch statement allows various courses of action to be taken depending on the next character in the string (character 1 here). Note the use of argv[+ +i] to increase i before use, allowing us to access the next string in a single compact statement. The functions atoi and atof are defined in stdlib.h. They convert from character strings to ints and doubles, respectively. A typical command line might be:
a.out -a 3 -b 5.6 -c "I am a string" -d 222 111

(The use of double quotes with -c here makes sure that the shell treats the entire string, including the spaces, as a single object.) Arbitrarily complex command lines can be handled in this way. Finally, here's a simple program showing how to place parsing statements in a separate function whose purpose is to interpret the command line and set the values of its arguments:

/*

/********************************/ /* */ /* Getting arguments from /* */ /* the Command Line */ */ /********************************/

*/

/* Steve McMillan */ /* Written: Winter 1995 #include < stdio.h> #include < stdlib.h> void get_args(int argc, char** argv, int* a_value, float* b_value) { int i; /* Start at i = 1 to skip the command name. */ for (i = 1; i < argc; i++) { /* Check for a switch (leading "-"). */ if (argv[i][0] == '-') { /* Use the next character to decide what to do. */ switch (argv[i][1]) { case 'a': case 'b': default: } *a_value = atoi(argv[++i]); break; *b_value = atof(argv[++i]); break; fprintf(stderr, "Unknown switch %s\n", argv[i]);

*/

39

} }

main(int argc, char** argv) { /* Set defaults for all parameters: */ int a = 0; float b = 0.0; get_args(argc, argv, &a, &b); printf("a = %d\n", a); printf("b = %f\n", b);

QUIZ QUESTIONS
1. int a,b,*ptr; ptr=&a; a=9; b=*ptr; a++; what is the value of a,b,*ptr. 2.int a.b*ptr;a=9; ptr=&a; b=*ptr; what is the value of a,b, *Ptr. 3.int a,b,*ptr;a=9; ptr=&a; b= *ptr; *ptr += 2; what is the value of a,b, *ptr. 4. int a,b, *ptr; a=9; ptr=&a; b= *ptr; ptr=&b; ++b; what is the value of a,b, *ptr ? 5. What is the need of malloc() function. 6. What is the need of calloc() function. 7. What is the need of pointer. 8. What is the need of & operator. 9. What is the need of * operator. 10.main() { static char a[] = BOMBAY; 40

char *b=BOMBAY; printf (\n %d %<d, sizeof (a), sizeof (b)); } What will be the output of this program. 11 main() { static inta[]={0, 1,2,3,4}; static int *p[]={a,a+1,a+2,a+3,a+4}; int *ptr = p; printf(%d%d\n,a,*a); printf(%d%d%d\n,p,*p,**p); printf (%d %d %d\n, ptr, *ptr, **ptr); } What will be the output of this program. 12.main() { static char str[ ] = For your eyes only; int i; char *p; for (p = str,i = 0; p + i<= str + strlen (str); p++,i++); printf(%c, *(p +i)); } What will be the output of this program. 13.main() { int i=3; printf(%d,*(&i)); } What will be the output of this program. 14.main() { static int stud[5][2] = {{1234,66},{1212,33},{1434,80}{1203,75} }; int i, j; for(i=0;i<=4;i++) { for(j=0;j<=1;j++) printf(%d,*(*(stud+i)+j)); } } What will be the output of this program. 15.What is the need of sizeof operator. 16. main() { char *p1="Name"; char *p2; p2=(char *)malloc(20); while(*p2++=*p1++); printf("%s\n",p2); } 17. main() { char *ptr = "Ramco Systems"; (*ptr)++; 41

printf("%s\n",ptr); ptr++; printf("%s\n",ptr); } 18.#include<stdio.h> main() { char s1[]="Ramco"; char s2[]="Systems"; s1=s2; printf("%s",s1); } 19. main() { char *p1="Name"; char *p2; p2=(char *)malloc(20); while(*p2++=*p1++); printf("%s\n",p2); } 20. main() { char *p1="Name"; char *p2; p2=(char *)malloc(20); while(*p2++=*p1++); printf("%s\n",p2); } 21. .while((*p++=*q++)!=0){} is equal to expl: while((*p++=*q++)!='\0'){} 22. . int *x[](); means 23. int a=1, b=2, c=3, *pointer; pointer=&c; a=c/*pointer; b=c; printf("a=%d b=%d",a,b); 24. int a[5],*p; for(p=a;p<&a[5];p++) { *p=p-a; printf("%d\n",*p); } 25. int a=15; int b=16; printf("%d %d \n",a&b,a/b); (bitwise operators) 26. scanf("xyz abc ABC 345" "% *[a-z A-Z]lf",&a); printf("lf",a); 27.struct class { int i; float a; 42

string[12]; } sizeof(class)=? 28. int *p; i=10; p=i; printf("%d",*p); 29. main() { char a[2]; *a[0]=7; *a[1]=5; printf("%d",&a[1]-a) } 30. #include<stdio.h main() { float value=10.00; printf("%g %0.2g %0.4g %f",value,value,value,value)

}
Review Questions 1. What are pointers? Why are they important? 2. Explain the features of pointers. 3. Explain pointer of any data type that requires four bytes. 4. Explain the use of (*) indirection operator. 5. What is an array of pointer? How is it declared? 6. Explain the relation between an array and a pointer. 7. Explain comparison of two pointers. 8. How one pointer points to another pointer 9. How will you recognize pointer to pointer? What does the number of *s indicate 10. Distinguish between the address stored in the pointer and the value at that address? 11. Write a program to read and display a two-dimensional array of 5 by 2 numbers. Reduce base address of an array by one and start element counting from one. 12. With the following declaration : int *p, x[l0]; char *t, S[100]; . Explain each of the following expressions.If there is an error, explain why it is an error i) 1. x 2. x+I 3.*(x+i) 4. x++ ii) 1.p=x; 2. *p; 3. p++; 4. p++; 5. p--; 6. --p; 13.Check the following problems; find and correct errors if any. What will be the output in each case. i) main() { int i,x[10]={1, 2, 3, 4}; for(i=0;i<10;i++) { printf(%d\n, *x); x++; } 43

} main() { int i,*ptr, x[10]={1,2,3,4}; for (i=0 ;i< 10;i++) { printf(%d\n, *ptr); ptr++; } } 14. Name some areas to application of two-dimensional arrays. 15.Write a program that uses the sizeof operator to print the size of an array declared in the program. Use the sizeof operator on the name of the array. ii)

UNIT -IV
Structures :
Structure is a collection of logically related items that can be potentially of different types. Each such item is called member, because the members of a structure can be of various types, the programmer can create aggregates of data that are suitable for a particular application. The dot operator is used to access the members of a structure. Suppose the following declaration:
struct m { int a; char b; char c[5]; }; struct m my_struct;

How many bytes the variable my_struct occupies in the memory? member a occupies two bytes, member b occupies 1 byte and member c occupies 5 bytes. Then size of my_struct is 2+1+5 = 8. Accessing Members of a Structure: Beside the dot operator ".", We will introduce the member access operator "->". 44

C provides the latter operator -> to access the members of a structure via a pointer, if a pointer variable is assigned the address of a structure, then a member of the structure can be accessed by a construct of the form pointer_to _structure -> member_name. PASSING OF STRUCTURES AS ARGUMENTS : Structures can be passed as arguments to functions. Struct complex { float real, image; } the structure complex is declared. This structure has two members and both of them arefloats, real part and the imap represent theimaginary part of the complex number. struct complex a = {2.0, -3.0}; struct complex b = (-4.0, -7.0}; struct complex c; in the main we have declared three variables and initialized two of them. However, it ispossible to accept, these two complex numbers interactively also using scanf(), which we shallpresent in the next program. void print_complex(struct complex x) { char sign = +; if (x.image < 0) { sign=-; x.image= abs (x.image); } printf (\n%0.2 %c j%0,2f-. x.real,sig,x.image); } SELF REFERENTIAL STRUCTURES : In C, we have the structures, which can be made self-referential. A self-referential structure is one that includes within its structure at least one member which is a pointer to the same structure type. With self-referential structures, we can create very useful data structures such as linkedlists, trees, etc. The creation and usage of self-referential structures is elaborately discussed inchapters on linked lists, trees and graphs. typedefREVITISED: There typedef was only illustrated for basic data types. We now extend the usage of typedef to other data types such as pointers and structures. The declaration typedef char * string makes string as a data type which is same as character pointer (char *). We can now use declaration and casts such as, string p; /*p is a character pointer */ POINTERS TO STRUCTURES : If a large structure is to be passed to a function, it is generally more efficient to pass a pointer than to copy the whole structure into a local variable in the function. Pointers to structures are just like the pointers to any other variable. If p is a pointer to a structure p->member-of-structure refers to the particular member. Now an assignment p = &a makes p point to structure a. The real part of the structure a can now be referenced as (*p).real and the imaginary part can be references (*p).image. The 45

parenthesis are necessary around p because the precedence of the structure member operator dot(.) is higher than *. Pointers to structures are so frequently used that alternative notation is provided without parentheses as a short hand. ARRAY OF STRUCTURES C provides the facility to declare arrays of structures. These structures can also be initialized just like any other data type. In this way, C is consistent in representing data type.That is how we can consistently define, structures within a structure or an array of structures and so on. This property is referred as orthogonality of a language. Struct oval_counter { char *name; int count; }; the structure oval_counter is declared outside the main with two members. The first one is the pointer to a character and the second is an integer. struct oval_counter x[] ={ {VOWELS, 0), {DIGITS, 0), {COSONENTS. 0), {SPECIAL SYMBOLS, 0} }; in the main the array of structure oval_counter is declared and initialized with appropriate pairs of names and the counter value

Unions :
A union, like structure, is a derived type. They follow the same syntax as structures but have members that share storage. A union type defines a set of alternative values that may be stored in a shared portion of memory. The declaration of this type is as follows:
union int_or_float{ int i; float f; }; union int_or_float a;/*The storage is allocated at this stage*/

This declaration allocates storage for the identifier a. For each variable the compiler allocates a piece of storage that can be accommodate the largest of the specified members. Note that the tag name along with the keyword union, can be used to declare variables of this type. BIT FIELD: In many hardware applications, it is necessary to pack several states of information into a single machine word. For example, the status of a printer could be lead as a single word into the program and each bit in the status word could mean some specific state of the printer like paper empty, power off, hardware error, etc. For each of this bits are referred as flags. The usual way to handle the status word is to define a set of MASKS* corresponding to relevant bit positions as in, #definePAREREMTY 01 #define POWEROFF 02 46

#define HWERROR 0 Note that the numbers chosen is a power of 2, since when we bitwise AND with the status only the bit at kth position(given by 2k) is not masked and all other bits will be 0s. Thus, if we test the status word, we know whether the particular bit is set or not. For example , if ((flags & POWEROFF) ==1) . . Where flags is the status word.Although, this is one way ot handling the status word, C offers, the capability of defining and accessing fields within a word directly rather than using bitwise, logical operators. This is possible with the bit fields. A bit-field is a set of adjacent bits with in a single word. Not)c the set can contain, 0, 1, 2, , etc., bits. For example, the above #defines, could be placed by the definition of three bit fields. struct{ unsigned int PAPEREMPTY : 1; unsigned int POWKROFF : 1; unsigned int HWERROR : 1; } flags; void main (void) { flags.PAPEREMPTY =0; flags.POWEROFF=0; flags.HWERROR =1; if(flags.PAPEREMPTY ==1) printf(\nNo Paper in the Printer.)} if(flags.POWEROFF == 1) printf(\nNo Power to the Printer.); if(flags.HWERROR ==1) printf(\nThare la a Hardware Error.); In the program we have initialized various bit fields with 0s and 1s However, in actual practice, the status word will be read into variable flags. QUIZ QUESTIONS 1. #include<stdio.h main() { float value=10.00; printf("%g %0.2g %0.4g %f",value,value,value,value) } what is the output of above program? 2. #include<stdio.h main() { float value=10.00; printf("%g %0.2g %0.4g %f",value,value,value,value) } what is the output of above program? 3. struct list { int x; struct list *next; 47

}*head; the struct head.x =100 above is correct / wrong 4.what is structure? 5.In structure storage class refers to? 6.Who defines user defined name in the structure ? 7.What is data member in c? 8.Start of structure is shown by which keyword? 9. main() { struct { int a, b; }x,y; x.a=10;y=x; printf( %d,y.a); } what is the output of above program? 10. A union can also be stored as member of the struct ? true/false . 11. Is it pointer can also store the address of the heterogeneous types of elements ? true /false 12. what the data type that is similar to structure with a difference in the way data is stored and retrieved? 13. main() { struct emp { char ch[7]; char *s; }; static struct emp ={ programming ,basic}; printf(%C%c ,e.ch[0],*e.s); printf(%s%s,e.ch,e.s); } what is the output of above program? 14. what is the use of structuctes with pointers? 15.what is a collection of related variables under one name? 16. what is the operator used to access the structure ? 17. what are self referential structures? 18. define bit fields? 19. which is used to pass arguments to a program when the program is invoked from the command line? 20. main(int argc,char * argv[] ) { int i; printf ( %d ,argc); for (i=1;i<argc;i++) printf(%s, argv [i]); } 21. The purpose of typedefs is provide better documentation to a program?T/F 48

22. p=&a means 23.what is the common word used for structure? 24.Trees and link lists are created by which type of structure? 25. we can store several Booleans variable in how many bytes if storage is limited ? 26. which are frequentl used analying inputs from hard ware device? 27.the bit fields can not be arranged in declaring as? 28.what is the operator used to assign bit fields? 29.when a structure refers with in another structure is called? 30.which is can also be used as member of structure? Review Questions 1. What is a structure in C? How structure is declared? 2. What is the use of struct keyword? Explain the use of dot operator. 3. How are structure elements stored in memory 4. Explain nested structure. Draw diagram to explain nested structure. 5. How are arrays of structure variables defined. How are they beneficial to the programmer? 6. What is a union in C? How is data stored using union? 7. What are the differences between union and structure? 8. Explain the importance of bit fields. How do bit fields saves memory space? 9. Is it possible to pass structure variable to function? Explain in detail the possible ways. 10 How are structure elements accessed vising pointer? Which operator is used? 11.Write statements that accomplish each of the following. Assume that the structure: struct person { char last name [15], first name[15] , age[4]; };. Has been defined and that the file is already open for writing. (a) Initialize the file name age. dat so that there are 100 records with last name = unassigned ,first name= and age = 0 (b) Input 10 last names, first names and ages and write them to the file. (c) Update a record; if there is no information in the record, tell the user No Information (d) Delete arecordtha has information by reinitializing that particular record. 12. main() { struct a { char ch[7]; char *str; }; static struct a s1 = {Nagpur, Bombay}; printf (%c%c,s1.ch[0],*s1.str); printf(%s%s\n,s1.ch,s1.str); } What will be the output of the above program . 13. main() { struct node { int data; struct node *link; }; struct node *p,*q; 49

p = malloc (sizeof (struct node)); q = malloc (sizeof (struct noae)); prifitf(%d %d, sizeof (p), sizeof (q)); } What will be the output of the above program . 14. main() { union a { int i; char ch[2]; }; union a u; u.i= 256; printf (%d %d %d,u.i,u.ch[0],,u.ch[1]); } What will be the output of the above program . 15.Explain the use of structures with pointers. 16.Explain the general syntax of structures both having one object and array of objects using appropriate examples.

UNIT V Standard I/O :


Character level I/O
C provides (through its libraries) a variety of I/O routines. At the character level, getchar() reads one character at a time from stdin, while putchar() writes one character at a time to stdout. For example, consider
#include < stdio.h> void main() { int i, nc; nc = 0; i = getchar(); while (i != EOF) { nc = nc + 1; i = getchar(); } printf("Number of characters in file = %d\n", nc); }

This program counts the number of characters in the input stream (e.g. in a file piped into it at execution time). The code reads characters (whatever they may be) from stdin (the keyboard), uses stdout (the X-terminal you run from) for output, and writes error messages to stderr (usually also your X-terminal). These streams are always defined at run time. EOF is a special return value, defined in stdio.h, returned by getchar() when it encounters an end-of-file marker when reading. Its value is computer dependent, but the C compiler hides this fact from the user by 50

defining the variable EOF. Thus the program reads characters from stdin and keeps adding to the counter nc, until it encounters the ``end of file''. An experienced C programmer would probably code this example as:
#include < stdio.h> void main() { int c, nc = 0; while ( (c = getchar()) != EOF ) nc++; } printf("Number of characters in file = %d\n", nc);

C allows great brevity of expression, usually at the expense of readability! The () in the statement (c = getchar()) says to execute the call to getchar() and assign the result to c before comparing it to EOF; the brackets are necessary here. Recall that nc++ (and, in fact, also ++nc) is another way of writing nc = nc + 1. (The difference between the prefix and postfix notation is that in ++nc, nc is incremented before it is used, while in nc++, nc is used before it is incremented. In this particular example, either would do.) This notation is more compact (not always an advantage, mind you), and it is often more efficiently coded by the compiler. The UNIX command wc counts the characters, words and lines in a file. The program above can be considered as your own wc. Let's add a counter for the lines.
#include < stdio.h> void main() { int c, nc = 0, nl = 0; while ( (c = getchar()) != EOF ) { nc++; if (c == '\n') nl++; } printf("Number of characters = %d, number of lines = %d\n", nc, nl); }

Can you think of a way to count the number of words in the file?

Higher-Level I/O capabilities


We have already seen that printf handles formatted output to stdout. The counterpart statement for reading from stdin is scanf. The syntax
scanf("format string", variables);

resembles that of printf. The format string may contain blanks or tabs (ignored), ordinary ASCII characters, which must match those in stdin, and conversion specifications as in printf. Equivalent statements exist to read from or write to character strings. They are: 51

sprintf(string, "format string", variables); scanf(string, "format string", variables);

The ``string'' argument is the name of (i.e. a pointer to) the character array into which you want to write the information.

Files: Storage of data in variables and arrays is temporary. Files are usd for permanent retention of
large amounts of data. Computer stores on secondary storage device such as magnetic disks,optical disks and tapes. C view search files simply as a sequence of bytes.Each file ends either with an end of file marker or at a specific byte number recorded in data structures,when a file is opened an object is created and a stream is associated with the object. The C file is composed of several interrelated functions.The most common of these are : ______________________________________________________________________________ Name Function fopen() fclose() putc() fputc() getc() fgetc() fgets() fputs() fseek() ftell() fprints() fscanf() feof() ferror() rewind() remove() fflush() Opens a file Closes a file Writes a character to a file. Same as putc() Reads a character from a file. Same as getc() Reads a file from a file Writes a string to a file Seeks to a specified byte in a file Returns the current file position Is to a file what printf() is to console Is to a file what scanf() is to the console. Returns true if end-of-file is reached. Returns true if end-of-file is reached. Resets the file position indicator to the beginning of the file. Erases a file. Flushes a file.

The File Pointer: The file name can be indicated by a file pointer.This can be used in a place of name of file.This can be written as FILE *fptr Where *fptr-File Pointer Variable declared from name FILE. Opening a file: To Store or to retrieve the data to and from a file should be opened in the beginning of the program.To open a file ,the function fopen() is used.This function returns a pointer to a file. It is as follows: File pointer=fopen(filename,mode); File pointer-This is the logical name given to the data and result file throught the program,then data\result file is reffered by this file pointer. File name-A file name in which the data to be stored or retrieved. Mode-A file can be opeed in various ways. Mode Meaning r Opens a text file for reading. w Creates a text file for writing. 52

a Append to a text file. rb Opens a binary file for reading. wb Create a binary file for reading. R+ Opens a text file for read/write. W+ Create a text file for read/write. A+ Append or create a text file for read/write. ______________________________________________________________________________

Operatations On Files :
Similar statements also exist for handling I/O to and from files. The statements are
#include < stdio.h> FILE *fp; fp = fopen(name, mode); fscanf(fp, "format string", variable list); fprintf(fp, "format string", variable list); fclose(fp );

The logic here is that the code must


define a local ``pointer'' of type FILE (note that the uppercase is necessary here), which is defined in < stdio.h> ``open'' the file and associate it with the local pointer via fopen perform the I/O operations using fscanf and fprintf disconnect the file from the task with fclose

The ``mode'' argument in the fopen specifies the purpose/positioning in opening the file: ``r'' for reading, ``w'' for writing, and ``a'' for appending to the file. Try the following:
#include < stdio.h> void main() { FILE *fp; int i; fp = fopen("foo.dat", "w"); fprintf(fp, "\nSample Code\n\n"); for (i = 1; i <= 10 ; i++) fprintf(fp, "i = %d\n", i); } fclose(fp); /* open foo.dat for writing */ /* write some info */

/* close the file

*/

Compile and run this code; then use any editor to read the file foo.dat.

QUIZ QUESTIONS UNIT V 1. The smallest data item in a computer can assume the value 0 or the value 1. what is n such Data item? 53

2. A field is a group of characters that conveys meaning for example, a field consisting s solely of Uppercase and lowercase letters can be used to represent a persons name. 3. What is a sequence bytes? 4. Which key identifies a record as belonging to particular person entity that is unique from all other Records in the file?5 5. The file name can be indicated by? 6. To open a file, the function is used as? 7. If error occurs fopen function returns a file pointer by returning? 8. All the files that are opened should be closed after all input operations with the file using which Function? 9) Which function reads characters from a file opened in read mode? 10) Fprintf function works similar to? 11) Which function is used for the printing of the result calculated in the program on the file referred by the file pointer? 12) Which function works in the same way as scanf ? 13) Which function is used to find out whether it is the end of file which is reached. ? 14) Which function is used to indicate the size of file in bytes. ? 15) This function writes the contents of any buffered data to the file associated with fp?. 16)If you call a function with file pointer being null, all files opened for output are flushed ?what is that function? 17) Which function erases the specified file. ? 18) In remove() function if successful, which value is returned? 19 Main() { char ch; printf(enter any number.); scanf(%d, &a); fflush(stdin); printf(Enter any character.); scanf(n%d%c,a,ch); } what is the output of above program? 20) . main() { static char str[ ]=Programming printf(%s\n%s, str, Programming) } What will be the output of following program segments? 21)main( ) { printf(%20s\n, Short leg); printf(%20s\n, Long leg); printf(%20s\n, deep fine leg); printf(%20s\n, backward short leg); printf(%20s\n, legs all the same!); }What will be the output of following program segments? 22) main() {static char str[ ]= The c standard library.chars; *s;s=str: 54

while(*s) { putch(*s); s++; }printf(\n); s=str; while(*s) { putchar(*s); s++; } What will be the output of following program segments? 23). main( ) { char name[20], sname[20]; puts (enter your name and surname\n); gets(name, sname); puts(name, sname); printf(%s%sname.sname); } What will be the output of following program segments? 24) main() { char strl [30], str2[30]; printf(Enter a sentence\n); scanf%s, strt); printf(%s, strl); fflush(stdin); printf(\Enter a sentence); gets(str2); printf(%d,str2); } what is the output of above program?

Review Questions (UNIT-V) 1.What are files? 2. What are streams? Discuss two types of streams.. 3.What is file pointer? What information is provided by it ? 4. Describe the functions fclose and fopen. 5. What are input and output functions written in C for files ? 6. Describe fputsO and fgetsO functions. 7. Write a program to find the size of the file using ftell and seek function. 8.Write a program to read five numbers from a file and calculate average of the numbers and print in another output file. 9. What are the different modes in which a file can be opened ? 10.What is difference between feof and EOF functions ? 55

11.Write a program in C that compares two files and issues the message file1 and file2 are identical . when the files are the same or issue the message file1 and file2: first difference in byte number = when they are different. The names of two files should appear as command line parameters. 12.Write a program to maintain the record of different parts available in the store using their part number, name, quantity, rate and write it in a file. 13.Write a program to prepare salary bill of company using an input data file to store the data and output file to store the pay slips of employers. 14.Write a program to prepare roll list of students in a file by supplying the roll no from the screen. 15.Distinguish between the following functions. a) scanf() andfscanf() b) getc() and getchar() c) putc() and fputc() d) putw() and getw() e) ferror() and ferror() f) feof() andeof()

UNIT - VI
DATA STRUCTURES : Stacks & Queues 60 Stack: 50 40 30 20 Top Top Stack created with size 5 (Stack is empty, Top=0) push one element (Stack having 1 element, Top=1) Push one element (Stack having 2 elements, Top=2) 50 40 30 20 20 Top 40 30 20 30 20

Top Top Top 56

Push three elements (Stack is full (5 elements),Top=5)

Pop one element (Stack having 4 elements, Top=4)

Pop one element (Stack having 3 elements, Top=3)

Pop three elements (Stack is empty, Top=0) Top

Stacked is deleted

Stack And Its Implementation In C :


The previous discussion used such construction (structures) in which the access to any particular element was provided by means of dot operator "." Certain practical applications require a restriction when accessing elements of data structure used, and one of the classical examples of such structures is a STACK. Definition: A stack is a collection (linear) of elements of the same type which can be accessed only at one end called a TOP of the stack. Stack structure is often called LIFO (Last In First Out) structure. According to the definition, the number of elements in a stack is potentially unlimited, and this structure allows Insertion / Deletion of elements at any time, it becomes a dynamic in nature. There are two basic operations on stack: 1. PUSH (Insertion Operation): Inserts an element at the TOP of the stack. 2. POP (Deletion Operation): Deletes an element from the TOP of the stack. When performing POP operations, a possible situation of UNDERFLOW (stack is empty) has to be checked.

Implementation of stacks using ARRAY structure :


This way of implementation uses a STATIC structure ARRAY (It is declared in the program and it is known at the compile-time) for representation of dynamic structure static (it changes in time). Such approach has certain disadvantage (Although array and stack are linear collections of elements of the same type). 57

The number of elements in array is limited (stack, according to definition is unlimited), and while using array for implementation of stack, we have to check a possible situation of OVERFLOW (no chance to push a new element on to the stack, because array is full). Stack is changing Dynamically, but the nature of array is static, Essentially stack should be created (stack should be declared). From the beginning stack is empty. (array can be considered as a home for stacks elements). stack is a structure that contains two elements : 1. Array 2. Single variable top, And it is empty because the variable top hold 0 in it.

When the first element is to be pushed onto the stack, we can clear the picture by the following diagram: Suppose operation PUSH is applied several times, then the current status of a stack can be represented as follows

Applications of stack structures :

Evaluation of arithmetic expressions:

Any parentheses ((...)) free expression is evaluated according to precedence rules (the order of the arithmetic operations), for binary (require two operands) arithmetic operations. These rules can be shortly summarized as follows 1. Exponentiation (^ or $). 2. Multiplication and Division (* and /), higher priority. 3. Summation and Subtraction (+ and -), lower priority. If you would like to change the "default" priority rules of expressions evaluation, you have to use parentheses. a - b * c not equivalent to (a - b) * c For writing arithmetic expressions based on binary operators we normally use so called INFIX form, for example the operator between two operand like a + b is written in INFIX form. If we would like the arithmetic expression represented in the INFIX form to be evaluated by the compiler automatically the computer will definitely face with certain problems: The initial expression (INFIX form), requires several steps of scanning in order to "extract" all subexpression involved into evaluation process: a-b*c+d/e, if there are operations that have the same precedence, they are performed from left to right.

scanning1: evaluation b*c, evaluation d/e scanning2: evaluation a-b*c, evaluation (a-b*c) + (d/e) Each expression may include a certain number of subexpression enclosed into parentheses, this implies that the order of expressions evaluation is changed,

58

and computer again has to scan the expression in order to search for the next subexpressions for evaluation. Beside the well known and commonly used INFIX form of arithmetic expressions, two other forms are known as PREFIX and POSTFIX are used as well. (PREFIX form is also called POLISH NOTATION, after polish mathematician Jan Lukasiewicz, who proposed it, POSTFIX form is the INVERSE POLISH NOTATION). INFIX FORM: (operand1)<operator>(operand2). PREFIX FORM: <operator>(operand1)(operand2). POSTFIX FORM: (operand1)(operand2)<operator>. Example1: a+b*c-d PREFIX FORM: -+a*bcd POSTFIX FORM: abc*+dIf (a+b) * c - d PREFIX FORM: -*+abcd POSTFIX FORM: ab+c*dExample2: a-b/c*e+d-f PREFIX FORM: -+-a*/bcedf POSTFIX FORM: abc/*e-d+fStack is becoming an underlying structure for performing calculations based on POSTFIX and PREFIX notation of the expression. The advantages of the two forms are obvious: 1. These forms are PARENTHESES FREE. 2. Scanning of the expression is done only once (from left to right) and the final result is automatically known when scanning is finished. Example3: Suppose we want to evaluate the expression a+b*c-d, when a = 2, b = 3, c = 4, d = 5.

Convert the INFIX form to postfix form.

abc*+d- (Scanning this order 234*+5-)

operation * should be performed and it requires two operands which are popped from the stack(4 and 3), then do the corresponding operation then include the result on the stack again. The second operation is +, which requires two operands as well, so element 12 and 2 are popped (2+12=14) and result is pushed onto the stack.

59

The third operation is - (14-5=9), operation is performed and result is pushed onto the stack. Note: While popping elements from the stack and performing required operations, don't forget that operators - and / are not commutative. It is important to keep in mind and control the order of their usage in sub expressions. Stack structure is also used for conversion of expression written in the INFIX form to its POSTFIX notation. While processing your program, a system (compiler) will do such conversion automatically and stack is becoming the underlying structure for doing this work. When the conversion is performed, its result (POSTFIX expression) is used for calculation of the expression's value and again stack is used here. The process of conversion (INFIX to POSTFIX) requires a certain rules to follow: 1. While scanning the INFIX expression from left to right operands are not pushed onto the stack, instead they go directly to output stream. (screen of monitor). 2. The opening parenthesis "(" automatically is pushed onto the stack, and when a corresponding closing parenthesis reached all characters which precede the opening parenthesis in the stack are popped (they go sequentially to the output stream) and both parenthesis " ( ", " ) " are destroyed (ignored), they stay in memory. Example4: Suppose the following expression: (a+b)*c-d; for simplicity of processing lets assume that a character is used to indicate a beginning or the end of the expression, so expression above will look like ( a + b ) * c - d We scan our expression from left to right INPUT ( a + b ) * c d STACK ( ( +( +( * * -* -* d * 60 c b a OUTPUT

Reading the output from top to bottom we get a POSTFIX form which looks as: ab+cd-*; which corresponds to the INFIX expression (a+b)*(c-d), and it is not the same as the original INFIX expression. why? While performing PUSH/POP operations on stack we have also to control a number of operands, which are used in corresponding operations (all discussed operations are binary operations ). Each operation (+, *, /) has two operands. QUEUES: A queue is a linear collection of elements of the same type. A queue has a front and rear. The new elements can be added to the queue only at one end, which is rear of the queue and the deletion of elements is possible also at one end, which is the front of the queue. It is possible to implement queue as a linear linked list. Three basic operations are applied to queue structure: 1. DELETION: delete(q), delete (remove) the element which currently at the front position in a queue. 2. INSERTION: insert(q,x), insert a new element at the rear of queue. 3. EMPTY: empty(q), checks whether the queue is empty or not. The situation UNDERFLOW is trying to delete an element while queue is empty, has to be checked using function EMPTY. The situation OVERFLOW is trying to insert an element while queue is full, it is checked using function insert(q,x). Operation insert(q,x) looks as follows: STEP1: [overflow?] if rear >= n then give an error message and exit (n is max number of element).

STEP2: [prepare a new position for inserted element] rear = rear + 1. STEP3: [insertion] set q[rear] = x STEP4: [before insertion was done, queue was empty: rear = 0 and front = 0] if front == 0 then front = 1 and exit.

Operation delete(q) can be represented in a similar way:


STEP1: [underflow?] if front == 0 then display error message and exit. STEP2: [deletion] x = q[rear], where variable x is temporary location in which the value to be deleted is stored in it. STEP3: [there was one element in the queue] if front == rear then front = rear = 0 STEP4: [incrimination] front = front + 1( the next, second element in the queue becomes the new front element). As we can notice performing of insert / delete operation specified above has an obvious shortage

61

Queue : 20

Front Rear Queue created with size 5 (Queue is empty, Front=0 Rear=0) 20

Front

Rear Inserted one element (queue having 1 element, Front=0 Rear=1) 20 50

30

30

40

60

Front

Rear Inserted one element (Queue having 2 elements, Front=0 Rear=2)

Front

Rear Inserted 3 elements (Queue is full (5 elements), Front=0 Rear=5)

30

40

50

60

40

50

60

62

Front Deleted one element (Queue having 4 elements, Front=1 Rear=5)

Rear

Front

Rear

Deleted one element (Queue having 3 elements, Front=2 Rear=5)

Front Rear Deleted three Elements (Queue is empty, Front=5 Rear=5) Queue is deleted

Circular Queue :

Front Rear Circular Queue created with size 7 (Queue is empty, Front = Rear=0) %7)

Front

10 Rear

One element is inserted into Circular Queue (Queue having one element rear= (rear+1)

60 70 Front 10 20 Rear Rear Front 10

50 40 20 30

Inserted one element (Queue having 2 elements) rear= (rear+1)%7

Inserted 5 elements (Queue is full) (7 elements) (rear= front)

63

60 70 Rear

50 40 20 30 Front Rear 70

60

50 40 30 Front

Deleted one element from the queue (Queue having 6 elements)

Deleted one element from the queue (Queue having 5 elements)

Front Rear Deleted 5 elements from the queue (Queue is empty, Front = Rear) Queue is deleted

QUIZ QUESTIONS (UNIT-VI)


1)What are basic operations of stack? 2)what is the time complexity of algorithm represented in which notation? 3)what are applications of stacks? 4)what is the function used to release dynamically allocated memory? 5)which operator has highest precedence in notation conversions? 6)from infix to prefix a+(b+c(*cd)+e)+f/g 7)which is non premitive linear structure? 8)in empty queue what are the values of rear and front? 9)how many locations are used when a circular queue of size n? 10)in how many ways queues can be implemented? 11)how many variables can be used to manipulate a queue? 12)the infix evaluation of postfix exepressin A*(B+C) 13) what is the data structure follows first in first out 14)what is abtract data types? 15)what is data structure? 16)what is linked list? 17)can we implement linked list by using stack?(T/F) 18)what is the function used to resize the size of memory block? 19)stack is ordered list in which all insertions and deletions are made at one end is known as? 20)what are primitive data structures? 21)Arrays comes under? 22)what are the basic function calls performed in stack? 23)evalute the postfix expression (ab+c*d)? 24)when do you say stack is empty and stack is full? 25)what is the significance of top in a stack? 26)how is queue different from stack? 64

27)what is the need of dequeues in queue? 28) what is circular queue? 29)transfer infix expression to postfix? (A-B)/(C*(C-D/C+D)) 30)convert into infix -/*A+BC-DE

Review Question (UNIT-VI)

1. Explain stack and queues.


2. Explain the representation of stack and queues. 3. Distinguish between stack and queue. 4.Differentiate between static and dynamic implementation. 5 Explain recursion with classifications 6.Explain infix, postfix, and prefix expressions. 7.Explain insertion and deletion operation with stack and queues 8.Write a program to demonstrate push() and pop() operations using dass and member functions. 9.Write a program to enter an integer. Reverse the digits of the integer. Use stack 10.Write a program to perform the following operations: (a) Push (b) Pop(c) Stack underflow (d) Stack overflow mechanism.

(e) Display all elements 11.Write a program to evaluate postfix expressions. 12.Write a program to perform stack operations. 65

13.Write a program to perform insert and delete operations with a circular queue and Display the elements. 14.Write an algorithm / C program to transform a postfix to prefix expression. 15.Write the postfix form ot the following expressions. A+BC+D A*B/C+D (A + B ) * D + E / ( F + A * D ) + C A+B%C+D.

UNIT VII
Linked Lists
LINKED LIST : Pointers are simple variables which keep the address of other variables. In C, array elements can be of type pointer. Addresses are numeric values which specify the location of the memory, which the value of the variable is stored. If we wish to allocate for the dynamic variable i a piece of memory, this means it is hold in the memory until it is necessary a call to function free() will deallocate and return to the system the part of memory which was used by the variable (dynamic variable i), physically nothing will be destroyed, you should not reference i any more (for you it is not exist). Pointers (links) provide a way to create quite complicated structures which consists of several nodes and one of the fields in each node is pointer (it points to the next node in the structure), such complicated structures are built at run-time using calls to the libraries malloc() and simple assignment statements. Structure of one node: 1. Information field (it keeps the value of the element). 2. Link field (it points to the next node). The link field on the last node should not point to anything, this can be done by assigning a value NULL to this pointer (The value NULL stands for address which does not correspond to any valid memory location. The main advantage of list structure is its dynamic nature, the number of elements in list is not declared, but instead the elements are allocated in the memory upon request (we need the new 66

element at run-time, so a call to malloc() is done), if we compare linked list structure and array structures we will see that in the case of linked list structure we are loosing the possibility of direct access to linked list's elements (in array this can be done by simple indexing). If we would like to reach any particular element of linked list we have to traverse a structure starting from a header. Example : macllo #include<stdio.h> #include<stdlib.h> int main() { int *c; c = malloc(sizeof(int));/*allocates a block of space in memory cosisting of int size bytes*/ return 0; } #include<stdio.h> #include<stdlib.h> int main() { int *c; c = malloc(sizeof(int)); free(*c);/*free()causes the space in memory pointed by c to be deallocated*/ return 0; } #include<stdio.h> struct a { int aa; char bb; shrot int cc;}; int main() { struct a d; d.bb = 'a'; /*access to variable bb of type character is done by means of dot operator "."*/ return 0; } How TRAVERSING can be implemented? In order to escape from using very long and complicated full names of node's fields, we can use loops in order to repeat simple traversing steps. Suppose we would like to reach a current tail of linked list. Traversing linked list structures is a very important operation which you will need while performing insert / delete operation and in calculating the number of elements in list. Suppose that we have a list structure and our aim is to insert a new element at the end of the list (this situation is quite regular when linked list structure is used for implementation of a queue). Before insertion we have to traverse linked list in order to find the current last element While the loop terminates we have a following situation with the linked list. Now we can start insertion itself-but this operation requires one extra pointer (it should be declared in the program exactly of the same type as header and temp), let us call it current. If we assume that linked list structure is used for implementation of a queue, then we can try to delete one element from the list and if it is a queue, then the deletion can be done only at the front position- header and temp. 67

Linked list structure does not impose any restrictions on the positions to insert / delete elements. Suppose that we want to delete one element from list, first of all we have to find this element (it can be achieved by traversing list). For traversing linked list we need to have two pointers (header is not used -it always keeps the starting address of the list), temp (will point to the element to be deleted after traversing is done) If linked list structure is used for implementation of a queue, then we have to control (keep address) of two key positions in a queue - front and rear. Depending on the application of linked list structure we may need also to control the number of elements which are in linked list at each moment of time, one of the possibilities to do it is to traverse linked list structure any time we want to know the number of elements, but if linked list is big enough and traversing is repeated frequently. Such control of number of elements becomes very time consuming. The other possibility to keep track on number of elements in linked list is to modify a header which can be represented as a struct structure with two fields. One of these fields keeps10 number of element of linked list. Declaration part in this case should be modified as in the \0 corresponding 20 10 \0

20 Single linked list: 20

10

30

\0

10 Data Field

30

\0

40

Link Field

Linked list with one element

30

\0

One element is inserted as first node 50 One element is inserted as last node 20 10 40 50 30 \0

One element is inserted at desired position (3rd position) 20 10 40 50 30 \0

20

10

40 One element is inserted after data is 40

20

10

40

50

10

68

Completed linked list

One element is deleted form the list (now list having 4 elements) Circularly Single linked list:

Doubly linked list structure :


From the previous discussion we know that each node in linked list has one pointer field which always keeps the address (if it is not the last element) of the next element in the structure, such linked list are often called ONE-WAY or SINGLE LINKED LIST. Certain applications require to know at each moment of time not only a successor of a current node, but also a predecessor of a current node, that is the reason why doubly linked list structure are used. In the same sense a representation of doubly linked list "combines together" two-one way linked list, and that is why a header consists of two pointer fields, each field references its own one-way linked list. Other than that, a processing of doubly linked list is not too much complicated in comparison with SINGLE linked list.The structure of each node in the list can be depicted as follows: Suppose we would like to perform insert operation (from the beginning list is empty), as it was while discussion of SINGLE linked list , we need extra pointers to perform standard operations of the list,Suppose that, the last indicated example is written after one step of linked list processing are already performed, and there are some elements in the doubly list, assume that our linked list has already one node. For checking of a presence of only one element in the structure, we can use a pointer current which points to the last element on the right side in the structure. After insertion of the second element situation looks as follow: Suppose we would like to insert a new node at the end (right side) of doubly linked list, but in order to find the current last element on the right side, we have to start doubly linked list traversal or we can use the value of header[1] which controls the current last node on the right side, when the element after which you would like to insert the new element is found, the insertion operation starts.

69

Suppose we would like to insert a new node somewhere in the middle of DLList. In this situation we have to find a position for insertion of a new element again we have to start traversing, and a pointer current in this case will point to the node which will become a predecessor of the inserted node. Deletion of nodes from DLList structures has its own specific, when we found the element to be deleted, we automatically know its predecessor and successor, the latter are going to be use in assignment of proper address after the required element is deleted in the case of SINGLE LList deletion is also related with previous traversing of the structure, but this traversing requires more effort to control the predecessor of deleted node. Suppose traversal od DLList is done, and we would like to delete the element (node): If DLList is empty , there is no chance to delete something (UNDERFLOW) .Suppose that DLList consists of several nodes, and pointer temp points (keeps the address) to the right most nodes of the structure (you can assign this value to pointer temp either by traversing the nodes, or by simple assigning the value of header[1] to temp). We would like to delete the node pointer temp currently points to \0 10 \0 The last fragment of the program shows an advantage of using DLList operation deletion was done only by using one pointer temp, and it becomes possible because the address of predecessor and successor nodes are automatically known when we specify the element to be deleted. \0 20 10 \0

Double linked list: \0 20 Link Field

10

30

\0 Link Field

\0

20

10 Data Field

30

\0

Double Linked list with one element 40 \0 20 10 40 30 \0 One element is inserted as first node

\0

20

10

40

50 One element is inserted as last node 50 30 \0 One element is inserted at desired position (3rd position) 50 30 \0

\0

20

10

40

70 20 10 40 50 30

One element is inserted after data is 40

Completed linked list

One element is deleted form the list (now list having 4 elements) Circularly doubly linked list:

The specific of the drawn structure of the drawn structure is in the last node- it is pointer field points to the first node which is referenced by header, CLList provide a convenient way to implement stack and queue. Schematically the implementation of both structures by means of CLList can be represented as follows: Suppose we want to remove one element (node) from queue which is implemented by means of CLList we would like to push one new element into stack which is implemented by means of CLLis . The advantage of CLList is in simplified approach to traversing of structure, because a search for particular element can be started not from the header, but from any current node (finally we are in the circle, and sooner or later the element we are looking for will be found, if it is in the structure). CLLists simplifies also a procedure of deletion. Unfortunately CLLists are becoming dangerous in the sense of potential traversing (if a logical mistake is done in specifying a condition to stop traversing). In order not to fall into infinite traversing, a structure of the header pointer can be slightly modified as follows: The header has the same structure as the other nodes in CLList. Within this representation of the header (and of the CLList in a whole), the structure of all elements is becoming the same, we should not forget that header is still not a part of linked list but the strange value in the informational (item) field of the node header serves as indicator of the number of passes (traversals) of the structure, and it provides a convenient way not to fall into infinite loop, while processing CLList. For example, if item field of nodes keeps the value of student's CGPA (0.0 <= CGPA <= 4.0) and all these values are positive implies that the strange value in the item field of the header can be some negative value ,Strictly, a structure of the header can be changed according to certain requirements of the probability under study, advantage of using CLList structures is in possibility of traversing starting from any node in the list, (but not necessary from the header). 71

Binary Trees :
Binary tree T with the element from the set E is a list which is either empty or it consists of three components. 1. A root of the tree T. 2. Right subtrees of the tree T. 3. Left subtrees of the tree T. Each element of the tree is called a node. The most reasonable representation of the binary tree is a graphical one, Suppose that Tz is a tree which starts from arbitrary node z of the tree T if the left subtree of T z is not empty then the roots of the left subtree is called the left child of the node z, with each node of the tree T we can associate a number which is called a node's level by default, the level of the root of the tree T has a level 0, its children stand at the level1, etc. The height of a tree T ( h(T) ) is the maximum level for each node of the tree, for the figure shown above h(T) = 2. Suppose that, tree T has a height of n, then the maximum number of nodes = 2 n+1-1. Potentially binary tree can be implemented by means of array and in the declaration part we have to specify a set of indices 1....2n+1-1, keeping 1 arrays element for 1 element in the tree regardless of presence of element (node) in the tree or its absence. If we would like to implement a binary tree as a linked list structure .If we have a collection of n objects, then these objects can be arranged in n! different ways, and it means that there are n! ways to perform traversal of these objects, Some traversals seem to be more natural than others. For example if objects are organized into linked list structure, it seems more logical to perform traversing starting from the header visiting the elements one by one in the linked order. If the structure under study is binary tree then the way traversal should be performed is not quite clear, and there are three main approaches which are commonly used in computer science: 1. PREORDER traversal: Start with root and follow the left subtree till we reach the leaves, then trace the right subtree till we reach the leaves. (root will be at the beginning). 2. INORDER traversal: Start with the leaves of the left subtree till root, then from leaves of the right subtree till you reach the root. (root will be in the middle). 3. POSTORDER traversal: Start with the leaves of the left subtree till you reach the root, then trace from the leaves of right subtree till root. (root will be at the end). The prefixes used above indicate the moment when the root should be processed. All the definitions specified here are recursive ones, for all of them we can easily find a base case (it is not expressed in terms of traversing): traversing of empty tree is equivalent to do-nothing. Prefixes used in the names of traversal approaches are the same as those used in the names of forms of arithmetic expressions representations-PREFIX,INFIX and POSTFIX. A question that may arise is how these forms are related to BINARY TREES TRAVERSAL? h(T) = 3 The corresponding PREFIX and INFIX forms of the INFIX expression given above are: INFIX : a^2 - 4 *b * c PREFIX: - ^ a 2 * * 4 b c

72

POSTFIX: a 2 ^ 4 b * c * Traversal of binary tree;


PREORDER traversal: - ^ a 2 * * 4 b c INORDER traversal: a ^ 2 - 4 * b * c POSTORDER traversal: a 2 ^ 4 b * c * -

Binary Search Tree :


According to the definition of the binary tree structure, its elements are taken from a set E which can be associated with some particular type at the stage of structure's implementation. In practical cases it is required that set E is ORDERED (in other words, type which corresponds to the set E is ordered). A binary tree with the elements of the type E is called a binary search tree, if for every node in the tree the key field of its informational part is greater than that for every node in the left sub tree, and less than that in every node in the right sub tree of the binary tree T. By key field we mean one of the fields in the nodes structure (struct) which is used for the search. Ordering of the elements of the binary tree becomes essential while performing operations insert / delete. Informational part of each node may include several fields (name , surname, student's ID number, ......) and among them we have to choose one key field (for example it can be student's ID number) and using it, whole structure of binary tree can be constructed. In order to implement binary search tree and its standard operations insert / delete, we have to make the corresponding declarations. Within the last example, in the declaration, the info field of the node has a struct. structure, and one of the field is chosen as a key the procedure insert becomes a recursive one because the insertion of the new node is expressed in terms of insertion of the node into a sub Tree and for sub tree insertion is done on its sub tree etc... The variant of function insert does not give us a chance to move through the levels of the tree, so some slight changes should be done. QUIZ QUESTIONS 1. 2. 3. 4. 5. 6. 7. 8. 9. What way the linked list represented by having each element pointing to the next element ? What is called each element in linked list ? What are the special data structure used to alternative strategy to allocate memory? What is called the non sequential collection of data elements in linked list ? Which field contains the actual values in linked list ? what is called if the nodes are not present in linked list ? What are the operations in linked list ? What are the types in linked list ? What is called a Singly Linked list one in which all nodes are linked together in some special manner ? 10. What is called the external point in linked list ? 11. In which directions the doubly linked list is traveled? 12. Which linked list is traveled in Bi-directional? 13. How many linked fields are contained in doubly linked list ? 14. In doubly linked list the node contains? 15. Which are widely used to represent and manipulate polynomials ? 16. What are the fields that contains the polynomial? 17. What are used to manipulate the sparse matrix ? 73

18. Linked list is not a ordered list ? True/False 19. In a linked list what is the next field of the last node pointer ? 20. What are the non linear data structures ? 21. What is called a designated node of the set of nodes ? 22. What s a binary tree? 23. What is a tree ? 24. What is a complete binary tree? 25. What are the types of tree traversals? 26. What is needed in simulate recursion for tree traversal? 27. What the ways to implement the singly linked list ? 28. Define the graph? 29. What are the representations of graph? 30. What is a vertices in a graph? 31. What are the maximum numbers of edges in a undirected graph? 32. Construct a binary tree of A+( B + C * D + E ) + F / G . 33. what is an AVL trees? 34. An AVL trees are perfectly balanced or not ? True /False 35. B tree is a balanced tree ? True/False 36. A tree is which type of data structure ? 37. What is a threaded binary tree? 38. What is a complexity of a adjacency matrix graph? 39. What are the types of graph traversal? 40. A minimum spanning tree are free trees and designed only on undirected graph ? True/False Review Questions 1.What is a tree ? 2.Define the following terms: a ) Degree b) Depth c) Path d) Forest. 3. Give an algorithm / C program, to reverse a singly linked circular list in place. 4.An unrestricted D queue is a double ended Queue, where insertions &deletions can be made in either ends of the Queue. Write a program, using linked list to implement a D queue. 5.Write a non recursive routine for post order. 6.Write a non recursive routine for preorder. 7.Give an algorithm to count the number of leaf nodes in a binary tree T. What is its computing time? 8.What is header? Explain its role in the linked list. 9.What is circular linked list? 10.Explain binary trees and spanning tree. 11.Explain traversing of a graph. 12.Enlighten spanning trees. 13.Explain doubly linked list 14.Describe graph and its representation. 15.Write a program to demonstrate spanning tree. 16.Write a program to demonstrate breadth-first search and depth-first search

74

UNIT VIII
SEARCHING :
A Searching algorithm is a algorithm that accepts an argument K ( the key value) and tries to find a record whose key is K . the algorithm may return the entire record or more commonly a pointer (location) of the record. It is possible that the searching for a particular key in a file may be unsuccessful; that is there is no record in the file ,whose key value matchers with that of the searching key K so that the algorithm may returns a special value or a NULL pointer. They are two types : 1. Linear search 2.Binary search. LINEAR SEARCH: In linear search to compare the search key value with every key going through the entire array. . The worst case time complexity of any algorithm that searchs linearly that will be O(n), where n is the number of keys( records). 1. 2. The file is not ordered or sorted on the key values. the file ism orders or sorted on the key value.

To better approach for the second case where it is possible to design a searching algorithm that has in worst case O(log n ) time complexity .

75

For convenience we have to declared an array of integer and initialized with key values. These key values may be read from an index file into a buffer and the values could be even strings. Printf ( enter the key to be searched :); Scanf(%d,&key); The search key is interactively accepted i = lin_search(a, 12, key) ; the routine linear search is called by passing three parameters namely the address of the array containing the keys, the number of keys and the search key value int lin_search( int x [] , int n , int k ) { int i ; Label1 for ( i =0 ; i<n ; i++) if ( x [ i ] == k) return i ; return- 1; } the lin_search routine it contains a for loop with the loop varable i running form 0 to n1. The if statement inside the loop returns the position if the key is found . Otherwise the routine retuns-1 indicates to the calling routine that the search key is not found .

BINARY SEARCH : In the binary search keys are stored in an index file in a sorted order through the actual file is not sorted the search in a sorted list could be much faster than in an unsorted list .In case of large files where n is large and search being used very frequently it is necessary to keep the index in a sorted order . so we can replace the binary search in place of linear search. The worst case complexity O(log n) . int bin_search ( int x [] , int n , int k ) { int low,high, mid ; low = 0; high= n; while ( high>=low) { mid= (low+high)/2; if (x [mid] == k) return (mid) ; if ( x [mid ] > k ) high = mid 1; else low = mid + 1; } return (-1 ) ; } 76

the recursive algorithm is more natural to a binary search . where the programs returns the values of the mid when a[ mid] == k . if both the conditions are not satisfied then the recursively the rbin _ search with the subset low to mid -1 or mid + 1 to high depends on the value of K .thus the number of recursive calls are equivalent to the number of the iteration in the previous program.

Sorting Methods
S. NO 1 2 3 4 5 6 7 8 9 10 11 Name of the Sort Normal Sort Bubble Sort Modified Bubble Sort Selection Sort Insertion Sort Radix (Bucket) Sort Quick Sort Merge Sort Shell Sort Heap Sort Radix Exchange Sort Complexity O(n2) O(n2) O(n2) O(n2) O(n2) O(n log d n) O(n log n) O(n log n) O(n2) O(n2) O(n log d k)

Enter the size of array

10

Enter the array elements 24 58 63 84 30 43 18 93 04 70


Normal Sort:
Pass 1: Pass 2: Pass 3: 93 24 24 24 93 58 58 58 93 63 63 63 30 30 30 43 43 43 18 18 18 84 84 84 04 04 04 70 70 70 77

Pass 4: Pass 5: Pass 6: Pass 7: Pass 8: Pass 9: Pass 10:

24 24 24 18 18 04 04

58 30 30 24 24 18 18

63 58 43 30 30 24 24

93 63 58 43 43 30 30

30 93 63 58 58 43 43

43 43 93 63 63 58 58

18 18 18 93 84 63 63

84 84 84 84 93 84 70

04 04 04 04 04 93 84

70 70 70 70 70 70 93

Note: Biggest element is at 1st pos in 1st pass, at 2nd pos in 2nd pass & last pos in last pass.

Radix (Bucket) Sort:


Pass 1: Pass 2: 30 04 70 18 63 24 43 30 93 43 24 58 84 04 63 70 58 18 84 93

Note: Units Place sorted in the 1st pass, 10s Place sorted in the 2nd pass.

Bubble Sort:
Pass 1: Pass 2: Pass 3: Pass 4: Pass 5: Pass 6: Pass 7: Pass 8: Pass 9: Pass 10: 24 24 24 24 24 18 18 04 04 04 58 58 30 30 18 24 04 18 18 18 63 30 43 18 30 04 24 24 24 24 30 43 18 43 04 30 30 30 30 30 43 18 58 04 43 43 43 43 43 43 18 63 04 58 58 58 58 58 58 58 84 04 63 63 63 63 63 63 63 63 04 70 70 70 70 70 70 70 70 70 70 84 84 84 84 84 84 84 84 84 93 93 93 93 93 93 93 93 93 93

Note: Biggest element is at last pos in 1st pass, 2nd biggest element is at last but one pos in 2nd pass & smallest element at 1st pos in the last pass.

Modified Bubble Sort:


78

Pass 1: Pass 2: Pass 3: Pass 4: Pass 5: Pass 6: Pass 7: Pass 8:

24 24 24 24 24 18 18 04

58 58 30 30 18 24 04 18

63 30 43 18 30 04 24 24

30 43 18 43 04 30 30 30

43 18 58 04 43 43 43 43

18 63 04 58 58 58 58 58

84 04 63 63 63 63 63 63

04 70 70 70 70 70 70 70

70 84 84 84 84 84 84 84

93 93 93 93 93 93 93 93

Note: Biggest element is at last pos in 1st pass, 2nd biggest element is at last-1 pos in 2nd pass, smallest element at 1st pos in the last pass. But once numbers sorted done process stopped.

Shell Sort:
Pass 1: Pass 2: Pass 3: 24 24 04 18 04 18 63 30 24 04 18 30 30 58 43 43 43 58 58 63 63 93 70 70 84 84 84 70 93 93

Note: Every element is compare with size/2 (4th) element, if bigger swap two elements and do the same step until swapping not done in 1st pass, Every element is compare with +2nd element, if bigger swap two elements & do the same step until swapping not done in 2 nd pass, Every element is compare with next element, if bigger swap two elements & do the same step until swapping not done in 3rd pass.

Selection Sort:
Pass 1: Pass 2: Pass 3: Pass 4: Pass 5: Pass 6: Pass 7: Pass 8: Pass 9: 04 04 04 04 04 04 04 04 04 58 18 18 18 18 18 18 18 18 63 63 24 24 24 24 24 24 24 84 84 84 30 30 30 30 30 30 30 30 30 84 43 43 43 43 43 43 43 43 43 84 58 58 58 58 18 58 58 58 58 84 63 63 63 93 93 93 93 93 93 93 70 70 24 24 63 63 63 63 84 84 84 70 70 70 70 70 70 70 93 93 79

Pass 10: 04

18

24

30

43

58

63

70

84

93

Note: smallest element is at 1st pos in 1st pass, 2nd smallest element is at 2nd pos in 2nd pass & biggest element at last pos in the last pass.

Insertion Sort:
Pass 1: Pass 2: Pass 3: Pass 4: Pass 5: Pass 6: Pass 7: Pass 8: Pass 9: 24 24 24 24 24 24 18 18 04 58 58 58 58 30 30 24 24 18 18 63 63 63 63 58 43 30 30 24 24 84 84 84 84 63 58 43 43 30 30 30 30 30 30 84 63 58 58 43 43 43 43 43 43 43 84 63 63 58 58 18 18 18 18 18 18 84 84 63 63 93 93 93 93 93 93 93 93 84 70 04 04 04 04 04 04 04 04 93 84 70 70 70 70 70 70 70 70 70 93

Pass 10: 04

Note: Every element is checked with before elements and inserted at proper position (Here swapping is not done).

Merge Sort:
24 58 63 84 30 43 18 93 04 70

Pass 1: Pass 2: Pass 3: Pass 4:

24 24 18 24 04 18

58 58

63 63 30 24

84 84 43 30

30 18 58 43

43 30 63 58

18 43 84 63

93 93 93 70

04 04 04 84

70 70 70 93

Note: Divided into 2 elements array and sorted each array in the 1st pass. Merge every two arrays and sorted(4 elements in each array) in the 2nd pass. Merge every two arrays and sorted(8 elements in each array) in the 3rd pass. Merge every two arrays and sorted

Quick Sort:
Pass 1: 04 18 63 84 30

(Key Element is First Element)


43 58 93 24 70 80

Pass 2: Pass 3: Pass 4: Pass 5: Pass 6: Pass 7: Pass 8: Pass 9:

04 04 04 04 04 04 04 04

18 18 18 18 18 18 18 18

63 24 24 24 24 24 24 24

84 58 58 43 30 30 30 30

30 30 30 30 43 43 43 43

43 43 43 58 58 58 58 58

58 84 84 84 84 70 63 63

93 93 93 93 93 63 70 70

24 63 63 63 63 93 93 84

70 70 70 70 70 84 84 93

Quick Sort:
Pass 1: Pass 2: Pass 3: Pass 4: Pass 5: Pass 6: Pass 7: 24 04 04 04 04 04 04 04 24 18 18 18 18 18 18 18 24 24 24 24 24 30 30 30 30 30 30 30 84 84 84 84 58 43 43

(Key Element is Middle Element)


43 43 43 43 43 58 58 63 63 63 63 63 63 63 93 93 93 93 93 93 70 58 58 58 58 84 84 84 70 70 70 70 70 70 93

Note: (Key element is First element or middle element) take the key element and then find the bigger element before key, find the smaller element after key and interchange those two. Now Take the elements before key element into one array & after key element into another array.

Radix Exchange Sort:


Given Binary Pass1 Numbers equivalents 24 58 63 84 30 43 18 93 04 0011000 0111010 0111111 1010100 0011110 0101011 0010010 1011101 0000100 Pass2 Pass3 Pass4 Pass5 Pass6 Pass7 Sorted Elements 04 18 24 30 43 58 63 70 84 93

0011000 0011000 0111010 1010100 1010100 0000100 0011110 1011101 0010010 0111010 0000100 0011110 1000110 0010010 0111111 1000110

0011000 0010010 0000100 0111010 1010100 1000110 0010010 0000100 0101011 0101011 1000110 0010010 1010100 0011000 1010100 0000100 0111010 0011000 1011101 0101011 0111010 0011110 1011101 1011101

0000100 0000100 1000110 0010010 0010010 0011000 1010100 0011110 0011000 0101011 1011101 0111010 0011110 0111111 0101011 1000110 0111010 1010100 0111111 1011101

0101011 0111111 1000110 0011110 0011110 1011101 0101011 0111111 0111111 0111111

70 1000110

81

Note: Convert decimal numbers into its Binary equivalents. Units place is sorted in the 1st pass,10s place is sorted in the 2nd pass,100s place is sorted in the 3rd pass, 1000s place is sorted in the 4th pass, 10000s place is sorted in the 4th pass, 100000s place is sorted in the 5th pass, 1000000s place is sorted in the 6th pass, 10000000s place is sorted in the last pass.

Heap Sort:

24 58 63 84 30 43 18 93 04 70

After Heap Given Elements are : 93 84 58 63 70 43 18 24 04 30


Pass 1: Pass 2: Pass 3: Pass 4: Pass 5: Pass 6: Pass 7: Pass 8: Pass 9: 84 70 63 58 43 30 24 18 04 70 63 30 30 30 24 04 04 18 58 58 58 43 18 18 18 24 24 63 24 24 24 24 04 30 30 30 30 30 04 04 04 43 43 43 43 43 43 43 18 58 58 58 58 58 18 18 18 63 63 63 63 63 63 24 04 70 70 70 70 70 70 70 04 84 84 84 84 84 84 84 84 93 93 93 93 93 93 93 93 93

Note: Create maximum heap with the given elements. Interchange First element with last element(maximum element go to last position). Then create with all the elements except sorted elements, interchange first element with last element (elements used for heap).

QUIZ QUESTIONS 1.What is the basic operation in computer science ? 2. What are the total comparisons in bubble sort? 3. What is sort & searching ? 4. Explain types of sort ? 5. In which sort the sorting list is divided into two sub lists? 6. What is the another name of exchange sort ? 7. What is the worst case time complexity of linear search ? 8. What is the worst case time complexity of binary search ? 9. What is the worst case time complexity of bubble sort ? 10 .What is the worst case time complexity of quick sort ? 11. What is the worst case time complexity of heap sort ? 12. What is the best case complexity of an insertion sort ? 13. The number of swaps in the bubble sort are far less then that of a selection sort ? T/F 14. In merge sort the merging operation is done using an auxiliary array ? T/F 15. Binary search can be used on an unsorted list ? True/False 16. What is the average time complexity of the Quick sort ? 17. Which sorting technique have need not swapping ? 18 . What is the advantage of the binary search ? 19. What is heap sort ? 20. What are the factors to be considered during the selection sort ? 21. What is quick sort ? 22. What is the need for an ordered table searching? 23. What is hashing ? 24. what is the need for hashing ? 25. What is radix sort ? 26. What is another name of shell sort ? 82

27. What the time complexity of the shell sort / 28. What is another name of radix sort ? 29. One of the examples of sort by distribution is radix sort ? True / False 30. In how many categories the sorting algorithms are classified ? Review Questions What is sorting and searching? How are they essential for database applications? Explain search methods. Make a distinction between linear and binary search. Explain types of sort. Distinguish between selection and exchange sort. Write a program to sort 10 elements using exchange sort. Write a program to find the given number in an array of 100 elements. Determine how many times it occurs in a given list. 8. Write a program to demonstrate binary search. Use character array and store 10 names. 9. Write a program to search the given name in a string array of 10 names. 10. Write a program to demonstrate successful and unsuccessful search. Display appropriate messages. 11. Sort the following lists in ascending order using selection sort: i) 56, 57, 92, 38, 44, 90, 61, 73. ii) D, A, T, A, S, T, R, U, c, I, U, R, E. 12. What is a quick sort? How does it differ from the bubble sort? 13. Write a C program to implement the insertion sort. Analyze its time requirements. 14. How many comparisons are required to sort an array of 50 elements using selection sort, if the original array values were already sorted ? 1. 2. 3. 4. 5. 6. 7.

83

You might also like