Você está na página 1de 36

Department of CSE & IT

Instructions for Computer Programming Lab

Pre-lab activities:

• Prepare observation note book which contains the following :


o Procedure/algorithm/program to solve the problems discussed in the
theory class
o Solutions to the exercises given in the previous lab session

• Refer the topics covered in theory class

In-lab activities:

• Note down errors observed while executing program and remedy for that.
• Note down corrections made to the code during the lab session
• Answer to vivo-voce
• Get the observation corrected
• Note down inferences on the topic covered by the programs executed

Post-lab activities:
• Solve the given exercises
• Devise possible enhancements that can be made to the solved problem to
simplify the logic

 Executed programs should be recorded in the lab record and corrected within
one week after completion of the experiment.

 After completion of every module, a test will be conducted, and assessment


results will have weight in the final internal marks.

General Instructions:
• Student should sign in the log register before accessing the system.
• Student is only responsible for any damage caused to the equipment in the
laboratory during his session.
• Usage of pen drives is not allowed in the lab.
• If a problem is observed in any hardware equipment, please report to the lab
staff immediately; do no attempt to fix the problem yourself.
• Systems must be shut down properly before leaving the lab.
• Please be considerate of those around you, especially in terms of noise level.
While labs are a natural place for conversations regarding programming,
kindly keep the volume turned down

C Programming Lab Manual 1


Department of CSE & IT

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY KAKINADA


C PROGRAMMING LAB Syllabus effective from 2010-11

Exercise l
Solving problems such as temperature conversion, student grading, income tax calculation,
etc., which expose students to use basic C operators

Exercise 2
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.

Exercise 3
a) Write a C program to find the sum of individual digits of a positive integer.
b) A Fibonacci sequence is defined as follows: the first and second terms in the sequence are
0 and 1. Subsequent terms are found by adding the preceding two terms in the sequence.
Write a C program to generate the first n terms of the sequence.
c) Write a C program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user.
d) Write a program which checks a given integer is Fibonacci number or not.

Exercise 4
a) Write a C program to calculate the following Sum: Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!
b) Write a C program to find the roots of a quadratic equation.

Exercise 5
a) The total distance travelled by vehicle in ‘t’ seconds is given by distance = ut+1/2at 2 where
‘u’ and ‘a’ are the initial velocity (m/sec.) and acceleration (m/sec2). Write C program to find
the distance travelled at regular intervals of time given the values of ‘u’ and ‘a’. The program
should provide the flexibility to the user to select his own time intervals and repeat the
calculations for different values of ‘u’ and ‘a’.
b) Write a C program, which takes two integer operands and one operator form the user,
performs the operation and then prints the result. (Consider the operators +,- ,*, /, % and use
Switch Statement)

Exercise 6
a) Simple programming examples to manipulate strings.
b) Verifying a string for its palindrome property

Exercise 7
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.
ii. To delete n Characters from a given position in a given string.
iii. To replace a character of string either from beginning or ending or at a specified location

Exercise 8
Write a C program that uses functions to perform the following operations using Structure:
i) Reading a complex number ii) Writing a complex number
iii) Addition of two complex numbers iv) Multiplication of two complex numbers
Exercise 9

C Programming Lab Manual 2


Department of CSE & IT

a) Addition of Two Matrices b) Calculating transpose of a matrix in-place manner.


c) Matrix multiplication by checking compatibility
Exercise 10
a) Write C programs that use both recursive and non-recursive functions for the following
i) To find the factorial of a given integer.
ii) To find the GCD (greatest common divisor) of two given integers.
iii) To solve Towers of Hanoi problem.
Exercise 11
a) Write a C functions to find both the largest and smallest number of an array of integers.
b) Write a C function that uses functions to perform the following:
i) that displays the position/ index in the string S where the string T begins, or –1 if S doesn’t
contain T.
ii) to count the lines, words and characters in a given text.
Exercise 12
a) Write a C function to generate Pascal’s triangle.
b) Write a C function to construct a pyramid of numbers.
Exercise 13
Write a C function to read in two numbers, x and n, and then compute the sum of
this geometric progression: 1+x+x2+x3+………….+xn
Write a C function to read in two numbers, x and n(no. of terms), and then compute sin(x)
and cos(x).
Exercise 14
a. Pointer based function to exchange value of two integers using passing by address.
b. Program which explains the use of dynamic arrays.
c. Program to enlighten dangling memory problem (Creating a 2-D array dynamically using
pointer to pointers approach.
Exercise 15
Examples which explores the use of structures, union and other user defined variables
Exercise 16
a) Write a C program which copies one file to another.
b) Write a C program to reverse the first n characters in a file. (Note: The file name and n are
specified on the command line)

***

C Programming Lab Manual 3


Department of CSE & IT

Exercise 1
1. Temperature conversion
a) Centigrade to Fahrenheit
Input: temp in 0c
Output: temp in F
Step 1: Start
Step 2: read temperature in centigrade
Step 3: fc × 9/5 +32
Step 4: print result
Step 5: end
b) Fahrenheit to centigrade
Input: temp in F
Output: temp in 0c
Step 1: Start
Step 2: read temperature in Fahrenheit
Step 3: cf-32 × 5/9
Step 4: print result
Step 5: end
2. Student Grading
Input: marks in 6 subjects
Output: grade
Step 1: Start
Step 2: read marks in six subjects
Step 3: compute total
Step 4: compute average
Step 5: check if average > 75
Step 6: print grade as A
Step 7: else if average is <75 and >60
Step 8: print grade as B
Step 9: else if average is <60 and >35
Step 10: print grade as C
Step 11: else print result as fail
Step 12: end

