+ All Categories
Home > Documents > Cpds Lab Manualdasdas

Cpds Lab Manualdasdas

Date post: 28-Oct-2015
Category:
Upload: san-geetha-b-c
View: 87 times
Download: 0 times
Share this document with a friend
Description:
dsadasdsa
111
CMR Institute of Technology Redefining Quality Education COMPUTER PROGRAMMING AND DATA STRUCTURES LABORATORY MANUAL For I - B.TECH (2010-11) Department of Computer Science & Engineering CMR INSTITUTE OF TECHNOLOGY Kandlakoya (v), Medchal road, Hyderabad-501 401 I - B.Tech CPDS Lab Manual 0
Transcript
Page 1: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

COMPUTER PROGRAMMING AND DATA STRUCTURES

LABORATORY MANUAL For

I - B.TECH (2010-11)

Department of Computer Science & Engineering CMR INSTITUTE OF TECHNOLOGY

Kandlakoya (v), Medchal road, Hyderabad-501 401

I - B.Tech CPDS Lab Manual 0

Page 2: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

COMPUTER PROGRAMMING LAB Objectives: To make the student learn a programming language. To teach the student to write programs in C to solve the problems. To Introduce the student to simple linear data structures such as lists, stacks, queues. Recommended Systems/Software Requirements: Intel based desktop PC ANSI C Compiler with Supporting Editors Week l. a) Write a C program to find the sum of individual digits of a positive integer. b) A Fibonacci Sequence is defined as follows: the first and second terms in the sequence are 0 and 1.Subsequent terms are found by adding the preceding two terms in the sequence. Write a C program togenerate the first n terms of the sequence. c) Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied by the user. Week 2. a) Write a C program to calculate the following Sum: Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! b) Write a C program toe find the roots of a quadratic equation. Week 3 a) Write C programs that use both recursive and non-recursive functions i) To find the factorial of a given integer. ii) To find the GCD (greatest common divisor) of two given integers. iii) To solve Towers of Hanoi problem. Week 4 a) The total distance travelled by vehicle in ‘t’ seconds is given by distance = ut+1/2at2 where ‘u’ and ‘a’ are the initial velocity (m/sec.) and acceleration (m/sec2). Write C program to find the distance travelled at regular intervals of time given the values of ‘u’ and ‘a’. The program should provide the flexibility to the user to select his own time intervals and repeat the calculations for different values of ‘u’ and ‘a’. b) Write a C program, which takes two integer operands and one operator from the user, performs the

I - B.Tech CPDS Lab Manual 1

Page 3: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

operation and then prints the result. (Consider the operators +,-,*, /, % and use Switch Statement) Week 5 a) Write a C program to find both the largest and smallest number in a list of integers. b) Write a C program that uses functions to perform the following: i) Addition of Two Matrices ii) Multiplication of Two Matrices Week 6 a) Write a C program that uses functions to perform the following operations: i) To insert a sub-string in to a given main string from a given position. ii) To delete n Characters from a given position in a given string. b) Write a C program to determine if the given string is a palindrome or not Week 7 a) Write a C program that displays the position or index in the string S where the string T begins, or – 1 if S doesn’t contain T. b) Write a C program to count the lines, words and characters in a given text. Week 8 a) Write a C program to generate Pascal’s triangle. b) Write a C program to construct a pyramid of numbers. Week 9 Write a C program to read in two numbers, x and n, and then compute the sum of this geometric progression: 1+x+x2+x3+………….+xn For example: if n is 3 and x is 5, then the program computes 1+5+25+125. Print x, n, the sum Perform error checking. For example, the formula does not make sense for negative exponents – if n is less than 0. Have your program print an error message if n<0, then go back and read in the next pair of numbers of without computing the sum. Are any values of x also illegal ? If so, test for them too. Week 10 a) 2’s complement of a number is obtained by scanning it from right to left and complementing all the bits after the first appearance of a 1. Thus 2’s complement of 11100 is 00100. Write a C program to find the 2’s complement of a binary number. b) Write a C program to convert a Roman numeral to its decimal equivalent.

I - B.Tech CPDS Lab Manual 2

Page 4: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Week 11 Write a C program that uses functions to perform the following operations: i) Reading a complex number ii) Writing a complex number iii) Addition of two complex numbers iv) Multiplication of two complex numbers (Note: represent complex number using a structure.) Week 12 a) Write a C program which copies one file to another. b) Write a C program to reverse the first n characters in a file. (Note: The file name and n are specified on the command line.) Week 13 a) Write a C programme to display the contents of a file. b) Write a C programme to merge two files into a third file ( i.e., the contents of the first file followed by those of the second are put in the third file) Week 14 Write a C program that uses functions to perform the following operations on singly linked list.: i) Creation ii) Insertion iii) Deletion iv) Traversal Week 15 Write C programs that implement stack (its operations) using i) Arrays ii) Pointers Week 16 Write C programs that implement Queue (its operations) using i) Arrays ii) Pointers Week 17 Write a C program that uses Stack operations to perform the following: i) Converting infix expression into postfix expression ii) Evaluating the postfix expression

I - B.Tech CPDS Lab Manual 3

Page 5: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Week 18 Write a C program that implements the following sorting methods to sort a given list of integers in ascending order i) Bubble sort ii) Selection sort Week 19 Write C programs that use both recursive and non recursive functions to perform the following searching operations for a Key value in a given list of integers : i) Linear search ii) Binary search Week 20 Write C program that implements the following sorting method to sort a given list of integers in ascending order: i) Quick sort Week 21 Write C program that implement the following sorting method to sort a given list of integers in ascending order: i) Merge sort Week 22 Write C programs to implement the Lagrange interpolation and Newton- Gregory forward interpolation. Week 23 Write C programs to implement the linear regression and polynomial regression algorithms. Week 24 Write C programs to implement Trapezoidal and Simpson methods. Text Books 1. C programming and Data Structures, P. Padmanabham, Third Edition, BS Publications 2. Mastering C, K.R. Venugopal and S.R. Prasad, TMH Publications.

I - B.Tech CPDS Lab Manual 4

Page 6: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

3. The Spirit of C, an introduction to modern programming, M.Cooper, Jaico Publishing House. 4 Practical C Programming,Steve Oualline,O’Reilly,SPD. TMH publications. 5. Computer Basics and C Programming, V. Rajaraman, PHI Publications. 6. Data structures and Program Design in C,R.Kruse,C.L.Tondo,B.P.Leung,M.Shashi,Pearson Education.

I - B.Tech CPDS Lab Manual 5

Page 7: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

CONTENTS

S No

Program Name

Page no

PART-A INTRODUCTION 1 a) Sum of individual digits of a positive integer

b) Fibonacci sequence c) Prime numbers between 1 and n.

26

2 a) Calculate Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! b) To find the roots of a quadratic equation

29

3 a) C programs that use both recursive and non-recursive functions i) To find the factorial of a given integer. ii) To find the GCD (greatest common divisor) of two given integers. iii) To solve Towers of Hanoi problem.

31

4 a) C program to find the distance traveled at regular intervals of time given the values of ‘u’ and ‘a’. b) To perform arithmetic operations using switch.

36

5 a) Find both the largest and smallest number in a list of integers. b) C program that uses functions to perform i) Addition of Two Matrices ii) Multiplication of Two Matrices

39

6 a) C program that uses functions to perform the following operations: i) To insert a sub-string in to a given main ii) To delete n Characters from a given position b) C program to determine if the given string is a palindrome or not

43

7 a) C program that displays the position of the sub string in a main string b) C program to count the lines, words and characters in a given text.

46

I - B.Tech CPDS Lab Manual 6

Page 8: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

8 a) C program to generate Pascal’s triangle.

b) C program to construct a pyramid of numbers 48

9 C program to read in two numbers, x and n, and then compute the sum of this geometric progression:1+x+x2+x3+………….+xn

50

10 a) C program to find the 2’s complement of a binary number. b) C program to convert a Roman numeral to its decimal equivalent.

51

11 C program that uses functions to perform the following operations: i) Reading a complex number ii) Writing a complex number iii) Addition of two complex numbers iv) Multiplication of two complex numbers (Note: represent complex number using a structure.)

54

12 a) C program which copies one file to another. b) C program to reverse the first n characters in a file.

56

13 a) Write a C program to display the contents of a file. b) Write a C program to merge two files into a third file

58

PART-B 14 C program that uses functions to perform the

following operations on singly linked list. i) Creation ii) Insertion iii) Deletion iv) Traversal

61

15 C programs that implement stack (its operations) using i) Arrays ii) Pointers

69

16 C programs that implement Queue (its operations) using i) Arrays ii) Pointers

76

17 C program that uses Stack operations to perform the following: i) Converting infix expression into postfix expression ii) Evaluating the postfix expression

83

I - B.Tech CPDS Lab Manual 7

Page 9: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

18 C program that implements the following sorting methods to sort a given list of integers in ascending order i) Bubble sort ii) Selection sort

88

19 C programs that use both recursive and non recursive functions to perform the following searching operations for a Key value in a given list of integers : i) Linear search ii) Binary search

92

20 C program that implements the following sorting method to sort a given list of integers in ascending order i) Quick sort

98

21 C program that implement the following sorting method to sort a given list of integers in ascending order: i) Merge sort

101

22

C programs to implement the Lagrange interpolation and Newton- Gregory forward interpolation

103

23 C programs to implement the linear regression and polynomial regression algorithms.

106

24 C programs to implement Trapezoidal and Simpson methods.

108

I - B.Tech CPDS Lab Manual 8

Page 10: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

PROGRAM DEVELOPMENT STAGES: a) Program design: At this stage define a problem and its solution. problem specification: the program must be thoroughly understand the problem and the input output and special processing specification represent the most important information collection during this phase.

Solution: The solution method is to be developed. b) Using planning tools: The solution method is described step by step when

solution method had been outlined. It must be represent by using alorithm notations or flow charts symbols.

c) Coding: It is relatively easier to convert the algorithm into a program in a computer language i.e. C,C++.

d) Compiling: Translate the program into machine code. typing errors(syntax errors) are found quickly at the time of compiling the program most C implementations will generate diagnostic messages when syntax errors are detected during compilation.

e) Executing: Running the program the run time errors may occur during the execution of programs even though it is free from syntax errors.

Syntactic & Run time errors generally produce error messages when program executed. These are easy to find and can be corrected. The logical error which is very difficult to detect. These are existence of logically incorrect instructions. These errors can be know only after output is executed. f) Testing and validation: Once program is written , a program must be tested and

then validated. The program always must guarantee to produce correct results. In above stages a), b),c) are purely manual process. remaining all

stages related its computer. ALGORITHM: A method of representing the step by step logical procedure for solving program in natural language is algorithm. SPARSE NOTATIONS FOR ALGORITHAMS:

1) General form of PROCEDURE Procedure NAME (parameter list) Declarations Statements end NAME 2) General form of FUNCTION

Function NAME (parameter list) Declarations Statements end NAME

I - B.Tech CPDS Lab Manual 9

Page 11: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

3) For comment line: // This is comment// 4) Variable declaration : integer x ,y; char c, d; Boolean a,b; 5) Assignment of variables <variable> <expression> 6) Boolean values: true ,false 7) Logical operators: and , or , not 8) Relational operators: < , <= , = , >=, > 9) Conditional statement: a) if cond then s1 else s2 endif

b) case : cond 1: s1 : cond 2 : s2 …………. : cond :n : else : s n+1

end case 10) Iterative statements:

a) while condition do s repeat b) loop s until condition repeat c) for vble <- start to finish by increment do s repeat

11) Input read (argument list); Output print(argument list); FLOWCHART:

There is another way to write the steps involved in any process ,this is by making use of various symbols . The symbols form a diagram that represents the steps in a pictorial fashion similar to an algorithm. This is also very easy to understand such a diagram is flow chart. Flowcharts help us understand the logic of an operation easily. They are good communication devices and also helps in algorithm maintenance. The most common symbols using drawing flow charts are given below:

I - B.Tech CPDS Lab Manual 10

Page 12: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

FLOWCHART SYMBOLS: Oval Terminal start/stop/begin/end Making data available for Input/ processing(Input) or Parallelogram Output recording of the process Document Print out Show data output in the Form of document Any processing to be done A process changes or

Rectangle Process moves data. An assignment Operation. Decision or switching type Diamond Decision of operations. Used to connect different Circle Connector parts of flowchart. Joins two symbols and Arrow Flow also represents flow of Execution. Bracket with Annotation Descriptive comments or Broken line explanation. Double sided Predefined Modules or subroutines Rectangle process specified elsewhere.

I - B.Tech CPDS Lab Manual 11

Page 13: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Special Symbols: if-else statement: For statement: F While statement::

Condition

Statements

Statements

Input n

Start i=0 i<n i++

false true

End

condition

statements

End

Switch statement: do-while

true

variable Body of first case

true

false

equals second case Body of second case

End

Statements

true

End

condition

Body of Default false

I - B.Tech CPDS Lab Manual 12

Page 14: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

STARTING TO TURBO 'C':Double clicking the mouse's left button on a

Turbo C icon or

By clicking start, selecting programs and then clicking Turbo C or Selecting MS-DOS prompt mode and change the directory to TC or Turbo C and then type TC at the DOS prompt and press Enter. Turbo C opens and displays a main menu. Pressing any key removes the version copyright notice, and places the cursor on the File option of the menu bar. HOT KEYS IN TURBO 'C':

