Você está na página 1de 160

LAB INSTRUCTIONS

1. Students should report to the concerned lab as per the time table.

2. Students who turn up late to the labs will in no case be permitted to do the program schedule for the day. 3. Student should bring a observation book of 200 pages and should draw the flowchart, Algorithm and write program in the observation book along with the sample input and output of the program while performing the execution of the program
4. After completion of the program, certification of the concerned staff in-charge in the

observation book is necessary.


5. The immediate last lab session program to be written in the lab record book and should be

submitted and corrected by the concerned faculty.


6. Viva must be conducted for each student for 5 mints in each lab session about the

understanding of the lab program.


7. The student should not be allowed without the observation book and without completion of

record book of the last immediate lab session.


8. To improve the understanding of the fundamentals of C&DS additional programs given by

the faculty are to be executed by the students.


9. Out of the 25 marks for internal, day-to-day work in the lab shall be evaluated for 15 marks

and internal examination for practical shall be evaluated for 10 marks conducted by the concerned faculty.
10. If a student is absent for a lab session the concerned faculty should intimate to the student

parents immediately. .

_____________________________________________________________________________________ 1 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

List of Experiments
Experiment NAME OF PROGRAM A)Sum of individual digits of given integer 1 B)generate first n terms of Fibonacci series C)generate prime numbers between 1 and n A)calculate sum of series 2 SUM=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! B) Roots of a quadratic equation. 3 a) To find the factorial of a b) To find the GCD of two c) To solve Towers of Hanoi problem 4)a)Calculation if s=ut+1/2at2 4 b) program, which takes two integer operands and one operator form the user(+,-,*,/,% use switch) 5)a)find largest and smallest number in a list of integers 5 b) program that uses functions to perform i)Addition of Two Matrices ii)Multiplication of Two Matrices Use functions to perform the following operations: a)i)insert sub-string into main string from given pos. ii)delete n Characters from a given position in given string. b) given string is a palindrome or not a) display the position or index in the string S where the string T begins, or 1 if S doesn't contain T. b) count the lines, words and characters in a given text. 8 9 a) generate Pascal's triangle b) construct a pyramid of numbers a) geometric progression: sum=1+x+x2+x3+.+xn 58 64 34 28 given integer. given integers. 18 12 5 PAGE NO

39

49

_____________________________________________________________________________________ 2 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

perform error checking 10 a) 2's complement of a number b) convert a Roman numeral to its decimal equivalent A)use functions to perform following ops on complex numbers a)read b)write c)add d)multiply (Use structure to represent complex number) a)program to copy one file to another 12 b)to reverse first n characters in file (file name and n specified on command line) Write a C program to display contents of file. 13 C program to merge two files into a third file (That is contents of first file followed by those of second are put in a third files) 90 83 69

11

78

14 15 16

Use functions to perform following ops On single linked list a)creation b)deletion c)display d)traversal in 2 way Implement stack operations using a)arrays b)pointers Implement queue operations using a)arrays b)pointers Use stack operations

95 106 114

17

a)to convert infix to postfix expression b)evaluate postfix expression

122

18

a)Bubble sort b) Selection sort Searching

127

19

a)linear search b)binary search

134

20 21

Sorting a)quick sort Sorting

140 146

_____________________________________________________________________________________ 3 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

a)merge sort 22 23 24 Implement the Lagrange interpolation and Newton- Gregory forward interpolation Implement the linear regression and polynomial regression algorithms Implement Trapezoidal and Simpson methods 150 157 160

Experiment: 1 1A. Write a Program in C to find the sum of individuals Digits of a positive Integer.
AIM: Teaching the students how to write simple logic in all these programs
_____________________________________________________________________________________ 4 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors Theory: a) In mathematics, the digit sum of a given integer is the sum of all its digits, (e.g.: the digit sum of 84001 is calculated as 8+4+0+0+1 = 13). Digit sums are most often computed using the decimal representation of the given number. Algorithm: step 1: start step 2: Read the number n step 3:initialize sum =0 step 4: repeat the steps 4-7 while n not equal to 0 step 5:do module division by 10 to get remainder step6: add the remainder to a sum variable step7:do division by 10 to get the quotient
Start

r=n%10

sum=sum+r n=n/10

step 8: print the sum step 7: stop


Input n

If n< 0 s=0.m=n

Flowchart

Repeat until n=0 r=n%10 s=s+r n=n/10 Invalid input

print m, s _____________________________________________________________________________________ 5 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL Stop

Yes

No

Yes No

Result: Input: Enter the number 987 Output: The sum of individual digits is 24

1B. Write a program to find 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 precedes two preceding two terms in the sequence, Write a C Program to Generate the first n terms of the sequence. AIM: Teaching the students how to write simple logic in all these programs Recommended systems/software requirements :
_____________________________________________________________________________________ 6 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Intel based desktop pc ANSI C compiler with supporting editors Theory: The Fibonacci Summation Series takes 0 and adds 1. Succeeding numbers in the series adds the previous two numbers and thus we have 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 to infinity. Do you see the pattern? 1+1=2, 1+2=3, 2+3=5, 3+5=8, 5+8=13..... Solution: step1: start step2: read number of Fibonacci number to be printed into n step3: initialize I to 2, f1 to 0, f2 to 1 step4: print f1,f2 step5: repeat the steps 5-10 upto while i<=n step6:temp = f1+f2 step7: f1 = f2 step8: f2 = temp step9: print f2 step10: i = i+1 step11: stop

Flowchart

Start Input n

f1=0, f2=1 Print f1, f2


Repeat the following for n-2 times

_____________________________________________________________________________________ 7 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

f=f1+f2 Print f f1=f2 f2=f

Stop

Result: Input: Enter the number of Fibonacci numbers to be printed: 8

Output: The first 8 Fibonacci numbers are 0, 1, and 1,2,3,5,8,13

1C. Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied by the user.
AIM: Teaching the students how to write simple logic in all these programs Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors Theory: C) In mathematics, a prime number (or a prime) is a natural number which has exactly two distinct natural number divisors: 1 and itself. The first twenty-five prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97. Solution:
_____________________________________________________________________________________ 8 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Algorithm: 1. Enter a no n 2. for i=1 to n do (a) k=prime(i). (b) if(k==1) (i) Print prime, i 3. Stop. Algorithm: prime(i)
1. 2. 3. 4. 5. 6. 7. 8.

p=sqrt(i). j=2,l=1 while(j<=p)( repeat 3 through 7) r=i%j if(r==0) then no 6, else step 7. l=0, goto step 8. j++. return(l)

Flowchart:
start Input n For i=1 to n

No

yes

k=prime(i)

No

If k= =1

_____________________________________________________________________________________ 9 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Yes Yes
Print i

stop Prime(i) p=sqrt(i) j=2,l=1 While(j<=p)

False

True
r=i% j

No
j++

If r==0

Yes
l=0
return(l)

Result: Input: Enter the number :10 Output:

The prime numbers are 1 2 3 5 7

Questions: 1. What is the purpose of including math.h header file in a c program? 2. The predefined function scanf() is declared in the ------- header file. 3. -----------header file contains the declarations of the mathematical functions.
_____________________________________________________________________________________ 10 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

4. the variable declared as int sort occupies ---- bytes of memory. 5. the format string that is used for printing int sort values is ----

6. the result of expression floor(24.6) is ----7. the type of the value that is returned from the predefined function sqrt (-35) is --8. List out the relational operators. 9. The predefined function printf() is declared in the ------- header file 10.variable declared as char x occupies how many bytes----11.list out logical operators 12.the result if (25/7)----------13.the result of (25%7)------------14. What is the purpose of including stdio.h header file in a c program.

Experiment: 2 2A. Write a C program to calculate the following Sum: Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!
AIM: To teach the students use logic to calculate these type of series then we calculate the series for any x and n And use of switch statement

_____________________________________________________________________________________ 11 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors Theory: a)sums of the power series cos(x) = 1 - x2/2 + x4/4! - x6/6! + ... . The series converges for all x.

Solution: Algorithm: 1. Input value of x 2. sum = 1.0 3. sign = -1 4. Repeat the following For i=2 to 10 do Steps 5 to 10 5. nu=pow(x, i) 6. de = fact (i) 7. term = nu/de 8. term *= sign 9. sum += term 10. sign*=-1 11. Print sum 12. Stop.

Algorithm for fact() (1) (2) (3) (4)


(5)

Receive n value p=1 Repeat for n times (i = 1 to n) p = p * i. Return p.

Flowchart:
Start

Input x

fact(n)

_____________________________________________________________________________________ 12 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

sum = 1.0; sign = -1 Repeat i=2 to 10 nu = pow(x, i) de = fact(i) term = nu/de sign*=-1 sum+=term

p=1

No

Repeat I = 1 to n

No

Yes Yes
p=p*i

Return p

Print sum

Stop

Result: Input: Enter the value of X : 0 and n=20 Output: The sum of series is 1.00000

2B. Write a C Program to find the roots of a quadratic equation.


Theory: b) Consider the general quadratic equation ax2+bx+c=0

_____________________________________________________________________________________ 13 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

here discriminant is defined as d=b2-4ac/2a when d=0 roots are equal r1=r2=-b/2a when d<0 roots are imaginary roots are r1=(-b +i sqrt(d))/2a r2= (- b- i sqrt(d))/2a when d>0 roots are r1=-b + sqrt(d)/2a r2= - b- sqrt(d)/2a

Algorithm: 1) Enter the values for a, b, c;


2) Calculate discriminate d = b2 4ac.

3) If discriminate is 0, then choice is 1, if d is greater than 0 then choice is 2 otherwise choice is 3. 4) Print a, b, c, d. 5) Choose the sequence based on choice = 1 step 6, choice = 2 goto step 7, choice = 3 goto step 8. i) print Equal roots ii) x1=-b/2*a iii) x2 = -b/2 * a. iv) print the roots x1, x2. v) goto step 9. i) ii) iii) iv) print roots are real and unequal. x1 = -b + d / 2a x2 = - b - d / 2a print x1, x2

_____________________________________________________________________________________ 14 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

v)

goto 9.

6) i) print roots are imaginary ii) print x1 ie complex root. iii) print x2 ie complex root. 7) Stop.

_____________________________________________________________________________________ 15 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Flowchart:
Start