C Programming Lab Manual 4


Department of CSE & IT

3. Income tax ( no tax upto 1.6 lakh, 10% upto 5 lakh, 20% for 5 to 8 lakh, 30% for
above 8 lakh)
Input : annual income (ai) , non taxable amount (nta) = 1,60,000-00
Output: tax amount
Step 1: start
Step 2: read annual income or monthly income
Step 3: check if ai < nta
Step 4: print tax is 0
Step 5: else if annual income is in between nta and 5 lakh
Step 6: tax  (ai – nta) * 10/100
Step 7: else if annual income > 5 lakh and less than 8 lakh
Step 8: tax(5 lakh-nta)*10/100 + (ai-5 lakh)*20/100
Step 9: else if annual income > 5 lakh and less than 8 lakh
Step 10: tax(5 lakh-nta)*10/100 + (3 lakh)*20/100 + (ai- 8 lakh)*30/100
Step 11: print tax
Step 12: end

Exercise 2
2’s complement of a given binary number
Input: char st[20]; integer i, j
Output:
Step 1: Start
Step 2: read binary no as string in to st
Step 3: repeat steps 4, 5 and 6 until i from (string length of st -1) to 0
Step 4: check if st[i] equal to ‘1’
Step 5: ji
Step 6: break
Step 7: repeat steps 8 to 11 until j from j-1 to 0
Step 8: check if st[j] equal to ‘1’
Step 9: st[j] ’0’
Step 10: else
Step 11: st[i] ’1’
Step 12: print result string st

C Programming Lab Manual 5


Department of CSE & IT

Step 13: Stop


Exercise 3
a) Program to find sum of individual digits of a positive integer
Algorithm: /* Sum_of_Digits */
Input: integer n
Output: sum of individual digits of ‘n’
Step 1: Start
Step 2: read n, s  0
Step 3: if n < 0 goto step 2
Step 4: repeat steps 5, 6 and 7 until n >0
Step 5: r  n mod10
Step 6: sum sum + r
Step 7: n  n/10
Step 8: print sum
Step 9: stop
b) Program to print fibonacci sequence up to given n terms.
Algorithm: /* Fibonacci_serieas */
Input: - integer n
Output: Fibonacci series upto n terms
Step 1: Start
Step 2: read n, f1  0 and f2  1
Step 3: print f1 and f2
Step 4: repeat steps 5 to 9 until n>0
Step 5: new_term  f1 + f2
Step 6: print new_term
Step 7: f1  f2
Step 8: f2  new_term
Step 9: n  n-1
Step 10: Stop
c) Program to print all prime numbers from 1 to given range n.
Input: integer n
Output: prime numbers upto given range n
Step 1: Start

C Programming Lab Manual 6


Department of CSE & IT

Step 2: read n
Step 3: repeat steps 4 to 10 for i : 0 to n
Step 4: flag  0
Step 5: repeat steps 6 to 8 for j: 2 to i/2
Step 6: if i mod j equals to 0
Step 7: flag 1
Step 8: break;
Step 9: if flag equal to 0
Step 10: print i
Step 11: Stop

d) Write a program which checks a given integer is Fibonacci number or not .


Input: any integer number
Output:
Step 1: Start
Ste 2: read n
Step 3: read n, f1  0 and f2  1 ntf1+f2, flag 0
Step 4: repeat steps 5 to 7 until nt < n
Step 5: check if nt equal to n
Step 6: flag1, break
Step 7: else f1f2, f2nt, ntf1+f2
Step 8: check if flag equal to 1
Step 9: print ‘given no is Fibonacci number’
Step 10: else print ‘not Fibonacci number’
Step 11: end

Exercise 4
a) To Calculate the following sum, Sum = 1-x2/2!+ x4/4!- x6/6!+ x8/8!- x10/10!
Input: integer x
Output: sum of the series
Step 1: Start
Step 2: read x, sum 1, s 1, i  2, j  0
Step 3: repeat steps 4 to 9 for i: form 2 to 10 in steps of 2

C Programming Lab Manual 7


Department of CSE & IT

Step 4: p 1, f 1
Step 5: repeat steps 6 and 7 for j: from 1 to i
Step 6: pp*x
Step 7: ff*j
Step 8: s  s * (-1)
Step 9: sum  sum + s * (p / f)
Step 10: print sum
Step 11: Stop

b) To find roots of quadratic equation


Input: integer a, b, c
Output: Roots of quadratic equation root1 and root 2
Step 1: Start
Step 2: read a, b, c
Step 3: d  b * b-(4 * a * c)
Step 4: if d>0 perform steps 5, 6 and 7 else go to step 8
Step 5: root1  (-b+sqrt(d))/(2*a)
Step 6: root2  (-b-sqrt(d))/(2*a)
Step 7: print root1, root2
Step 8: check if d = 0 do steps 9 & 10 else goto step 11
Step 9: root1root2  -b/(2*a)
Step 10: print root1, root2
Step 11: print ‘roots are imaginary’
Step 12: Stop

Exercise 5
a) The total distance traveled by vehicle in ‘t’ seconds is given by d=ut+0.5at 2. Write a C
program to find the distance traveled in regular intervals of time for different values of
u & t.
Input: integer u, a, interval, no_of_intervals
Output: Distance traveled at regular intervals
Step 1: Start
Step 2: ch  ’y’