F1 Provides context-sensitive help for the items selected. F2 Save the current file to disk. F3 Window to enter file name to load. F5 Toggle: Zoom or Unworn active window. F6 Switch to active window. F7 Move to previous error. F8 Move to next error. F10 Go to the top line of main menu bar. ALT-F5 To view the results. Alt-F9 Compile current file to .OBJ. Alt-D Pull-down Debug menu. Alt-E Go to Edit mode. Alt-F Pull-down File menu. Alt-O Pull-down Options menu. Alt-R Pull-down Run menu (may Compile Link first). Alt-X Exit from the Turbo C to DOS/Windows desktop. Ctrl-F9 Run the current file. Esc To cancel the running command. C SYNTAX Structure of 'C' Program: Documentation section ex: /*name of the program*/ Link section #include<stdio.h> Definition section Global declaration section main( ) function section main() { { Declaration part int i=10; Execution part printf("%d",i); } }

I - B.Tech CPDS Lab Manual 13

Page 15: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Sub program section Function 1 Function 2 ………… Documentation section: It consists with name of the program and other details. Link section: It provides header files to the computer to link library functions. Definition section: It defines all Symbolic constants. Global declaration section: It declares Global variables which are useful in all functions of the program. main( ) function section: It consists with declaration part and executable part. Sub program section: It contains the entire user defined functions called in main

function. Character set: The Character set in C are grouped into 1)Letters,2)Digits, 3)Special characters.

a) Alphabets: A,B,C…….Z; a, b, c ……z. b) Digits 0,1,2……..9.

c) Special character: @,#,$,^………….etc. Key words: These are pre defined words have a fixed meanings. All key words must be written in lower case letters.

Auto break case char const char continue default do double

else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

Constants: Constants in C refer to fixed values do not change during the execution of the program.

1) Integer constant: It refer to a sequence of digits, 0 through 9 preceded by - or +. Ex: 149, -980, +45. 2) Real constants: the quantities which are represented by numbers containing fractional part. Ex:0.78, 2.45. It is also represented in exponential notation Ex: the value 4356.78 can represented as 4.35678e3. 3) Single character constant: It contains a character enclosed within a

pair of single quote marks. Ex: '2' , 'a' .

I - B.Tech CPDS Lab Manual 14

Page 16: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

4) String constant: It is a sequence of characters enclosed in double quotes.

Ex: "india" , "2*3", "n". 5) Back slash character constant(Escape sequences):

'\n' for new line '\t' for horizontal tabulator '\v ' for vertical tabulator '\0' Null character.

Data Types: Data type size range int 2 bytes -32,768 to 32,767 char 1 byte -128 to 128 float 4 bytes -3.4e-38 to 3.4e+38 double 8 bytes -1.7e-308 to1.7e+308 Variables: It is a data name that may be used to store value. Variable name may

consist of letters ,digits, underscore(_) characters subject to the following conditions: 1) Variable must begin with letter. 2) Variable name should not be more than 8 characters. 3) Upper case and Lower case are significant. 4) Variable name should not be key word. 5) White space is not allowed.

Declaration of variables: Declaration tells to the compiler variable name with specifying data type.

a) Primary type : Syntax : data-type variable1,variable2,……..variable n;

Ex : float marks; b) User defined type : C supports a feature known as type definition that allows user to define an identifier. Syntax : typedef data-type identifier;

Ex: typedef int units; c) Enumerated data type: It contains enumeration constants represented by identifiers. Syntax: enum identifier { value 1,value 2,…..value n};

Ex: enum day { Monday, Tuesday,……Sunday};

d) Declaring variable as constant: The value of variable can be made to remain constant. syntax: const data-type variable = value;

Ex : const int max = 40;

I - B.Tech CPDS Lab Manual 15

Page 17: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

e) Declaring variable as volatile :The value of variable may be changed by some external reasons from out side. Syntax : volatile data-type variable;

Ex : volatile int date ; Declaration of storage classes: a) Automatic variable: Local variable known to only to the function in which is declared default is auto .

syntax : auto data-type variable; Ex : auto int number;

b) Extern variables: Global variable known to all functions in the file. It is used to crossing files.

Syntax: extern data-type variable; Ex: extern int number; c) Static variables: Local variable, which exists and retains its value even after the control is transferred to the calling function.

Syntax : static data-type variable; Ex :static int x;

d) Register variables: Local variable, which is stored in the CPU register. It is fast access variable. Syntax : register data-type variable;

Ex :register int x; ** Very local variables are more priority than local, local variables are more priority than global.

Assigning values to variables: Value can be assigned to variables using the assignment operator. Syntax : data-type variable-name =constant; Ex: int units =123; Multiple assigning : Ex : x = y= z = max; Type casting: C allows, if the operation are of different it types the lower type is converted to the higher type to before operation proceed. Syntax : (type-name) expression/value; Ex: x = (int) 7.5 result = 7 Abstract data type: It is a tool which specifies the logical properties of a data type . Syntax: abstract typedef < integer , integer > RATIONAL Defining symbolic constants: This is useful when a constant will be used number of places in a program. # define symbolic-name value Ex : #define MAX 100 # define PI 3.14159

I - B.Tech CPDS Lab Manual 16

Page 18: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Operators: a) Arithmetic operators: +, - , * , / , %

b)Assignment operators: Use to assign result of expression to variable. = operator

c) Relational operators: These are used to compare two operands and then depend on their relation certain decision are made.

< ,> , <= , >= ,!= ,==, d) Increment operators: Used for incrementing by 1. ++var (pre) ,var++ (post) e) Decrement operators: Used for decrementing by 1. --var (pre), var-- (post) f) Bit operators: These are low level operators it works only on integers used for testing and shifting bits. & (and), | (or) ,<< (left shift) ,>>(right shift) , ^(ones compliment)

g) Logical operators :These operators are used test more than one condition. The result must be in either TRUE or FALSE. Logical not operator changes TRUE to FALSE vise versa. && (and) , || (or) , ! ( Logical not) f) comma operator: It is used to combine two related expressions. ( , )

Precedence of operators:

Operator priority * / % high + - low Note: evaluate from left to right

Format descriptor: %d for signed decimal integer %u for unsigned decimal integer %s for string %f for float %c for character

Input / Output functions: These functions permit the transfer data between computer and the standard input/output devices.

a) Formatted I/O Functions: Used to transfer single character, numerical values, strings.

Output syntax printf( "control string", arg1, arg2,………….argN); Ex: printf ("%c", a); Input syntax: scanf( "control string ", & var1,&var 2,……&var n); Ex: scanf("%d", &x);

I - B.Tech CPDS Lab Manual 17

Page 19: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

b)Character I/O Functions: Used to transfer single character. Input syntax: char variable = getchar(); Output syntax: putchar(char variable); c) String I/O Functions: Used to transfer strings. Input syntax: gets(string); Output syntax : puts(string); Control flow structures: 1)Selective control structure(conditional structures):

a) Simple if statement: syntax: if(condition)

{ statement-block; }

b) if-else statement syntax: if(condition)

{ statement-block; } else { statement- block; } c) else if statement syntax: if(condition 1) { statement-block; } elseif(condition 2) { statement-block; } else { statement-block; }

c) nested if-else statement

syntax: if(condition1) { if(condition 2) { statement-block; } else { statement-block; }

I - B.Tech CPDS Lab Manual 18

Page 20: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

else { statement-block; }

d) switch statement :It provides an alternative of several if statements.

Syntax: switch (expression) { case value1: statement 1; break; case value2: statement 2; break; …………….. ……………. Default: statements; break; }

e) Ternary operator ( ? : ): It is used replace the statements in the

form if-then-else syntax: conditional expression ? expression 1: expression 2 Ex: flag = (x<0) ? 0 : 1

Iterative control structure(Repetitive structures): These structures repeats sequence of instructions until condition satisfies.

a) while loop: syntax: while(expression) { statement: } b) do - while loop: The statements in the loop are executed

and the testing done at the end of loop. syntax: do { statement; } while(condition); c) for loop:

syntax: for ( initialization ; condition ; increment) { statement; } d) break statement: It transfer the control to the end of the construct.

if(condition)

I - B.Tech CPDS Lab Manual 19

Page 21: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

break; e) continue statement: It transfers the control to next iteration by skipping following statements. if(condition) continue;

f) goto statement: It transfer control to the statement that follows the label where it is defined.

if( condition) goto label Arrays: An array is a group of related data items that share a common name a) One dimensional array: It is a list of items can be given a variable name using only one subscript. syntax : data-type array-name [array-size]; Ex: int number[10]; Initialization: syntax: data-type array-name [array-size]={list of values}; Ex: int number [5] = {1,4,6,10,32 };

b) Two dimensional array : It is a list of items can be given a variable name using two subscripts.

Syntax: data-type array-name [row-size][column-size]; Ex: int table[2][4]; Initialization : data-type array-name[row-size][column-size]={list of values}; Ex: int table[2][4]={ {1,6,4,8,9},{4,3,8,5}};

a) Multi dimensional array: syntax: data-type array-name [s 1][s 2][s3]……..[sn]; Ex: float table [4][5][2]; String: String is an array of characters terminated by the null character.

a) String declaration: syntax: char string-name[size]; Ex: char city[10]; Initialization: Ex : char city[10]= "hyderabad"; b) String functions: String concatenation strcat(s1,s2); String comparison int n= strcmp(s1,s2); String copying strcpy(s1,s2) ; String length int n=strlen(string);

Pointers: It is nothing but a variable that contains the address of another variable.

Pointer&variable: Declaration of pointer variable: Syntax: data-type * pointer-variable; Ex: int *p; (integer pointer) char *p; (character pointer) float*p; (float pointer)

I - B.Tech CPDS Lab Manual 20

Page 22: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Initialization: Syntax: pointer-variable= &variable; Ex: int a=10; int*p; p=&a;

Pointers to pointer: Syntax : data-type ** pointer variable; Declaration of void pointer : Syntax: void * pointer-variable; Ex: void * e; e= &a;

Pointers & arrays: Declaration of array of pointers: Syntax: data-type *variable[size]; Ex: char *ptr[5]; Declaration of pointer to array: Ex: (int *p) [5]; Pointers &functions: Declaration of pointer to function; Syntax: return-type data-type (*fptr)(fun.arg.list); Ex : int test (double); int(*p)(double); p=test; Pointers &structures: Declaration of pointer to structures: Syntax : Struct tag { data-type member1; data-type member2; ……….. }: struct tag * p,a; p=&a; Accessing structure contents by pointer variable

a) Dot operator ( . ) ex : (*ptr).member1; b) Arrow operator (->) ex: ptr-variable->

member1;

Structure with pointers: Ex: struct node { int data; struct node * link;(link is a pointer to structure) };

I - B.Tech CPDS Lab Manual 21

Page 23: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Functions: It is meant for performing a specific task which is repeated each time the program calls it. Functions are two types 1) Library functions 2) User defined functions.

Function definition(called function): It introduces a new function by declaring type of value it returns and parameters.

Syntax: function-name(formal arg-list) argument declaration: { local variable declaration; executable statement1; ……………… return(expression); } Function declaration(function call): Syntax: function-name (actual arguments); Actual arguments: These parameters used in calling function. They may be constant or variable. Formal arguments: These parameters used in called function. These must be variable.

Command line Arguments: It is a parameter applied to a program when program is invoked. Syntax: main(arg c, arg v) argc(argument counter) : It is an integer variable which contains number of arguments. argv(argument vector):It is an array of string, it contains arguments passed from command line. argv[0] always specifies name of the program. Structures: It is a collection of logically related data items of different types using a single name. Structure allocates separate memory space for each member.

Structure definition: It creates a format of structure variables that may be used in structure. syntax: struct structure-name Ex: struct student { { data-type variable 1; int rollno: data-type variable 2; float marks; ……………………; ………….; }; }; Structure declaration: It allocates a memory for declared structure. syntax: struct structure-name variable1,variable2……; ex: struct student s1,s2,s3;

I - B.Tech CPDS Lab Manual 22

Page 24: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Structure initialization: ex : struct student s1={ 123 , 67.89}; Accessing structure contents: Syntax : Dot operator ( . ) structure-name . structure-member; Arrow operator(->) pointer to structure. Structure member.

Union: It permits several different data types to be stored in the same memory space on single name. Union save the memory space but it can handle only one member at a time.

Union definition: Syntax: union union-name { data-type member 1; data-type member 2; …………………

};

Union declaration: syntax : union union-name variable;

Memory Allocation Functions: Memory allocation classified in to two categories.

1) Static memory allocation, which is at, compiles time. 2) Dynamic memory allocation which is at run time.

a) Allocating a block of memory: Syntax: ptr = (cast-type*) malloc(n* (sizeof(data-type));

b) Allocating multiple blocks of memory: Syntax: ptr=(cast-type*) calloc (n, sizeof(data-type)); c) Releasing the used space:

Syntax: free(ptr); d) Altering the size block: Syntax : ptr = realloc(ptr, newsize);

File Handling Functions: File is a collection of similar type of records. fwrite(), fread() files are binary files ,remaining files are ASCII files

a) Declaration of file pointer: Syntax: FILE *fp;

b) File opening: Syntax: fp = fopen("filename",mode); if mode = r Open in reading mode. = w Open in writing mode.

c) File closing: Syntax: fclose(fp); d) Character i/o from files Syntax: fgetc(fp); fputc( character,fp); e) String i/o with files: syntax: fgets( string,length,fp);

I - B.Tech CPDS Lab Manual 23

Page 25: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

fputs(string,fp); f) Formatted i/o with files fscanf(fp,"control string",list); fprintf(fp,"control string",list);

f) Records i/o with files: Used to perform i/o operations on binary files.