Enter values a, b, c d= b2 - 4 ac

Yes

If d=0

No
If d>0

ch = 1

No
ch = 3

Yes
ch = 2

Print a, b, c, d

Swi tch cas e ch

1
Print Equal roots

2
Print roots are real & unequal

3
Print Imaginary roots

x1 = x2 = - b / 2a x1 = - b+d/2a Print x1, x2 x2=-b-d/2a Print x1 is complex

Print x1, x2

Print x2 is complex

Stop

_____________________________________________________________________________________ 16 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Output: 1. Enter a,b,c values5 2 1 A= 5.00 B= 2.00 c= 1.00 Discriminant D=-16.00 Imaginary roots x1= -0.20+i 0.40 x2= -0.20-i 0.40 2. Enter a,b,c values2 4 2 A= 2.00 B= 4.00 c= 2.00 Desciminat D= 0.00 Equal Roots x1=x2= -1.00 Questions : 1. when division operator / is applied to an integer what is the output-----------2. which of them is given high priority ,arthematic operator or relational operator ------------3. what are the logical operators ----------4. in which type of operators first the value is decremented and then the required operation is performed---------5. what are the format specifiers for character and strings---6. what is type casting------------7. what is the output for printf(%-6d,9876); 8. format specifications contained in the control string should match the agreement in the order(y/n)---------9. -------is used when we want to exit from the loop 10. ------ loop executes atleast once and then checks whether the given condition is true or false 11. ---- dimensional array contains n rows,m columns and p surfaces 12. can the automatic arrays be initialized 13. can subscript of an array be a real value or char value

Experiment: 3
_____________________________________________________________________________________ 17 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

3A. Write C programs that use both recursive and non-recursive functions i) To find the factorial of a given integer.
AIM: To explain the students the difference between recursive and non recursive functions Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors Theory: a)In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5!=1 X 2 X 3 X 4 X 5 = 120 and 7!=1 x 2 x 3 x 4 x 5 x 6 x 7=720

using recursive function. In recursive functions the function calls itself Non-Recursive Approach: Algorithm: (1) Input a +ve integer No n. (2) Check whether n is +ve or not. i) ii) If n is ve print cant be evaluated the factorial goto step (4). Else calculate fact i.e., n! call function fact(n).

(3) Print factorial of n. (4) Stop. Algorithm for fact(): (1) f = 1 (2) Repeat i=1 to n times. f = f * i. (3) Return f. Flowchart:
Start

Flowchart: fact(n)
Start

_____________________________________________________________________________________ 18 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Enter a +ve no n

f=1

No Yes
if n<0 f=fact(n)
Invalid input

for i = 1 to n

No

Yes

f*=i

Print f, n

Return f

Stop

Recursive Approach Flow Chart: Start Input n fact(n) Print n, fact(n) Stop

Flowchart: fact(n)
fact(n)

No If n<= _____________________________________________________________________________________ 19 1
MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Yes
return(n*fact(n1)) return(1)

Result: Input: Enter the number : 5 Output: The result is 120

3B. Write a C Program to find GCD (Greatest Common Divisor) of two given integers use both recursive and non-recursive functions.
Theory: In mathematics, the greatest common divisor (gcd), also known as the greatest common factor (gcd) or highest common factor (hcf), of two non-zero integers, is the largest positive integer that divides both numbers without remainder. gcd(42, 56) = 14, therefore,

Recursive Approach Algorithm: step1: start step2: Read a,b step3: rst=gcd(a,b) step4: print rst step5: stop

int gcd(x,y) start

_____________________________________________________________________________________ 20 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

if(y=0) return x else return(gcd(y, x%y)) stop using non recursive functions by using loops step1: start step2: read a,b step3: repeat step 3 and 4 until (a <>0) if (a != 0) temp = a step4: calculate a value a = a%b b = temp step5: print temp step6: stop

Flowchart:
Start Input 2 Nos, a, b

_____________________________________________________________________________________ 21 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

gcd=hcf(a, b) Print a, b, gcd Stop

Flowchart: hcf(p, q)
hcf(p, q) r = p-(p/q2)

If r= =0 return(q )

No

Yes
hcf(p, q)

return(r)

Result: Input: Enter two numbers : 15 24 Output: The GCD is 3

3C. Write a 'C' Program to solve tower of HANOI problem using both Recursive and Non-Recursive.
Theory: The Tower of Hanoi or Towers of Hanoi (also known as The Towers of Brahma) is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide
_____________________________________________________________________________________ 22 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

onto any rod. The puzzle starts with the disks neatly stacked in order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod. No disk may be placed on top of a smaller disk.

Recursive Approach Algorithm: step1: start step2: initialize s=L, i=C, d=R step3: Read n step4: call Hanoi(n,s,i,d) step5: stop

void Hanoi(n,source,inter,dest)\ start if (n=1) then print('Move the disk from ', source, ' to ', dest) else start
_____________________________________________________________________________________ 23 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Hanoi(n-1, source, inter, dest); Hanoi(1, source, dest, inter); Hanoi(n-1, inter, dest, source); stop; Stop

NonRecursive Approach Algorithm: step1: start step2: initialize dest(final place of disk)s=L, i=C, d=R step3: Read n step4: set disk=n step5: repeat while disk > 0 do if disk is already on dest, or, moving it succeeds then if disk = max then max= max - 1 if max = 0 then return // done end if let dest be the final place of max end if else let dest be the alternative place between dest and the current place of disk end if decrement disk by 1 end while let p and q be the places different of dest let disk be the smaller of the disks on top of p and q let dest be the place between p and q with greater disk on top end repeat step6: stop Flowchart:
Start

_____________________________________________________________________________________ 24 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

snvalue=L invalue=C dnvalue=R Input Disks, n Print Tower of Hanoi problem with disks, n hanoi(n, snvalue, invalue, dnvalue) Stop hanoi(n, snvalue, invalue, dnvalue)

If n!=0

No

Yes
hanoi(n1,sndl,dndl,indl) Print Move disk n from sndl to dndl hanoi(n-1, indl, sndl, dndl) return

Result: Input: Enter no of disks: 3 Output:


_____________________________________________________________________________________ 25 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Move the disk from source to inter Move the disk from source to dest Move the disk from inter to dest Move the disk from source to inter Move the disk from dest to inter to inter Move the disk from source

Move the disk from dest to source Move the disk from inter to source Move the disk from source to inter Move the disk from inter to dest Move the disk from source to inter Move the disk from source to dest Move the disk from source to dest Questions: 1) what happens if we use a break into a inner loop ---------------2) what happens if we use a continue into a inner loop ----------3)difference between recursive and non recursive functions-------4)minimum no of times the while loop is executed----------------5)each case statement in switch is separated by-------------6) minimum no of times the do-while loop is executed--------------7) minimum no of times the for loop is executed----------------8)the break statement is used in------------9)what is output of program main() { int c=0; do{ printf(%d,c++); }while(c<=9); } 10.number of loop constructs in c language-----------------------

_____________________________________________________________________________________ 26 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 4 4A. The total distance traveled 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 traveled 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'.
AIM: To explain the students the use of multi way selection statement. Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors Theory: a)In physics, equations of motion are equations that describe the behavior of a system (e.g., the motion of a particle under an influence of a force) as a function of time. S=ut+1/2at2 S=distance traveled by vehicle in t seconds U=initial velocity(m/sec) Algorithm: 1. Begin. 2. Input initial velocity u. 3. Input Acceleration a. 4. Input starting time and final time i & n. 5. Input time interval it.
6. Print Time Distance U m/sec A m/sec2 .

T=time in sec

A=acceleration(m/sec2)

7. For (t = i ; t<= n ; t+=it) repeat following steps (i) (ii) d=u*t+a*pow(t, 2)/2. Print t , d, u, a.

_____________________________________________________________________________________ 27 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

8. Stop.

Flowchart: Start

Input Initial velocity u

Input acceleration a Input start time i Input ending time n Input Interval it

Repeat t=i to
n with step it

No

Yes d=ut+1/2 at2 Print t, d, u, a

Stop

_____________________________________________________________________________________ 28 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Result: Input: Enter Initial velocity 4 Enter Acceleration: 5 Enter starting time/final time: 1 10 Enter time interval: 1 Output: Time Distance 1 6.50 2 18.00 3 34.50 4 56.00 5 82.50 6 114.00 7 150.50 8 192.00 9 238.50 10 290.00 U m/sec 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 a m/sec2) 5.00 5.00 5.00 5.00 5.00 5.00 5.00 5.00 5.00 5.00

4B.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)
Theory: switch statement is one of the control statement also called as multi way selection statement. which provides

Easier debuggability (e.g. setting breakpoints on code vs. a call table) easier to read (subjective) and easier to maintain than an equivalent series of if-else statements operators used here are (+,-,*,/,%)

Algorithm: 1. Begin 2. Enter a, b values. 3. Print MENU. (i) Print + Addition.

_____________________________________________________________________________________ 29 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

(ii) Print - Subtraction. (iii) Print * Multiplication. (iv) Print / Division. (v) Print % Remainder. (vi) Print E Exit. 4. Print Enter your choice. 5. If op==E then goto step 8 otherwise follow the below steps 6. Switch(op) a. case +: i. ii. iii. iv. b. case -: v. vi. vii. viii. c. case *: ix. x. xi. xii. d. case /: Print Addition. c=a+b. Print Sum=c. break Print Subtraction. c=a-b. Print Difference=c. break Print Multiplication. c=a*b. Print Product=c. break

xiii. Print Division. xiv. c=a/b. xv. Print Quotient=c. xvi. break e. case %: xvii. Print Remainder. xviii. c=a%b. xix. Print Remainder=c. xx. break f. default: xxi. Print Invalid Option. xxii. break 7. while(1) then goto step 3. 8. Stop.

_____________________________________________________________________________________ 30 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

flowchart: Start

Input a, b Menu + Addition - Subtraction * Multiplication / Division % Remainder E Exit Input choice op Yes If op = E No

Swi tch (OP )

+ c=a+b Print sum c

c=ab Print Diff c

* c=a*b Print product c

/ c=a/b Print Quaff c

% c=a%b Print remainder c

Stop

Result: Input: Enter a and b: 5 3 Output:


_____________________________________________________________________________________ 31 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