C Programming Lab Manual 8


Department of CSE & IT

Step 3: repeat steps 4 to 10 until ch != ’n’


Step 4: read u, a, interval, no_of_intervals
Step 5: t 0
Step 6: repeat steps 7, 8 and 9 for i: from 1 to no_of_intervals
Step 7: t  t + interval
Step 8: d u* t+ 0.5* a * t * t
Step 9: print ‘distance traveled= d’
Step 10: read ch (i.e., y [yes] or n [no])
Step 11: Stop

b) Write a c program, which takes two integer operands and one operator from the
user, performs the operation and then prints the result.
Input: integer a, b & operator
Output: Result based on operator
Step 1: Start
Step 2: read two integers a, b and the operator
Step 3: if operator is ’+’ goto step 8
Step 4: if operator is ’-’ goto step 9
Step 5: if operator is ’*’ goto step10
Step 6: if operator is ’/’ goto step 11
Step 7: if operator is ’%’ goto step 12
Step 8: print result of a+b
Step 9: print result of a-b
Step 10: print result of a*b
Step 11: print result of a/b
Step 12: print result of a%b
Step 13: Stop
Exercise 6
a) Simple programming examples to manipulate strings.
/* strlen, strcpy, strrev, strcat*/
Input : st1, st2
Output:
Step 1: Start

C Programming Lab Manual 9


Department of CSE & IT

Step 2: read st1, st2, ch


Step 3: switch ch
Step 4: if ch equal to 1
Step 5: repeat step 6 until st1[i] not equal to NULL
Step 6: increment count
Step 7: print ‘count’
Else if ch is equal to 2
Step 8: repeat step 9 until st1[i] not equal to NULL
Step 9: rs  st1[i]
Step 10: print ‘rs’
Else if ch is equal to 3
Step 11: repeat step 12 & 13 until j from string length to 0
Step 12: re[i]st1[j]
Step 13: i+1, j-1
Step 14: print ‘rs’
Else if ch is equal to 4
Step 15: repeat step 16 until st2[i] not equal to NULL
Step 16: st1[strlen(st1)+i)st2[i]
Step 17: print ‘st1’
Step 18: Stop

b) Write a C program to check whether the given string is palindrome or not.


Input: char st[20], chk0
Output:
Step 1: Start
Step 2: read string st
Step 3: repeat step 4 until st[i] not equal to null
Step 4: len len + 1
Step 4: repeat steps 5, 6 for i: form 0 to len/2
Step 5: check if st[i] ≠ st[len-i]
Step 6: chk1
Step 7: check if chk equal to 0
Step 8: print ‘given string is palindrome’

C Programming Lab Manual 10


Department of CSE & IT

else
Step 9: print ‘given string is not palindrome’
Step 10: end

Exercise 7
Write a c program that uses functions to perform the following operations
i) To insert a sub-string into given main string form a given position
ii) To delete n char form a given position in a given string
iii) To replace a character of string either from beginning or ending or at a specified
location

Input: char choice, st1[20], st2[20] ; integer l1, l2


Output: modified string
Step 1: Start
Step 2: read choice
Step 3: switch choice
Step 4: case 1
read st1, st2, pos
l1call sub-routine st_len(st1)
l2 call sub-routine st_len(st2)
call sub-routine insert_string(st1, st2, l1, l2)
Step 5: case 2
read st1, pos, n
l1 call sub-routine stlen(st1)
call sub-routine del_n_chars(st1, pos, n)
Step 6: case 3
read st1, chat_to_replace , char_to_replaceby
call sub-routine replace_char(st1, ch_re, ch_re_by)
Step 7: Stop
Algorithm for sub routine st_len(char st[])
Step 1: begin
Step 2: len0
Step 3: repeat step 4 until st[i] not equal to null

C Programming Lab Manual 11


Department of CSE & IT

Step 4: len len + 1


Step 5: return len
Step 6: end
Algorithm for sub routine insert_string(char st1[], char st2[], int l1, int l2)
Step 1: begin
Step 2: repeat step 3 for i: form l1+l2-1 to pos
Step 3: st1[i]st1[i-l2]
Step 4: repeat step 5 for i: from 0 to l2
Step 5: st1[i+pos-1]  st2[i]
Step 6: st1[l1+l2]  ‘\0’
Step 7: print result string st1
Step 8: end
Algorithm for sub routine del_n_chars(char st1[], int pos, int n)
Step 1: begin
Step 2: repeat step 3 for i from pos-1 to null
Step 3: st1[i]st1[i+n]
Step 4: st[i]  ‘\0’
Step 5: print result string st1
Step 6: end
Algorithm for sub routine replace_char(char st1[], char ch_re, char ch_re_by)
Step 1: begin
Step 2: switch choice 1. From begin 2. From end 3. From location
Step 3: case 1
Loop until st1[i] not equal to NULL
check if st1[i] equal to ch_re
st1[i]ch_re_by
Step 4: case 2
Loop until st1[i] from strlen of st1 to 0
check if st1[i] equal to ch_re
st1[i]ch_re_by
Step 5: case 3
read pos
Loop until st1[i] from pos to strlen of st1

C Programming Lab Manual 12


Department of CSE & IT

check if st1[i] equal to ch_re


st1[i]ch_re_by
Step 6: print st1
Step 7: end

Exercise 8
Write a C Program that uses functions to perform the following operations using
Structure:
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers

Input: struct complex_number {float real, float img}


