Computer Scien PDF
Computer Scien PDF
Good programmers use their brains, but good guidelines save us having to think out every case.
Francis Glassborow
This lab supplement provides a list of programs that can be written and executed by students as pro-
gramming lab exercises. Hints and variations have been provided to make the exercises interesting and
easier to implement. A special effort has been made to include all the lab exercises prescribed in the
syllabus for the C Programming and Data Structures course at JNTU.
I. Just Beginning
C code. C code run. Run code run...please!
Barbara Ling
1. Write a C program to find the sum of individual digits of a positive integer.
Hint: For extractning the digits, make use of the % operator. If you get stuck, refer to Chapter 6.
Variation: The running sum of digits is the final single digit sum, e.g., the running sum of
digits of the number 3249 is 9 (3 + 2 + 4 + 9 = 18 Æ 1 + 8 = 9) Write a program to calculate the
running sum of the digits of a positive integer.
2. The 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.
Hint: The simplest way to generate the Fibonacci series is to use a for loop. However, the Fibonacci
sequence may also be generated using a recursive function. The following is a recursive function
which generates the nth Fibonacci number
int fibonacci(int n)
{
if (n < 3) //stop condition
return (1); //stop condition met
}
else
return ( fibonacci(n-2) + fibonacci(n-1));
// recursive calling
}
Let’s C:A Supplement to Computer Programming Lab 55
Write a function which generates and prints the first n terms of the Fibonacci sequence recursively.
Variation: The number (1 + 5 )/2 is called the golden ratio or the number phi and is denoted by
j. The ratio of two consecutive Fibonacci numbers (F n /Fn – 1) tends closer and closer to phi as we
go higher up in the Fibonacci series. Given the approximated value of phi as 1.61803398875,
write a program which calculates the ratio of two consecutive Fibonacci numbers (F and F n – 1),
compares it to the given value of phi, and calculates the error in the value computed.
3. Write a C program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user.
Hint: n is prime if it is indivisible by numbers from 2 to n/ 2.
4. Write a C program to calculate the following sum:
Sum = 1 – x2/2! + x4/4! – x6/6! + x8/8! – x10/10!
Hint: n!=1*2*3*...*n. For calculating powers of x, use the pow() function defined in math.h
(see Chapter 7) or write a user-defined function to calculate the nth power of a given number.
5. Write a C program to find the roots of a quadratic equation.
Hint: For a quadratic equation of the form
ax2 + bx + c = 0
the roots are given by
x1 = (– b + sqrt(b2 – 4ac))/2a
x 2 = (– b – sqrt(b2 – 4ac))/2a
when the discriminant (b2 – 4ac) is positive (see Chapter 9).
Variation: Write a program which will display complex roots as well as real roots. This program
will calculate the roots of the quadratic equation even if the discriminant (b2 – 4ac) is negative.
1. Write C programs that use recursive and non-recursive functions to find the factorial of a given
integer.
Hint: n! = 1*2*3....*n
2. Write C programs that use recursive and non-recursive functions to find the GCD (greatest com-
mon divisor) of two given integers.
Hint: The non-recursive function for calculating the GCD of two numbers is given below
3. Write C programs that use recursive and non-recursive functions to solve the Towers of Hanoi
problem.
56 C Programming & Data Structures
Hint: Towers of Hanoi are discussed in detail in Chapter 7. A simple algorithm for a recursive
solution to the Towers of Hanoi is as follows:
The non-recursive solution may be implemented using three stacks which represent the three
needles.
Variation: Try writing a code which will visually display the steps of the solution to the Towers
of Hanoi. Use the * symbol and spaces to create your figure, for example, the initial state of the
towers with three disks may be represented as:
* * *
* * *
*** * *
***** * *
******* * *
A B C
Do not worry about your difficulties in mathematics. I can assure you that mine are still greater.
Albert Einstein
1. 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’.
2. Write a C program, which takes two integer operands and one operator from the user, performs
the operation and then prints the result. (Consider the operators +,-,*, /, % and use switch
statement)
Hint: Refer to Chapter 5 for details.
3. Write a C program to find both the largest number and smallest number in a list of integers.
Hint: Store the list in an array. Take two variables, max and min. Assign the first number in the
list to both max and min. Then scan the list and compare max and min to each member of the list.
Update the values of max and min.
Let’s C:A Supplement to Computer Programming Lab 57
Alternatively, separate functions for finding maximum and minimum can be written. These func-
tions will take the array of integers as an argument and return the maximum and minimum
respectively.
4. Write a C program that uses functions to perform the following matrix operations:
(i) Addition of two matrices
(ii) Multiplication of two matrices
Hint: The order of a matrix is given by m × n where m is the number of rows of the matrix and
n is the number of columns of the matrix. For addition, the order must be the same. For multipli-
cation, the number of columns of the first matrix must be equal to the number of rows of the
second matrix. The simplest algorithm for matrix multiplication is
for(i=0;i<m;i++)
for(j=0;j<n;j++)
for(k=0;k<p;k++)
C[i][k]+ = A[i][j] * B[j][k];
where Am × n and Bn × p are the two matrices being multiplied and Cm × p is the product matrix.
Variation: Modify your matrix program to perform all matrix functions such as calculating the
determinant of a given matrix, generating the inverse and transpose of a matrix, and identifying
whether a given matrix is a null matrix or not.
{
int i;
if(n==0) return;
for(i=p;i<strlen(s);i++)
s[i]=s[i+n];
return;
}
4. Write a C program to count the lines, words, and characters in a given text.
Hint: Characters can be alphabets, numbers, or special characters (excluding whitespaces). Lines
are terminated by CRLF(\n). Words are terminated by whitespaces. Chapter 13 discusses the
above counting implementations for files. Write the program for strings and then for files.
V. Number Crunching
1 (x + y)0
1 1 (x + y)1
1 2 1 (x + y)2
1 3 3 1 (x + y)3
1 4 6 4 1 (x + y)4
1 5 1 5
2 2 4 5 2 1 2 4 5 4
3 3 3 3 4 5 3 2 1 2 3 3 4 5 4 3
4 4 4 4 2 3 4 5 4 3 2 1 2 3 4 2 3 4 5 4 3 2
The pyramids illustrated above have five rows each. However, a good pyramid of numbers pro-
gram must input the number of rows from the user and generate the pyramid accordingly. The
simplest code will use two for loops—one to print the numbers and one to print the spaces.
3. 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
60 C Programming & Data Structures
For example, if n is 3 and x is 5, then the program computes 1 + 5 + 25 + 125. Print x, n, and the
sum. Perform error checking. For example, the formula does not make sense for negative expo-
nents, 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.
Hint: The sum of geometric series is given by
(xn + 1 – 1)/(x – 1) for x > = 1
(– xn + 1)/(1 – x) for 0 < x < 1
4. 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.
Hint: See Appendix B for details on 1’s complement and 2’s complement.
Variation: An alternative method to obtain the 2’s complement is by first obtaining the 1’s
complement. The 1’s complement is arrived at by complementing all the digits of the binary
number (1’s complement of 11100 is 00011). The 2’s complement is obtained by adding 1 to the
1’s complement. Therefore, the 2’s complement of 11100 is given by 00011 + 1. Write a program
which calculates the 2’s complement of a given number through this method. Your program must
display the 1’s complement and the 2’s complement.
5. Write a C program to convert a Roman numeral to its decimal equivalent.
Hint: The various Roman numeral symbols and their decimal equivalents are as follows:
I = 1; V = 5; X = 10; L = 50; C = 100; D = 500; M = 1000
These numerals are written with a single over bar to indicate multiplication by 1000 and with a
double over-bar to indicate multiplication by a million. Therefore, V = 5000 and V = 5000000.
6. 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 numbers using structures.)
Hint: A complex number is of the form a + ib, where a is the real part and b is the imaginary part.
(a + ib) + (c + id) = (a + b) + i(c + d)
(a + ib) * (c + id) = (ac – bd) + i(ad + bc)
A complex number may be represented as
typedef struct{
int re; //real part
int im; //imaginary part
}complex;
void read_complex(&complex);
void print_complex(complex);
complex add_complex(complex,complex);
complex multiply_complex(complex,complex);
We can use the fseek() function to position the file pointer to the beginning of the text file, after
we have read n characters from it. Alternatively, the first character can be interchanged with the
nth, the second with the (n – 1)th, and so on, using the fseek() function directly. For details about
the functioning of fseek(), see Section 14.2.
3. Write a C program that uses functions to perform the following operations on singly linked list:
(i) Creation (ii) Insertion (iii) Deletion (iv) Traversal
Hint: See Chapter 16 for details on singly linked lists. Use a dummy node as described in Section
16.3 for an easier implementation.
Variation: Write a program to perform similar operations on a circularly linked list.
4. Write a C program that uses functions to perform the following operations on doubly linked list:
(i) Creation (ii) Insertion (iii) Deletion (iv) Traversal in both ways
Hint: See Section 16.3 for details on doubly linked lists.
Variation: Write a program to implement the above functions in a doubly circularly linked list.
5. Write C programs that implement stack operations using
(i) Arrays (ii) Pointers
Hint: A stack is a LIFO list. All insertion (push) and deletion (pop) is performed at one end of the
stack, called the top. The different implementations of stacks and the relevant operation functions
are detailed below:
(i) As an array
typedef struct{
int stack_elements[MAX_LEN]; //MAX_LEN is a predefined
macro
int tos; // top of stack
}stack,*stackptr;
stackptr createstack()
{/* The stack is dynamically created. All elements of the
stack are initialised to -9999 and tos is initialised to -1*/
stackptr sptr;
int i;
62 C Programming & Data Structures
sptr = (stackptr)malloc(sizeof(stack));
for(i=0;i<MAX_LEN;i++)
sptr->stack_elements[i] = -9999;
sptr->tos = -1;
return sptr;
}
int push(stackptr sptr,int n)
{//push an integer on to the stack
if(isfull(sptr)) {printf(Stack is full\n);return 0;}
(sptr->tos)++;
sptr->stack_elements[sptr->tos] = n;
return 1;
}
int pop(stackptr sptr, int* p)
{ //pops the top element from the stack and returns it in p
if(isempty(sptr)) {printf(Stack is empty\n);return 0;}
else *p = sptr->stack_elements[sptr->tos];
(sptr->tos);
return 1;
}
int isempty(stackptr sptr)
{ //returns true if stack is empty and false otherwise
if(sptr->tos==-1) return 1;
else return 0;
}
int isfull(stackptr sptr)
{ //returns true if stack is full and false otherwise
if(sptr->tos==MAX_LEN-1) return 1;
else return 0;
}
typedef struct{
int count; //keeps track of how many elements there are in the
stack
stacknodeptr top_of_stack; //points to the 1st el- ement in
the stack
}stack,*stackptr;
Let’s C:A Supplement to Computer Programming Lab 63
Sample function prototypes:
Note that the isfull() function is not required here. However, it can be implemented if the
programmer decides that the stack can only have a certain maximum number of elements. In
which case, isfull() will compare the value of count to that of the maximum number of stack
elements allowed.
6. Write C programs to implement queue operations using
(i) Arrays (ii) Pointers
Hint: A queue is a FIFO list. All insertion (enqueue) is performed at the rear and all deletion
(dequeue) is performed at the front. The different implementations of queues and the relevant
operation functions are detailed below:
(i) As an array
typedef struct{
int queue_elements[MAX_LEN]; //MAX_LEN is a predefined
macro
int front; // front of queue
int rear; //rear of queue
}queue,*queueptr;
queueptr createqueue()
{/* The queue is dynamically created. All elements of the queue are
initialised to -9999 and front and rear are initialised to -1*/
queueptr qptr;
int i;
qptr = (queueptr)malloc(sizeof(queue));
for(i=0;i<MAX_LEN;i++)
qptr->queue_elements[i] = -9999;
qptr->front = qptr->rear = 1;
return qptr;
}
Note that this implementation of isfull() is not entirely correct. The reason is that some elements
may have been dequeued at the front, while the rear pointer still remains at the last position in the
array. The queue might actually even be empty! Hence, even though the queue is not full, the
function will return true. Think about a way around this.
(ii) As a linked list
The queue node may be implemented as:
Traversal
Preorder traversal: Node Æ Left Child Æ Right Child
Inorder traversal: Left Child Æ Node Æ Right Child
Postorder traversal: Left Child Æ Right Child Æ Node
Sample implementation of inorder traversal
The preorder and postorder implementations are similar to the function given above.
1. Write C programs that use both recursive and non-recursive functions to perform the following
searching operations for a key value in a given list of integers : (i) Linear search (ii) Binary
search
Hint: Non-recursive methods for linear and binary search are discussed in Chapter 15. A recur-
sive function for binary search on a sorted array is given below:
{
mid=( index_begin + index_final)/2;
if (array[mid]==key)
return mid;
else if (key<array[mid])
return binary_recur(array, index_begin, mid-1,key);
else
return binary_recur(array, mid-1, index_final, key);
}
return -1;
}
2. Write C programs that implement the following sorting methods to sort a given list of integers in
ascending order:
(i) Bubble sort (ii) Quick sort
Hint: For bubble sort see Section 15.1 and for quick sort see Section 15.2.
3. Write C programs that implement the following sorting methods to sort a given list of integers in
ascending order:
(i) Insertion sort (ii) Merge sort
Hint: For insertion sort see Section 15.1 and for merge sort see Section 15.2.
( x − x1 ) ... ( x − x k −1 ) ( x − x k )... ( x − x n )
Qk (x) = for 1 £ k £ n
( x − x1 ) ... ( x k − x k −1 ) ( xk − x k ) ... ( x k − xn )
The Newton–Gregory forward interpolation is also called Newton’s forward difference formula
and is given as
Let’s C:A Supplement to Computer Programming Lab 67
α (α − 1)... (α − ( n − 2))
f(x1 + a h) ª f(x1) + a Df(x1) + … + Dn–1 f (x1)
( n − 1)!
2. Write C programs to implement the linear regression and polynomial regression algorithms.
Hint:
Linear Regression
We have a set of n data points. We need to determine the best-fit line for these points. The least
squares method is employed here to obtain the line. The least squares method is as follows—for a
set of n data points, the best fit line is determined by the following formulae:
Let the best fit line be
y = mx + c
m and c are given by
n
∑ ( xi − x ) ( yi − y )
i =1
m = n 2
∑ ( xi − x )
i =1
c = y − mx
A sample program using 20 data points follows:
U /*Bestfit line using least-squares method*/
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAX_POINTS 20
int main()
{
int K; / * loop counter * /
int N; / * INPUT: Number of points * /
d o u b l e M, C; / * Slope and Y-intersection * /
double X[MAX_POINTS]; / * x-coordinates of points * /
double Y[MAX_POINTS]; / * y-coordinates of points * /
double Xmean; / * Average value for x coord. * /
double Ymean; / * Average value for y coord. * /
double SumX; / * Sum of X coordinate values * /
double SumXY; / * Sum of product X*Y * /
printf(Enter number N of data points:);
scanf(%d,&N);
if(N > 20)
{
UAll programs bearing the U symbol in this supplement have been adapted from the C program supplement to John H.
Mathews 1992, Numerical Methods for Mathematics, Science, and Engineering, Prentice Hall, Englewood Cliffs,
New Jersey.
68 C Programming & Data Structures
Ymean = 0.0;
Ymean+ = Y[K-1];
Ymean = Ymean / N;
SumX = 0.0;
SumXY = 0.0;
printf( \n );
printf( Least-square line y = Mx + C\n);
Let’s C:A Supplement to Computer Programming Lab 69
printf( The coefficients are :\n);
printf( M = %lf and C = %lf .\n, M, C);
printf( \n );
return 0;
} /* End of main program */
Polynomial Regression
Any polynomial can be chosen to fit a set of data points. Data linearization is used to construct the
non-linear fit. The following program gives a choice of 10 polynomials to the user. The user can
use any of these polynomials to fit their set of data points. Depending on the user’s choice, the
program calculates the coefficients of the corresponding polynomial from the data set points.
#define MAX_POINTS 20
int main()
{
int K; /* loop counter * /
int N; /* INPUT: Number of points * /
double A, B; /* Slope and Y-intersection * /
double X[MAX_POINTS]; /* x-coordinates of points * /
double Y[MAX_POINTS]; /* y-coordinates of points * /
double Xmean; /* Average value for x coord. * /
double Ymean; /* Average value for y coord. * /
double SumX; /* Sum of X coordinate values * /
double SumXY; /* Sum of product X*Y * /
int ch; /* Case of nonlinear Regression
(users choice) */
double C, D, L; / * Coefficients in formulae * /
exit(0);
}
printf(The number of data points N = %d\n, N);
/* Select case */
case 4:
for(K = 1; K <= N; K++)
Let’s C:A Supplement to Computer Programming Lab 71
X[K-1] = 1.0 / X[K-1];
for(K = 1; K <= N; K++)
Y[K-1] = 1.0 / Y[K-1];
break;
case 5:
for(K = 1; K <= N; K++)
X[K-1] = log(X[K-1]);
break;
case 6:
for(K = 1; K <= N; K++)
Y[K-1] = log(Y[K-1]);
break;
case 7:
for(K = 1; K <= N; K++)
X[K-1] = log( X[K-1] );
for(K = 1; K <= N; K++)
Y[K-1] = log( Y[K-1] );
break;
case 8:
for(K = 1; K <= N; K++)
Y[K-1] = sqrt(Y[K-1]);
break;
case 9:
for(K = 1; K <= N; K++)
Y[K-1] = log( Y[K-1] / X[K-1] );
break;
case 10:
printf( Enter the value of the constant L: );
scanf(%lf, &L);
for(K = 1; K <= N; K++)
Y[K-1] = log(L / Y[K-1] - 1.0);
break;
}//end switch
Xmean = 0.0;
Ymean = 0.0;
SumX = 0.0;
/* Sum (x_k - Xmean) squared */
SumXY = 0.0;
switch(ch)
{
case 2:
C = -1.0 / A;
D = -B / A;
break;
case 6:
C = exp(B);
break;
case 7:
C = exp(B);
break;
case 9:
C = exp(B);
D = -A;
break;
case 10:
C = exp(B);
break;
}//end switch
/* Output */
case 2:
printf(y = %lf / [ x + %lf]\n, D, C);
break;
case 3:
printf(y = 1 / [ %lf * x + %lf ]\n, A, B);
break;
case 4:
printf(y = x / [ %lf + %lf * x ]\n, A, B);
break;
case 5:
printf(y = %lf * ln(x) + %lf\n, A, B);
break;
case 6:
printf(y = %lf * exp(%lf * x)\n, C, A);
break;
case 7:
printf(%lf * x^(%lf)\n, C, A);
break;
case 8:
printf(y = [ %lf * x + %lf ]^(2)\n, A, B);
break;
case 9:
printf(y = %lf * x * exp(- %lf * x)\n, C, D);
break;
case 10:
printf(y = %lf / [ 1 + %lf * exp(%lf * x)\n, L, C, A);
break;
}//end switch
} /* End of main program */
The trapezoidal rule for approximating an integral is as follows (for details consult any numerical
analysis textbook):
74 C Programming & Data Structures
N Q
where
b−a
h= (ii)
n
and
i = 0, 1, 2, ..., n (iii)
Therefore, the algorithm to evaluate an integral using this method is simple. The user defines the
function within the integral, and inputs the values of the lower bound, a, the upper bound, b, and
the number of sampling points, n. Using these the value of h is calculated. Evaluating the right
hand side of Eqn (i) is a simple exercise. Here is an example which evaluates the integral
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
printf( \n );
printf(Enter the boundaries of the integral [a,b]\n);
printf(Example: a = -1 and b = 1, so type: -1 1: );
scanf(%lf %lf,&a, &b);
printf(The boundaries of the integral are: %lf %lf\n,a, b);
printf( \n );
printf(Enter the number of subintervals: );
scanf(%d,&M);
printf(You said : %d subintervals.\n,n);
h = (b - a) / n; //Subinterval width
//This loop evaluates the 2nd term on RHS of equation (i) above for
Let’s C:A Supplement to Computer Programming Lab 75
( i = 1; i <= n-1; i++ )
{
x = a + h*i;
sum+ = func(x);
}
//The final approximate value of the integral using the Trapezoidal
Rule
sum = h * ( func(a) + func(b) + 2 * sum )/2;
printf( \n );
printf( The approximate value of the integral of func(x)\n);
printf( on the interval %lf %lf\n, a,b);
printf( using %d subintervals computed using the
trapezoidal\n,n);
printf( rule is : %lf\n,sum);
printf( \n );
return 0;
} // end main()
//sample definition of func
double func(double x)
{
return ( 1 / ( 1 + pow(x,2) ) ); }
Simpson’s Method
Simpson’s method is another numerical approximation technique for definite integrals. It con-
verges faster than the Trapezoidal method to the definite inte- gral represented by the approxima-
tion. However, in most cases the accuracy required is not more than a few decimal places. Hence
the two methods can be used interchangeably. Simpson’s method is as follows (Students interested
in details, such as rate of convergence and error in approximation, may con- sult any standard
textbook on numerical methods):
LM OP
za
b
f ( x ) dx =
h
3 N
n −1
i =1
n
( f (a ) + f (b)) + 2 ∑ f ( x2 i ) + 4 ∑ f ( x2 i ) − 1 (i)
i =1 Q
where
b−a
h= (ii)
2n
and
i = 0, 1, 2, …, n (iii)
As in the case of the Trapezoidal method, the evaluation of the integral is simple. Only two
summations have to be calculated. The following program uses Simpson’s method to evaluate a
definite integral. The example integral taken is:
za 1 +1x 2 dx
b
76 C Programming & Data Structures
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
int i; // loop counter
int n; // INPUT : number of subintervals
double a,b; // INPUT : boundaries of integral
double h; // Subinterval width
double SumEven = 0; // approx. Even integral
double SumOdd = 0; // approx. Odd integral
double sum = 0; //approx. integral value
double x;
printf( \n );
printf(Enter the boundaries of the integral [a,b]\n);
printf(EXAMPLE: A = -1 and B = 1, so type: -1 1\n);
scanf(%lf %lf,&a, &b);
printf(The boundaries of the integral are: %lf %lf\n,a, b);
printf( \n );
printf(Enter the number of SUBINTERVALS:);
scanf(%d,&n);
printf( \n );
printf( The approximate value of the integral of f(x)\n);
printf( on the interval %lf %lf\n, a,b);
printf( using %d subintervals computed using the Simpsons\n,2*n);
printf( Method is : %lf\n,sum);
Let’s C:A Supplement to Computer Programming Lab 77
printf( \n );
}// main
//definition of integrand
double func(double x)
{
return ( 1 / ( 1 + pow(x,2) ) );
}