MENU + Addition - Subtraction * Multiplication / Division % Remainder MENU + Addition - Subtraction * Multiplication / Division % Remainder E Exit g Invalid Option E (Exited) Questions: 1. what are the advantage of switch-case statement ? 2. what are the limitations of a switch-case statement ? 3. why a break statement is generally added at the end of every case statement ? 4. the case labels can contain the floating points constants (T/F) 5. the character variable in C is allocated ------ bytes of memory 6. --------makes one selection when there are several choices to be made 7. what is meant by type casting 8. can we use a switch statement to switch on strings 9. ---- is used to terminate the control from the loop statements of the switch case structure

Experiment: 5

_____________________________________________________________________________________ 32 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

5A. Write a C program to find both the larges and smallest number in a list of integers.
AIM: Teaching the students how to use 1-D arrays to read list of similar data and use of 2-D arrays to read matrices Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors Theory: a)Here we are using arrays to read a list of integers. In the entire list we assign first element as both minimum and maximum. After that we compare each element of list with maximum and minimum. If it is less than minimum then that is minimum If it is greater than maximum then that is maximum. ALGORITHM: Step1: start Step2: read n Step3: repeat step3 until i<n Read a[i] Step4: small=a[0] Step5: lar=a[0] Step6: repeat step6 until i<n If(a[i]<small) Small=a[i] If(a[i]>lar) Lar=a[i] Step7: print lar,small Step8: stop

_____________________________________________________________________________________ 33 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Result: Input: Enter the value of n : 5 Enter the numbers: 12 14 11 15 17 Output: The result is lar=17 small=11

5B. Write a C program that uses functions to perform the following: i)Addition of Two Matrices ii)Multiplication of Two Matrices
b) A matrix is a rectangular arrangement of numbers. The horizontal and vertical lines in a matrix are called rows and columns, respectively. The numbers in the matrix are called its entries. To specify a matrix's size, a matrix with m rows and n columns is called an m-by-n matrix or m n matrix, while m and n are called its dimensions Operation Definition The sum A+B of two m-by-n matrices A and B is calculated entrywise: (A + B)i,j = Ai,j + Bi,j, where 1 i m and 1 j n. Multiplication of two matrices is defined only if the number of columns of the left matrix is the same as the number of rows of the right matrix. If A is an m-by-n matrix and B is an n-by-p matrix, then their matrix product AB multiplication is the m-by-p matrix whose entries are given by A[m,n]*b[n,p]=c[m,p]

Addition

_____________________________________________________________________________________ 34 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

ALGORITHM: Step1: start Step2: read the size of A matrix r1,c1 Step3: repeat for i=1 to r1 Repeat for j=1 to c1 Read a[i][j] Step4: read the size of B matrix r2,c2 Step5: repeat for i=1 to r2 Repeat for j=1 to c2 Read b[i][j] Step6: if(r1==r2) and (c1=c2) Print addition is Repeat for i= 1 to r1 Repeat for j=1 to c1 C[i][j]=a[i][j]+ b[i][j] Else Print addition not possible Step7: repeat for i=1 to r1 Repeat for j=1 to c1 print c[i][j] Step8: if(c1=r2) Print multiplication is Repeat for i=1 to r1 Repeat for j=1 to c2 C[i][j]=0

_____________________________________________________________________________________ 35 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Repeat for k=1 to c1 C[i][j]=c[i][j]+(a[i][k]*b[k][j]) Else Print multiplication not possible Step9: repeat for i=1 to r1 Repeat for j=1 to c2 Print c[i][j] Step10: stop

Result: Input: Enter the values of r1,c1 : 2 2 Read the elements of A matrix 1 1 1 1 Enter the values of r2,c2 : 2 2 Read the elements of B matrix 1 1 1 1

Output:

Addition is: 2 2 2 2 multiplication is 2 2 2 2

_____________________________________________________________________________________ 36 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Questions: 1.array is used to represent------------------2.one dimensional array is also known as --------------3.array elements are represented by---------------4.array elements occupy ---------------memory locations 5.array subscript in c always start with------------6.identify correct declaration a)int a[10[10] b)int a(10)(10) c)int a[10,10] 7.maximum no of elements in array declaration of a[4][5]----8.when should array is used 9.the value in the [] array declaration specifies------------10.character array known as-------------

_____________________________________________________________________________________ 37 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 6 6A. Write a C program that uses functions to perform the following operations: i)To insert a sub-string in to given main string from a given position.
AIM: Teaching the students how to use character arrays and how to perform insertion to the strings Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors ALGORITHM: step1: start step2: read the main string and store it in mainstr step3: read inserting string and store it in insstr step4: read position of insertion and store it in pos step5:find length of main string and store it in l1=strlen(mainstr) step6: find length of inserting string and store it in l2=strlen(insstr) step7: if(pos>l1)i.e if position is beyond length of main string then Step8:insert string at end of main string step9:mainstr[l1++]=insstr[i] step10:print mainstr step11:otherwise( else ) step12:initialize temporary variable temp step13:at first from beginning to pos store main string in temp step14:from position to l2 store inserting string in temp step15: the remaining main string is stored temporary variable step16: print the temp variable ,
_____________________________________________________________________________________ 38 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step17: stop

_____________________________________________________________________________________ 39 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

START

READ MAIN STRING

READ INSERTING STRING READ POSITION OF INSERTION READ B[I][J] l1=strlen(mainstr) l2=strlen(insstr)

if(pos>l1) Yes insert string at end of main string mainstr[l1++]=insstr[i] print mainstr

N o from beginning to pos store main string in t variable

then from position to l2 store inserting string in temporary variable

then the remaining main string is stored temporary variable

STOP

_____________________________________________________________________________________ 40 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Input: Enter main string: ramu is good boy Enter string to be inserted :very Enter position to be inserted:10 Expected Output:

Ramu is very good boy

6B) To delete n Characters from a given position in a given string.


AIM: Teaching the students how to use character arrays and how to perform deletion to the strings. Algorithm: step1: start step2: read the string and store it in variable string step3: find length of string and store it in l=strlen(string) step4: read no of chars to delete and store it in (del) step5: read the position from delete and store it in (pos) step6: if(pos>l) step7: print deletion not possible step8: else begin step9: initialize j=pos step10:repeat step11:increment j step12:str[j]=str[i] step13:str[j]=null
_____________________________________________________________________________________ 41 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step14: until i=pos+del <= l step15:end step16: print str step17: stop

_____________________________________________________________________________________ 42 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

START

READ STRING

READ NO OF CHARS TO DELETE(DEL) READ POSITION OF INSERTION(POS) READ B[I][J] l=strlen(string)

if(pos>l) T

initialize j=pos T increment j str[j]=str[i]; str[j]=null str[j]=null i=pos+del <= l

print deletion not possible

F PRINT STR

STOP

Result:
_____________________________________________________________________________________ 43 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Input: Enter main string: ramu is a good boy Enter how many characters u want to delete:5 Enter position to be delete:10

Expected Output: Ramu is a boy

Questions: 1.What is a string? 2.What is a character? 3.which is string related function in this program a)strlen b)delete c)position 4.the function used to compare the strings is --------5.the function used to copy one string to another is-----

6C.Write a C program to determine if the given string is a palindrome or not


AIM: A C program to determine if the given string is a palindrome or not

ALGORITHM: Step1: start Step2: initialize flag=1 Step3: read string and store it in string Step4: find length of string and store it in l=strlen(string) Step5: compare first character of string with last character
_____________________________________________________________________________________ 44 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Step6: If they are not equal Step7: Flag=0 Step8:This process repeated upto middle of string(len/2) Step9: if(flag=1) Step10:Print string is palindrome Step11:Else Step12:Print string is not palindrome Step13:end if Step14:stop

Flowchart:

_____________________________________________________________________________________ 45 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

START

READ STRING

FLAG=1, I=0 LEN=STRLEN(STR) I++ I=0

I<LEN/2

I<LEN/2 IF STR[I]! =STR[LEN-I] T F

FLAG=0

FLAG=1

PRINT NOT PALINDROME

PRINT PALINDROME

STOP

Result: Input:

_____________________________________________________________________________________ 46 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Enter a string: liril Expected Output:

The given string is palindrome

Questions: 1. which is string related function: a)strcmp b)cut c)copy 2. the function used to compare the strings is --------3. the function used to copy one string to another is----4. when two strings are equal them strcmp() returns----5. to find length of a string function is-------6. program execution starts with -------- function 7. how many main() functions can be written in program----8. a function is identified by an open parenthesis followed by -----9. default return type of function is-----------10. what are actual parameters-------------

Experiment: 7

_____________________________________________________________________________________ 47 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

7A. 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.
AIM: Teaching the students how to use character arrays and how to display the portion of string and count no of lines words and chars in the strings

Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

ALGORITHM:

Step1: start step2: read the main string and store it in mainstr step3: read sub string string and store it in substr Step4: find position by strstr function and store it in pos pos=strstr(mainstr,substr) Step5: if(pos) find position and store it in posn Step6: Posn=pos-mainstr+1 Step7:Else Step8:Posn=-1 Step9: print substring is found in mainstr at posn Step10:stop

_____________________________________________________________________________________ 48 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

START

READ MAIN STRING(S)

READ SUBSTRING(T)

POS=STRSTR(S,T)

if(pos) T POSN=-1

POSN=POSN-S+1

PRINT STR

STOP

Result:
_____________________________________________________________________________________ 49 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Input: Enter main string: softwareengineer Enter substring: engineer Expected Output: Engineer is found in software at position 9

Questions: 1.What is the string function used here a)strstr b)strc)strcmp 2intially position value is____________ 3.syntax to calculate for position is______________ 4.what is meant by character arrays ___________________. 5.syntax to find the difference in between strings is _________________.

7B. Write a C program to count the lines, words and characters in a given text
_____________________________________________________________________________________ 50 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Aim: A C program to count the lines, words and characters in a given text. Theory:for counting no of lines words characters in given text we use any special characters to stop the counting we use line count is lc word count is wc character count is i

ALGORITHM:

Step1: start Step2: initialize character count cc=0,word count wc=1,line count lc=1 Step3: read the string character by char till it end with any special character like # C=getchar() Step4: sting is placed in variable str Step5: every string last character is null so assign str[i]=null Step6: repeat step7 upto end of string ie str[i]=null Step7: Begin Step8:If(str[i]==\n) (newline) Step9:Increment lc Step10:increment Wc Step11:Else Step12:If(str[i]= and str[i+1]!= )(if space or tab or double space is there it is treted as word step13:increment Wc
_____________________________________________________________________________________ 51 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step14:increment cc Step15: print character count cc Step16: print word count wc Step17: print line count lc Step18: stop