Output: result of chosen operation
Step 1: Start
Step 1: declare struct complex z1 with members as real, and imag
Step 5: for reading call sub-routine read_com(z1) and read_com(z2)
Step 6: for writing a complex number call sub-routine write_com(z1)
Step 7: addition of two complex numbers call sub-routine add_com()
Step 8: multiplication of two complex numbers call sub-routine mul_com()
Step 9: print result
Step 10: Stop
Algorithm for sub routine read_com()
Step 1: begin
Step 2: read z1.real
Step 3: read z1.imag
Step 4: end
Algorithm for sub routine write_com()
Step 1: begin
Step 2: print z1.real ‘+i’ z1.imag
Step 3: end

C Programming Lab Manual 13


Department of CSE & IT

Algorithm for sub routine add_com()


Step 1: begin
Step 2: z3.realz1.real + z2.real
Step 3: z3.imag  z1.imag + z2.imag
Step 4: end
Algorithm for sub routine mul_com()
Step 1: begin
Step 2: z3.real (z1.real*z2.real) – (z1.imag*z2.imag)
Step 3: z3.imag  (z1.real * z2.imag) + (z1.imag * z2.real)
Step 4: end

Exercise 9
a) Addition of Two Matrices

Input: integer r1, c1, r2, c2, a[10][10], b[10][10]


Output:
Step 1: Start
Step 2: read order of matrix a into r1, c1
Step 3: read order of matrix b into r2, c2
Step 4: call sub-routine mat_read (a,r1,c1)
Step 5: call sub-routine mat_read (b,r1,c1)
Step 6: check if r1 ≠ r2 and c1 ≠ c2
Step7: print ‘addition not possible’ go to step 10
Step8: else call sub-routine mat_add(a, b, d, r1, c1)
Step9: call sub-routine mat_print(d,r1,c1)
Step 10: Stop
Algorithm for sub routine mat_read(int rm[], int r, int c)
Step 1: begin
Step 2: repeat steps 3, 4 for i: from 1to r
Step 3: repeat step 4 for j: from 1 to c
Step 4: read rm[i][j]
Step 5: end
Algorithm for sub routine mat_add(int a[][], int b[][], int d[][], int r1, int c1)

C Programming Lab Manual 14


Department of CSE & IT

Step 1: begin
Step 2: repeat steps 3, 4 for i: from 1 to r1
Step 3: repeat step 4 for j: form 1 to c1
Step 4: d[i][j]a[i][j] + b[i][j]
Step 5: end
Algorithm for sub routine mat_print(int pm[][], int r1, int c1)
Step 1: begin
Step 2: repeat steps 3 to 5 for i: from 1 to r
Step 3: repeat step 4 for j: form 1 to c
Step 4: print pm[i][j]
Step 5: print ‘ ‘
Step 6: end

b) Calculating transpose of a matrix in-place manner.


Input: integer r1, c1, a[10][10]
Output:
Step 1: Start
Step 2: read order of matrix a into r1, c1
Step 3: call sub-routine mat_read (a,r1,c1)
Step 4: call sub-routine mat_tran(a, b, d, r1, c1)
Step 5: call sub-routine mat_print(d,r1,c1)
Step 6: Stop
Algorithm for sub routine mat_read(int rm[], int r, int c)
Step 1: begin
Step 2: repeat steps 3, 4 for i: from 1to r
Step 3: repeat step 4 for j: from 1 to c
Step 4: read rm[i][j]
Step 5: end
Algorithm for sub routine mat_tran(int a[][], int r1,int c1)
Step 1: begin
Step 2: repeat steps 3 to 5 for i: from 1 to r1
Step 3: repeat steps 4 & 5 for j: from 1 to c2
Step 4: check if i<j

C Programming Lab Manual 15


Department of CSE & IT

Step 5: swap a[i][j] with a[j][i]


Step 6: end
Algorithm for sub routine mat_print(int pm[][], int r1, int c1)
Step 1: begin
Step 2: repeat steps 3 to 5 for i: from 1 to r
Step 3: repeat step 4 for j: form 1 to c
Step 4: print pm[i][j]
Step 5: print ‘ ‘
Step 6: end

c) Matrix multiplication by checking compatibility


Input: integer r1, c1, r2, c2, a[10][10], b[10][10]
Output:
Step 1: Start
Step 2: read order of matrix a into r1, c1
Step 3: read order of matrix b into r2, c2
Step 4: call sub-routine mat_read (a,r1,c1)
Step 5: call sub-routine mat_read (b,r1,c1)
Step 6: check if c1 ≠ r2
Step 7: print ‘multiplication not possible’ goto step 11
Step 8: else
Step 9: call sub-routine mat_multi(a, b, c, r1, c1, r2, c2)
Step 10: call sub-routine mat_print(c,r1,c2)
Step 11: Stop
Algorithm for sub routine mat_read(int rm[], int r, int c)
Step 1: begin
Step 2: repeat steps 3, 4 for i: from 1to r
Step 3: repeat step 4 for j: from 1 to c
Step 4: read rm[i][j]
Step 5: end
Algorithm for sub routine mat_multi(int a[][],int b[][],int c[][], int r1,int c1,int r2,int c2)
Step 1: begin
Step 2: repeat steps 3 to 6 for i: from 1 to r1

C Programming Lab Manual 16


Department of CSE & IT

Step 3: repeat steps 4 to 6 for j: from 1 to c2