fwrite( &structure,size of one record,,no.of records,fp); fread( &structure,size of struct,no. of records,fp); h) Random access to files: To returns current offset position in the file. long int n=ftell(fp); To reposition the pointer at the beginning of file rewind(fp); To shift in current position on a file. fseek(fp,offset,position);

i) Error handling: Test end of file condition.

Syntax: feof(fp); Test status of file an error has been detected. Syntax: ferror(fp); DOS CAMMANDS The book is summarizes the main features and used of data structures, using C programming language under MS_DOS operating system, hence the following DOS commands helps to use the operating system

File: A file consists of group of characters. A file consists of two parts: 1. File name Ex: STAFF 2. Extension Ex: TXT, .EXE, .COM, .DOC, .DAT, .PAS, .C, .CPP, AND.BAT Directory: A directory is nothing but group of files like:

Ex: File name file size date of creation time of creation

CMRIT.EXE 22 27-08-03 12.00AM

DOS Commands: There are basically two types of commands:

1. Internal Commands

2. External Commands 1. Internal Commands: These commands are generally loaded when an operating

system itself is loaded into the memory. So these commands are stored in computer main memory. Ex: CLS, DIR, TYPE, TIME, DATE, REN etc.

2. External Commands: These commands are stored in Disk Files. Stored in

Secondary memory like disk. Ex: FORMAT, MEM etc.

MS-DOS Prompt: C: \ MYDIR

TIME: This command displays time of system and ask the user to change if he wants

I - B.Tech CPDS Lab Manual 24

Page 26: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Syntax: TIME

DATE: This command displays date of the system and asks the user to change

if he wants. Syntax: DATE

DIR: This command displays contents in the directory.

Syntax: DIR </Options>

COPY : By using this command a user can copy various file into another file and

also copy a group files from one directory to other directory and also copy a group

files from one disk to the other disk. .

Syntax: COPY <File1> <File2>

COPY <File1><Directory Name>

COPY < Disk1 > < Disk>

Ex: COPY my.txt your.txt

COPY my.txt c:\tc

COPY c: \my. txt a:

TYPE: Displays the content of the file Syntax: TYPE <FILE>

Ex: TYPE AUTOEXEC.BAT REN: Renames one file to another name. It will changes the filename. Syntax: REN <File!> <File2> Ex: REN my.txt cmrcet.txt CLS: Clears the screen Syntax: CLS Ex: CLS

CD: Changes the directory

Syntax: CD <Directory Name>

Ex: CD CMRIT

Changes from any directory to Parent directory CD\ Changes from any Directory to Root directory MD: Creates a new sub-directory. A sub-directory is nothing but directory with in a Directory Syntax: MD<Directory Name>

I - B.Tech CPDS Lab Manual 25

Page 27: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

C PROGARMS WEEK—1

1a)/* A Fibonacci Sequence is defined as follows: the first and second terms in the sequence are 0 and 1. Subsequent terms are found by adding the preceding two terms in the sequence. Write a C program to generate the first n terms of the sequence.*/

Program: #include <stdio.h> void main() { int num1=0, num2=1,no,counter,fab; clrscr(); printf("<===========PROGRAM TO FIND THE FIBONACCI SERIES UP TO N NO. IN SERIES=========>"); printf("\n\n\n\t\tENTER LENGTH OF SERIES (N) : "); scanf("%d",&no); printf("\n\n\t\t\t<----FIBONACCI SERIES---->"); printf("\n\n\t\t%d %d",num1,num2); //LOOP WILL RUN FOR 2 TIME LESS IN SERIES AS THESE WAS PRINTED IN ADVANCE for(counter = 1; counter <= no-2; counter++) { fab=num1 + num2; printf(" %d",fab); num1=num2; num2=fab; } getch(); } Result:

<===========PROGRAM TO FIND THE FIBONACCI SERIES UP TO N SERIES=========> ENTER LENGTH OF SERIES (N) :5 <----FIBONACCI SERIES---->" 0 1 1 2 3

I - B.Tech CPDS Lab Manual 26

Page 28: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

1.b) /* Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied by the user. */

Program:

#include <stdio.h> void main() { int no,counter,counter1,check; clrscr(); printf("<-----------------------PRIME NO. SERIES------------------------>"); printf("\n\n\n\t\t\tINPUT THE VALUE OF N: "); scanf("%d",&no); printf("\n\nTHE PRIME NO. SERIES B/W 1 TO %d : \n\n",no); for(counter = 1; counter <= no; counter++) { check = 0; //THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT. for(counter1 = counter-1; counter1 > 1 ; counter1--) if(counter%counter1 == 0) { check++; // INCREMENT CHECK IF NO. IS NOT A PRIME NO. break; } if(check == 0) printf("%d\t",counter); } getch(); } Result:

<-----------------------PRIME NO. SERIES------------------------> INPUT THE VALUE OF N:10 0 1 2 3 5 7

I - B.Tech CPDS Lab Manual 27

Page 29: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

1.c) /* Write a C program to find the sum of individual digits of a positive integer.*/

Program:

#include<stdio.h> #include<conio.h> void main() { int num, k=1, sum=0; clrscr(); printf("Enter the number whose digits are to be added:"); scanf("%d",&num); while(num!=0) { k=num%10; sum=sum+k; k=num/10; num=k; } printf("Sum of the digits:%d",sum); getch(); } Result:

Enter the number whose digits are to be added:1234 Sum of the digits:10

I - B.Tech CPDS Lab Manual 28

Page 30: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-2 2.a) /* Write a C program to calculate the following Sum: Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! */

Program:

#include <stdio.h> #include <math.h> void main() { int counter,f_coun; float sum=0,x,power,fact; clrscr(); printf("<-----------------------PROGRAM FOR SUM OF EQ. SERIES----------------------->"); printf("\n\n\tEQUATION SERIES : 1- X^2/2! + X^4/4! - X^6/6! + X^8/8! - X^10/10!"); printf("\n\n\n\tENTER VALUE OF X : "); scanf("%f",&x); for(counter=0, power=0; power<=10; counter++,power=power+2) { fact=1; //CALC FACTORIAL OF POWER VALUE for(f_coun=power; f_coun>=1; f_coun--) fact *= f_coun; //EQ. FOR SUM SERIES sum=sum+(pow(-1,counter)*(pow(x,power)/fact)); } printf("SUM : %f",sum); getch(); }

Result: <-----------------------PROGRAM FOR SUM OF EQ. SERIES-----------------------> ENTER VALUE OF X:2 SUM :0.5840

I - B.Tech CPDS Lab Manual 29

Page 31: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

2.b)/* Write a C program toe find the roots of a quadratic equation. */

Program: #include<stdio.h> #include<conio.h> #include<math.h> void main() { float a,b,c,root1,root2; clrscr(); printf("\n Enter values of a,b,c for finding roots of a quadratic eq:\n"); scanf("%f%f%f",&a,&b,&c); /*checking condition*/ if(b*b>4*a*c) { root1=-b+sqrt(b*b-4*a*c)/2*a; root2=-b-sqrt(b*b-4*a*c)/2*a; printf("\n*****ROOTS ARE*****\n"); printf("\n root1=%f\n root2=%f",root1,root2); } else printf("\n Imaginary Roots."); getch(); }

Result: Enter values of a,b,c for finding roots of a quadratic eq: 4,5,6 Roots are real and imaginary. Enter values of a,b,c for finding roots of a quadratic eq: 2,3,4 Roots are imaginary Root1=00.750000+j1.198958 Root2=-0.750000-j1.198958.

I - B.Tech CPDS Lab Manual 30

Page 32: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-3 3.a) /* Write C programs that use both recursive and non-recursive functions To find the factorial of a given integer.*/

Program: #include<stdio.h> #include<conio.h> unsigned int recr_factorial(int n); unsigned int iter_factorial(int n); void main() { int n,i; long fact; clrscr(); printf("Enter the number: "); scanf("%d",&n); if(n==0) printf("Factorial of 0 is 1\n"); else { printf("Factorial of %d Using Recursive Function is %d\n",n,recr_factorial(n)); printf("Factorial of %d Using Non-Recursive Function is %d\n",n,iter_factorial(n)); } getch(); } /* Recursive Function*/ unsigned int recr_factorial(int n) { return n>=1 ? n * recr_factorial(n-1) : 1; } /* Non-Recursive Function*/ unsigned int iter_factorial(int n) { int accu = 1; int i; for(i = 1; i <= n; i++) { accu *= i; } return accu; }

I - B.Tech CPDS Lab Manual 31

Page 33: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Result: Enter the number:5 Factorial of 5 Using Recursive Function is 120 Factorial of 5 Using Non-Recursive Function is 120 3.b)/* Write C programs that use both recursive and non-recursive functions To find the GCD (greatest common divisor) of two given integers.*/

Program: #include<stdio.h> #include<conio.h> #include<math.h> unsigned int GcdRecursive(unsigned m, unsigned n); unsigned int GcdNonRecursive(unsigned p,unsigned q); int main(void) { int a,b,iGcd; clrscr(); printf("Enter the two numbers whose GCD is to be found: "); scanf("%d%d",&a,&b); printf("GCD of %d and %d Using Recursive Function is %d\n",a,b,GcdRecursive(a,b)); printf("GCD of %d and %d Using Non-Recursive Function is %d\n",a,b,GcdNonRecursive(a,b)); getch(); } /* Recursive Function*/ unsigned int GcdRecursive(unsigned m, unsigned n) { if(n>m) return GcdRecursive(n,m); if(n==0) return m; else return GcdRecursive(n,m%n); } /* Non-Recursive Function*/ unsigned int GcdNonRecursive(unsigned p,unsigned q) { unsigned remainder; remainder = p-(p/q*q); if(remainder==0) return q; else GcdRecursive(q,remainder); }

I - B.Tech CPDS Lab Manual 32

Page 34: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Result: Enter the two numbers whose GCD is to be found:12 48 GCD of 12 and 48 Using Recursive Function is 12 GCD of 12 and 48 Using Non-Recursive Function is 12 3.c)/* Write C programs that use both recursive and non-recursive functions To solve Towers of Hanoi problem.*/

Program: #include<conio.h> #include<stdio.h> /* Non-Recursive Function*/ void hanoiNonRecursion(int num,char sndl,char indl,char dndl) { char stkn[100],stksndl[100],stkindl[100],stkdndl[100],stkadd[100],temp; int top,add; top=NULL; one: if(num==1) { printf("\nMove top disk from needle %c to needle %c ",sndl,dndl); goto four; } two: top=top+1; stkn[top]=num; stksndl[top]=sndl; stkindl[top]=indl; stkdndl[top]=dndl; stkadd[top]=3; num=num-1; sndl=sndl; temp=indl; indl=dndl; dndl=temp; goto one; three: printf("\nMove top disk from needle %c to needle %c ",sndl,dndl); top=top+1; stkn[top]=num; stksndl[top]=sndl; stkindl[top]=indl; stkdndl[top]=dndl; stkadd[top]=5;

I - B.Tech CPDS Lab Manual 33

Page 35: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

num=num-1; temp=sndl; sndl=indl; indl=temp; dndl=dndl; goto one; four: if(top==NULL) return; num=stkn[top]; sndl=stksndl[top]; indl=stkindl[top]; dndl=stkdndl[top]; add=stkadd[top]; top=top-1; if(add==3) goto three; else if(add==5) goto four; } /* Recursive Function*/ void hanoiRecursion( int num,char ndl1, char ndl2, char ndl3) { if ( num == 1 ) { printf( "Move top disk from needle %c to needle %c.", ndl1, ndl2 ); return; } hanoiRecursion( num - 1,ndl1, ndl3, ndl2 ); printf( "Move top disk from needle %c to needle %c.", ndl1, ndl2 ); hanoiRecursion( num - 1,ndl3, ndl2, ndl1 ); } void main() { int no; clrscr(); printf("Enter the no. of disks to be transferred: "); scanf("%d",&no); if(no<1) printf("\nThere's nothing to move."); else printf("Non-Recursive"); hanoiNonRecursion(no,'A','B','C'); printf("\nRecursive"); hanoiRecursion(no,'A','B','C'); getch(); }

I - B.Tech CPDS Lab Manual 34

Page 36: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Result: Enter the no. of disks to be transferred:4 Move disk 1 from L to C Move disk 2 from L to R Move disk 1 from C to R Move disk 3 from L to C Move disk 1 from R to L Move disk 2 from R to C Move disk 1 from L to C Move disk 4 from L to R Move disk 1 from C to R Move disk 2 from C to L Move disk 1 from R to L Move disk 3 from C to R Move disk 1 from L to C Move disk 2 from L to R Move disk 1 from C to R

I - B.Tech CPDS Lab Manual 35

Page 37: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK- 4: 4.a)/* Write a C program, which takes two integer operands and one operator form the user,performs the operation and then prints the result. (Consider the operators +,-,*, /, % and use Switch Statement)*/

Program: #include<stdio.h> #include<conio.h> void main() { int a,b,res,ch; clrscr(); printf("\t *********************"); printf("\n\tMENU\n"); printf("\t********************"); printf("\n\t(1)ADDITION"); printf("\n\t(2)SUBTRACTION"); printf("\n\t(3)MULTIPLICATION"); printf("\n\t(4)DIVISION"); printf("\n\t(5)REMAINDER"); printf("\n\t(0)EXIT"); printf("\n\t********************"); printf("\n\n\tEnter your choice:"); scanf("%d",&ch); if(ch<=5 & ch>0) { printf("Enter two numbers:\n"); scanf("%d%d",&a,&b); } switch(ch) { case 1: res=a+b; printf("\n Addition:%d",res); break; case 2: res=a-b; printf("\n Subtraction:%d",res); break; case 3: res=a*b; printf("\n Multiplication:%d",res); break; case 4:

