Академический Документы
Профессиональный Документы
Культура Документы
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
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. .
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
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
122
18
127
19
134
20 21
140 146
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
If n< 0 s=0.m=n
Flowchart
Yes
No
Yes No
Result: Input: Enter the number 987 Output: The sum of individual digits is 24
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
Stop
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
Yes Yes
Print i
False
True
r=i% j
No
j++
If r==0
Yes
l=0
return(l)
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
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.
Flowchart:
Start
Input x
fact(n)
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
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
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
v)
goto 9.
6) i) print roots are imaginary ii) print x1 ie complex root. iii) print x2 ie complex root. 7) Stop.
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
1
Print Equal roots
2
Print roots are real & unequal
3
Print Imaginary roots
Print x1, x2
Print x2 is complex
Stop
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
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)
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
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
Flowchart: hcf(p, q)
hcf(p, q) r = p-(p/q2)
If r= =0 return(q )
No
Yes
hcf(p, q)
return(r)
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
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
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-----------------------
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.
8. Stop.
Flowchart: Start
Input acceleration a Input start time i Input ending time n Input Interval it
Repeat t=i to
n with step it
No
Stop
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 (+,-,*,/,%)
(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.
flowchart: Start
Input a, b Menu + Addition - Subtraction * Multiplication / Division % Remainder E Exit Input choice op Yes If op = E No
Stop
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
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
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
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
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:
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-------------
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
START
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
STOP
Input: Enter main string: ramu is good boy Enter string to be inserted :very Enter position to be inserted:10 Expected Output:
step14: until i=pos+del <= l step15:end step16: print str step17: stop
START
READ STRING
if(pos>l) T
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
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-----
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:
START
READ STRING
I<LEN/2
FLAG=0
FLAG=1
PRINT PALINDROME
STOP
Result: Input:
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
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
START
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
START
READ C
STR[I]=\0 I=0
NC++
PRINT NC,NW,NL
STOP
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>?
Flowchart:
START
PRINT BIGNO
STOP
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
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++
K=K-1
STOP
Result:
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-------------
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
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
Flowchart:
If n<=0|| x<=000
yes
no
Sum=1
no
Repeat i=1 to n
yes Sum=sum+pow(x, i)
Print sum
Stop
Result: Input:
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-------------
8.to change the string from lowercase to uppercase which function is used---------9.define function declaration------10.parameters are used to------------ & ------------
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
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
No
Result: Input:
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=
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:
Output:
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
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
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:
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
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
Result: Input:
Enter the complex number c1: 2 3 Enter the complex number c2: 2 3
Output:
Questions:
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
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
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()
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
Flowchart:
Yes No
Yes No
Yes No No Yes
Result:
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--------
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:
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
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---------------------
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
Start
3) FLOWCHART:
FILE *f2
Putc(ch,f2)
Close (f2)
Close (f2)
Stop
FLOWCHART
Start
FILE *f2
I=0
If I<argc
Close (f2)
I=0
If I<argc
Close (f2)
Stop
contents of text file c>f12_7 ddd eee fff ggg c:\c\f12_7.exe text aaa bbb ccc ddd eee fff ggg
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
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.
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.
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:
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:
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.
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
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 --------------
3. Searching a Linked list requires, Linked list be created---------------4. The fields in the single linked list are -----------------
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.
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
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
/* 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
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
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 -----------------
Experiment: 16 Use functions to perform following OPERATIONS on Queues using arrays and pointers
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
10
F=0 R=0
10
20
F=0 10 20
R=1 30
F=0 10 20 30
R=2 40
R=3
10
20
30
40
F=0
R=3
20
30
40
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.
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
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
PR
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 -----------
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
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
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]
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:
Output:
Sorted array is 12 23 32 44 56
Write C programs that implement the following sorting methods to sort a given list of integers in ascending order:
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
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
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
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
Output:
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
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
3. Find first element larger than pivot (underlined) and the last element not larger than pivot (italicised)
6. Swap
7. Scan
9. Pivoting is now complete. Recursively sort sub arrays on each side of pivot.
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++
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
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------------
Example problem
ALGORITHM:
Step1: start Step2: read n1(sorted elements of ist array) Step3: repeat thru step3 until i<n1 read a[i]
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
step10: repeat thru step10 until i<n print c[i] step11: stop
Result: Input:
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--------------
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]
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
Enter value of y0: 68.7.8 Enter value of x0: 8 Enter value of y0: 81.3
Output:
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)
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:
Questions:
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
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
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
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
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--------------
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:
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
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-----------