Step 4: c[i][j]0
Step 5: repeat step 6 for k: from 1 to c1
Step 6: c[i][j]  c[i][j] + a[i][k] * b[k][j]
Step 7: end
Algorithm for sub routine mat_print(int pm[][], int r1, int c1)
Step 1: begin
Step 2: repeat steps 3 to 5 for i: from 1 to r
Step 3: repeat step 4 for j: form 1 to c
Step 4: print pm[i][j]
Step 5: print ‘ ‘
Step 6: end

Exercise 10
a) To find factorial of given number using both recursive and non-recursive functions.
Algorithm: /* factorial_recursive & non-recursive */
Input: integer n
Output: factorial of given number
Step 1: Start
Step 2: read n
Step 3: factorial  call sub-routine fact(n)
Step 4: print factorial
Step 5: factorial call sub-routine fact_rec(n)
Step 6: print factorial
Step 7: Stop
Algorithm for sub-routine fact(int n)
Step 1: begin
Step 2: f 1, i 1
Step 3: repeat step 4 for i: from 1 to n
Step 4: ff*i
Step 5: return f
Step 6: end
Algorithm for sub routine fact_rec(int n)

C Programming Lab Manual 17


Department of CSE & IT

Step 1: begin
Step 2: f 1
Step 3: if n equal to 0 go to step 4 else go to step 5
Step 4: return 1
Step 5: f  n* fact_rec(n-1)
Step 6: return f
Step 7: end

b) To find GCD of given two numbers using both recursive and non-recursive functions.
Algorithm: /* GCD_recursive & non-recursive */
Input: integer a, b
Output: GCD of a, b
Step 1: Start
Step 2: read a, b
Step 3: call sub routine gcd_non_rec(a, b)
Step 4: print GCD
Step 5: call sub routine gcd_rec (a, b)
Step 6: print GCD
Step 7: Stop
Algorithm for Sub Routine gcd_non_rec(int a, int b)
Step 1: begin
Step 2: check if a < b then
Step 3: swap a,b values
Step 4: repeat steps 5 to 9 until b not equals 0
Step 5: ca mod b
Step 6: if c equals to 0
Step 7: return b
Step 8: ab
Step 9: bc
Step 10: end
Algorithm for Sub Routine gcd_rec(int a, int b)
Step 1: begin
Step 2: check if b equal to 0

C Programming Lab Manual 18


Department of CSE & IT

Step 3: return a
Step 4: else
Step 5: call sub-routine gcd_rec(b, a mod b)
Step 6: end

c) Towers of Hanoi problem using both recursive and non-recursive functions.


Algorithm: /* Towers of Hanoi_recursive */
Input: integer n
Output:
Step 1: Start
Step 2: read n
Step 3: call sub-routine toh(n)
Step 4: Stop
Algorithm for sub routine toh(int n)
Step 1: begin
Step 2: check if n equals to 1 return
Step 3: Move disk from source to dest
Step 4: else
Step 5: call sub routine toh(n-1, source , aux, dest)
Step 6: Move disk from source to dest
Step 7: call sub routine toh (n-1, aux, dest, source)
Step 8: end

Exercise 11
a) Write a C functions to find both the largest and smallest number of an array of
integers.
Input: integer n
Output: largest = max, smallest = small
Step 1: Start
Step 2: read n
Step 3: repeat step 4 for i : 0 to n
Step 4: read a[i]
Step 5: maxa[0], smalla[0]
Step 6: repeat steps 7 to 10 for i: from 1 to n

C Programming Lab Manual 19


Department of CSE & IT

Step 7: check if a[i] > max


Step 8: max a[i]
Step 9: check if a[i] < small
Step 10: small a[i]
Step 11: print max and small
Step 12: Stop

b) Write a C function that uses functions to perform the following:


i) displays the position/ index in the string S where the string T begins, or –1 if S doesn’t
contain T.
Input: char st1[20], st2[20]; integer len, res
Output:
Step 1: Start
Step 2: read string st1 and st2, res  -1
Step 3: len  call sub-routine st_len(st2)
Step 4: res  call sub-routine st_chk_index(st1, st2, len)
Step 5: check if res equal to -1
Step 6: print ‘String not found’
else
Step 7: print ‘String found at position’
Step 8: Stop
Algorithm for sub routine st_len(char st[])
Step 1: begin
Step 2: len0
Step 3: repeat step 4 until st[i] not equal to null
Step 4: len len + 1
Step 5: return len
Step 6: end
Algorithm for sub routine st_chk_index(char st1[], char st2[], int len)
Step 1: begin
Step 2: repeat steps 3 to 9 for i from 0 to length of st1
Step 3: check if st1[i] equal to st2[0]
Step 4: n0
Step 5: repeat steps 6, 7 for j form 0 to length of st2

C Programming Lab Manual 20


Department of CSE & IT

Step 6: check if st[i+j] equal to st2[j]


Step 7: n  n+1
Step 8: check if n equal to len
Step 9: return(i+1)
Step 10: return -1
Step 11: end

ii) to count the lines, words and characters in a given text.


Input: chat st[100]
Output:
Step 1: Start
Step 2: c  0, w 1, ln  0, i0
Step 3: repeat steps 4, 5 until escape
Step 4: read st[i]
Step 5: i+1
Step 6: repeat steps 7 to 13 until i from 0 to length of string st
Step 7: check if st[i] >=65 and st[i] <=90 or st[i] >=97 and st[i]<=122
Step 8: c+ 1
Step 9 else
Step 10: check if st[i] equal to 32 and st[i+1] ≠ 32
Step 11: w+  1
Step 12: check if st[i] equal to 13
Step 13: ln+1
Step 14: print result no_of_char = c, no_of_lines = ln, no_of_words = w + ln-1
Step 15: Stop