I - B.Tech CPDS Lab Manual 36

Page 38: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

res=a/b; printf("\n Division:%d",res); break; case 5: res=a%b; printf("\n Remainder:%d",res); break; case 0: printf("\n Choice Terminated"); exit(); break; default: printf("\n Invalid Choice"); } getch(); }

Result: ********************* MENU ******************** (1)ADDITION (2)SUBTRACTION (3)MULTIPLICATION (4)DIVISION (5)REMAINDER (0)EXIT

******************** Enter your choice:1

Enter two numbers:2 3 Addition:5 4.b)/* The total distance travelled by vehicle in 't' seconds is given by distance = ut+1/2at2 where 'u' and 'a' are the initial velocity (m/sec.) and acceleration (m/sec2). Write C program to find the distance travelled at regular intervals of time given the values of 'u' and 'a'. The program should provide the flexibility to the user to select his own time intervals and repeat the calculations for different values of 'u' and 'a'*/

Program: #include <stdio.h> #include <math.h> void main() {

I - B.Tech CPDS Lab Manual 37

Page 39: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

int tim_intrval, counter,time; float accl, distance=0, velos; clrscr(); printf("<===========PROGRAM FOR CALC TOTAL DISTANCE TRAVELED BY A VECHIAL===========>"); printf("\n\n\n\t\t\tNO OF TIME INTERVALS : "); scanf("%d",&tim_intrval); for(counter = 1; counter <= tim_intrval; counter++) { printf("\n\t\t\tAT T%d TIME(sec) : ",counter); scanf("%d",&time); printf("\t\t\tVELOCITY AT %d sec (m/sec) : ",time); scanf("%f",&velos); printf("\t\t\tACCLERATION AT %d sec (m/sec^2): ",time); scanf("%f",&accl); distance += (velos*time + (accl*pow(time,2))/2); } printf("\n\n\n\tTOTAL DISTANCE TRAVELLED BY VEHICLE IN %d INTERVALS OF TIME : %f",tim_intrval,distance); getch(); }

Result: <===========PROGRAM FOR CALC TOTAL DISTANCE TRAVELED BY A VECHIAL===========>

Enter the time interval value in seconds:12 Enter the acceleration value in m/(sec square):34 Enter the initial velocity value in m/sec:56 The distance traveled in meters is:3120.000000.

I - B.Tech CPDS Lab Manual 38

Page 40: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-5 5.a)/* Write a C program that uses functions to perform the following: i) Addition of Two Matrices ii) Multiplication of Two Matrices*/

Program: #include<stdio.h> void main() { int ch,i,j,m,n,p,q,k,r1,c1,a[10][10],b[10][10],c[10][10]; clrscr(); printf("************************************"); printf("\n\t\tMENU"); printf("\n**********************************"); printf("\n[1]ADDITION OF TWO MATRICES"); printf("\n[2]MULTIPLICATION OF TWO MATRICES"); printf("\n[0]EXIT"); printf("\n**********************************"); printf("\n\tEnter your choice:\n"); scanf("%d",&ch); if(ch<=2 & ch>0) { printf("Valid Choice\n"); } switch(ch) { case 1: printf("Input rows and columns of A & B Matrix:"); scanf("%d%d",&r1,&c1); printf("Enter elements of matrix A:\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&a[i][j]); } printf("Enter elements of matrix B:\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&b[i][j]); } printf("\n =====Matrix Addition=====\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++)

I - B.Tech CPDS Lab Manual 39

Page 41: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

printf("%5d",a[i][j]+b[i][j]); printf("\n"); } break; case 2: printf("Input rows and columns of A matrix:"); scanf("%d%d",&m,&n); printf("Input rows and columns of B matrix:"); scanf("%d%d",&p,&q); if(n==p) { printf("matrices can be multiplied\n"); printf("resultant matrix is %d*%d\n",m,q); printf("Input A matrix\n"); read_matrix(a,m,n); printf("Input B matrix\n"); /*Function call to read the matrix*/ read_matrix(b,p,q); /*Function for Multiplication of two matrices*/ printf("\n =====Matrix Multiplication=====\n"); for(i=0;i<m;++i) for(j=0;j<q;++j) { c[i][j]=0; for(k=0;k<n;++k) c[i][j]=c[i][j]+a[i][k]*b[k][j]; } printf("Resultant of two matrices:\n"); write_matrix(c,m,q); } /*end if*/ else { printf("Matrices cannot be multiplied."); } /*end else*/ break; case 0: printf("\n Choice Terminated"); exit(); break; default: printf("\n Invalid Choice"); } getch(); } /*Function read matrix*/

I - B.Tech CPDS Lab Manual 40

Page 42: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

int read_matrix(int a[10][10],int m,int n) { int i,j; for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); return 0; } /*Function to write the matrix*/ int write_matrix(int a[10][10],int m,int n) { int i,j; for(i=0;i<m;i++) { for(j=0;j<n;j++) printf("%5d",a[i][j]); printf("\n"); } return 0; }

Result: ************************************ MENU [1]ADDITION OF TWO MATRICES [2]MULTIPLICATION OF TWO MATRICES [0]EXIT ********************************** Enter your choice:1 Input rows and columns of A & B Matrix:2 2 Enter elements of matrix A: 1 1 1 1 Enter elements of matrix B: 2 2 2 2 =====Matrix Addition===== 3 3 3 3

I - B.Tech CPDS Lab Manual 41

Page 43: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

5.b)/* Write a C program to find both the largest and smallest number in a list of integers*/

Program: main( ) { int a[10],small,lar,i,n; printf(“Enter the value of n”); scanf(“%d”,&n); for(i=0;i<n;i++) { Printf(“enter a[%d]value:”,i); Scanf(“%d”,&a[i]); } Small=a[0]; Lar=a[0]; For(i=1;i<10;i++) { If(a[i]>lar) Lar=a[i]; If(a[i]<small) Small=a[i]; } Printf(“Largest integer is :%d\n”,lar); Printf(“Smallest integer is :%d\n”,small);

Getch(); }

Result: Enter the value of n 5 Enter a[0] value:10 Enter a[1] value:5 Enter a[2] value:20 Enter a[3] value:9 Enter a[4] value:6 Largest integer is:20 Smallest integer is:5

I - B.Tech CPDS Lab Manual 42

Page 44: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-6 6.a)/* Write a C program that uses functions to perform the following operations: To insert a sub-string in to given main string from a given position.*/

Program: #include <stdio.h> #include <conio.h> #include <string.h> void main() { char a[10]; char b[10]; char c[10]; int p=0,r=0,i=0; int t=0; int x,g,s,n,o; clrscr(); puts("Enter First String:"); gets(a); puts("Enter Second String:"); gets(b); printf("Enter the position where the item has to be inserted: "); scanf("%d",&p); r = strlen(a); n = strlen(b); i=0; // Copying the input string into another array while(i <= r) { c[i]=a[i]; i++; } s = n+r; o = p+n; // Adding the sub-string for(i=p;i<s;i++) { x = c[i]; if(t<n) { a[i] = b[t]; t=t+1; } a[o]=x; o=o+1; }

I - B.Tech CPDS Lab Manual 43

Page 45: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

printf("%s", a); getch(); }

Result: Enter First String: Ramu is a good boy Enter Second String: very Enter the position where the item has to be inserted:10 Ramu is a very good boy 6.b)/* Write a C program to determine if the given string is a palindrome or not */

Program: #include<stdio.h> #include<string.h> enum Boolean{false,true}; enum Boolean IsPalindrome(char string[]) { int left,right,len=strlen(string); enum Boolean matched=true; if(len==0) return 0; left=0; right=len-1; /* Compare the first and last letter,second & second last & so on */ while(left<right&&matched) { if(string[left]!=string[right]) matched=false; else { left++; right--; } } return matched; } int main() { char string[40]; clrscr(); printf("****Program to test if the given string is a palindrome****\n"); printf("Enter a string:"); scanf("%s",string); if(IsPalindrome(string)) printf("The given string %s is a palindrome\n",string);

I - B.Tech CPDS Lab Manual 44

Page 46: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

else printf("The given string %s is not a palindrome\n",string); getch(); return 0; }

Result: ****Program to test if the given string is a palindrome**** Enter a string: madam The given string madam is a palindrome 6.c)/* Write a C program that uses functions to perform the following operations: To delete n Characters from a given position in a given string.*/

Program: #include <stdio.h> #include <conio.h> #include <string.h> void delchar(char *x,int a, int b); void main() { char string[10]; int n,pos,p; clrscr(); puts("Enter the string"); gets(string); printf("Enter the position from where to delete"); scanf("%d",&pos); printf("Enter the number of characters to be deleted"); scanf("%d",&n); delchar(string, n,pos); getch(); } // Function to delete n characters void delchar(char *x,int a, int b) { if ((a+b-1) <= strlen(x)) { strcpy(&x[b-1],&x[a+b-1]); puts(x); } }

Result: Enter the string Ramu is a very good boy Enter the position from where to delete 10 Enter the number of characters to be deleted 4 Ramu is a good boy

I - B.Tech CPDS Lab Manual 45

Page 47: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-7 7.a)/* Write a C program to count the lines, words and characters in a given text*/

Program: #include <stdio.h> main() { char line[81], ctr; int i,c,end = 0,characters = 0,words = 0,lines = 0; printf("KEY IN THE TEXT.\n"); printf("GIVE ONE SPACE AFTER EACH WORD.\n"); printf("WHEN COMPLETED, PRESS 'RETURN'.\n\n"); while( end == 0) { /* Reading a line of text */ c = 0; while((ctr=getchar()) != '\n') line[c++] = ctr; line[c] = '\0'; /* counting the words in a line */ if(line[0] == '\0') break ; else { words++; for(i=0; line[i] != '\0';i++) if(line[i] == ' ' || line[i] == '\t') words++; } /* counting lines and characters */ lines = lines +1; characters = characters + strlen(line); } printf ("\n"); printf("Number of lines = %d\n", lines); printf("Number of words = %d\n", words); printf("Number of characters = %d\n", characters); }

Result: KEY IN THE TEXT. GIVE ONE SPACE AFTER EACH WORD. WHEN COMPLETED, PRESS 'RETURN'. Admiration is a very short-lived passion.

I - B.Tech CPDS Lab Manual 46

Page 48: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Admiration involves a glorious obliquity of vision. Always we like those who admire us but we do not like those whom we admire. Fools admire, but men of sense approve. Number of lines = 5 Number of words = 36 Number of characters = 205 7.b)/* Write a C program that displays the position or index in the string S where the string T begins, or -1 if S doesn't contain T*/

Program: #include<stdio.h> #include<string.h> #include<conio.h> void main() { char s[30], t[20]; char *found; clrscr(); /* Entering the main string */ puts("Enter the first string: "); gets(s); /* Entering the string whose position or index to be displayed */ puts("Enter the string to be searched: "); gets(t); /*Searching string t in string s */ found=strstr(s,t); if(found) printf("Second String is found in the First String at %d position.\n",found-s); else printf("-1"); getch(); }

Result: Enter the first string: software engineer Enter the string to be searched:engineer Second String is found in the First String at 9position.

I - B.Tech CPDS Lab Manual 47

Page 49: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-8 8.a) /* Write a C program to generate Pascal's triangle. */

Program: #include<stdio.h> #include<conio.h> void main() { int bin,p,q,r,x; clrscr(); bin=1; q=0; printf("Rows you want to input:"); scanf("%d",&r); printf("\nPascal's Triangle:\n"); while(q<r) { for(p=40-3*q;p>0;--p) printf(" "); for(x=0;x<=q;++x) { if((x==0)||(q==0)) bin=1; else bin=(bin*(q-x+1))/x; printf("%6d",bin); } printf("\n"); ++q; } getch(); }

Result: Rows you want to input:5 Pascal's Triangle for 5 rows: 1

1 1 1 2 1

1 3 3 1 1 4 6 4 1

I - B.Tech CPDS Lab Manual 48

Page 50: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

8.b)/* Write a C program to construct a pyramid of numbers. */

Program: #include<stdio.h> #include<conio.h> void main() { int num,i,y,x=35; clrscr(); printf("\nEnter the number to generate the pyramid:\n"); scanf("%d",&num); for(y=0;y<=num;y++) { /*(x-coordinate,y-coordinate)*/ gotoxy(x,y+1); /*for displaying digits towards the left and right of zero*/ for(i=0-y;i<=y;i++) printf("%3d",abs(i)); x=x-3; } getch(); }

Result: Enter the number of lines: 5 Pyramid of numbers for 5 is: 1 2 3 2 3 4 5 4 3 4 5 6 7 6 5 4 5 6 7 8 9 8 7 6 5

I - B.Tech CPDS Lab Manual 49

Page 51: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-9 9.a) /*Write a C program to read in two numbers, x and n, and then compute the sum of this geometric progression: 1+x+x2+x3+………….+xn For example: if n is 3 and x is 5, then the program computes 1+5+25+125.Print x, n, the sum Perform error checking. For example, the formula does not make sense for negative exponents - if n is less than 0. Have your program print an error message if n<0, then go back and read in the next pair of numbers of without computing the sum. Are any values of x also illegal ? If so, test for them too. */

Program: #include<stdio.h> #include<conio.h> #include<math.h> void main() { int s_sum,i,x,n; clrscr(); printf("Enter the values for x and n:"); scanf("%d %d",&x,&n); if(n<=0 || x<=0) { printf("Value is not valid\n"); } else { printf("Value is valid\n"); s_sum=1; for(i=1;i<=n;i++) { s_sum=s_sum+pow(x,i); } printf("Sum of series=%d\n",s_sum); } getch(); }