_____________________________________________________________________________________ 52 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

START

READ C

WHILE C! =# T STR[I]=C, I=I+1 C=getchar F

STR[I]=\0 I=0

While str[i]! =\0 a

_____________________________________________________________________________________ 53 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

a F IF(STR[I] =\n T lc++ , WC++ Wc++ Wc++ T F IF(STR[I] =\n T F

NC++

PRINT NC,NW,NL

STOP

Result: (test data)Input: Ramu is good boy Computer Engineer College#

Expected Output: Character count is:45 Word count is:8

_____________________________________________________________________________________ 54 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Line count is:4 Questions: 1.the ternary operator supported in C is -----2.the bitwise complement operator supported in C is ---3. -------- are having highest precedence in C lang among all operators 4. the expression 4+2%8 evaluates to-------5.every program in a program must end with a ------------6.write the syntax of scanf statement 7.----statement is used for unconditional branching in C 8.what is initialization ? 9.find the sqrt(23.4). 10.the operator at higher level precedence are evaluated first.<T/F>?

_____________________________________________________________________________________ 55 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 8 8A. Write a C program to generate Pascal's triangle.


AIM: Teaching the students how to form the number in the form of pyramid. traingle Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors ALGORITHM: Step1: start Step2:initialize bigno=1,count=0 Step3: read no of rows and store it in n Step4: repeat step4 upto (count<n) Step5:Print the pascal triangle from centre of screen Step6: Repeat Step7:If(i=0 or j=0) Step8:Bingo=1 Step9:Else Step10:Bingo=(bingo*(j-i+1))/i STEP11: the steps 4 TO 11 UPTO I<= count Step12:Print bingo Step13: print new line Step14:stop

_____________________________________________________________________________________ 56 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Flowchart:
START

READ N BIGNO=1, Coun=0 COUNT=0 I++ I=0

I<COUNT F IF I=0 OR J=0 T BIGNO=1 BIGNO=(bingo*(j-i+1))/i

PRINT BIGNO

STOP

_____________________________________________________________________________________ 57 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Input: Enter no of rows:4 Expected Output: pascal triangle with 4 rows 1 1 1 1 3 2 3 1 1 1

8B. Write a C program to construct a pyramid of numbers.


_____________________________________________________________________________________ 58 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Aim: A C program to construct a pyramid of numbers ALGORITHM: Step1: start Step2:initialize count,j,k Step2: read no of rows and store it in n Step3: repeat for count=1 to n Print the pascal triangle from centre of screen STEP4: K=count STEP5: Repeat THE STEPS 5-8 UPTO j< count Step6: Print k Step7:Increment k Step8:K=k-2 Step9:Repeat THE STEPS 9-11 UPTO j<= count Step10:Print k Step11:Decrement k Step12:Print new line Step13: End Step14: stop

_____________________________________________________________________________________ 59 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

START

READ N J=1, count=1, K=count K=count j++ j=1 j<COUNT T PRINT K K=K+1

K=K-2

j++

j=1 j<=COUNT T PRINT K

K=K-1

STOP

Result:

_____________________________________________________________________________________ 60 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Input: Enter no of rows:3 Expected Output: 1 2 3 4 3 5 4 2 3

Questions:

1.unconditional structure is--------------2.identify wrong statement a)if(a>b); b)if a<b; c)if(a<b) 3.storage class controls-----------------4.automatic storage class has------------5.the storage class type of external static has--------6.global variables are automatically initialized to ---------7.syntax of user defined data type ---------8.define formal parameters------9.difference between call by value and call by reference 10.purpose of #define-------------

_____________________________________________________________________________________ 61 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 9 9A. 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.
AIM: Teaching the students how to calculate series of expression and how to perform error checking

Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

Theory:

In mathematics, a geometric progression, also known as a geometric sequence, is a sequence of numbers where each term after the first is found by multiplying the previous one by a fixed nonzero number called the common ratio 1+x+x2+x3+-----+xn

_____________________________________________________________________________________ 62 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

ALGORITHM:

Step1: start Step2: initialize term=1,sum=1 Step3: repeat step3 while true begin Read n If(n<0) begin Print negative exponents are not valid Continue End Read x Break End Step4: repeat thru step4 until n>0 Begin Term=term*x Sum=sum +term N=n-1 End Step5: print sum Step6: stop

_____________________________________________________________________________________ 63 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Flowchart:

Start Input x,n,su m

If n<=0|| x<=000

yes

Print value is not valid

no
Sum=1

no

Repeat i=1 to n

yes Sum=sum+pow(x, i)

Print sum

Stop

Result: Input:

_____________________________________________________________________________________ 64 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Enter the exponent value3 Enter value of x:5

Output: Geometric sum is 156

Questions: 1.typedef statement is used for -----------2.which storage class may help in faster execution---------3.what is error in given function f(int x,int y) { int x; x=20 return x;} 4.the following code prints computer-------no of times main() { printf(\n computer); main() } 5.no of bytes occupied by double x------------6.define error checking--------------7.how many types of storage classes-------------

_____________________________________________________________________________________ 65 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

8.to change the string from lowercase to uppercase which function is used---------9.define function declaration------10.parameters are used to------------ & ------------

_____________________________________________________________________________________ 66 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 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.
AIM: Teaching the students how to find 2s complement of given number and how to write roman numeral to decimal equivalent Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors Theory: 10a) The two's complement of a binary number is defined as the value obtained by subtracting the number from a large power of two (specifically, from 2N for an N-bit two's complement). Ex: number is 1s complement Add 1 11101 00010 1 ----------------2s complement is 00011 ALGORITHM:

Step1: start Step2: read num Step3: len=strlen(num) Step4: pos=len Step5: repeat for i=len-1 to 0 Begin
_____________________________________________________________________________________ 67 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

If(num[i]==1) Pos=i Break Repeat for i=0 to pos Begin If(num[i]==0) Num[i]=1 Else Num[i]=0 End Print num End Step6:stop

_____________________________________________________________________________________ 68 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Flowchart:
Start

l=strlen(binary)

for i=l 1 to 0

False

True
if binary[i]=0

Yes

No
a[i] = 0 a[i]=1

for i=l-1 to 0

False

True Yes
If a[i] = 0 if i=l-1

No
If check ==1 && a[i] = 0

Yes
a[i] = 1

No

a[i] = 0

No
a[i] = 1

Yes

If check == 1 && a[i] = 1

No

check = 1 check = 0 a[i] =Yes 0 check = 1

a[l] = \0 return _____________________________________________________________________________________ 69 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Result: Input:

Enter the binary number :11100

Output:

2s complement is 00100

10B. Roman numerals follow a fairly strict rule in sequence in order to reduce ambiguity in numbers. To create Roman numerals we must first define which letters represent which values, and what exceptions there are to the basic rule. Write a C program to convert a Roman numeral to its decimal equivalent.
Theory: First, the following letters represent the associated values:

I=

V= 5 X = 10 L = 50 C = 100 D = 500 M = 1000

_____________________________________________________________________________________ 70 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

The basic rule states that numerals are read from left to right, larger valued letters precede smaller valued letters, and multiple letters in a row represent multiples of that value. For instance: I II III VIII CVIII CCVIII DCCVIII MDCCVIII = 1708 = = = = = = = 1 2 3 8 108 208 708

ALGORITHM:

Step1: start Step2:read roman number (r) Step3: initialize count[r]=0 Step4: repeat for i=0 to r Begin if i == "M": count[i] = 1000 if i == "D": count[i] = 500 if i == "C": count[i] = 100 if i == "L": count[i] = 50 if i == "X": count[i] = 10 if i == "V": count[i] = 5
_____________________________________________________________________________________ 71 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

if i == "I": count[i] = 1 end step5:total=0 step6: repeat for i=0 to size begin if(count[i]>count[i-1]) total-=count[i-1] else total+=count[i-1] end step6: total += count[ SIZE - 1 ] step7: print total step8: stop Result: Input:

Enter the roman numeral: MDCCVIII

Output:

Its decimal equivalent is : 1708

Questions:

Find the output of the following: 1.main( ) { int x=100; if(!!x) printf(x=%d,!x); else printf(x=%d,x); } a. 0 b. 2 c. 1.5 d. 100

_____________________________________________________________________________________ 72 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

2. main( ) { float a=0.5, b=0.9; if(a&&b>0.9) printf(it is ur style); else printf(it is my style); } a. it is ur style b. it is our style c. it is my style d. no output 3. main( ) { int x=10, y=20; if(!(!x) && x) printf(x=%d,x); else printf(y=%d,y); } a. 10 b. 20 c. 1 d. 0 4. main( ) { char ch=291; printf(%d%d%c,32770,ch,ch); } a. 291 b. -32766 35# c. 32770chch d. 32770 5.main ( ) { int a,b; a = -3- -3; b = -3 - - (-3 ); printf(a=%d b= %d,a,b); } a. a=0 b=-6 b. a=-3 b=+3 c. a=-6 b=+6 d. a=6 b=0 6.main( ) { int x; x= -3 + 4 7 * 8 / 5 % 10;
_____________________________________________________________________________________ 73 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

printf(x = %d,x); } a. 23 b. 6 c. 7

d. 0

7.main( ) { int x=3, y=4, z=4; printf(ans = %d, (z>=y>=x?100:200)); } a. 100 b. 300 c. 200 d. No Output 8.main( ) { int a=30, b=40, x; x=(a!=10) && (b=50); printf(x= %d,x); } a. 10 b. 50 c. 1 d. 0 9.main( ) { float x=12.25, y=13.65; if(x=y) printf(x and y are equal); else printf(x and y are not equal); } a. x and y are not equal b. x and y are equal c. No output 10.main ( ) { int i=1, j=1; for(;j;printf(%d%d\t,i,j)) j=i++ <= 5; } a. 21 31 41 51 61 70 c. 20 30 40 50 60 70 b. 21 30 41 50 61 70 d. 21 31 41 51 61 71