Exercise 12
a) Write a C function to generate Pascal’s Triangle.
Input: integer n
Output:
Step 1: Start
Step 2: read n (no of rows), bin1
Step 3: repeat steps 4 to 11for i: from 0 to n

C Programming Lab Manual 21


Department of CSE & IT

Step 4: repeat step 5 until k 0 to 20-i*3


Step 5: print space
Step 6: repeat steps 7 to 11 for j: from 0 to i
Step 7: check if i equal to 0 or j equal to 0
Step 8: bin1
Step 9: else
Step 10: bin  (bin*(i-j+1))/j
Step 11: print bin
Step 12: Stop

b) Write a C function to construct a pyramid of numbers.


Input: integer n
Output:
Step 1: Start
Step 2: read n, static x1
Step 3: repeat steps 4 to 8 until i < n
Step 4: repeat step 5 for k: 0 to 20-i*3
Step 5: print space
Step 6: repeat steps 7,8 for j: from 0 to i
Step 7: print x
Step 8: xx+1
Step 9: Stop

Exercise 13
a) Write a C function to read in two numbers, x and n, and then compute the sum of
this geometric progression: 1+x+x2+x3+………….+xn
Input: integer x, n
Output:
Step 1: Start
Step 2: read x and n, p0
Step 3: check if n less than 0
Step 4: print error message and goto step 2
Step 5: else

C Programming Lab Manual 22


Department of CSE & IT

Step 6: sum1
Step 7: repeat step 8 to 10 for i: from 1 to n
Step 8: repeat step 9 for j: from 1 to i
Step 9: p  p*x
Step 10: sum  sum + p
Step 11: print x, n, sum
Step 12: Stop

b) Write a C function to read in two numbers, x and n(no. of terms), and then compute
sin(x) and cos(x).
sin(x) = x - x3/3! + x5/5! – x7/7! + . . . .
Step 1: Start
Step 2: read n, x
Step 3: sum  x, pt  x
Step 4: repeat steps 5 to 8 until i < n
Step 5: nt pt * (x*x) / (2*i)(2*i+1)
Step 6: sum +  sign * nt
Step 7: pt  nt
Step 8: sign *= -1
Step 9: print sum of sin series
Step 10: Stop

cos(x) = 1 – x2/2! + x4/4! – x6/6! + . . . .


Step 1: Start
Step 2: read n, x
Step 3: sum1, pt1
Step 4: repeat steps 5 to 8 until i < n
Step 5: nt pt * (x*x) / (2*i-1)(2*i)
Step 6: sum +  sign * nt
Step 7: pt  nt
Step 8: sign *= -1
Step 9: print sum of cos series
Step 10: Stop

C Programming Lab Manual 23


Department of CSE & IT

Exercise 14
a. Pointer based function to exchange value of two integers using passing by address.
Step 1: Start
Step 2: read a,b
Step 3: print ‘ a, b values ’ i.e., before swaping
Step 4: call sub-routine swap(&a, &b)
Step 5: print ‘ a,b values’ i.e., after swaping
Step 6: Stop

Algorithm for swap(int *a, int *b)


Step 1: Begin
Step 2: temp  *a, *a  *b, *b temp
Step 3: end

b. Program which explains the use of dynamic arrays.


Step 1: Start
Step 2: read n (no of elements), int *ar
Step 3: ar  malloc(sizeof (int ) * n)
Step 4: repeat step 5 until i < n
Step 5: read array element
Step 6: repeat step 6 until i < n
Step 7: print array element
Step 8: free memory
Step 9: Stop

c. Program to enlighten dangling memory problem (Creating a 2-D array dynamically


using pointer to pointers approach.
Step 1: Start
Step 2: read n (no of elements), int **ar, x, y
Step 3: ar  malloc( x * sizeof (int ))
Step 4: repeat step 5 until i < x
Step 5: ar[i]  malloc (y * sizeof(int*))
Step 6: loop: for i from 0 to x
loop: for j from 0 to y
Step 7: read array element

C Programming Lab Manual 24


Department of CSE & IT

Step 8: loop: for i from 0 to x


loop: for j from 0 to y
Step 9: print array element
Step 10: free memory
Step 11: Stop

Exercise 15
Examples which explores the use of structures, union and other user defined variables
a) Write a c program to store student details like regd no, name, marks in 3 subjects
for n number of students.
Input:
Output:
Step 1: Start
Step 2: declare structure student
Step 3: loop; for i from 0 to n
Step 4: read rno, name, marks in 3 sub’s
Step 5: loop: for i from 0 to n
Step 6: print student details
Step 7: Stop

b) write a C program explores the use of union.


Input:
Output:
Step 1: Start
Step 2: declare union
Step 3: read an union element
Step 4: print union element
Step 5: Stop

Exercise 16
a) Write a program which copies one file to another
Step 1: Start
Step 2: declare File pointers *fp1, *fp2
Step 3: read filename for source

C Programming Lab Manual 25


Department of CSE & IT