Result: Enter the values for x and n:5 3 Value is valid Sum of series=156

I - B.Tech CPDS Lab Manual 50

Page 52: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-10 10a) /* 2’s complement of a number is obtained by scanning it from right to left and complementing all the bits after the first appearance of a 1. Thus 2’s complement of 11100 is 00100. Write a C program to find the 2’s complement of a binary number.*/

Program: #include <stdio.h> #include<conio.h> void complement (char *a); void main() { char a[16]; int i; clrscr(); printf("Enter the binary number"); gets(a); for(i=0;a[i]!='\0'; i++) { if (a[i]!='0' && a[i]!='1') { printf("The number entered is not a binary number. Enter the correct number"); exit(0); } } complement(a); getch(); } void complement (char *a) { int l, i, c=0; char b[16]; l=strlen(a); for (i=l-1; i>=0; i--) { if (a[i]=='0') b[i]='1'; else b[i]='0'; } for(i=l-1; i>=0; i--) { if(i==l-1) { if (b[i]=='0')

I - B.Tech CPDS Lab Manual 51

Page 53: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

b[i]='1'; else { b[i]='0'; c=1; } } else { if(c==1 && b[i]=='0') { b[i]='1'; c=0; } else if (c==1 && b[i]=='1') { b[i]='0'; c=1; } } } b[l]='\0'; printf("The 2's complement is %s", b); }

Result: Enter the binary number 11100 The 2's complement is 00100. 10.b) /* Write a C program to convert a Roman numeral to its decimal equivalent. */

Program: #include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> void main() { int *a,len,i,j,k; char *rom; clrscr(); printf("Enter the Roman Numeral:"); scanf("%s",rom); len=strlen(rom); for(i=0;i<len;i++) { if(rom[i]=='I')

I - B.Tech CPDS Lab Manual 52

Page 54: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

a[i]=1; else if(rom[i]=='V') a[i]=5; else if(rom[i]=='X') a[i]=10; else if(rom[i]=='L') a[i]=50; else if(rom[i]=='C') a[i]=100; else if(rom[i]=='D') a[i]=500; else if(rom[i]=='M') a[i]=1000; else { printf("\nInvalid Value"); getch(); exit(0); } } k=a[len-1]; for(i=len-1;i>0;i--) { if(a[i]>a[i-1]) k=k-a[i-1]; else if(a[i]==a[i-1] || a[i]<a[i-1]) k=k+a[i-1]; } printf("\nIts Decimal Equivalent is:"); printf("%d",k); getch(); }

Result: Enter the Roman Numeral:XIV Its Decimal Equivalent is 14

I - B.Tech CPDS Lab Manual 53

Page 55: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-11 11. /* Write a C program that uses functions to perform the following operations: i) Reading a complex number ii) Writing a complex number iii) Addition of two complex numbers iv) Multiplication of two complex numbers (Note: represent complex number using a structure.) */

Program: #include<stdio.h> #include<math.h> void arithmetic(int opern); struct comp { double realpart; double imgpart; }; void main() { int opern; clrscr(); printf("\n\n \t\t\t***** MAIN MENU *****"); printf("\n\n Select your option: \n 1 : ADD\n 2 : MULTIPLY\n 0 : EXIT \n\n\t\t Enter your Option []\b\b"); scanf("%d",&opern); switch(opern) { case 0: exit(0); case 1: case 2: arithmetic(opern); default: main(); } } void arithmetic(int opern) { struct comp w1, w2, w; printf("\n Enter two Complex Numbers (x+iy):\n Real Part of First Number:"); scanf("%lf",&w1.realpart); printf("\n Imaginary Part of First Number:");

I - B.Tech CPDS Lab Manual 54

Page 56: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

scanf("%lf",&w1.imgpart); printf("\n Real Part of Second Number:"); scanf("%lf",&w2.realpart); printf("\n Imaginary Part of Second Number:"); scanf("%lf",&w2.imgpart); switch(opern) { /*addition of complex number*/ case 1: w.realpart = w1.realpart+w2.realpart; w.imgpart = w1.imgpart+w2.imgpart; break; /*multiplication of complex number*/ case 2: w.realpart=(w1.realpart*w2.realpart)-(w1.imgpart*w2.imgpart); w.imgpart=(w1.realpart*w2.imgpart)+(w1.imgpart*w2.realpart); break; } if (w.imgpart>0) printf("\n Answer = %lf+%lfi",w.realpart,w.imgpart); else printf("\n Answer = %lf%lfi",w.realpart,w.imgpart); getch(); main(); }

Result: ***** MAIN MENU *****

Select your option: 1 : ADD 2 : MULTIPLY 0 : EXIT Enter your Option 1

Enter two Complex Numbers (x+iy): Real Part of First Number:2 Imaginary Part of First Number:3 Real Part of Second Number:2 Imaginary Part of Second Number:3 Answer =4+6i

I - B.Tech CPDS Lab Manual 55

Page 57: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-12 12.a) /* Write a C program which copies one file to another.*/

Program: #include <stdio.h> #include <conio.h> #include <process.h> void main(int argc, char *argv[]) { FILE *fs,*ft; char ch; clrscr(); if(argc!=3) { puts("Invalid number of arguments."); exit(0); } fs = fopen(argv[1],"r"); if(fs==NULL) { puts("Source file cannot be opened."); exit(0); } ft = fopen(argv[2],"w"); if (ft==NULL) { puts("Target file cannot be opened."); fclose(fs); exit(0); } while(1) { ch=fgetc(fs); if (ch==EOF) break; else fputc(ch,ft); } fclose(fs); fclose(ft); getch(); }

Result: Contents of the first file are copied into second file

I - B.Tech CPDS Lab Manual 56

Page 58: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

12.b) /* Write a C program to reverse the first n characters in a file. (Note: The file name and n are specified on the command line.)*/

Program: #include <stdio.h> #include <conio.h> #include <string.h> #include <process.h> void main(int argc, char *argv[]) { char a[15]; char s[20]; char n; int k; int j=0; int i; int len; FILE *fp; if(argc!=3) { puts("Improper number of arguments."); exit(0); } fp = fopen(argv[1],"r"); if(fp == NULL) { puts("File cannot be opened."); exit(0); } k=*argv[2]-48; n = fread(a,1,k,fp); a[n]='\0'; len=strlen(a); for(i=len-1;i>=0;i--) { s[j]=a[i]; printf("%c",s[j]); j=j+1; } s[j+1]='\0'; getch(); }

Result: First n characters of the given file are reversed

I - B.Tech CPDS Lab Manual 57

Page 59: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-13 13 a)Write a C program to display the contents of a file.

Program: #include<stdio.h> Void main() { FILE *fp; Int c; If(fp=fopen(“my.dat”,”w”))==NULL) { Printf(“\n\nERROR”); Exit(1); } While((c=getc(stdin))!=EOF) Putc(c,fp); Printf(“\nDONE”); Fclose(fp); Getch(); }

Result: DONE Displays the Contents of the Given File. 13 b)Write a C program to merge two files in to a third file (i.e the contents of the first file followed by those of the second are put into the third file)

Program: #include<stdio.h> #include<conio.h> #include<stdlib.h> Void main(int argc,char *argv[]) { FILE *f1,*f2,*f3; Clrscr(); If(argc<3) Exit(2); If(f1=fopen(argv[1],”r”))==NULL) { Printf(“\nERROR”); Exit(1); } If(f2=fopen(argv[2],”r”))==NULL) { Printf(“\nERROR”);

I - B.Tech CPDS Lab Manual 58

Page 60: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Exit(2); } If((f3=fopen(argv[3],”w”))==NULL) { Printf(“\nERROR”); Exit(1); } While((c=fgetc(f1))!=EOF) Fputc(c,f3); Fclose(f1); While((c=fgetc(f2))!=EOF) Fputc(c,f3); Fclose(f2); Fclose(f3); } Printf(“\nDONE”); }

Result: DONE Contents of the first file followed by those of the second are put into the third file.

I - B.Tech CPDS Lab Manual 59

Page 61: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

PART-B

I - B.Tech CPDS Lab Manual 60

Page 62: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-14 14.Write a C program that uses functions to perform the following operations on singly linked list i)creation ii)Insertion iii)Deletion iv)Traversal SINGLE LINKED LIST

A linked list contains elements at arbitrary locations. Each node of the list must. Linked lists are classified in to two categories 1) Single linked list list 2) Double linked list. Linked list implemented by self-referential structures linked list: It is unidirectional list, consists with node contains two fields. DATA: It contains information. PTR: It contains address of next node. Implementation of single linked list:

FUNCTIONS USED: Function name return type parameters create struct node no parameters insert() void struct node del() void struct node count() int struct node reverse() void struct node search() void struct node display() void struct node VARIABLES USED: Variable name data type purpose new pointer to struct node to store new node address start pointer to struct node to store store starting node address pre pointer to struct node to store previous node address temp pointer to struct node to store temporary node address

I - B.Tech CPDS Lab Manual 61

Page 63: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

x int store data of new node pos int store position where element to be insert,del. ch int store choice ptr pointer to struct node pointer field of any node data int information field of any node

ALGORITHM : Function INSERT(X, FIRST)

X New item to be inserted

START Address / Pointer to the first item of a linked list

DATA Information field of a node

PTR Pointer field of a node

AVAIL Address/Pointer to the top element of the availability stack TEMP Temporary pointer variable

1. // Obtain new from availability nodes stack// NEW AVAIL

2 //Initialize fields of new node and its link to the list// DATA (NEW) X

PTR (NEW) NULL 3. //inserting element at starting of the list// if((START=NULL)and(POS=1) then PTR(NEW)START STARTNEW endif Return(START)

4. // inserting middle of the list at given position// TEMPSTART while((I<=POS) and (PTR (TEMP)!=NULL)) do TEMP PTR (TEMP) II+1 repeat //set the link fields of new node // PTR (NEW) PTR (TEMP) PTR (TEMP)NEW Return(START)

5. // inserting node at end of the list// while(PTR (TEMP)!=NULL) do TEMP PTR (TEMP) repeat // set link field of last node to NEW// PTR (TEMP)NEW

I - B.Tech CPDS Lab Manual 62

Page 64: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Procedure DELETE(X, START) X Address of a node to be deleted START Address of the first node in the linked list POS position of the node which is to be deleted TEMP temporary node 1. // Check for under flow// if START = NULL then Print('Underflow') Return endif 2. //delete a node at the starting of the list//

if(POS==1) then START PTR (START) else 3. // delete node at middle position of the list//

TEMPSTART while((PTR (TEMP)!=NULL) and (I<POS)) do TEMP PTR (TEMP) II+1 repeat PTR (TEMP) PTR (PTR (TEMP))

4. // delete a node at the end of the list// while(PTR (TEMP)!=NULL) do TEMP PTR (TEMP)

repeat TEMPNULL

return

Program: /*program on single linked list*/ #include<stdio.h> #include<conio.h> #include<malloc.h> #include<stdlib.h> #include<process.h>

struct node {

int data; struct node *ptr;

} ; //creation of list//

I - B.Tech CPDS Lab Manual 63

Page 65: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

struct node *create() {

/*declaration of structure*/ struct node *new,*start,*pre;

int x; printf("\n Enter element-1 to stop;"); scanf("%d",&x); start=pre=NULL; while (x!=-1) {

new=(struct node *)malloc(sizeof(struct node)); new->data=x; new->ptr=NULL; if (start==NULL)

start=new; else

pre->ptr=new; pre=new; printf ("\n\t Enter the element -1 to stop:"); scanf("%d",&x);

} return(start);

} /*display the list*/ void display(struct node *start) { struct node *temp; temp=start; while (temp!=NULL) { printf("%d-->",temp->data); temp=temp->ptr; } } /*inserting element in to list*/ void *insert(struct node *start) { struct node *temp,*new;

int i,x,pos; printf("\n Enter the value and the position"); scanf("%d%d",&x,&pos); new=(struct node*)malloc(sizeof(struct node)); new->data=x; new->ptr=NULL; if(pos==1 || start==NULL)

{ new->ptr=start; start=new;

I - B.Tech CPDS Lab Manual 64

Page 66: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

} else

{ temp=start; i=2; while(i<pos&&(temp->ptr!=NULL )) { temp=temp->ptr; ++i; } new->ptr=temp->ptr; temp->ptr=new; } return(0); } /*deletion of nodefrom the list*/ void *del(struct node *start) { struct node *temp; int i,pos;

printf("\n Enter the position of the Element to be delete"); scanf("%d",&pos); if(start!=NULL) { if (pos==1) start=start->ptr; else { temp=start; i=2; while (temp!=NULL&&i<pos) { temp= temp->ptr; ++i; } if (temp!=NULL) temp->ptr=(temp->ptr)->ptr; else

printf("\n no element"); } } display(start); return(0);

} /*count no. of nodes*/ int count (struct node *start) { struct node *temp;

I - B.Tech CPDS Lab Manual 65

Page 67: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

int c=0; temp=start; while (temp->ptr!=NULL) { temp=temp->ptr; c++; } return(c+1); }

/*reversing the list*/ void reverse (struct node *start) { struct node *a,*b,*c; a=start; b=NULL; while (a!=NULL) { c=a->ptr; a->ptr=b; b=a; a=c; } start=b; display(start); }