_____________________________________________________________________________________ 74 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 11 11A. 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.)
AIM: Teaching the students how to read and write complex numbers and how to represent them with structures

Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

Theory: In mathematics, the complex numbers are an extension of the real numbers obtained by adjoining an imaginary unit, denoted i, which satisfies:[1]

Every complex number can be written in the form a + bi, where a and b are real numbers called the real part and the imaginary part of the complex number, respectively Complex numbers are added, subtracted, multiplied, and divided by formally applying the associative, commutative and distributive laws of algebra, together with the equation i 2 = 1: Addition: (a+bi)+(c+di)=(a+c)+(b+d)i (ac-bd)+(ad+bc)i

Multiplication: ALGORITHM:

_____________________________________________________________________________________ 75 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Declaring complex number as structure Struct compnum Begin Int a Int b End Struct compnum c1,c2 Step1: start Step2: read c1(first complex number) Step3: read c2(2nd complex number) Step4: call add(c1,c2) Step5: call multi(c1,c2) Step6:stop Function add(struct c1,struct c2) Begin Res1=c1.a+c2.a Res2=c1.b+c2.b Print addition is res1+I res2 End Function multi(struct c1,struct c2) Begin Res1=(c1.a*c2.a)-(c1.b*c2.b) Res2=( c1.a*c2.b)+(c1.b*c2.a) Print multiplication is res1+I res2 End

_____________________________________________________________________________________ 76 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Flowchart:

Start ch = menu()

Yes

If ch == 3

No
Swi tch ch

1
Input complex c1 c1 = input() Input complex c2 c2 = input() c = add(c1, c2) Print c1 output(c1) Print c2 output(c2) Print c output(c)

2
Input complex c1 c1 = input() Input complex c2 c2 = input() c = mul(c1, c2) Print c1 output(c1) Print c2 output(c2) Print c output(c)

True
While(t) Stop

False

_____________________________________________________________________________________ 77 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Result: Input:

Enter the complex number c1: 2 3 Enter the complex number c2: 2 3

Output:

Addition is 4+6i Multiplication is -5+12i

Questions:

1. Which of the following language is predecessor to C Programming Language? A B BCPL C++

2. C programming language was developed by Dennis Ritchie Ken Thompson Bill Gates Peter Norton

3. C was developed in the year ___ 1970 4. C is a ___ language High Level Low Level Middle Level Machine Level 1972 1976 1980

5. C language is available for which of the following Operating Systems? DOS Windows Unix All of these

6. Which of the following symbol is used to denote a pre-processor statement?

_____________________________________________________________________________________ 78 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

7. Which of the following is a Scalar Data type Float Union Array Pointer

8. Which of the following are tokens in C? Keywords Variables Constants All of the above

9. What is the valid range of numbers for int type of data? 0 to 256 -32768 to +32767 -65536 to +65536 No specific range

10. Which symbol is used as a statement terminator in C? ! # ~ ;

_____________________________________________________________________________________ 79 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 12 12A. Write a C program which copies one file to another.


AIM: Teaching the students how to use command line arguments and how to copy the content of one file to other

Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

Theory:

C supports a number of functions that have the ability to perform basic file operations. File operation functions in C: Function Name fopen() Operation Creates a new file for use Opens a new existing file for use Closes a file which has been opened for use Reads a character from a file

fclose

getc()

putc() fprintf()

Writes a character to a file Writes a set of data values to a file Reads a set of data values from a file

fscanf()

_____________________________________________________________________________________ 80 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Command line arguments: In order to access the command words, the main() function must have a prototype similar to the following. int main(int argc, char * argv[]) The names argc and argv are usually used for the parameters, but a programmer could use different names. Start The command words can be accessed as argv[0] through argv[argc - 1]. The program name is the C:\> filename sfile first word on the command line, which is argv[0]. The command-line arguments are argv[1] dfile through argv[argc - 1]. ALGORITHM: step1: start Copy argv[1] to sfile step2: initialize two file pointers fs=source and fd = destination Copy argv[2] to dfile step3: if (agrc!=3) printf error step4: fs=fopen(argv[1],r) step5: fd=fopen(argv[2],w) Open sfile in read mode If sfpt==NULL Open dfile If argc!=3

step6: repeat step6 until not feof(fs) begin ch=fgetc(fs) fputc(ch,fd) end step7:fclose(fs) step8:fclose(fd) step9:stop

If dfpt==NULL While !feop(sfpt) Read c from sfpt Write c into dfpt

Flowchart:

Close sfile Close dfile Stop

_____________________________________________________________________________________ 81 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Yes No

Yes No

Yes No No Yes

Result:

_____________________________________________________________________________________ 82 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Input: Read file name at command line file1 file2 Output: File is copied to file 2 Questions: 1.what are the integer oriented functions in files---------------2.To read the characters from file which function is used--------3. To write the characters to file which function is used--------4..the difference between append and writing--------

12B. 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.)
_____________________________________________________________________________________ 83 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step1: start step2: initialize file pointer recfile step3: read no of chars from file (n) step4: recfile=fopen(filename,r) step5: if recfile=null print error in opening the file step6: fread(nchars,sizeof(char)*n,1,filename) step7: len=strlen(nchars) step8: repeat step8 until i<len/2 temp=nchars[i] nchars[i]=nchars[len-1-i] nchars[len-1-i]=temp step9: recfile=fopen(filename,w) step10: if recfile=null print error in opening the file step11:fwrite(nchars,sizeof(char)*n,1,filename) step12:stop

Flowchart:

Start C:\> filename sfile dfile if argc!=3 Yes

No Copy argv[1] to sfname


_____________________________________________________________________________________ 84

Print MLR INSTITUTE OF TECHNOLOGY, DUNDIGALfile not found

Open sfname in read mode if sfpt==NULL No Convert argv[2] to integer


n = fread(text, l, sfpt)

Yes

text[n]=\0 l=length(text) j j=1 rev[j]=\0 j=j+1 for i=0;i<l;i++ True rev[i] = text[i]
j--

False
Pprint reversed string rev

Stop

Result: Input: Read the file name at command line file1 Read first n chracters:10 Output: After reversing the first 10 characters the file is: file1

_____________________________________________________________________________________ 85 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Questions: 1.define stream: 2.I/O stream can be----------3.FILE defined in stdio.h is---------------------4.a file pointer is -------------------5.general form of fprintf----------------------6.general form of fscanf---------------------

_____________________________________________________________________________________ 86 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 13 13A) Program to write data file and display contents of file

ALGORITHM: step1: start step2: take a character ch and define a file pointer f2 step3: open a file data.dat for writing step4: while ((ch=getch()!=eof) read a character ch step5: close the file data.dat step6: open the same file for reading while((ch=get(f2)!=EOF) display character on monitor step7: close the data.dat step8:stop

_____________________________________________________________________________________ 87 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Start

3) FLOWCHART:
FILE *f2

Open Data file to write

While ((Ch= =getch ar())! =EOF)

Putc(ch,f2)

Close (f2)

Open data file to read

While ((Ch= = getc()) ! ==EOF )

Putchar (ch, f2)

Close (f2)

Stop

_____________________________________________________________________________________ 88 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

5) Result: MLRIT MLRIT

13B) Program to merge two files


ALGORITHM: step1: start step2: take argc,argv in main function an array of word and i step3: define a file pointer step4: open a file command.dat for writing for(i=0;i<argc;i++) Display argv[i] close the file step6:open the same file for reading for(i=1;i>argc;i++) display word step7: close the file step8: stop

_____________________________________________________________________________________ 89 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

FLOWCHART

Start

FILE *f2

F2=Open data file to write

I=0

If I<argc

Write to file, argv[i]

Close (f2)

F2=Open file to read data

I=0

If I<argc

Read data from file

Output: c>f12_6 text aaa bbb ccc

Close (f2)

Stop

_____________________________________________________________________________________ 90 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

contents of text file c>f12_7 ddd eee fff ggg c:\c\f12_7.exe text aaa bbb ccc ddd eee fff ggg

_____________________________________________________________________________________ 91 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 14 Use functions to perform following ops on single linked list a)creation b)deletion c)display d)traversal

Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors LINKED LISTS: A linked list is data structure that consists of a sequence of data records such that in each record there is a field that contains a reference (i.e., a link) to the next record in the sequence. Structure

Item

Single linked list representation: In single linked list each node consist of 2 fields one is data field and link field which points to next node and last node link field is null

12

23

34

45

start

_____________________________________________________________________________________ 92 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

There are mainly three kinds of linked lists:


Singly linked list Doubly linked list Circular linked list.

Singly link list: In the singly link list each node have two fields one for data and other is for link reference of the next node. The node have null only to the last node of the link field. This can be seen in the following picuture.

Fig: Singly Link List Doubly link list: In the doubly link list each node have three field two fields for link which is the reference to next and previous and one for data record. The node have null only to the first node of previous and last node at the next. This can be seen in the following picture.

Fig: Doubly Link List

Circular link list: If talking about singly circular link list each node have two fields one for data record and other for link reference to the next node. The last node has link reference to the first node. There in no null present in the link of any node.

_____________________________________________________________________________________ 93 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Below depict the operational behaviors of stack. You can see one thing that push and pop operation is done at one end and whatever element we keep on stack is shown at the top of stack. Before insertion:

ALGORITHM TO INSERT A NODE: FIRST INSERTION

DESCRIPTION: X is a new node to be inserted, first is a pointer to indicate the first element of linked list. X is a node contains info & link parts & this algorithm inserts a new node at the beginning.

Algorithm: a)

step 1: start step 2: check for availability of free space from avail list if(avail= null)) then print(number of free spaces); return; step 3: obtain a node from free list (creating a node) new=avail step 4: adjust avail pointer avail= link(avail)
_____________________________________________________________________________________ 94 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step 5: store the information & insert the node as first node info(new) x; link(new) first step 6: return the modified linked list address return(new) step 7: stop

After insertion:

ALGORITHM TO INSERT A NODE: END INSERTION DESCRIPTION: X is a new node to be inserted, first is a pointer to indicate the first element of linked list.

Algorithm:

step 1: start step 2: check for availability of free space from avail list if(avail= null)) then print(number of free spaces); return;
_____________________________________________________________________________________ 95 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step 3: obtain a node from free list (creating a node) new=avail step 4: adjust avail pointer avail= link(avail) step 5: store the information & link field of the node link(new)null step 6: check the list whether it is empty If(first=null) then return(new); step 7: if list is not empty traverse the list to last node t first step 8: move to the end of list repeat while link(first)!=null tlink(t); step 9: after moving to the last node set the link field of last node to new node link(t) new step 10: return the modified linked list address step 11: stop