Step 4: fp1fopen(source,”w”)
Step 5: check if fp1 equal to NULL
Step 6: print file not opened, go to step 26
Step 7: else
Step 8: repeat steps 9, 10 char != 27 (ASCII value 27 for ESC key)
Step 9: read char
Step 10: fputc(ch, fp1)
Step 11: close file pointer(fp1)
Step 12: read filename for destination
Step 13: fp1fopen(source, “r”)
Step 14: check if fp1 equal to NULL
Step 15: print file not found, go to step 26
Step 16: else
Step 17: fp2fopen(destination,”w”)
Step 18: check if fp2 equal to NULL
Step 19: print file not open go to step 26
Step 20: else
Step 21: repeat steps 15, 16 until fp1!= EOF
Step 22: ch  fgetc(fp1)
Step 23: fputc(ch, fp2)
Step 24: close file pointer fp1
Step 25: close file pointer fp2
Step 26: Stop
b) Write a C program to reverse first n chars in a file.
Step 1: Start (no of arguments, arguments values)
Step 2: declare file pointer *fp
Step 3: fp  fopen (argv[1],”r+”)
Step 4: Check if fp equal to NULL
Step 5: print file not found
Step 6: else
Step 7: nargv[2]
Step 8: repeat step 9 for i: from 0 to n
Step 9: st[i]fgetc(fp)

C Programming Lab Manual 26


Department of CSE & IT

Step 10: st[i]null


Step 11: strrev(st)
Step 12: rewind(fp);
Step 13: fwrite(st,1,n,fp)
Step 14: close file pointer fp
Step 15: Stop

Appendix A - Assignment Problems


Task Sheet-I
1 1) Write a program to illustrate bitwise operators.
2 2) Write a program to print all the alphabets and their equivalent ASCII values.
3 3) Write a program to calculate the sum of squares of first n natural numbers using
while loop.
4 4) Write a program to print the multiplication table in the following format.

1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25

1 5) Write a program to calculate sum of squares of cubes of first n natural numbers.


2 6) Write a program to reverse the given number.
3 7) Write a program to calculate mn value using do-while loop.
4 8) Write a program to check whether the given number is a palindrome or not.
5 9) Write a program to check whether the given number is an Armstrong number or
not.
6 10) Write a program to check whether the given number is a perfect number or not.
Task Sheet-II

C Programming Lab Manual 27


Department of CSE & IT

1 1) Write a program to print the elements of an array in reverse order.


2 2) Write a program to add all the elements of a two dimensional array.
3 3) Write a program to find the transpose of a given matrix.
4 4) Write a program to find the smallest and largest element in a two dimensional
array.
5 5) Write a program to copy string to another without using string handling functions.
6 6) Write a program to check whether a given string is a palindrome or not.
7 7) Write a function to find the largest element in an array.
8 8) Write a recursive function power (base, exponent) that when invoked returns base
exponent.
9 9) Program to sort the characters in a given string.
10 10) Write a function to convert all the upper case letters to lower case and lower case
letters to upper case in a given string.

Task Sheet-III
1 1) Write a program to calculate length of the string using pointers.
2 2) Write a function to swap two variables using pointers.
3 3) Program to illustrate pointer arithmetic.
4 4) Write a function to calculate sum of two numbers using pointers to functions.
5 5) Write a program to perform matrix multiplication using pointers.
6 6) Write a program to find the largest in an array using pointers.
7 7) Program to arrange the given numbers in ascending order.
8 8) Write a C program using pointer for string comparison.
9 9) Program to reverse the string using pointers.
10 10 The names of employees of an organization are stored in three arrays, namely, first
name, second name, and last name. Write a program using pointers to concatenate the
three parts into one string to be called name.

Task Sheet-IV
1) Write a C program to compute the monthly pay of 100 employees using each employee’s
name, basic-pay. The DA is computed as 52% of the basic pay. Gross-salary (Basic-
pay+DA).Print the employees name and gross salary.
1 2) Write a program to calculate and print student wise total for 50 students and 3

C Programming Lab Manual 28


Department of CSE & IT

subjects. The structure should contain 3 subjects and total.


2 3) Write a program to calculate and print student wise total for 50 students and 3
subjects using pointers. The structure should contain 3 subjects.
3 4) Program for illustration of user defined data types using typedef.
4 5) Program for illustration of nested structures.
5 6) Program to add or delete a record of a particular employee based on his code. The
structure should contain name, designation, code, salary. Program should also provide
the flexibility to update any employees record.
6 7) A company markets Hardware items. Create a structure “hwitem” that stores the
title of the item, it’s price, an array of three floats so that it can record the sale in
rupees of a particular item for the last three months, category of the item and it’s
original equipment manufacturer. Write a short program that provides facility to read
N number of items information, append new item, and displays all records.
7 8) Define a structure to represent a data. Use your structures that accept two different
dates in the format mmdd of the same year. And do the following: Write a C program
to display the month names of both dates.

Task Sheet-V
1 1) Write a C program to read a text file and to count Number of characters, Number
of words and Number of sentences and write in an output file.
2 2) Write a C program to read the text file containing some paragraph. Use fseek() and
read the text after skipping n characters from the beginning of the file.
3 3) Write a C program to read the text file containing some paragraph. Print the first n
characters from the beginning of the file.
4 4) Write a program to print the output of the following format in an OUTPUT file.
Number Square Cube
2 4 8
3 9 27
5) Write a C program to read data from a file named INPUT containing numbers.
Write all even numbers to file called EVEN and odd numbers to file called ODD.
6) Program to print the n characters from mth position in the file.
7) Program to print the current position value of the file pointer.

C Programming Lab Manual 29


Department of CSE & IT

8) Write a C program to open a pre-existing file and add information at the end of file.
Display the contents of the file before and after appending
9) Program to copy one file to another.
10) Write program to read a text file and convert the file contents in capital (upper-
case) and write the contents in an output file.