/*Searching an element*/ void search(struct node *start,int pos) { struct node *temp; int c=1; temp=start; while (temp!=NULL) if (temp->data==pos) { printf("\n%d is located at %d",pos,c);

break; }

else { temp=temp->ptr; c++; }

} /*main program*/ void main () {

int i,ch,ans,key; struct node *start;

I - B.Tech CPDS Lab Manual 66

Page 68: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

clrscr(); printf("\n MENU"); printf("\n 1.Create. \n 2.Insert .\n 3.Delete \n 4.Display \n 5. Count \n 6.Reverse the list.\n7.Search\n 8.Exit"); do {

printf("\n\t Enter ur choice"); scanf ("%d", &ch) ; if(ch>8||ch<=0) {

printf("Invalid choice, try again"); break;

} switch (ch) {

case 1: start=create(); break; case 2: insert(start); break;

case 3: del(start); break;

case 4: display(start);

break; case 5:

ans=count(start); printf("\n Count is %d",ans);

break; case 6: reverse(start);

break; case 7:

printf("Enter an element to be searched:"); scanf ("%d", &key) ; search(start,key);

break; case 8: exit(0); break; }

}while(ch<=8); getch(); }

I - B.Tech CPDS Lab Manual 67

Page 69: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Result: MENU l.Create. 2.Insert . 3.Delete 4.Display 5.Count 6.Reverse the list. 7.Search 8.Exit. Enter ur choice 1 Enter element -1 to stop 10 Enter ur choice 1 Enter element -1 to stop 20 20 10

I - B.Tech CPDS Lab Manual 68

Page 70: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-15 15 a)Write a C program that implement stack (its operations) using Arrays&Pointers.

STACK

Stack is an ordered collection of data items which insertion and deletion operations are performs at one end( top of the stack).Stack is represented by array S with MAX size, TOP is a stack pointer, which specifies status of the stack.

Stack works under Last In First Out (LIFO) principle. Ex: A coin stacker. Push operation is not possible if stack is in overflow (i,e.TOP=MAX). Pop operation is not possible if stack is in underflow (i.e. TOP=0) Stacks are used to evolution of simple expressions, conversion of infix, postfix, prefix expressions and in recursion methods. Implementation of stack using arrays:

FUNCTIONS USED: Function name return type parameters push () void s[],item pop() int s [] display() void s[] VARIABLES USED: Variable name data type purpose s[] int to store stack elements max int size of stack top int stack pointer item int to store element to be pushed y int to store element to be pop ch int to store choice

ALGORITHM :

Procedure PUSH (S ,ITEM)

S . An Array of MAX size representing stack.

TOP Stack pointer

ITEM Element to be push 1. //Check for stack overflow//

I - B.Tech CPDS Lab Manual 69

Page 71: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

if TOP >= MAX then Print ('Stack Overflow') Return endif 2. //Increment pointer Top to provide space for inserting element// TOP TOP + 1

3. //Insert ITEM at top of the stack// S[TOP] ITEM

Return

Function POP (S)

S An Array of MAX size representing stack.

TOP stack pointer

Y Element deleted 1. //Check for stack underflow// if TOP = 0 then Print ('Stack Underflow') Return endif 2. //Retrieve the top element of stack// Y (S[TOP]) 3 //Decrement pointer TOP to save the space//

TOP TOP-1 Return(Y)

Program: #include<stdio.h> #include<conio.h> int top=-1; void push(int [],int); int pop (int[ ]); void display (); int s[10];

void main() {

int ch; int item,y; clrscr ( ) ; printf("\n\t MENU "); printf("\n\t1. Push");

I - B.Tech CPDS Lab Manual 70

Page 72: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

printf( "\n\t 2.Pop"); printf("\n\t 3.Display."); printf("\n\t 4.Exit"); do {

printf("\n Enter ur choice"); scanf ( "%d" , &ch) ; if (ch>4||ch<=0) {

printf ("\n Invalid choice "); break;

} switch(ch)

{ case 1 : printf("\n\t Enter the element: "); scanf("%d",& item ); push(s, item ); break; case 2: y=pop ( s ) ; printf("\n\t the deleted break value %d" ,y); break; case 3 : display(); break; case 4 : exit(0); break; }

}while(ch<=4); } void push(int s[],int item ) {

if(top>10) printf("\t stack is overflow");

else { top=top+ 1 ; s[top]= item ; }

} int pop(int s[]) {

int x; if(top==-1) printf("\n\t the stack is underflow"); else

I - B.Tech CPDS Lab Manual 71

Page 73: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

{ x=s[top]; top--;

} return x;

} void display() {

int i; for(i=top;i>=0;i--) printf( "%d\t" ,s[i]);

}

Result:

MENU 1. Push 2.Pop 3.Exit. 4.Display. Enter ur choice 1 Enter the element: 23 Value is pushed Enter ur choice 1 Enter the element: 13 Value is pushed Enter ur choice 1 Enter the element: 25 Value is pushed Enter ur choice 3 25 13 23

Implementation of stack using single linked list: FUNCTIONS USED: Function name return type parameters Push() struct node struct node Pop() struct node struct node Display() void struct node VARIABLES USED: Variable name data type purpose

I - B.Tech CPDS Lab Manual 72

Page 74: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

new pointer to struct node to store new node address temp pointer to struct node to store temporary node address x int store data of new node ch int store choice top struct pointer stack pointer ptr struct pointer to store any node address field 15 b) Write a C program that implement stack (its operations) using Pointers.

Program:

#include<stdio.h> #include<conio.h> #include<malloc.h>

struct node {

int data; struct node*ptr;

} ; /*inserting (push) an element*/ struct node*push(struct node* top) {

struct node *new; int x; new=(struct node*)malloc(sizeof(struct node)); printf("\n"); printf("\n Enter the value to push"); scanf("%d",&x); new->data=x; new->ptr=top; top=new; return (top) ;

} /*display the elements*/ void display(struct node *top) { while (top!=NULL) { printf("\t%d",top->data); top=top->ptr; } } /*deletion(pop) of node from stack*/ struct node*pop(struct node*top) {

struct node*temp; temp=top;

I - B.Tech CPDS Lab Manual 73

Page 75: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

if (top==NULL) printf("\n Stack is empty");

else {

temp=temp->ptr; free (top) ;

top=temp; } printf("\n One value deleted"); return (top) ;

} /*main program*/

void main ( ) {

struct node*top; int ch; top=NULL; clrscr(); printf("\n MENU"); printf("\n1.Push.\n2.Pop.\n3.Exit."); do {

printf("\n Enter ur choice"); scanf ("%d", &ch) ; if(ch>3||ch<=0) {

printf("Invalid choice, try again"); break;

} switch (ch) {

case 1: top=push(top); display(top);

break; case 2:

top=pop(top) ; display(top); break;

case 3: exit(0); break; }

}while(ch<=3); getch(); }

I - B.Tech CPDS Lab Manual 74

Page 76: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Result: MENU 1.Push. 2.Pop. 3.Exit. Enter ur choice 1 Enter the value to push 22 Enter ur choice 1 Enter the value to push 32 Enter ur choice 1 Enter the value to push 12 Enter ur choice 1 12 32 22

I - B.Tech CPDS Lab Manual 75

Page 77: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-16 16 a)Write a C program that implements queue (its operations) using Arrays&Pointers

QUEUES: Queue is an ordered list of data items such that new item inserts in to a queue at rear end, and deletes an item from queue at front end. Queue is represented with an array Q of MAX size ,FRONT and REAR are the front and rear pointers of the queue. Queue works under First In First Out (FIFO) principle. Ex: A 'Q' for a bus. Insertion is not possible if queue is in overflow (REAR=MAX). Deletion is not possible if queue is in underflow (FRONT=0)

Implementation of queue using arrays: FUNCTIONS USED: Function name return type parameters insert ( ) void q,max,item deletion () int q display() void q VARIABLES USED: Variable name data type purpose q[] int to store queue elements max int size of the queue f,r int to store queue front ,rear pointers item int element to be insert ch int to store choice y int to store deletion element ALGORITHM :

Procedure INSERT (Q, MAX, ITEM)

Q An Array of MAX size representing queue

F Front index of the queue

R Rear index of the queue

I - B.Tech CPDS Lab Manual 76

Page 78: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

ITEM Information to be inserted at the rear of queue. At the time of creation of Q, F R 0; 1. // Check for queue overflow//

if R >= MAX then

Print ('Queue overflow')

Return

endif

2. //Increment Rear pointer to provide space for inserting element// RR+ 1 3. //Insert new element at rear end of queue//

Q[R] ITEM 4. //If initially, the queue is empty, adjust the front pointer//

if F= 0 then F 1 endif

return

Function DELETION (Q)

Q Array of size MAX representing queue.

F Pointer to the front of queue

R Pointer to the rear of queue

Y Temporary variable 1. //Check for queue underflow// if F 0 then Print ('Queue Underflow') Return endif 2. //Delete the queue element at front end and store it into item// YQ[F] 3. //If queue is empty after deletion, set front and rear pointers to 0// if F = R then F0 R0 4. //Otherwise increment front pointer// else F F+ 1 Return (Y)

Program: #include<stdio.h> #include<conio.h>

I - B.Tech CPDS Lab Manual 77

Page 79: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

int r=-1; int f=-1; void insert(int[],int,int); int deletion(int[]); void display(int[]); void main ( ) {

char ch; int y,item; int n,q[10]; clrscr () ; printf("\n\t MENU"); printf("\n\t1. Insert."); printf("\n\t 2.Delete."); printf("\n\t 3.Display."); printf("\n\t 4. Exit."); do {

printf("\n\t Enter ur choice"); scanf ( "%d" , &ch) ; if (ch>4||ch<=0) {

printf ("\n\t Invalid choice "); break;

} switch(ch)

{ case 1 : printf("\n\t Enter the element to be insert:"); scanf("%d",& item ) ; insert(q,10, item ) ; break;

case 2 : y=deletion(q) ; printf("\n\tThe deleted value:%d",y); break; case 3 : display (q) ; break; case 4: exit (0); } }while(ch<=4) ; getch () ; } void insert(int q[] ,int n,int item) {

if (r>=n)

I - B.Tech CPDS Lab Manual 78

Page 80: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

{ printf("\n\t Queue is overflow"); return;

} else {

r=r+1; q[r]= item; printf("\n\t The value is inserted"); if (f==-1)

f=0; }

} int deletion(int q[]) {

int y; if (f = =-1)

{ printf("\n\t the Queue is Empty");

} y=q[f] ; if (f==r) f=r=-1; else f++;

return y; } void display(int q[]) {

int i; for (i=f;i<=r;i++)

printf("\t%d",q[i]); getch();

}

Result: MENU 1. Insert. 2.Delete. 3.Display. 4. Exit. Enter ur choice 1 Enter the element to be insert : 23 The value is inserted Enter ur choice 1

I - B.Tech CPDS Lab Manual 79

Page 81: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Enter the element to be insert : 12 The value is inserted Enter ur choice 1 Enter the element to be insert: 45 The value is inserted Enter ur choice 3 23 12 45

Implementation of queue using single linked list:

FUNCTIONS USED: Function name return type parameters insert() void frint struct node,rear struct node del() void front struct node display() void rear struct node VARIABLES USED: Variable name data type purpose new pointer to struct node to store new node address temp pointer to struct node to store temporary node address x int store data of new node ch int store choice ptr struct pointer to store pointer any node front struct pointer to store front pointer of queue rear struct pointer to store rear pointer of queue 16 b)Write a C program that implements Queue(its operations) using Pointers.

Program: #include<stdio.h> #include<conio.h> #include<malloc.h> #include<stdlib.h>

struct node {

int data; struct node*ptr;

} ; /*inserting an element*/

void insert(struct node **front,struct node **rear) {

struct node*new; int x;

I - B.Tech CPDS Lab Manual 80

Page 82: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

new=(struct node*)malloc(sizeof(struct node)); printf("\n Enter value to insert"); scanf("%d",&x) ; new->data=x; new->ptr=NULL; if (*front==NULL) {

*front=new; *rear=new;

} else {

(*rear)->ptr=new; ( * rear) =new;

} } /*display the values*/ void display(struct node *front) {

printf("\n"); while (front!=NULL) {

printf(" \t%d",front->data) ; front=front->ptr;

} } /*deletion of element from the queue*/ void del(struct node **front) {

struct node *temp; if( (*front) !=NULL) {

temp= *front; (*front)=(*front)->ptr;

free(temp) ; printf("\n One element deleted");

} } /*main program*/ void main ( ) {

struct node *front=NULL; struct node *rear=NULL; int ch; clrscr(); printf("\n MENU"); printf("\n1.Insert.\n2.Delete.\n3.Exit."); do

I - B.Tech CPDS Lab Manual 81

Page 83: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

{ printf("\n Enter ur choice"); scanf ("%d", &ch) ; if(ch>3||ch<=0) {

printf("Invalid choice, try again"); break;

} switch (ch) {

case 1: insert(&front,&rear); display(front);

break; case 2:

del(&front); display(front); break;

case 3: exit(0); break; }

}while(ch<=3); getch() ; }

Result: MENU 1.Insert 2.Delete. 3.Exit. Enter ur choice 1 Enter value to insert 22 Enter ur choice 1 Enter value to insert 12 Enter ur choice 1 Enter value to insert 32 Enter ur choice 1 22 12 32

I - B.Tech CPDS Lab Manual 82

Page 84: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-17 Conversion of infix expression to postfix notation:

FUNCTIONS USED: Function name return type parameters ipf int operator(char) spf int operator(char) VARIABLES USED: Variable name data type purpose s[] char to store stack elements p[] char to store postfix expression a[] char to store given infix expression top int stack pointer i,j int to store subscripts of arrays ALGORITHM : procedure INFIX_POSTFIX( ) // Insert '(' at the beginning and')' at the of the given string//

1. // Scan the input infix expression from left to right taking one symbol