ALGORITHM TO INSERT A NODE: SPECIFIC INSERTION DESCRIPTION: X is a new node to be inserted, first is a pointer to indicate the first element of linked list.

Algorithm:

_____________________________________________________________________________________ 96 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step 1: start step 2: check for availability of free space from avail list if(avail= null)) then print(number of free spaces); return; step 3: obtain a node from free list (creating a node) new=avail step 4: adjust avail pointer avail= link(avail) step 5: store the information & link field of the node link(new)null step 6: check the list whether it is empty If(first=null) then return(new); step 7: reading the position (or) location where to insert the node i.e. read POS initialize c=0 where c is the count for nodes step 8: initialize temporary pointer t first step 9: traverse the list to a particular position repeat while(link(t)<>null) { t link(t); c c+1; }
_____________________________________________________________________________________ 97 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step 10: check the position if(pos=c) then link(new)link(t); link(t) new; else repeat step8 step 11: return first node pointer return(first) step 12: stop

Before deletion:

ALGORITHM TO DELETE A NODE: DESCRIPTION: Delete the node whose value is given in X. First is a pointer to indicate the first element of the linked list. In this algorithm we use two pointers i.e. temp & prev. Temp is a pointer used to find the desired node & prev is a pointer keeps track of previous element of the temp.

ALGORITHM: step 1: start


_____________________________________________________________________________________ 98 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step 2: check for underflow. If(first = null) then Print( number of nodes to delete ) step 3: initialize the search for node whose value is X temp first step 4: repeat step 5 while(info(temp)<>X) & (link(temp)<>null) step 5: update the previous pointer prevtemp step 6: move to next node templink(temp) step 7: end of the list if(temp<>X) then Print (node not found) return step 8: deleting the node X i.e. if(X=info(first)) then first link(first) else link(prev) link(temp) step 9: return node to availability to stack/list i.e. link(X) avail; avail X; step 10: stop

_____________________________________________________________________________________ 99 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

After deletion:

Display ALGORITHM: step 1: start step 2: check for underflow. If(first = null) then Print( List is empty ) step 3: initialize the node temp first step 4: repeat step 5 thru step 6 while(link(temp)<>null) step 5: print data in the node print info(temp) step 6: move to next node templink(temp) step 7: end of the list step 8 : stop

QUESTIONS: 1. Linked list are not suitable for -----------------------2. Linked list are more efficient then arrays for --------------

_____________________________________________________________________________________ 100 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

3. Searching a Linked list requires, Linked list be created---------------4. The fields in the single linked list are -----------------

_____________________________________________________________________________________ 101 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

_____________________________________________________________________________________ 102 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 15 Use functions to perform following OPERATIONS on stacks using arrays and pointers

AIM: Teaching the students how to perform operations on stacks Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors Theory: Stacks: A stack is a collection of ordered elements, where insertions and deletions are done at one end known as top of stack Principle : Last-In-First-Out (LIFO) The last element added to the stack will be the first one to be removed

Stack is very similar to a list except that a stack is more restricted. The figure below should give you a good idea of the abstract view of what stack is. Follow the directions to manipulate the simple stack and learn about the operations that the stack provides.

_____________________________________________________________________________________ 103 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Stack representation using pointers: Inorder to iimplement stack using pointers,each node contain stack item and pointer to the next node.and stack pointer to keep track of top of the stack.

Operations : 1. PUSH : Inserts the item at the top of the stack. 2. POP : Removes the item from the top of a non-empty Stack push pop

Representation of stack:

Top=-1 empty stack


_____________________________________________________________________________________ 104 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

The inserting elements into stack

over Push push push push 40 30 30 20 10 10 20 10 20 10 push flow 40 30 20 10

Top

top

top

top

top

Deleting the elements from stack: Pop 40 30 20 10 30 20 10 20 10 10 pop pop pop pop

top

top

top

top underflow

Push Algorithm Push(S[ ], Top, x)

_____________________________________________________________________________________ 105 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

/* This function inserts an element x to the top of the stack which is represented by S, containing N elements with a pointer Top denoting the top element of the stack */

Step 1 : [ Check for the stack overflow] If (Top >= N) then Printf(STACK OVERFLOW) End if Step 2 : [ Increment Top ] Top Top +1 Step 3 : [Insert element] S[Top] x Step 4 : [finished] Return

Pop

Algorithm Pop(S[ ], Top) /* This function removes the top element from stack S and returns this element. Top is a pointer to indicate the top element of the stack */

Step 1 : [ Check for under flow on the stack ] If (Top = 0) then Printf(STACK UNDER FLOW) return End if Step 2 : [ Decrement Top ] Top Top - 1
_____________________________________________________________________________________ 106 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Step 3 : [Return the popped element] Return( S[Top+1])

Display Algorithm Display(S[ ]) /* To Display the contents of the Stack S. Stack S is an array consisting of N elements. Top is a pointer variable to indicate the top element of the stack */ Step 1 : [ Check for the stack empty or not ] If (Top = 0) then Printf(STACK EMPTY) End if Step 2 : [ Display the stack elements ] Repeat for I = Top down to 1 Print(S[i]) [End Repeat] Step 3 : [Return the popped element] Stop

_____________________________________________________________________________________ 107 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Questions: 1. A stack is a linear data structure which data is stored and retrieved in a -------------2. A data structure needed to convert infix notation to postfix form ------------3. A stack is a special form of -----------4. Stack can be used to implement to ---------------5. A data structure uses in subroutine calls is -----------------

_____________________________________________________________________________________ 108 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

_____________________________________________________________________________________ 109 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

_____________________________________________________________________________________ 110 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 16 Use functions to perform following OPERATIONS on Queues using arrays and pointers

AIM: Teaching the students how to perform operations on queues

Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

Theory:

Queues: A Queue is an ordered collection of items from which items may be deleted at one end (called the front of the queue) and into which items may be inserted at the other end (the rear of the queue). Principle : First-In-First-Out (FIFO) The first element added to the queue will be the first one to be removed Operations : 1. Insertion: Inserts the item at the rear end of the queue. 2. Deletion: Removes the item at the front of a non-empty queue Representation of queue: front=F rear=R

_____________________________________________________________________________________ 111 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

F=-1 R=-1 Inserting elements into queue

10

F=0 R=0

10

20

F=0 10 20

R=1 30

F=0 10 20 30

R=2 40

F=0 Deleting elements from queue:

R=3

10

20

30

40

F=0

R=3

20

30

40

_____________________________________________________________________________________ 112 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

F=1 30

R=3 40

F=2 40

R=3

F=R=3

Queue underflow

. This idea is similar to customer lines at a in any bill payment store(eg. phone bill payment queue). When customer A is ready to check out, he or she enters the tail(end) of the waiting line. When the preceding customers have paid, then customer A pays and exits from the head of the line. The billpayment line is really a queue that enforces a "first come, first serve" policy. Pointer Implementation A second approach to creating a list is to link groups of memory cells together using the pointers. Each group of memory cells is called as a node. With this implementation every node contains the data item and the pointer to the next item in the list. You can picture this structure as a chain of nodes linked together by the pointers. As long as we know where the chain begins, we can follow the links to reach any item in the list. Often this structure is called as a linked list.

_____________________________________________________________________________________ 113 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Queue Insert operaton Algorithm QInsert(Q[ ],F,R,n, x) /* F and R are pointer to the front and rear elements of a queue, this queue Q is an array consisting of n elements and x is an element to insert at the rear end of the queue*/

Step 1 : [ Check for Queue overflow] If (R >= N) then Printf(QUEUE OVERFLOW) return End if Step 2 : [ Increment rear pointer ] R R +1 Step 3 : [Insert element] Q[R] x Step 4 : [Set front pointer, if necessary] If ( F = 0) then

_____________________________________________________________________________________ 114 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

F1 Return

Algorithm Qdelete(Q[ ], F,R) /* F and R the pointers to the front and rear elements of a queue. Last element is deleting from Q. x is a temporary element to hold the deleted element*/

Step 1 : [ Check for under flow ] If (F = 0) then Printf(Q UNDER FLOW) return End if Step 2 : [ Delete element ] x Q[F]
_____________________________________________________________________________________ 115 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Step 3 : [Set the front pointer] If(F=R) then FR0 Else FF+1

Step 4 : [Return the deleted element] return(x)

PR

_____________________________________________________________________________________ 116 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Display Algorithm QDisplay(Q[ ]) /* F and R are the pointers to the front and rear elements of a queue Q. It is to display the elements of the Queue array Q */

Step 1 : [ Check for the queue empty or not ] If (R=F = 0) then Printf(QUEUE EMPTY) End if Step 2 : [ Display the queue elements ] Repeat for I = F to R Print(Q[i]) [End Repeat] Stop

Questions: 1. Queues serve a major role in --------2. Queue is served on the principle of ----------3. Queue can be used to implement -----------4. The process of accessing a data on a tape is similar to manipulating data on a ------5. A linear list of elements in which deletion can be done from one end (front) and insertion can be place at the other end is known as -----------

_____________________________________________________________________________________ 117 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 17 Use stack operations 17A. to convert infix to postfix expression

AIM: Teaching the students how to evaluate postfix expression and convert infix to postfix expression

Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

_____________________________________________________________________________________ 118 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

_____________________________________________________________________________________ 119 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

_____________________________________________________________________________________ 120 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

17B. evaluate postfix expression