C Programming Lab Manual 30


Department of CSE & IT

Appendix B - Objective Questions

Predict the output or error(s) for the following:


1
1. main()
{
int i=-1,j=-1,k=0,l=2,m;
m=i++&&j++&&k++||l++;
printf("%d %d %d %d %d",i,j,k,l,m);
}
2. main()
{
int i=3;
switch(i)
{
default:printf("zero");
case 1: printf("one");
break;
case 2:printf("two");
break;
case 3: printf("three");
break;
}
}
3. main()
{
printf("%x",-1<<4);
}
4. main()
{
int c=- -2;
printf("c=%d",c);
}
5. main()
{
int i=10;
i=!i>14;
printf ("i=%d",i);
}
6. main()
{
char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
7. main()
{
extern int i;

C Programming Lab Manual 31


Department of CSE & IT

i=20;
printf("%d",i);
}

8. #define int char


main()
{
int i=65;
printf("sizeof(i)=%d",sizeof(i));
}
9. #define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}

10. #include <stdio.h>


#define a 10
main()
{
#define a 50
printf("%d",a);
}

C Programming Lab Manual 32


Department of CSE & IT

Appendix C - Textual References


1. C Programming and Data Structures, P. Padmanabham, Third Edition, BS Publications
2. Data Structures: A pseudo code approach with C, second edition R.F. Gilberg and B.A.
Forouzan
3. Programming in C, P.Dey & M. Ghosh, Oxford Univ.Press.
4. C and Data Structures, E Balaguruswamy, TMH publications.
5. DataStructures Using C – A.S.Tanenbaum, Y. Langsam, and M.J. Augenstein,
PHI/Pearson education.
6. The C Programming Language, B.W. Kernighan, Dennis M.Ritchie, PHI/Pearson
Education
7. C Programming with problem solving, J.A. Jones & K. Harrow, Dreamtech Press
8. Programming in C – Stephen G. Kochan, III Edition, Pearson Eductaion.
9. Data Structures and Program Design in C, R.Kruse, C.L. Tondo, BP Leung, Shashi M,
Second Edition, Pearson Education.

Appendix D - Internet References


1. www.cprogramming.com/tutorial.html
2. www.java2s.com/Tutorial/C/CatalogC.htm
3. http://www.howstuffworks.com/c.htm
4. http://www.cs.cf.ac.uk/Dave/C/
5. www.owlnet.rice.edu/~comp320/2005/notes/tut03-data_structures
6. http://www.iu.hio.no/~mark/CTutorial/CTutorial.html#Pointers
7. http://www.academictutorials.com/data-structure/data-structure-trees.asp
8. www.kelso.scotborders.sch.uk/.../higher.htm
9. http://www.physics.unlv.edu/~pang/cp_c.html
10. http://www.indiastudychannel.com/resources/13019-C-Program-stack-using-linked-
list.aspx

C Programming Lab Manual 33


Department of CSE & IT

Appendix E - Common C Coding Mistakes

Here is a summary of common coding mistakes students have encountered in writing


programs in this class. If you are having problems with your program, you might find a quick
solution here.

Input problems

1. Use the correct conversion specifier for the declared data type in a scanf(). A float
is %f, an int is %d, and a double is %lf (lower case L). If you declare a variable to be
an int, don't try to input it with a %f specifier.

2. Don't use a precision specification in a scanf() conversion specifier. For example,


scanf("%.2f", &payRate) will not work (at least the ".2" part won't). Use
scanf("%f", &payRate) instead. Width specifiers can be used, however.

3. Use the addressing operator (&) for your variables used as targets for input with
scanf()'s, unless the target is already an address (such as the name of an array or a
pointer variable).

4. The scanf() function can't be used with the %s specifier to input a string that contains
white space (like "Electric sander"). Use another function, like gets().

5. When using getchar() or scanf() with a %c (character) conversion specifier, be


aware that the last input operation (like a previous scanf() or getchar()) may have
left characters in the keyboard buffer.

Output problems

1. Do not use the addressing operator (&) for arguments in a call to printf( ).

2. When using puts( ), a newline character ('\n') is automatically appended, so don't use
it for a prompt if you want the user's input on the same line.

Problems with decision structures

C Programming Lab Manual 34


Department of CSE & IT

1. There is no semicolon after the condition:

if (x > 0) /* correct */
...

if (x > 0); /* wrong */


...

2. Use braces ( { } ) around the body of an if or else branch that contains multiple
statements. You don't need them with a single statement in the body.

3. If you have a dual-alternative selection to implement, use the if...else rather than
switch – it's cleaner.

4. There is no condition in the else branch – only in the if branch.

Problems with loops

1. There is no semicolon after the condition in a while:

while (x > 0) /* correct */


...

while (x > 0); /* wrong - infinite loop */


...

2. The loop index (loop control variable) is not updated inside the loop

Problems with strings

1. You can't compare two strings with with a relational or equality operator (like >= or
==). You must use one of the comparison functions from string.h, like strcmp() or
strncmp( ), or write your own function.

2. To assign (copy, duplicate) one string to another, use one of the copy functions from
string.h like strcpy( ) or strncpy( ), not the assignment operator (=).

File handling problems

C Programming Lab Manual 35


Department of CSE & IT

You can fopen() a file more than once in a program, but a fclose() must be executed
between fopen()'s. Review your algorithm to make sure you really need multiple file open
and closes.

C Programming Lab Manual 36

Você também pode gostar