at a time till end of string//

while(A[I]!=NULL CHAR) do

2. // If an operand is encountered, place it into the output//

if((A[I]>64 and A[I]<92) or(A[I]>96andA[I]<123))then

P[J++]A[I] //add to post fix//

3. //If a left parenthesis ('(')is encountered, push it into the stack//

else if(A[I]='(') then

S[++TOP]A[I] //push stack//

4. //If a right parenthesis (')')is encountered, pop the stack and append

the operator to the output until the left parenthesis is encountered.

Discard both-parenthesis//

else if(A[I]=')') then

while(S[TOP]!='(') do

P[J++]S[TOP--]

repeat

5. //If an operator is encountered (say current operator)

Repeatedly pop the stack and append the popped operator to output if it

I - B.Tech CPDS Lab Manual 83

Page 85: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

satisfies the stack top operator is same or higher precedence than the

current operator just encountered and the stack is not empty. Else push

current operator into the stack. Else push the operator to stack.//

else while(TOP=0&&(ipf(A[I])<=spf(S[TOP)) do

P[J++]=S[--TOP] repeat

S[++TOP] =A[I] ; endif repeat

6. //Pop the stack and add to output string till the stack is empty.// print(P[])

Program: #include<stdio.h> #include<conio.h> #include<math.h> char s[20],p[20]; char temp; int top,i,j; int ipf(char); int spf(char); main()

{ char a[20]; temp='+' ; clrscr() ; printf("\n\t Enter any equation:") ; scanf ("%s" ,a) ; printf("\n %s",a) ; i=j=0; top=-1; s[top++]='(' ; while(a[i]!='\0') { if ((a [i] >64&&a [i] <92) || (a [i] >96&&a [i] <123))

p[j++] =a[i]; else if(a[i]==')') {

while(s[top]!='(') p[j++] = s[top--] ;

temp= s[--top] ; } else { while(top>=0&&(ipf(a[i])<=spf(temp)))

I - B.Tech CPDS Lab Manual 84

Page 86: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

{ p[j++]=temp; temp= s[--top] ; } s[++top] =a[i] ; temp=a[i] ; } i++; } while(top>=0) { if(s[top]=='(') top--;

else p [j++] = s[top--] ; }

p[j++]='\0'; printf("\n") ; for(i=0;i<=j;i++)

printf("%c",p[i]); getch() ;

return(0) ; }

int ipf(char c) { if((c=='+') || (c=='-')) return(1); else if((c=='*')||(c=='/')) return(3); else if(c=='^') return(6); else if(c=='(') return(9); else return(0); } int spf(char c) { if((c=='+') || (c=='-')) return(2); else if((c=='*')|| (c=='/')) return(4); else if(c=='^') return(5); else return(0); }

I - B.Tech CPDS Lab Manual 85

Page 87: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Result:

Enter any equation: a+b-c a+b-c ab+c-

Evaluation of postfix Expression: VARIABLES USED: Variable name data type purpose a[] char array to store given post fix stack[] float stack to store answer of expression i int array index top int stack pointer

ALGORITHM :

procedure POSTFIX_EVALUATE ( )

1. Scan the expression from left to right for one symbol at a time. 2. If it is an operand, push into the stack; else pop the two operands from the stack,apply the indicated operation,and push the result into the stack. 3. Repeat the steps 1 and 2 above, until end of the input expression. 4. pop the top element of the stack, which is result of the expression.

Program: #include<stdio.h> #include<conio.h> #include<math.h> void main ( )

{ static float stack [20] ; int i,top=-l; static char a[30]; clrscr () ; printf("\n\t Enter the string :"); scanf("%s",a) ; while(a[i] !='\0')

{ if (( (int) a[i] >47) && ((int) a [i] <58)

stack [++top] = ((int)a[i]-48);

I - B.Tech CPDS Lab Manual 86

Page 88: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

else if(a[i]=='+' || a[i]=='-'|| a[i]=='*' || a[i]=='/') { if(a[i]=='+') {

stack[top-l]= stack[top-l]+ stack [top] ; top--;

} if (a[i] == '-' )

{ stack[top-l]= stack[top-l]- stack [top] ; top--;

} if(a[i]=='*')

{ stack[top-l]= stack[top-l]* stack [top] ; top--;

} if(a[i]=='/')

{ stack[top-l]= stack[top-l]+ stack [top] ; top--;

} } i++; } printf ("%f" ,stack[0]) ; getch() ; }

Result: Enter the string : 7 3 + 5- 5.000000

I - B.Tech CPDS Lab Manual 87

Page 89: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEk-18 18. Write C programs that implement the following sorting methods to sort a given list of integers in ascending order: i) Bubble sort ii)Selection sort

BUBBLE SORT

Sorting is an arranging the given elements in order i.e. ascending/ descending. Sorting methods are 1) Bubble sort 1) Insertion sort 3) Selection sort 4) Quick sort 5) Heap sort (Tree sort). Bubble sort: In this method compare each pair of adjacent elements in a array of elements, swapped until smallest/ greatest element bubbled up to the top. Implementation of Bubble sort:

VARIABLES USED: Variable name datatype purpose a[] int to store given arrayel ements n int size of the list i,j int to repeat loops temp int temporary variable ALGORITHM: Function Bubble-Sort (A, N) A Array of N elements to be sorted I,J Index TEMP Variable to count the number of exchanges .

1. //read the elements into array// for I1 to N increment by 1 do Read( A[]) repeat

2. for I1 to<N increment by 1 do 3. for J1 to <N increment by 1 do

4. if(A[J+l]<A[J]) then //adjust unordered elements// TEMPA[J] A[J]A[J+l]

A[J+l]TEMP endif

repeat

I - B.Tech CPDS Lab Manual 88

Page 90: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

repeat return;

Program: #include<stdio.h> #include<conio.h> int a[50]; bubblesort(int a[] ,int n) { int i,j,temp; for(i=0;i<n-1;i++) { for(j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } return; } void main ( ) { int n,i; clrscr(); printf("\n\t How many numbers do u want to enter"); scanf("%d",&n); printf("\n\t Enter the numbers:"); for(i=0;i<n;i++) scanf("%d",&a[i]); bubblesort(a,n) ;

printf("\n\t Numbers after sorting:"); for(i=0;i<n;i++)

printf("%d ",a[i]); getch (); }

I - B.Tech CPDS Lab Manual 89

Page 91: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Result:

How many numbers do u want to enter 5 Enter the numbers: 21 34 12 56 10 Numbers after sorting: 10 12 21 34 56 SELECTION SORT In this method, search for smallest element on the array of elements and swap with first element. Next, search smallest element in remaining array of elements and swap with second element. Repeat this process until only the last two elements in array are compared. Implementation of selection sort: VARIABLES USED: Variable name datatype purpose a[] int to store given elements n int size of the list i,j int increment variables temp int temporary variable ALGORITHM: Procedure Selection - Sort (A, N) A Array of N elements to be sort. TEMP temporary variable MIN Position variable of the smallest element I,J Index

1 //Read the elements into array// for I1 to N increment by 1 do

Read( A[]) repeat 2. for I1 to N increment by 1 do 3. //Initialise minimum index// MIN I 4. //Make a pass and obtain element with smallest value//

for JI+1 to N increment by 1 do if A[J] < A[MIN] then MINJ end if repeat 5. //Swapping smallest element with current index element//

TEMPA[I]

A[I]A[MIN]

I - B.Tech CPDS Lab Manual 90

Page 92: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

A[MIN]TEMP repeat

return;

Program: #include<stdio.h> #include<conio.h> int a [50] ; selectionsort(int a[],int n) { int i,j,min,temp; for(i=0;i<n;i++) { min=i; for(j=i+1;j<n;j++) { if (a [j] <a [min] ) min=j; } temp=a [i] ; a[i]=a[min] ; a[min]=temp; } return; } void main () { int i,j,n; clrscr () ; printf ("\n\t How many numbers do you want enter ?"); scanf ( "%d" , &n) ; printf("\n\t Enter the numbers"); for(i=0;i<n;i++) scanf("%d",&a[i]); selectionsort(a,n); printf("\n\t Numbers after sorting"); for(i=0;i<n;i++) printf("%d ",a[i]); getch() ; }

Result: How many numbers do you want enter? 5 Enter the numbers: 21 34 12 56 10 Numbers after sorting: 10 12 21 34 56

I - B.Tech CPDS Lab Manual 91

Page 93: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-19 19) Write C programs that use both recursive and non recursive functions to perform the following searching operations for a Key value in a given list of integers :i)Linear search ii) Binary search LINEAR SEARCH

Searching is finding a given element in an array of elements. Searchings are three methods 1) Linear search ,2) Binary search , 3) Fibonacci search . Linear search: We begin search by comparing the first element of an array with key element. If it matches search end, otherwise move to next element and compare. If no key element search is Unsuccess search. Implementation of linear search:

VARIABLES USED: Variable name datatype purpose a[] int to store given list of values key int element to be found i,flag,n int to store index ,boolean,no.of elements ALGORITHM: Function linear-search (A, N, KEY) A Array of N elements. KEY Element to be found I Index FLAG Boolean 1 or 0 1 // Search start with first element // I 1 FLAG0

2. //Scan one by one element to search key element// for I 0 toN increment by 1 do

if(A[I]=KEY) then //key element found// FLAG1 break

endif repeat 3. //Successful Search?// if(FLAG=0) then

print( 'Element not found.') return(0)

I - B.Tech CPDS Lab Manual 92

Page 94: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

else print ('Element found at location ')

return(I) endif

Program:

#include<stdio.h> #include<conio.h> void main( ) { int i, n, key=0, a[50], f=0; clrscr(); printf("Enter Number of elements in the array? ");

scanf ("%d", &n); printf ("Enter array elements"); for (i=0;i<n;i++) {

scanf (" %d", &a[i]); } for(i=0;i<n;i++) {

printf("%d\t",a[i]); }

printf("\n Enter element to be searched"); scanf("%d",&key); for (i=0;i<n;i++) { if(key==a[i]) {

f=1; break;

} }

if(f==0) printf (" \n Element not found. "); else printf ("Element %d found at location %d.\n", key, i+1); getch( ); }

Result:

Enter Number of elements in the array? 7 Enter array elements

2 30 4 10 12 15

I - B.Tech CPDS Lab Manual 93

Page 95: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Enter Element to be searched 10 Element 10 found at location 4.

BINARY SEARCH: This method starts with looking at the middle element of the array if it matches the key element then the search is completed. Otherwise the key element may be in upper half or lower half. The search progress with the upper half if the key element is less than middle element or with the lower half if the key element is greater than middle element Pre requisite of Binary search method is input elements array must be in ordered. Implementation of binary search (iterative): VARIABLES USED: Variable name datatype purpose a[] int to store given list of elements key int element to be found i,flag,n int to store index ,boolean,no.of element low,mid,high int to store intervals of list ALGORITHM: (ITERATIVE ) Function binary-search (A, N, KEY) A Array of N elements in ascending order KEY Element to be found LOW Temporary variable for lower limit of the search interval MID Temporary variable for middle limit of the search interval HIGH Temporary variable for upper limit of the search interval FLAG Boolean 1 or 0 1) //Initialization of boundaries of the list// LOW 1 HIGH N FLAG1 2) //Perform Search// while (LOW =< HIGH) do

3) //Obtain index of midpoint of search interval//

MID ((LOW + HIGH)/2) 4) //Compare middle element with key// if KEY < A[MID] then HIGH MID - 1 else if KEY> A [MID] then LOW MID + 1 else print ('Element found at position')

I - B.Tech CPDS Lab Manual 94

Page 96: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

FLAG0 return (MID); repeat while

5) //Unsuccessful Search// if (FLAG) then

print ('Element not found') return (0) endif

Program:

#include <stdio.h> #include<conio.h> void main( ) {

int a[50],i,n,low,high,mid,key,flag=1; clrscr(); printf ("\n Enter Number of elements in the array "); scanf (" %d", &n); printf (" \ nEnter elements in ascending order: " ); for (i = 0; i < n; i++)

scanf (" %d", &a[i]); printf (" \n Enter Element to be searched "); scanf (" %d", &key); low = 0; high = n - 1; while (low <=high) { mid = (low + high) / 2; if (key < a[mid])

high = mid - 1 ; else if (key> a[mid])

low = mid + 1 ; else { if (key == a[mid]) { printf(" \n Search successful."); printf("\n %d found at location %d." ,key, mid+1); flag = 0; break; } }

} if (flag) printf (" \n Search Unsuccessful.");

I - B.Tech CPDS Lab Manual 95

Page 97: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

getch(); }

Result: Number of elements in the array? 8 Enter elements in ascending order: 12 23 34 45 56 789 432 543 Enter Element to be searched? 789 Search successful. 789 found at location 6.

Implementation of binary search (recursive)

ALGORITHM: (RECURSIVE) Function Rbsearch (LOW, HIGH, A,KEY) A Array of N elements in ascending order KEY Element to be found LOW Temporary variable for lower limit of the search interval MID Temporary variable for middle limit of the search interval HIGH Temporary variable for upper limit of the search interval 1. // Intialise boundaries of the list// LOW 1 HIGH N 2. //Obtain index of midpoint of search interval// MID (LOW + HIGH)/2 3. // Compare middle element with key element// if KEY < A [MID] then LOC binary-search-R (LOW, MID - 1, A,KEY ) else if KEY > A[MID] then LOC binary-search-R (MID + 1, HIGH,A, ) else if(KEY=A[MID]) then return(MID) else return (LOC). endif

program: #include <stdio.h> int key; void main( ) {