EVALUATION OF A POSTFIX EXPRESSION Algorithm 6.3: This algorithm finds the VALUE of an arithmetic expression P written in postfix Notation. 1. Add a right parenthesis ) at the end of P. [This acts as a sentinel.] 2. Scan P from left to right and repeat Step 3 and 4 for each element of P until The sentinel ) is encountered. 3. If an operand is encountered, put it on STACK. 4. If an operator X is encountered, then: (a) Remove the two top elements of STACK, where A is the top element and B is the next-to-top element. (b) Evaluate B X A. (c) Place the result of (b) back on STACK. [End of If structure.] [End of Step 2 loop]. 5. Set VALUE equal to the top element on STACK. 6. Exit. Questions: 1. The postfix form of A+(B*C) is -----------2. The postfix form of A-B(C*D$E) is -------------3. The postfix form of A$B*C-D+E/F/*(G+H) is ------4. Which is the postfix form of the following prefix A-B/(C*D$E) is-----5. Which is the postfix form of the following prefix -A/B*C$DE is -------

_____________________________________________________________________________________ 121 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

_____________________________________________________________________________________ 122 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 18 Write C programs that implement the following sorting methods to sort a given list of integers in ascending order: A) Bubble sort
AIM: Teaching the students what is sorting ,where we are using the sorting techniques bubble sort and quick sort Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

Theory:

a) Is a straightforward and simplistic method of sorting data that is used in computer science education. The algorithm starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent elements to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass. While simple, this algorithm is highly inefficient and is rarely used except in education. For example, if we have 100 elements then the total number of comparisons will be 10000. A slightly better variant, cocktail sort, works by inverting the ordering criteria and the pass direction on alternating passes. Its average case and worst case are both O(n).

10

11

_____________________________________________________________________________________ 123 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

ALGORI THM:

variable used in algorithm last=position of last unsorted element pass=pass counter exch=count no of exchanges made on any pass

step1: start step2: read n step3: repeat thru step3 until i<n read a[i] step4: last=n step5: repeat thru step5 for pass=1,2,3,n-1 begin exch=0 repeat for i=1 to last-1 begin if a[i]>a[i+1] interchange a[i]and a[i+1]

_____________________________________________________________________________________ 124 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

a[i]>a[i+1]exch=exch+1 end step6: if exch=0 then return else last=last-1 step7:print sorted array a[i] step8:finish

Result: Input:

Enter how many elements: 5 Enter the elements: 56 44 32 12 23

Output:

Sorted array is 12 23 32 44 56

_____________________________________________________________________________________ 125 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Write C programs that implement the following sorting methods to sort a given list of integers in ascending order:

18B) Selection sort


Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

Theory: a) Selection sort is a simple sorting algorithm, a comparison sort in which the sorted array (or list) is built one entry at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages:
_____________________________________________________________________________________ 126 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

simple implementation efficient for (quite) small data sets more efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such as selection sort or bubble sort: the average running time is n2/4, and the running time is linear in the best case stable (i.e., does not change the relative order of elements with equal keys) in-place (i.e., only requires a constant amount O(1) of additional memory space) online (i.e., can sort a list as it receives it)

Example: The following table shows the steps for sorting the sequence 5 7 0 3 4 2 6 1. On the left side the sorted part of the sequence is shown in red. For each iteration, the number of positions the inserted element has moved is shown in brackets. Altogether this amounts to 17 steps. 5 5 0 0 0 0 0 0 7 7 5 3 3 2 2 1 0 0 7 5 4 3 3 2 3 3 3 7 5 4 4 3 4 4 4 4 7 5 5 4 2 2 2 2 2 7 6 5 6 6 6 6 6 6 7 6 1 1 1 1 1 1 1 7 (0) (0) (2) (2) (2) (4) (1) (6)

ALGORITHM:

Step1: start Step2: read n Step3: repeat thru step3 until i<n read a[i] step4: insertionsort(a,0,n-1) step5: repeat thru step5 until i<n

_____________________________________________________________________________________ 127 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

print a[i] step6: stop

function insertionSort(array A) begin for i := 1 to length[A]-1 do begin value := A[i] j := i-1 while j 0 and A[j] > value do begin A[j + 1] := A[j] j := j-1 end A[j+1] := value end end

Result: Input: Enter how many elements: 5 Enter the elements: 56 44 32 12 23 Output:

Sorted array is 12 23 32 44 56

_____________________________________________________________________________________ 128 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

_____________________________________________________________________________________ 129 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 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 AIM: Teaching the students how to search for a particular element in unordered list and ordered list

Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

Theory: a) In computer science, linear search is a search algorithm, also known as sequential search, that is suitable for searching a list of data for a particular value. It operates by checking every element of a list one at a time in sequence until a match is found. Linear search runs in O(n). where n is the number of elements in the list. The best case is that the value is equal to the first element tested, in which case only 1 comparison is needed. The worst case is that the value is not in the list (or it appears only once at the end of the list), in which case n comparisons are needed

_____________________________________________________________________________________ 130 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

ALGORITHM:

Step1: start Step2: read n Step3: repeat step3 until i<n Read a[i] Step4: read element to be searched (ele) Step5: repeat step5 until a[i]<>ele Increment i Step6: if i>n begin Element not found Else Element found Return i end step7:stop

Result: Input:

Enter how many elements: 4 Enter the elements: 23 12 34 45 Enter the element to be searched:34

_____________________________________________________________________________________ 131 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Output:

The element 34 is found at location 3

19B Binary search


b) In computer science, a binary search algorithm (or binary chop) is a technique for locating a particular value in a sorted list. The method makes progressively better guesses, and closes in on the location of the sought value by selecting the middle element in the span (which, because the list is in sorted order, is the median value), comparing its value to the target value, and determining if it is greater than, less than, or equal to the target value. A guessed index whose value turns out to be too high becomes the new upper bound of the span, and if its value is too low that index becomes the new lower bound. Only the sign of the difference is inspected: there is no attempt at an interpolation search based on the size of the difference. Pursuing this strategy iteratively, the method reduces the search span by a factor of two each time, and soon finds the target value or else determines that it is not in the list at all. A binary search is an example of a dichotomic divide and conquer search algorithm

_____________________________________________________________________________________ 132 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

ALGORITHM:

Variable used in algorithm K: It consists of N elements in ascending order. Low: It is the lower limit of the search interval. Middle: It is the middle limit of the search interval. High : It is the upper limit of the search interval.

Step1: start Step2: [Initialize] Low 1 High N Step3: repeat thru step 4 while Low <=High Middle (Low + High)/2 Step4: if X<k[MIDDLE] then High MIDDLE+1 Else if X> K[MIDDLE] then Low MIDDLE -1 Else print successful search Return(MIDDLE). Step5: print unsuccessful search Return 0 Step6: stop Result:
_____________________________________________________________________________________ 133 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Input:

Enter how many elements: 5 Enter the elements: 12 23 34 45 56 Enter the element to be searched:34 Output: The element 34 is found at location 3

_____________________________________________________________________________________ 134 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 20 Program to sort a given list of individuals using Quick sort.


Quick sort b) a divide and conquer algorithm which relies on a partition operation: to partition an array, we choose an element, called a pivot, move all smaller elements before the pivot, and move all greater elements after it. This can be done efficiently in linear time and in-place. We then recursively sort the lesser and greater sub lists. Efficient implementations of quick sort (with in-place partitioning) are typically unstable sorts and somewhat complex, but are among the fastest sorting algorithms in practice. Together with its modest O(log n) space usage, this makes quick sort one of the most popular sorting algorithms, available in many standard libraries. The most complex issue in quick sort is choosing a good pivot element; consistently poor choices of pivots can result

_____________________________________________________________________________________ 135 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

in drastically slower O(n) performance, but if at each step we choose the median as the pivot then it works in O(n log n). Example problem 1. This is the initial array that you are starting the sort with

2. The array is pivoted about its first element p =3

3. Find first element larger than pivot (underlined) and the last element not larger than pivot (italicised)

4. Swap those elements

5. Scan again in both directions

6. Swap

7. Scan

8. The pointers have crossed: swap pivot with italicised.

9. Pivoting is now complete. Recursively sort sub arrays on each side of pivot.

_____________________________________________________________________________________ 136 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

The array is now sorted. ALGORITHM: Step1: start Step2: read n Step3: repeat thru step3 until i<n read a[i] step4: call quicksort(a,0,n-1) step5: repeat thru step5 until i<n print a[i] step6: stop function quicksort(int a[],int left, int right) begin l=left r=right pivot=a[left] repeat while (left<right) begin repeat while ((a[right]>=pivot) and (left<right)) right if(left<>right) begin a[left]=a[right] left++

_____________________________________________________________________________________ 137 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

end repeat while ((a[left]<=pivot) and (left<right)) left++ if(left<>right) begin a[right]=a[left] right-end end while a[left]=pivot pivot=left left=l right=r if(left<pivot) call quicksort(a,left,pivot-1) if(right>pivot) call quichsort(a,pivot+1,right) end function Result: Input: Enter how many elements: 5 Enter the elements: 56 44 32 12 23 Output: Sorted array is 12 23 32 44 56

_____________________________________________________________________________________ 138 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

_____________________________________________________________________________________ 139 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Questions:

1.time complexity of bubble sort in best case is----------2. time complexity of quick sort in best case is-------------3. time complexity of bubble sort in worst case is--------4. time complexity of quick sort in worst case is------------5.define sorting 6.divide and conquer technique is used in which sorting-----7.best sorting technique is ---------8.quick sort is an application of------------

_____________________________________________________________________________________ 140 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

9.bubble sort is also called as---------10.quick sort is also called as---------------

_____________________________________________________________________________________ 141 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 21 Program to sort list of integers using MERGE SORT


i) merge sort Merge sort is based on a divide and conquer strategy . First, the sequence to be sorted is decomposed into two halves (Divide). Each half is sorted independently (Conquer). Then the two sorted halves are merged to a sorted sequence (Combine) (Figure ).

Example problem

ALGORITHM:

Step1: start Step2: read n1(sorted elements of ist array) Step3: repeat thru step3 until i<n1 read a[i]

_____________________________________________________________________________________ 142 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step4: read n2( sorted elements of 2nd array) Step5: repeat thru step5 until j<n2 read a[j] step6: initialize i=0,j=0,k=0 step7: repeat while (i<n1 and j<n2) begin if(a[i]<b[j]) c[k]=a[i] increment i else c[k]=b[j] increment j increment k end step8: repeat while i<n1 begin c[k]=a[i] increment i increment k end step9: repeat while j<n1 begin c[k]=a[j] increment j increment k end

_____________________________________________________________________________________ 143 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

step10: repeat thru step10 until i<n print c[i] step11: stop

Result: Input:

Enter how many elements: 5 Enter the elements: 56 44 32 12 23 Output:

Sorted array is 12 23 32 44 56

Questions:

1.time complexity of merge sort in best case is----------2. time complexity of insertion sort in best case is-------------3. time complexity of merge sort in worst case is--------4. time complexity of insertion sort in worst case is------------5.define sorting 6.divide and conquer technique is used in which sorting-----7.best sorting technique is ---------8.merge sort is an application of-----------9. space complexity of merge sort in best case is----------10. space complexity of insertion sort in best case is--------------

_____________________________________________________________________________________ 144 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

_____________________________________________________________________________________ 145 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 22 22a) Implement the Lagrange interpolation .


AIM: Teaching the students how to implement the Lagrange interpolation Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

Theory: a)The Lagrange interpolating polynomial is the polynomial through the points , , ..., of degree , and is given by that passes

where

written explicitly

ALGORITHM:

Step1: start Step2: enter no of items(num),initialize ans=0 Step3: repeat step3 until i< n Read x[i]

_____________________________________________________________________________________ 146 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Read y[i] Step4: enter the value of x for which y to be calculated Read xfix Step5: repeat for i=0 to num Begin Temp=i Repeat for j=0 to num Begin If(i!=j) Temp=temp*(xfix-x[j])/(x[i]-x[j]) End Temp=temp*y[i] Ans=ans+temp End Step6: print ans Step7: stop

Result:

Input: Enter no of terms: 4 Enter value of x0: 2 Enter value of y0: 94.8 Enter value of x0: 5 Enter value of y0: 87.9 Enter value of x0: 14

_____________________________________________________________________________________ 147 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Enter value of y0: 68.7.8 Enter value of x0: 8 Enter value of y0: 81.3

Output:

The value is 74.925003

_____________________________________________________________________________________ 148 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

22b) Write C programs to implement the Newton- Gregory forward interpolation.


AIM:Teaching the students how to implement the Newton- Gregory forward interpolation.

ALGORITHM:

Step1: start Step2: enter no of items(num),initialize ans=0 Step3: repeat step3 until i< n Read x[i] Read y[i] Step4: enter the value of x for which y to be calculated Read xfix Step5: diff=x[1][0]-x[0][0]; x=(x-table[0][0])/diff; ans=0; xterm=xfix; repeat for i=0 to num first=x[0][i+1]; xterm=xterm*(x-i); step6: repeat for i=0 to num Begin Temp=i Repeat for j=0 to num Begin If(i!=j)

_____________________________________________________________________________________ 149 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Temp=temp*(xfix-x[j])/(x[i]-x[j]) End Temp=temp*y[i] Ans=ans+temp End

Step6: print ans Step7: stop

Result: Input:

Enter no of terms: 4 Enter value of x0: 2 Enter value of y0: 94.8 Enter value of x0: 5 Enter value of y0: 87.9 Enter value of x0: 14 Enter value of y0: 68.7.8 Enter value of x0: 8 Enter value of y0: 81.3

Output:

The value is 92.925003

_____________________________________________________________________________________ 150 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Questions:

1. Which escape character can be used to begin a new line in C? \a \b \m \n

2. Which escape character can be used to beep from speaker in C? \a \b \m \n

3. Character constants should be enclosed between ___ Both a and b None of these

4. String constants should be enclosed between ___ Both a and b None of these

5. Which of the following is invalid? a abc

6. The maximum length of a variable in C is ___ 8 16 32 64

7. What will be the maximum size of a float variable? 1 byte 2 bytes 4 bytes 8 bytes

8. What will be the maximum size of a double variable? 1 byte 4 bytes 8 bytes 16 bytes

9. A declaration float a,b; occupies ___ of memory 1 byte 4 bytes 8 bytes 16 bytes

10. The size of a String variable is 1 byte 8 bytes 16 bytes None

_____________________________________________________________________________________ 151 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

_____________________________________________________________________________________ 152 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 23 Implement the linear regression and polynomial regression algorithms.


AIM: Teaching the students how to implement the linear regression and polynomial regression algorithms. Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

Theory: 23a) In statistics, linear regression is used for two things; to construct a simple formula that will predict a value or values for a variable given the value of another variable. to test whether and how a given variable is related to another variable or variables.

Linear regression is a form of regression analysis in which the relationship between one or more independent variables and another variable, called the dependent variable, is modelled by a least squares function, called a linear regression equation. This function is a linear combination of one or more model parameters, called regression coefficients. A linear regression equation with one independent variable represents a straight line when the predicted value

ALGORITHM:

Step1: start Step2: read no of data points (n) Step3: For every k = 1; : : : ;m do 1a. Form the set Ck containing the pair (xk; yk) and the samples (x; y) step4: S associated with the c

_____________________________________________________________________________________ 153 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

1 nearest neighbors x to xk. 1b. Perform a linear regression to obtain the weight vector vk of a linear unit tting the samples in Ck. Step5: Perform a clustering process in the space Rn+1 to subdivide the set of weight vectors vk into s groups Vi. Step6: Build a new training set S0 containing the m pairs (xk; ik), being Vik the cluster including vk. Train a multicategory classication method to produce the matrices Ai for the regions Xi. Step7: For every i = 1; : : : ; s perform a linear regression on the samples (x; y) 2 S with x 2 Xi to obtain the weight step8: stop Result: Input:

Enter no of terms: 4 Enter value of x0: 2 Enter value of y0: 94.8 Enter value of x0: 5 Enter value of y0: 87.9 Enter value of x0: 14 Enter value of y0: 68.7.8 Enter value of x0: 8 Enter value of y0: 81.3

_____________________________________________________________________________________ 154 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Output: The value is 54.925003

Questions:

1. Pointers are supported in ----------- language 2. Define pointers. 3. Operators exclusively used in pointers----------4. The operand address of pointer is 5. Number of arguments used in calloc ()-----------6. Number of arguments used in malloc ()-----------7. Function used for dynamic deallocation of memory is-----8. Adentify invalid pointer operator a) & b)* c)>> d) none 9. Define structure----10. Define union--------------

_____________________________________________________________________________________ 155 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Experiment: 24 a) Implement Trapezoidal Methods.


AIM: Teaching the students how to implement Trapezoidal and methods. Recommended systems/software requirements : Intel based desktop pc ANSI C compiler with supporting editors

Theory:

24a) In mathematics, the trapezoidal rule (also known as the trapezoid rule, or the trapezium rule in British English) is a way to approximately calculate the definite integral,area is given by ALGORITHM:

Step1: start Step2: read no of terms Step3: repeat step3 for i=0 to num Begin Read x[i] Read y[i] End Step4: h= x[i-1]-x[i-2] Step5: repeat for i= 1 to num-1 Ans=ans+4*y[i]*2*[y+1] Step6: ans=ans+y[0]+y[num-1] Step7: ans=ans+0.5*h Step8: print ans
_____________________________________________________________________________________ 156 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Step9: stop Result: Input: Enter no of terms: 7 Enter value of x0: 1 Enter value of y0: 2.105 Enter value of x1: 2 Enter value of y1: 2.808 Enter value of x2: 3 Enter value of y2: 3.614 Enter value of x3: 4 Enter value of y3: 4.604 Enter value of x4: 5 Enter value of y4: 5.857 Enter value of x5: 6 Enter value of y5: 7.451 Enter value of x6: 7 Enter value of y6: 9.451 Enter value of x6: 8 Enter value of y6: 9.451 Output:

The integral of is 74.925

24b) Write C programs to implement Simpson methods.


AIM: Teaching the students how to implement Simpson methods.
_____________________________________________________________________________________ 157 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Area a= (b-a)/3n*(FO+4(f1+f3+f5+.) +2(f2+f4+f6+..))

ALGORITHM:

Step1: start Step2: read no of terms Step3: repeat step3 for i=0 to num Begin Read x[i] Read y[i] End Step4: h= x[i-1]-x[i-2] Step5: repeat for i= 1 to num-2 begin Ans=ans+4*y[i]*2*[y+1] Increment I by 2 end Step6: ans=ans+y[0]+y[num-1] Step7: ans=ans*h/3.0 Step8: print ans Step9:stop

Result: Input:

Enter no of terms: 5

_____________________________________________________________________________________ 158 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Enter value of x0: 1 Enter value of y0: 13 Enter value of x1: 2 Enter value of y1: 13 Enter value of x2: 3 Enter value of y2: 70 Enter value of x3: 4 Enter value of y3: 80 Enter value of x4: 5 Enter value of y4: 100

Output:

The integral of is 257.6667 Numbers At the tip of Pyramid is the number 1, which makes up the first

Questions:

1. What is a proper method of opening a file for writing as binary file? 1. FILE *f = fwrite( "test.bin", "b" ); 2.FILE *f = fopenb( "test.bin", "w" ); 3.FILE *f = fopen( "test.bin", "wb" ); 2. Which one of the following functions is the correct choice for moving blocks of binary data that are of arbitrary size and position in memory? 1. memcpy()2. memset() 3. strncpy() 4. strcpy() 3. int x = 2 * 3 + 4 * 5; What value will x contain in the sample code above? 1.22 2. 26 3. 46 4. 50 4. void * array_dup (a, number, size) const void * a; size_t number; size_t size; {
_____________________________________________________________________________________ 159 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

void * clone; size_t bytes; assert(a != NULL); bytes = number * size; clone = alloca(bytes); if (!clone) return clone; memcpy(clone, a, bytes); return clone; }The function array_dup(), defined above, contains an error. Which one of the following correctly analyzes it? 1.If the arguments to memcpy() refer to overlapping regions, the destination buffer will be subject to memory corruption. 2.array_dup() declares its first parameter to be a pointer, when the actual argument will be an array. 5. int var1; If a variable has been declared with file scope, as above, can it safely be accessed globally from another file? 1. Yes; it can be referenced through the register specifier. 2.No; it would have to have been initially declared as a static variable. 3.No; it would need to have been initially declared using the global keyword.[Ans] 4.Yes; it can be referenced through the publish specifier. 6. time_t t; Which one of the following statements will properly initialize the variable t with the current time from the sample above? 1 t = clock();[Ans] 2.time( &t ); 7. Which one of the following provides conceptual support for function calls? 1. The system stack [Ans] 2.The data segment 8.fopen () used to open----------9. Puspose of switch statement-----------10. Array is used to represent-------------11. The operator used to access the structure member-----------

_____________________________________________________________________________________ 160 MLR INSTITUTE OF TECHNOLOGY, DUNDIGAL

Você também pode gostar