int a[50],i,n,loc; int bin(); clrscr(); printf ("\n Enter Number of elements in the array? ");

I - B.Tech CPDS Lab Manual 96

Page 98: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

scanf ("%d", &n); printf ("\n Enter Array elements (ascending order) "); for (i=0;i<n;i++) scanf (" %d", &a[i]); printf("\n Enter element to be searched"); scanf("%d",&key); loc=bin(a,0,n); if(loc==0)

printf("\n Un success search"); else printf("\n Success, element %d found at location %d ",key,loc); getch();

} int bin(int a[],int low,int high) { int mid; if(low<=high) { mid=(low+high)/2; if(key<a[mid]) bin(a,low,mid-1); else if(key>a[mid]) bin( a,mid+1,high); else if(key==a[mid]) return(mid+1); } else return 0; return 0; }

Result: Enter Number of elements in the array? 8 Enter elements in ascending order: 12 23 34 45 56 789 432 543 Enter Element to be searched 789 Success, element 789 found at location 6.

I - B.Tech CPDS Lab Manual 97

Page 99: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-20 20)Write C program that implement the following sorting methods to sort a given list of integers in ascending order: i Quick sort

QUICK SORT In this method, the array of elements divided into two partition so that the pivot element is placed in proper position satisfying

1) All elements to the left of pivot element are less than pivot element 2) All elements to right of the pivot element are greater than or equal to

the pivot element. Repeat this process until array contains single element.

Implementation of quick sort: VARIABLES USED: Variable name datatype purpose a[] int to store given elements n int size of thelist i,j int increment variables temp int temporary variable ub,lb int to store intervals key int to store pivot element ALGORITHM: Procedure quick sort(A, LB, UB) A Array of n elements LB lower bound of the current sub-list UB upper bound of the current sub-list I Index variable J Index variable KEY Pivot element 1. //Read the elements into array//

for I1 to N increment by 1 do Read( A[])

repeat 2. if (LB<UB) then //checked whether list contains more than one element//

3 ILB, JUB . KEYLB 4. while (I<J) do //scan elements from left to right//

5. while(A[I]=A[KEY]) and (UB)) do II+1 Repeat //scan elements from right to left //

I - B.Tech CPDS Lab Manual 98

Page 100: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

6. while(A[J]>A[KEY]) do JJ-1 repeat

7. if(I<J)then swap(A[I],A[J]) endif repeat 8. swap(A[J] ,A[KEY]); 9. Call Quick_Sort (A, LB, J - 1) //Sort left sub-list// 10. Call Quick_Sort (A, J, + 1, UB) //Sort right sub-list// endif end quiksort Program: #include <stdio.h> swap(int *a,int *b) { int temp; temp=*a; *a=*b; *b=temp; return; } quicksort(int a[10] ,int lb,int ub) { int i=lb,j=ub,key=lb; if (lb<ub) { while (i<j) { while((a[i]<a[key])&&(lb<ub)) i++; while(a[j]>a[key]) j--; if(i<j) swap(&a[i] ,&a[j]); } swap(&a[j],&a[key]); quicksort(a,lb,j-1) ; quicksort (a,j+1,ub) ; } return; } void main () {

I - B.Tech CPDS Lab Manual 99

Page 101: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

int i,n,a[100]; clrscr () ; printf("\n\t How many numbers do u want to enter?"); scanf("%d",&n) ; printf("\n\t Enter the numbers:"); for(i=0;i<n;i++) scanf("%d",&a[i]); quicksort(a,0,n-1); printf("\n\t Numbers after sorting:"); for(i=0;i<n;i++) printf("%d ",a[i]); getch () ; } Result: How many numbers do u want to enter? 5 Enter the numbers: 21 34 12 56 10 Numbers after sorting: 10 12 21 34 56

I - B.Tech CPDS Lab Manual 100

Page 102: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-21 /* Write C program that implement the following sorting methods to sort a given list of integers in ascending order: i) Merge sort */ Program: #include <stdio.h> #include <stdlib.h> #define MAX_ARY 10 void merge_sort(int x[], int end, int start); int main(void) { int ary[MAX_ARY]; int j = 0; printf("\n\nEnter the elements to be sorted: \n"); for(j=0;j<MAX_ARY;j++) scanf("%d",&ary[j]); /* array before mergesort */ printf("Before :"); for(j = 0; j < MAX_ARY; j++) printf(" %d", ary[j]); printf("\n"); merge_sort(ary, 0, MAX_ARY - 1); /* array after mergesort */ printf("After Merge Sort :"); for(j = 0; j < MAX_ARY; j++) printf(" %d", ary[j]); printf("\n"); getch(); } /* Method to implement Merge Sort*/ void merge_sort(int x[], int end, int start) {

I - B.Tech CPDS Lab Manual 101

Page 103: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

int j = 0; const int size = start - end + 1; int mid = 0; int mrg1 = 0; int mrg2 = 0; int executing[MAX_ARY]; if(end == start) return; mid = (end + start) / 2; merge_sort(x, end, mid); merge_sort(x, mid + 1, start); for(j = 0; j < size; j++) executing[j] = x[end + j]; mrg1 = 0; mrg2 = mid - end + 1; for(j = 0; j < size; j++) { if(mrg2 <= start - end) if(mrg1 <= mid - end) if(executing[mrg1] > executing[mrg2]) x[j + end] = executing[mrg2++]; else x[j + end] = executing[mrg1++]; else x[j + end] = executing[mrg2++]; else x[j + end] = executing[mrg1++]; } } Result:

Enter the elements to be sorted : 2 54 73 21 7 Before : 2 54 73 21 7 After Merge Sort : 2 7 21 54 73

I - B.Tech CPDS Lab Manual 102

Page 104: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-22 /* Write C programs to implement the Lagrange interpolation and Newton- Gregory forward interpolation.*// Lagrange interpolation: Program: #include<stdio.h> #include<conio.h> #define MaxN 90 void main() { float arr_x[MaxN+1], arr_y[MaxN+1], numerator, denominator, x, y=0; int i, j, n; clrscr(); printf("Enter the value of n: \n"); scanf("%d", &n); printf("Enter the values of x and y: \n"); for(i=0; i<=n; i++) scanf("%f%f", &arr_x[i], &arr_y[i]); printf("Enter the value of x at which value of y is to be calculated: "); scanf("%f", &x); for (i=0; i<=n; i++) { numerator=1; denominator=1; for (j=0; j<=n; j++) if(j!=i) { numerator *= x-arr_x[j]; denominator *= arr_x[i]-arr_x[j]; } y+=(numerator/denominator)*arr_y[i]; } printf("When x=%4.1f y=%7.1f\n",x,y); getch(); } Result: Enter the value of n:3 Enter the values of x and y 1 1 2 4 3 9 Enter the value of x at which value of y is to be calculated 6 When x=6.00 y= 36.000

I - B.Tech CPDS Lab Manual 103

Page 105: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Newton- Gregory forward interpolation.: Program: #include<stdio.h> #include<conio.h> #define MaxN 100 #define Order_of_diff 4 void main () { float arr_x[MaxN+1], arr_y[MaxN+1], numerator=1.0, denominator=1.0, x, y, p, h, diff_table[MaxN+1][Order_of_diff+1]; int i,j,n,k; clrscr(); printf("Enter the value of n \n"); scanf("%d",&n); printf("Enter the values of x and y"); for(i=0; i<=n; i++) scanf("%f%f", &arr_x[i], &arr_y[i]); printf("Enter the value of x at which value of y is to be calculated"); scanf("%f", &x); h=arr_x[1]-arr_x[0]; for(i=0; i<=n-1; i++) diff_table[i][1]=arr_y[i+1]-arr_y[i];/*Creating the difference table and calculating first order differences*/ for(j=2; j<=Order_of_diff; j++)/*Calculating higher order differences*/ for(i=0; i<=n-j; i++) diff_table[i][j]=diff_table[i+1][j-1] - diff_table[i][j-1]; i=0; while(!(arr_x[i]>x)) /* Finding x0 */ i++; i--; p=(x-arr_x[i])/h; y=arr_y[i]; for (k=1; k<=Order_of_diff; k++) { numerator *=p-k+1; denominator *=k; y +=(numerator/denominator)*diff_table[i][k]; } printf("When x=%6.1f, y=%6.2f\n",x, y); getch(); }

I - B.Tech CPDS Lab Manual 104

Page 106: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Result: Enter the value of n 2 Enter the values of x and y 1 1 2 4 3 9 Enter the value of x at which value of y is to be calculated 2.5 When x=2.5 y=6.50

I - B.Tech CPDS Lab Manual 105

Page 107: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

WEEK-23 \* Write C program to implement the linear regression and polynomial regression algorithms. *\ Program: #include<stdio.h> #include<conio.h> #include<math.h> #include<string.h> float mean(float *a, int n); void deviation(float *a, float mean, int n, float *d, float *S); void main() { float a[20],b[20],dx[20],dy[20]; float sy=0,sx=0,mean_x=0,mean_y=0,sum_xy=0; float corr_coff=0,reg_coff_xy=0, reg_coff_yx=0; char type_coff[7]; int n=0,i=0; clrscr(); printf("Enter the value of n: "); scanf("%d",&n); printf("Enter the values of x and y:\n"); for(i=0;i<n;i++) scanf("%f%f",&a[i],&b[i]); mean_x=mean(a,n); mean_y=mean(b,n); deviation(a,mean_x,n,dx,&sx); deviation(b,mean_y,n,dy,&sy); for(i=0;i<n;i++) sum_xy=sum_xy+dx[i]*dy[i]; corr_coff=sum_xy/(n*sx*sy); printf("Enter the type of regression coefficient as 'x on y' or 'y on x': "); fflush(stdin); gets(type_coff); if(strcmp(type_coff,"x on y")==1) { reg_coff_xy=corr_coff*(sx/sy); printf("\nThe value of linear regression coefficient is %f",reg_coff_xy); } else if(strcmp(type_coff,"y on x")==1) {

I - B.Tech CPDS Lab Manual 106

Page 108: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

reg_coff_yx=corr_coff*(sy/sx); printf("\nThe value of linear regression coefficient is %f",reg_coff_yx); } else printf("\nEnter the correct type of regression coefficient."); getch(); } float mean(float *a, int n) { float sum=0, i=0; for(i=0;i<n;i++) sum=sum+a[i]; sum=sum/n; return (sum); } void deviation(float *a, float mean, int n, float *d, float *s) { float sum=0,t=0; int i=0; for(i=0;i<n;i++) { d[i]=a[i]-mean; t=d[i]*d[i]; sum=sum+t; } sum=sum/n; *s=sqrt(sum); } Result: Enter the value of n:3 Enter the values of x and y: 1 1 2 4 3 9 Enter the type of regression coefficient as 'x on y' or 'y on x':x on y The value of linear regression coefficient is -3.333333

I - B.Tech CPDS Lab Manual 107

Page 109: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Week-24 /*Write C programs to implement Trapezoidal Simpson methods.*/ Trapezoidal Method: Program: #include<stdio.h> #include<conio.h> main() { int i,num; float x[100],h,y[100],ans=0.0 ; clrscr() ; printf(“ Enter the number of terms :” ) ; scanf(“%d”,&num); for(i=0;i<num;i++) { printf(“/n Enter the value of x %d:”,i); scanf(“%f”,&x[i]); printf(“/n Enter the value of y %d:”,i); scanf(“%f”,&y[i]); } h=x[i-1]-x[i-2]; for(i=1;i<=(num-1);i=i+2) { ans=ans+4*y[i]+2*y[i+1]; } ans=ans+y[0]+y[num-1] ; ans=ans*0.5*h ; printf(“/n/n Integral of x is : %f ” ,ans); getch(); } Result : Enter the number of terms: 7 Enter the value of x 0 : 1 Enter the value of y0: 2.105 Enter the value of x 1: 2 Enter the value of y1: 2.808 Enter the value of x 2 : 3 Enter the value of y2: 3.614 Enter the value of x 3 : 4 Enter the value of y3: 4.604 Enter the value of x 4 : 5

I - B.Tech CPDS Lab Manual 108

Page 110: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

Enter the value of y4: 5.857 Enter the value of x 5 : 6 Enter the value of y5: 7.451 Enter the value of x 6 : 7 Enter the value of y6: 9.467 Integral of x is : 30.12 Simpson Method Program: #include<stdio.h> #include<conio.h> main() { int i,num; float x[100],h,y[100],ans=0.0 ; clrscr() ; printf(“ Enter the number of terms :” ) ; scanf(“%d”,&num); for(i=0;i<num;i++) { printf(“/n Enter the value of x %d:”,i); scanf(“%f”,&x[i]); printf(“/n Enter the value of y %d:”,i); scanf(“%f”,&y[i]); } h=x[i-1]-x[i-2]; for(i=1;i<(num-2);i=i+2) { ans=ans+4*y[i]+2*y[i+1]; } ans=ans+y[0]+y[num-1] ; ans=(ans*h)/3.0 ; printf(“/n/n Integral of x is : %f ” ,ans); getch(); } Result : Enter the number of terms: 5 Enter the value of x 0 : 1 Enter the value of y0: 13 Enter the value of x 1: 2 Enter the value of y1: 13 Enter the value of x 2 : 3 Enter the value of y2: 70 Enter the value of x 3 : 4

I - B.Tech CPDS Lab Manual 109

Page 111: Cpds Lab Manualdasdas

CMR Institute of Technology Redefining Quality Education

I - B.Tech CPDS Lab Manual 110

Enter the value of y3: 80 Enter the value of x 4 : 5 Enter the value of y4: 100 Integral of x is : 257.6667


Recommended