INDEX
Ex-No Name of the Program
Page
1
Sum of individual digits of a positive integer
1
2
Fibonacci Sequence
2
3
Prime numbers between 1 and n
4
4
Sum = 1 - x
2/2! + x
4/4! - x
6/6! + x
8/8! - x
10/10! 5
5
Roots of a quadratic equation
6
6
Factorial of a given integer (recursive and non-recursive functions)
8
7
GCD of two given integers (recursive and non-recursive functions)
9
8
Towers of Hanoi problem (recursive and non-recursive functions)
11
9
distance = ut+1/2at
214
10
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).
15
11
The largest and smallest number in a list of integers
17
12
Insert an element into the array, and delete an item from the array.
18
13
A C program that uses functions to perform the following:
(i) Addition of Two Matrices
(ii) Multiplication of Two Matrices
20
14
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.
21
15
Test whether the given string is a palindrome or not.
24
16
Index in the string S where the string T begins, or – 1 if S doesn’t contain T.
24
17
Count the lines, words and characters in a given text.
26
18
Generate Pascal’s triangle.
26
19
Construct a pyramid of numbers.
27
20
Input an integer and display it in words. Example:
Input: 2075 Output: two zero seven five
28
21
Compute the sum of this geometric progression:
1 + x + x
2+ x
3+……+ x
n29
22
Bitwise operators
31
23
Convert a decimal number into its equivalent binary, octal, and hexadecimal
numbers.
24
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.
34
25
Convert a Roman numeral to its decimal equivalent.
35
26
Write a C program that uses functions to perform the following operations:
(Note: represent complex number using a structure.)(a) Reading a complex number
(b) Writing a complex number
(c) Addition of two complex numbers
(d) Multiplication of two complex numbers
36
27
Application of array of structures.
38
28
Write a C program which copies one file to another.
40
29
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.)
41
30
Write a C program that uses functions to perform the following operations on
singly linked list:
(a) Creation (b) Insertion (c) Deletion (d) Traversal
42
31
Write a C program that uses functions to perform the following operations on
doubly linked list:
(a) Creation (b) Insertion (c) Deletion (d) Traversal in both ways
46
32
Write C programs that implement Stack (its operations) using
(a) Arrays (b) Pointers
50
33
Write C programs that implement Queue (its operations) using
(a) Arrays (b) Pointers
53
34
Write a C program that uses Stack operations to perform the following:
(a) Converting infix expression into postfix expression
(b) Evaluating the postfix expression
57
35
Write a C program that uses functions to perform the following:
(a) Creating a Binary Tree of integers
(b) Traversing the above binary tree in preorder, inorder and
postorder.
61
36
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:
(a) Linear search (b) Binary search
63
37
Bubble sort
66
38
Insertion sort
67
39
Quick sort
68
Sum of the digits of a number
1. Sum of the digits of an integer number.
We need to access individual digits of the number. The number 275 is a decimal number
which we can write as
2
x10
2+ 7
x10
1+ 5
x10
0It is probably easy to access individual digits. The question is at which end should we start? It
will be best to separate the least significant digit (i.e., the rightmost digit). To do this, we
need to cut off the least significant digit in the number. In other words, we want to end up
with 27 with the 5 removed and identified.
We apply the following three steps (Let the number be stored in n and remainder in d). We
initialize the sum to zero. Let n = 275.
d = n mod 10
(1)
Æ
d = 5
sum = sum + d
(2)
Æ
sum = 5
n = n / 10
(3)
Æ
n = 27
These three steps will be carried out until n becomes zero.
sumOfDigits sum = 0 n ≠ 0 d = n mod 10 n = n / 10 Yes No Print sum Read nProgram 1: Sum of the digits of a number
#include <stdio.h> void main(void) { int n, m, d, sum ; sum = 0; printf("\nEnter n = ");// read n
scanf("%d", &n); m = n;// save n in m
while( n != 0 ) { d = n % 10; sum = sum + d; n = n / 10; }printf("Sum of the digits of %d is %d", m, sum); }
Output:
Enter n = 275
Sum of the digits of 275 is 14
Fibonacci sequence
2. Generate and print the first n terms of Fibonacci sequence where n ≥ 1
.
The first few terms are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . .
The first two terms are 0 and 1. Each one of the terms is generated by the sum of two
previous terms.
a: the term before the preceding term
b: the preceding term
c: new term
Then to start with we have: a = 0
first Fibonacci number
b = 1
second Fibonacci number
Fibonacci
a = 0
b = 1
Trace of Fibonacci algorithm
for n = 10
i a b c
2 0 1
3 0 1 1
4 1 1 2
5 1 2 3
6 2 3 5
7 3 5 8
8 5 8 13
9 8 13 21
10 13 21 34
i = 2 print a, b read n No i < nProgram 2: Fibonacci sequence
#include <stdio.h> void main(void) { int i,n, a, b, c; a = 0; b = 1; i = 2; printf("\nEnter n = "); scanf("%d", &n); printf("%d %d", a, b); while( i < n ) { i = i + 1; c = a + b; printf(" %d", c); a = b; i = i + 1 c = a + b a = b b = c print c Yes stop
b = c; } }
Output:
Enter n = 10 0 1 1 2 3 5 8 13 21 34Prime numbers
3. Prime numbers between 1 and n.
A prime number is a positive integer that is exactly divisible only by 1 and itself. The first few
prime numbers are:
2 3 5 7 11 13 17 23 29 31 37 …
All primes apart from 2 are odd.
As a starting point in developing the prime number generator let us explore how we can
establish whether or not a particular number is a prime. To do this, let us consider a number
13. The definition of prime number suggests that to determine whether or not 13 is prime, we
need to divide it in turn by the set of numbers 2, 3, 4, 5 …12. If any of these numbers divide
into 13 without remainder we will know it cannot be prime number. Therefore, to test an
integer n for prime, n-2 calls to the mod operation are required. As our n is 13, we need 11
calls. As n grows, the cost of making these divisions and tests is going to get very expensive.
We must therefore look for ways of improving the efficiency of the algorithm. Firstly, we can
try to keep to a minimum the number of numbers that we have to test for primes, and
secondly we can try to improve the efficiency of testing a number for prime.
Following up these suggestions, we know that apart from 2, we do not need to examine
any of the even numbers, and only first half of the numbers is enough for testing prime. That
is, we can test for mod operation with numbers, from 3 to n/2. Hence, the following set of
numbers is sufficient to test 13 for prime.
3 4 5
6
Program 3: Prime numbers (from 1 to n)
#include <stdio.h> #define TRUE 1 #define FALSE 0 void main(void) { int n, k, m, isPrime;printf("Prime numbers, Enter n = "); scanf("%d", &n);
printf("2 3 "); // first 2 prime numbers for( m=3; m <= n; m = m+2 )
isPrime = FALSE; for(k=2; k <= m/2; k++) { if(m % k == 0) { isPrime = FALSE; break; }
else isPrime = TRUE;
}
if(isPrime)
printf("%d ", m);
} }
Output of this program is:
Prime numbers, Enter n = 100
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
Summation of series
4. Sum = 1 - x
2/2! + x
4/4! - x
6/6! + x
8/8! - x
10/10!
Studying the series, we see that powers and factorials follow the sequence
2, 4, 6, 8, . . .
We can easily generate this even sequence by starting with 0 and successively adding 2. We
can compute the general term as
x
i/i! = x/1
xx/2
xx/3 . . .
xx/i
for i
≥ 1
To explore this term, we examine the overlap for some specific terms of the series. For
example,
x
2/2! = (x
xx )/(2
x1)
= [x
2/(2
x1)](1)
i = 2
x
4/4! = (x
xx
xx
xx )/(4
x3
x2
x1)
= [x
2/(4
x3)]( x
2/2!)
i = 4
x
6/6! = (x
xx
xx
xx
xx
xx)/(6
x5
x4
x3
x2
x1) = [x
2/(6
x5)]( x
4/4!)
i = 6
Each of these terms can be described by the general term: [x
2/(i(i-1))] for i = 2, 4, 6, . . .
Therefore to generate consecutive terms of the series we can use
Current
i
thterm = x
2/(i(i-1))
x(previous term)
We can incorporate this directly into our term expression with the following initial
conditions:
sum = 1; term = 1;
i = 0;
We can generate i
thterm and summation iteratively from their previous terms.
i = i + 2;
term = –term
xx
xx / (i
x(i-1));
sum = sum + term;
Program 4: Sum the series: 1 - x
2/2! + x
4/4! - x
6/6! + x
8/8! - x
10/10!
#include <stdio.h>void main(void) {
int i=0;
float x = 2.0, term = 1.0, sum = 1.0;
for( int j = 0; j < 5; j++ )
// sum of 6 terms (including 1)
{i = i + 2;
term = -term *x*x / ( i*(i-1)); sum = sum + term;
}
printf("\n sum = %f", sum); }
Output of this program is:
sum = -0.416155
Quadratic equation
5. Roots of a quadratic equation ax
2+ bx + c = 0.
The roots of the quadratic equation, ax
2+ bx + c = 0 are given by:
x = [–b ± √(b
2– 4ac) ]/2a
The discriminant, d = (b
2– 4ac)
Case (1): When d is greater than zero, the two roots are real.
x1 = (–b + √d )/2a and
x2 = (–b – √d )/2a
Case (2): When d is equal to zero, the two roots are equal.
Case (3): When d is less than zero, the two roots are imaginary. Each of the two roots has
two parts: real-part-1, imaginary-part-1 and real-part-2, imaginary-part-2.
real-part-1, xr1 = –b/2a
imaginary-part-1, xi1 = +√d /2a
real-part-2,
xr2 = –b/2a
imaginary-part-2, xi2 = –√d /2a
Program 5: Roots of a quadratic equation
#include <stdio.h> #include <math.h> void main(void) { float a, b, c; // coefficients double d; // discriminantfloat x1, x2, xr1, xi1, xr2, xi2; // roots printf("Enter coefficients: a, b, c: " ); scanf("%f %f %f", &a, &b, &c);
if( a == 0.0 )
{ printf("One root = %8.2f", (-c/b)); return;
}
d = b*b - 4.0*a*c;
if(d > 0) // Roots are real
{
printf("Roots are real: "); x1 = (-b + sqrt(d))/(2.0*a); x2 = (-b - sqrt(d))/(2.0*a); printf("%8.2f %8.2f", x1, x2); return;
}
if(d == 0) // Roots are equal
{
printf("Two roots are equal: %8.2f ", -b/(2.0*a) ); return;
}
if(d < 0) // Roots are imaginary {
printf("Roots are imaginary:");
xr1 = -b/(2*a);
xi1 = sqrt(-d)/(2*a);
xr2 = xr1;
xi2 = -xi1;
printf("\nreal part-1=%8.2f, imag part-1=%8.2f", xr1, xi1); printf("\nreal part-2=%8.2f, imag part-2=%8.2f", xr2, xi2); return; } }
Output:
Enter coefficients: a, b, c: 0 2 4 One root = -2.00Enter coefficients: a, b, c: 1 2 4 Roots are imaginary:
real part-1= -1.00, imag part-1= 1.73 real part-2= -1.00, imag part-2= -1.73 Enter coefficients: a, b, c: 1 2 1
Two roots are equal: -1.00 Enter coefficients: a, b, c: 1 4 2 Roots are real: -0.59 -3.41
Factorial
6. Factorial: Given a number n, compute the n factorial (written as n!) where n ≥ 0.
We can start the development of this algorithm by examining the definition of n!. We are
given that
n! = 1
x2
x3
x. . . (n-1)
xn
for n ≥ 1
and by definition 0! = 1.
We can generalize that n! can always be obtained from (n-1)! By simply multiplying it by n,
(for n ≥ 1). That is,
n! = n
x(n-1)! for
n ≥ 1
factorial( )n
f = 1, i = 0
No
i < n
Flowchart for factorial algorithm
i = i + 1 Yes
return
f = f
*
iProgram 6: Factorial of a number
#include <stdio.h>
long factorial( int n)
// non-recursive function
{
int i = 0;
long f = 1;
while( i < n )
{
i++;
f = f * i;
}
return
f;
}
long recFactorial( int n) // recursive function
{
if( n == 0 )
return
1;
else
return
n*recFactorial(n-1);
}
void main(void)
{
int
n;
printf("Enter n = ");
scanf("%d",
&n);
printf("\nFactorial of %d is %ld", n, factorial(n));
printf("\nFactorial of %d is %ld by recursive function",
n,
recFactorial(n));
}
Output of this program is:
Enter n = 6
Factorial of 6 is 720
Factorial of 6 is 720 by recursive function
Greatest Common Divisor
7. Greatest common divisor: Given two non-zero integers m and n, design an
algorithm for finding their greatest common divisor (gcd).
The gcd of two integers m and n is the largest integer d that divides both m and n evenly. Let
r be the remainder of m divided by n. If r is 0, then n is the gcd. Otherwise, set m equal to n,
then n equal to r, and repeat the process. The gcd() algorithm is as follows:
gcd(m, n)
The two integers, m and n are given.
1. r = m
mod
n
[get
remainder
from
dividing
m by n]
2. Repeat steps 3 to 5, while r ≠ 0 [continue until zero remainder is obtained]
3.
m = n
[smaller integer assumes the role of larger integer]
4.
n = r
[remainder
takes
the
role
of
the
divisor]
5.
r = m
mod
n
[get remainder from dividing larger integer by smaller]
[end of while-loop]
6. gcd = n
7.
Return(gcd)
Program 7: Greatest Common Divisor
#include <stdio.h>int gcd(int m, int n)
// non-recursive function
{ int r = m % n; while( r != 0 ) { m = n; n = r; r = m % n; } return(n); }
int recGcd(int m, int n)
// recursive function
{ if( n == 0 ) return m; else return gcd(n, m % n); } void main(void) { int m, n; printf("Enter m ,n: "); scanf("%d %d", &m, &n);
printf("\n gcd(%d, %d) is %d", m ,n, gcd(m,n)); printf("\n gcd(%d, %d) is %d by recursive function",
m ,n, gcd(m,n));
}
Output of this program is:
Enter m ,n: 36 63 gcd(36, 63) is 9Towers of Hanoi
8. Towers of Hanoi problem
Towers of Hanoi is a puzzle that was popular near the end of the 19th century. The puzzle
consists of a board with three pegs and a series of disks of increasing diameter. The disks are
stacked on one peg so that each disk rests on a larger one. The puzzle is how to transfer all
the disks from one peg to another by means of a sequence of individual moves, subject to the
restriction that no disk is placed upon a smaller disk. The layout of this game is shown in the
following figure.
5 4 3 2 1 A B CThe puzzle is defined in terms of n disks (n > 0). We label the three pegs A, B, and C,
and number the disks from smaller to largest 1, 2, 3, …, n.
In the simplest and nontrivial case, with n = 3 disks, it is easy to see that the solution to
the puzzle is the following sequence of seven moves:
1. A → B
2. A → C
3. B → C
4. A → B
5. C → A
6. C → B
7. A → B
These moves are illustrated in the following figure:
1
3 2
A B C
1 3 2 A B C
2. A
→ C
1 3 A B C3. B
→ C
2 3 A B C4. A
→ B
1 2 3 A B 1 2 C5. C → A
3 A B 1 2 C6. C
→ B
A B 1 3 C7. A
→ B
2The solution to the Towers of Hanoi puzzle is naturally recursive. Consider the case of 4
disks. Since we have already solved the problem for 3 disks, we know what moves to make to
move top 3 disks from peg A to peg B. Therefore, these are the first 7 moves for the case of 4
disks. The complete solution is:
1. Move the top 3 disks from A to B.
2. Move the remaining disk from A to C.
3. Move the top 3 disks from B to C.
Step 1 and step 3 each require 7 individual moves, so the total is really 15 moves. The
recursive solution is implemented in the following program.
Note that one disk takes 1 move, two disks take 3 moves, and three disks take 7 moves.
In general, this recursive solution requires 2
n-1 moves for n disks.
The solution to the Towers of Hanoi illustrates the power and simplicity of recursion. To
move n disks from A to B, move all but the last disk from A to C; then move the last disk
from A to B; then move all the other disks from C to B.
Program 8: Towers of Hanoi
#include <stdio.h>void print(int n, char x, char y, char z) {
static int i; if( n == 1 )
printf("\n %3d. %c -> %c", ++i, x, y); else
{ print(n-1, x, z, y);
printf("\n %3d. %c -> %c", ++i, x, y); print(n-1, z, y, x); } } void main() { int nDisks;
printf("\n Towers of Hanoi "); printf("\n Number of disks: "); scanf("%d", &nDisks); print(nDisks, 'A', 'B', 'C'); }
Output:
Towers of Hanoi Number of disks: 3 1. A -> B 2. A -> C 3. B -> C 4. A -> B 5. C -> A 6. C -> B
7. A -> B
d = ut+1/2at
2
9. Total distance traveled by a 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/sec
2). 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’.
Program 9: distance = ut+1/2at
2#include <stdio.h>
void main() {
float d, // distance traveled in meters (m)
u, // initial velocity in m/sec
a, // acceleration in m/sec/sec
t, // time in seconds
dt; // time interval in seconds
int i, j; u = 0.00; a = 4.00; t = 10.00; dt = 10.00; printf("\n---"); printf("\n u a d t"); printf("\n---"); for( i = 1; i <= 5; i++ ) { for( j = 1; j <= 10; j++ ) { d = u * t + 0.5 * a * t * t; printf("\n%12.2f %12.2f %12.2f %12.2f", u, a, d, t); t = t + dt; } u = u + 5.00; a = a + 2.00; } }
Output:
--- u a d t --- 0.00 4.00 200.00 10.00 0.00 4.00 800.00 20.00 0.00 4.00 1800.00 30.00 0.00 4.00 3200.00 40.00 0.00 4.00 5000.00 50.00 0.00 4.00 7200.00 60.00 0.00 4.00 9800.00 70.00 0.00 4.00 12800.00 80.00 0.00 4.00 16200.00 90.00 0.00 4.00 20000.00 100.00 5.00 6.00 36850.00 110.00 5.00 6.00 43800.00 120.00 5.00 6.00 51350.00 130.005.00 6.00 59500.00 140.00 5.00 6.00 68250.00 150.00 5.00 6.00 77600.00 160.00 5.00 6.00 87550.00 170.00 5.00 6.00 98100.00 180.00 5.00 6.00 109250.00 190.00 5.00 6.00 121000.00 200.00 10.00 8.00 178500.00 210.00 10.00 8.00 195800.00 220.00 10.00 8.00 213900.00 230.00 10.00 8.00 232800.00 240.00 10.00 8.00 252500.00 250.00 10.00 8.00 273000.00 260.00 10.00 8.00 294300.00 270.00 10.00 8.00 316400.00 280.00 10.00 8.00 339300.00 290.00 10.00 8.00 363000.00 300.00 15.00 10.00 485150.00 310.00 15.00 10.00 516800.00 320.00 15.00 10.00 549450.00 330.00 15.00 10.00 583100.00 340.00 15.00 10.00 617750.00 350.00 15.00 10.00 653400.00 360.00 15.00 10.00 690050.00 370.00 15.00 10.00 727700.00 380.00 15.00 10.00 766350.00 390.00 15.00 10.00 806000.00 400.00 20.00 12.00 1016800.00 410.00 20.00 12.00 1066800.00 420.00 20.00 12.00 1118000.00 430.00 20.00 12.00 1170400.00 440.00 20.00 12.00 1224000.00 450.00 20.00 12.00 1278800.00 460.00 20.00 12.00 1334800.00 470.00 20.00 12.00 1392000.00 480.00 20.00 12.00 1450400.00 490.00 20.00 12.00 1510000.00 500.00
Calculator
10. Write a C program, which takes two integer operands and one operator form the
user, performs the operation and then prints the result. (Consider the operators +,
-, *-, /-, % and use switch statement)
Program 10: Calculator
#include <stdio.h> void main(void) {int a, b;
// operands
char opr;
// operator
char prompt = 'Y';
int getResult(int, char, int);
// function prototype
while( 1 ) {
printf("\nEnter operand-1 operator operand-2 \n"); scanf("%d %c %d", &a, &opr, &b);
printf(" = %d \n", getResult(a,opr, b)); fflush(stdin);
printf("\n Continue (Y/N): "); scanf("%c", &prompt);
if( prompt == 'N' || prompt == 'n' ) break; }
printf("\n *** program end *** "); }
int getResult( int a, char op, int b ) { switch( op ) { case '+' : return (a + b); case '-' : return (a - b); case '*' : return (a * b); case '/' : if( b == 0 ) { printf("Division-by-zero"); return 0; } else return ( a / b ); case '%' : return (a % b);
default: printf("Incorrect operator - result is void"); return 0; }
}
Output of this program is as follows:
Enter 'N' to end the program. Enter operand-1 operator operand-2 12 * 10
= 120
Continue (Y/N): Y
Enter operand-1 operator operand-2 150 - 200
= -50
Continue (Y/N): y
Enter operand-1 operator operand-2 25 + 45
= 70
Continue (Y/N): y
Enter operand-1 operator operand-2 50 / 5
= 10
Continue (Y/N): y
Enter operand-1 operator operand-2 25 / 0
Division-by-zero = 0 Continue (Y/N): y
Enter operand-1 operator operand-2 95 % 8
= 7
Continue (Y/N): y
Enter operand-1 operator operand-2 45 & 10
Incorrect operator - result is void = 0 Continue (Y/N): N
*** program end ***
Max and Min in a list
11. The largest and smallest numbers in a list of integers.
MaxMin a : array of integers n: array size i = 1 read a, n min = a[o] max = a[o]
Flowchart to find the maximum and minimum of a given list
i < nNo
print min, max
stop Yes i = i + 1 a[i] < min min = a[i] a[i] >max max = a[i] No Yes No Yes
Program 11: Max and min in a list of integers
#include <stdio.h> void main(void) { int a[10] = { 77, 95, 33, 22, 55, 99, 11, 66, 88, 44 }; int i, n = 10;int max, min;
max = a[0];
// set max to first array element
min = a[0];// set min to first array element
for( i = 1; i < n; i++ ){
if( a[i] > max )
// if current element > max,
max = a[i]; // set max = current element
if( a[i] < min )
// if current element < min,
min = a[i]; // set min = current element
}
printf("max = %d \nmin = %d", max, min);
}
Output:
max = 99 min = 11
Insertion & Deletion - Arrays
Program 12: Insertion of an item into and deletion of an item from the array
#include <stdio.h>void create( int a[], int n ) {
for( int i = 0; i < n; i++ ) {
printf( "a[%d] = ", i ); scanf( "%d", &a[i] ); }
}
void display( int a[], int n ) {
for( int i = 0; i < n; i++ ) printf( "%5d", a[i] ); }
void insert( int a[], int n, int item, int pos ) {
for( int i = n; i >= pos; i-- )
a[i] = a[i-1];
}
int delet( int a[], int n, int item ) {
int i, pos, found = 0; for( i = 0; i < n; i++ )
if( a[i] == item )
{ pos = i;
found = 1;
}
if( found ) {
for( i = pos; i < n; i++ )
a[i] = a[i+1];
} else
printf("\n %d not found - deletion is void.", item);
return found;
}
void main() {
int arr[10];
int n = 6; // array size
create( arr, n );
printf("\n Original array:" ); display( arr, n );
insert( arr, n, 40, 3 ); // insert 40 at position 3
n++; // increment array size by 1
printf("\n Array after insertion of 40:" ); display( arr, n );
int flag = delet( arr, n, 30 ); // delete 30 if( flag )
{ n--; // decrement array size by 1
printf("\n Array after deletion of 33:" ); display( arr, n );
}
flag = delet( arr, n, 33 ); // delete 33 if( flag )
{ n--; // decrement array size by 1
printf("\n Array after deletion of 33:" ); display( arr, n ); } }
Output:
a[0] = 11 a[1] = 22 a[2] = 33 a[3] = 44 a[4] = 55 a[5] = 66Original array: 11 22 33 44 55 66
Array after insertion of 40: 11 22 33 40 44 55 66 30 not found - deletion is void.
Array after deletion of 33: 11 22 40 44 55 66
Matrix operations
13. A C program that uses functions to perform the following:
(a) Addition of two matrices
(b) Multiplication of two matrices
Add two matrices to get the third one. The three matrices must be of the same order. Program
12(a) adds two matrices
a
and
b
, element by element to obtain the matrix
c
.
Program 13(a): Addition of two matrices
#include <stdio.h> void main(void) { int a[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int b[3][4] = {{5, 10, 15, 20},{25, 30, 35, 40}, {45, 50, 55, 60 }}; int c[3][4], i, j;void printMatrix(int[][4], int, int); for( i = 0; i < 3; i++ )
for( j = 0; j < 4; j++ )
c[i][j] = a[i][j] + b[i][j]; printf("\nMatrix a:"); printMatrix(a, 3, 4); printf("\nMatrix b:"); printMatrix(b, 3, 4); printf("\nMatrix c:"); printMatrix(c, 3, 4); }
void printMatrix(int mat[][4], int m, int n) { int i, j; for( i = 0; i < m; i++ ) { printf("\n"); for( j = 0; j < n; j++ ) printf("%5d",mat[i][j]); } }
Matrix a: 1 2 3 4 5 6 7 8 9 10 11 12 Matrix b: 5 10 15 20 25 30 35 40 45 50 55 60 Matrix c: 6 12 18 24 30 36 42 48 54 60 66 72
Program 13(b): Multiplication of two matrices
/* Multiplication of two matrices: C = A x B */
#include <stdio.h> void main() { int a[3][3] = { {3, 2, 0}, {1, 5, 1}, {2, 3, 4} }; int b[3][4] = { {2, 0, 1, 1}, {1, 3, 0, 3}, {2, 2, 2, 1} }; int c[3][4]; int i, j, k;/* No . of columns of a = No. of rows of b (here it is 3) Order of matrix c is 3 x 4 */
for ( i = 0; i < 3; i++ )/* Matrix multiplication: c = a x b */
for ( j = 0; j < 4; j++ )
{ c[i][j] = 0;
for ( k = 0; k < 3; k++ )
c[i][j] = c[i][j] + a[i][k] * b[k][j]; }
printf("\n matrix C (3 x 4)= A x B:");
/* Print matrix C */
for ( i = 0; i < 3; i++ ) { printf("\n"); for ( j = 0; j < 4; j++ ) printf("%4d", c[i][j]); } }Output:
matrix C (3 x 4)= A x B: 8 6 3 9 9 17 3 17 15 17 10 15String operations
14. A C program that uses functions to perform the following operations:
(a) To insert a sub-string into a given main string from a given position.
(b) To delete n Characters from a given position in a given string.
string
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 M I S S I P P I ‘0\’substring
0 1 2 3 4 5 6 7 8 9 S S I ‘0\’Insert substring into string from 5th position:
(a)
Copy
string from 5
thposition to string tmp.
string
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 M I S S I P P I ‘0\’ 0 1 2 3 4 5 6 7 8 9 P P I ‘0\’tmp
(b) Copy substring to string from 5
thposition of the string.
string
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 M I S S I S S I ‘0\’ 0 1 2 3 4 5 6 7 8 9 S S I ‘0\’substring
(c) Copy tmp to string.
string
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 M I S S I S S I P P I ‘0\’ 0 1 2 3 4 5 6 7 8 9 P P I ‘0\’tmp
Program 14: Insertion of a substring into a string and deletion of ‘n’ chars from the string
#include <stdio.h>void insert( char s[], char ss[], int pos) {
int i, j;
char tmp[10];
j = 0;
for( i = pos; s[i] != NULL; i++ )
tmp[j++] = s[i];
tmp[j] = NULL;
for( i = 0; ss[i] != NULL; i++ )
s[pos++] = ss[i];
for( i = 0; tmp[i] != NULL; i++ )
s[pos++] = tmp[i];
s[pos] = NULL; }
void delet( char s[], int pos, int count) {
int i, j;
for( i = pos, j = pos+count; s[j] != NULL; i++, j++)
s[i] = s[j]; s[i] = NULL; } void main() { char str[20] = "MISSIPPI"; char substr[10] = "SSI";
printf("String and substring before insertion:\n"); printf("String: ");
puts(str);
printf("Substring: "); puts(substr);
insert(str, substr, 5); // insert "SSI" from 5th position printf("String after insertion: ");
puts(str);
delet(str, 2, 6); // delete 6 chars from 2nd position printf("String after deletion: ");
puts(str);
}
Output of this program is
:String and substring before insertion: String: MISSIPPI
Substring: SSI
String after insertion: MISSISSIPPI String after deletion: MIPPI
Palindrome
15. Test whether the given string is a palindrome or not.
Program 15: Palindrome
#include <stdio.h> #include <string.h> int isPalindrome(char str[]) { int n = strlen(str); int flag = 1;for( int i=0; i < n/2; i++ ) if( str[i] != str[n-i-1] ) { flag = 0; break; } return flag; } void main() { char str[] = "MALAYALAM"; if( isPalindrome(str) ) printf("%s is a palindrome\n", str); else
printf("%s is not a palindrome\n", str);
strcpy(str, "MISSING");
if( isPalindrome(str) )
printf("%s is a palindrome\n", str); else
printf("%s is not a palindrome\n", str);; }
Output:
MALAYALAM is a palindrome MISSING is not a palindrome
String matching
16. Index in the string S where the string T begins, or -1 if S does not contain T.
A simple method to string matching is starting the comparison of T (substring) and S (text
string) from the first character of S and the first character of T. If there is a mismatch, the
comparison starts from the second character of S, and so on.
S S I P 0 1 2 3 Index, j T M I S S I S S I P P I Index, i 0 1 2 3 4 5 6 7 8 9 10 S S S I P
(1) i = 0 and j = 0 mismatch
S S I P(2) i = 1 and j = 0 mismatch
S S I P(3) i = 2, 3, 4 and j = 0, 1, 2 match
i = 5 and j = 3
mismatch
S S I P(4) i = 3 and j = 0 match
i = 4 and j = 1
mismatch
S S I P(5) i = 4 and j = 0 mismatch
S S I P(6) i = 5, 6, 7, 8 and
j = 0, 1, 2, 3
match
Trace of the string matching algorithm
Program 16: String matching
#include <stdio.h> #include <string.h>
int contains( char str[], char ss[]) {
int i, j;
int n = strlen(str);
// length of string, str
int m = strlen(ss);// length of substring, ss
i = 0; while( i <= n-m ) { j = 0; while( str[i] == ss[j] ) {i++; // try to match all chars in ss
j++;
if( j == m ) return i-m; } i = i - j + 1; } return -1; } void main() {
char S[] = "MISSISSIPPI"; // string S
char T[] = "SSIP"; // substring T
int index = contains(S, T); printf("index = %d", index);
}
Output:
Counting lines, words, and chars in a text
17. Count number of lines, words, and characters in a given text.
Program 17: Count number of lines, words, and characters in a given text.
#include <stdio.h>void main()
{ char ch, text[81], space = ' ';
int i, nchars = 0, nwords = 0, nlines = 0; while(1) { i = 0; while( (ch = getchar()) != '\n') { text[i] = ch; nchars++;
if( ch == space ) nwords++; i++;
}
nlines++; nwords++;
text[i] = '\0';
if( text[0] == '\0' ) break; }
nlines--; nwords--;
printf("\n No. of chars = %d", nchars); printf("\n No. of words = %d", nwords); printf("\n No. of lines = %d", nlines);
}
Output:
Strings are used to store text data.
Strings are useful in many programming applications. A string is an array of characters.
The end of the string is marked with a null character.
No. of chars = 177 No. of words = 32 No. of lines = 4
Pascal’s triangle
18. Generate a Pascal’s triangle.
Pascal’s triangle of size
n
xn
is defined as follows:
First
column
(
j = 0
), last row (
i = n-1
), and diagonal elements (
i = j
) are
1
’s.
P
ij= 1
for
i = j
,
i = n-1
, or
j = 0
Other elements of the triangle are generated by the following formula:
P
ij= P
i-1, j-1+ P
i-1, jfor i > 0 and j > 0,
Pascal's Triangle ( n = 10 ):
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 1 1 1 1 1 1 1 1 1
Program 18: Pascal’s triangle
#include <stdio.h> #define N 25void Pascal( int p[][N], int n ) { int i, j; for ( i = 0; i < n; i++ ) for ( j = 0; j <= i; j++ ) if( j == 0 || i == n-1 || i == j ) p[i][j] = 1; else
p[i][j] = p[i-1][j-1] + p[i-1][j];
}
void main() {
static int p[N][N]; int i, j, n;
printf("\n Pascal's Triangle, size, n = "); scanf("%d", &n);
Pascal(p, n);
printf("\n Pascal's Triangle:"); for ( i = 0; i < n; i++ ) { printf("\n\n"); for ( j = 0; j <= i; j++ ) printf("%5d", p[i][j]); } }
Pyramid of numbers
Program 19: Pyramid of numbers
#include <stdio.h> void main() { int i, j, k, p, n=10; p = n; for( i = 0; i < n; i++ ) { printf("\n"); for(k=0; k<p; k++) printf(" "); p--; for( j = 0; j < i; j++ ) printf("%4d", i); } }Output for n = 10:
2 2 1 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9Number to words
20. Display a number in words.
For example, the number 2075 is printed as:
two zero seven five.
Store the individual digits of a number,
n
in an array,
d[i]
for
i
=
0
to
nd-1.
where
nd
indicates number of digits or array size. Then convert the digit to word,
using switch statement in the reverse order and print the word. For
n = 2075
, the
following figure illustrates the procedure.
(1) Individual digits are stored in
d[i]
; least significant digit,
5
is stored in
d[0]
, next
7
in
d[1]
, and so on.
d[0]
d[1]
d[2]
d[3]
5 7 0 2
(2) Print the word of the digit in reverse order, using the for-loop:
for( i = nd-1; i >= 0; i-- )Program 20: Number to words
#include <stdio.h>void numberToWords(int n) {
int nd;
// number of digits
int d[5];
// array to store individual digits
int i;
nd = 0;
while( n != 0 )
// separate and store individual digits in array, d[i]
{d[nd++] = n % 10; n = n / 10; }
for( i = nd-1; i >= 0; i-- )
// print the digits in words
{switch( d[i] )
{
case 0: printf("zero "); break; case 1: printf("one "); break; case 2: printf("two "); break; case 3: printf("three "); break; case 4: printf("four "); break; case 5: printf("five "); break; case 6: printf("six "); break; case 7: printf("seven "); break; case 8: printf("eight "); break; case 9: printf("nine "); break; } } } void main() { int n; printf("Enter n = "); scanf("%d", &n); numberToWords(n); }
Output:
Enter n = 2075two zero seven five
Geometric Progression
21. Compute the sum of the geometric progression:
1 + x + x
2+ x
3+ . . . + x
n(1) Generate the next term by multiplying the previous
term
by
x
.
(2)
Add
term
to
sum
.
(3) Repeat steps (1) and (2) for
n
times.
Program 21: Sum of geometric progression
#include <stdio.h>float geoSum(float x, int n) {
float sum = 1.0, term = 1.0;
int i;
for( i = 1; i <= n; i++ ) {
term = term * x;
// x, x
2, x
3, . . .
sum = sum + term;// 1 + x + x
2+ x
3+ . . .
} return sum; } void main() { float x; int n; printf("\n x = "); scanf("%f", &x); printf("\n n = "); scanf("%d", &n);printf("\n Sum of geometric progression is %f", geoSum(x, n));
}
Output/Input of this program is:
x = 2.0 n = 5
Bitwise Operators
22. A program that illustrates the bitwise operators.
Bitwise operators are used to modify the individual bits rather than the number. Both
operands in a bitwise expression must be of an integral type.
Operator
What it does
&
bitwise AND
Compares two bits and generates a 1 result if both bits are 1,
otherwise it returns 0.
|
bitwise inclusive OR
Compares two bits and generates a 1 result if either or both
bits are 1, otherwise it returns 0.
^
bitwise exclusive OR
Compares two bits and generates a 1 result if both bits are
complementary, otherwise it returns 0.
~
bitwise complement
Inverts each bit.
>>
bitwise shift right
Moves the bits to the right, discards the far right bit and
assigns the left most bit to 0.
<<
bitwise shift left
Moves the bits to the left, it discards the far left bit and
assigns the right most bit to 0.
Program 22: Bitwise operators
#include <stdio.h> void main() { int a = 25; int b = 13; int c = 12;printf("\n %d & %d = %d", a, b, a & b); printf("\n %d | %d = %d", a, b, a | b); printf("\n %d ^ %d = %d", a, b, a ^ b); printf("\n ~%d = %d", b, ~b); printf("\n %d >> 2 = %d", c, c>>2); printf("\n %d >> 1 = %d", c, c>>1); printf("\n %d << 2 = %d", c, c<<2); printf("\n %d << 1 = %d", c, c<<1); }
Output:
25 & 13 = 9 25 | 13 = 29 25 ^ 13 = 20 ~13 = -14 12 >> 2 = 3 12 >> 1 = 6 12 << 2 = 48 12 << 1 = 24This
output
is illustrated in the following table, by showing the bit-pattern of the decimal integer
numbers and their bitwise operations.
215 214 213 212 211 210 29 28 27 26 25 24 23 22 21 20 32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 Decimal number 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 25 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 13 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 25&13=9 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 25 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 13 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 25|13=29 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 25 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 13 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 25^13=20 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 12>>2=3 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 12 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 12<<2=48
Note:
The effect of shifting a variable to the right by one bit position is “dividing by 2”.
The effect of shifting a variable to the left by one bit position is “multiplying by 2”.
Notice the last two examples.
Number system
23. Convert a decimal number into its equivalent binary, octal, and hexadecimal
numbers.
Program 23: Conversion of a decimal number into binary, octal, and hexadecimal numbers
#include <stdio.h>void binary(int n ) {
static int bits[16]; int i, m = 16; for( i = 0; i < m; i++ ) { bits[i] = n % 2; n = n / 2; }
printf("\n Binary number: "); for( i = m-1; i >= 0; i-- )
printf("%d ", bits[i] ); }
void octal(int n ) {
static int nOctal[5]; int i, m = 0; for( i = 0; i < 5; i++ ) { if( n == 0 ) break; nOctal[i] = n % 8; n = n / 8; m++; }
printf("\n Octal number: "); for( i = m-1; i >= 0; i-- ) printf("%d", nOctal[i] ); } void hexadecimal(int n) { char hex[16] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E','F'}; static char nHex[5];
int i, d, m = 0; for( i = 0; i < 5; i++ ) { if( n == 0 ) break; d = n % 16; nHex[i] = hex[d]; n = n / 16; m++; }
printf("\n Hexadecimal number: "); for( i = m-1; i >= 0; i-- ) printf("%c", nHex[i] ); } void main() { int numb;
printf("\n Decimal number: "); scanf("%d", &numb);
binary(numb); octal(numb); hexadecimal(numb);
}
Input/Output for three decimal numbers:
Decimal number: 100
Binary number: 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0
Octal number: 144
Decimal number: 169 Binary number: 0 0 0 0 0 0 0 0 1 0 1 0 1 0 0 1 Octal number: 251 Hexadecimal number: A9 Decimal number: 32767 Binary number: 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Octal number: 77777 Hexadecimal number: 7FFF
2’s complement of a number
24. 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.
Step-1: Input a decimal number.
Step-2: Convert this decimal number into binary number.
Step-3: Convert the binary number into 2’s complement..
Program 24: 2’s complement of a number
#include <stdio.h> int bits[16]; int m = 16; void binary(int n ) { int i; for( i = 0; i < m; i++ ) { bits[i] = n % 2; n = n / 2; }
printf("\n Binary number: "); for( i = m-1; i >= 0; i-- )
printf("%d ", bits[i] ); }
void twosComplement() {
static int twos[16];
int i; for( i = 0; i < m; i++ ) if( bits[i] == 1 ) { twos[i] = bits[i]; break; } for(i++; i < m; i++ ) if( bits[i] == 1 ) twos[i] = 0;
else twos[i] = 1; printf("\n 2's complement: "); for( i = m-1; i >= 0; i-- ) printf("%d ", twos[i] ); } void main() { int numb;
printf("\n Decimal number: "); scanf("%d", &numb);
binary(numb); twosComplement(); }
Output for three decimal numbers:
Decimal number: 28 Binary number: 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 2's complement: 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 Decimal number: 12340 Binary number: 0 0 1 1 0 0 0 0 0 0 1 1 0 1 0 0 2's complement: 1 1 0 0 1 1 1 1 1 1 0 0 1 1 0 0 Decimal number: 32767 Binary number: 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2's complement: 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
Roman numeral to decimal
25. Convert a Roman numeral to its decimal equivalent
Examples of Roman numerals to decimal numbers
---
Decimal
number
Roman
numeral
Decimal number Roman numeral
---
1
I
99
IC
2
II
100
C
3
III
…
…
4
IV
114
CXIV
5
V
…
…
…
…
500
D
9
IX
…
…
10
X
613
DCXIII
11
XI
…
…
…
…
1500 MD
49
IL
1000 M
50
L
1666 MDCLXVI
51
LI
995
VM
---
Program 25: Conversion of a Roman numeral to its decimal equivalent
#include<stdio.h>#include<string.h> void main()
{
int numb[10], n, i, dec;
char roman[10];
printf(" Enter the Roman numeral: "); scanf("%s", roman); n = strlen(roman); for(i = 0; i < n; i++) { switch( roman[i] ) {
case 'I': numb[i] = 1; break; case 'V': numb[i] = 5; break; case 'X': numb[i] = 10; break; case 'L': numb[i] = 50; break; case 'C': numb[i] = 100; break; case 'D': numb[i] = 500; break; case 'M': numb[i] = 1000; break;
default: printf("\n Invalid Value");
} }
dec = numb[n-1];
for(i = n-1; i>0; i--) {
if(numb[i] > numb[i-1])
dec = dec - numb[i-1];
else if(numb[i]==numb[i-1] || numb[i] < numb[i-1]) dec = dec + numb[i-1];
}
printf("\n Its Decimal Equivalent is: %d", dec); }
Input/Output for 3 inputs:
Its Decimal Equivalent is: 114
Enter the Roman numeral: CXIV
Enter the Roman numeral: MDCLXVIII Its Decimal Equivalent is: 1668
Enter the Roman numeral: CLIX Its Decimal Equivalent is: 159
Complex numbers
26. C program that uses functions to perform the following operations:
(Note: represent the complex number using a structure.)
(a) Reading a complex number
(b) Writing a complex number
(c) Addition of two complex numbers
(d) Multiplication of two complex numbers
Let x1 and
y1
be the real and imaginary parts of a complex number-1; and
x2 and
y2
be the real and imaginary parts of a complex number-2.
Sum of these two complex numbers:
real part is
x1+x2
imaginary part is
y1
+
y2
Product of these two complex numbers:
real part is
x1
*
x2
–
y1
*
y2
imaginary part is
x1
*
y2
+
x2
*
y1
Program 26: Operations on complex numbers
#include <stdio.h>typedef struct {
float x; // real part
float y; // imaginary part
} complex; void main() {
complex cn1, cn2, sum, product;
/* function prototypes */
complex read(void);
void print(complex);
complex add(complex, complex); complex multiply(complex, complex);
cn1 = read();
// read complex numbers
cn2 = read();
printf("\nTwo complex numbers:");
// display complex numbers
print(cn1);print(cn2);
sum = add(cn1, cn2); // add two complex numbers
printf("\n\nSum of these two numbers:"); print(sum);
product = multiply(cn1, cn2);
// multiply two complex numbers
printf("\n\nProduct of these two numbers:"); print(product);
}
complex read() {
complex cn;
printf("Input a complex number:\n"); printf("real part: ");
printf("imaginary part: "); scanf("%f", &cn.y); return cn; } void print(complex cn) {
printf("\nreal:%6.2f \t imag:%6.2f", cn.x, cn.y); }
complex add(complex cn1, complex cn2) {
complex cn;
cn.x = cn1.x + cn2.x; cn.y = cn1.y + cn2.y;
return cn;
}
complex multiply(complex cn1, complex cn2) {
complex cn;
cn.x = cn1.x * cn2.x - cn1.y * cn2.y; cn.y = cn1.x * cn2.y + cn2.x * cn1.y;
return cn;
}
Output:
Input a complex number: real part: 1.0
imaginary part: 2.0 Input a complex number: real part: 3.5
imaginary part: 1.5 Two complex numbers:
real: 1.00 imag: 2.00 real: 3.50 imag: 1.50 Sum of these two numbers: real: 4.50 imag: 3.50 Product of these two numbers:
real: 0.50 imag: 8.50
Array of structures
27. C program that uses functions to perform the following operations:
(Note: represent the student using a structure.)
(a) Read an array of student records (structures)
(b) Display the student data
Program 27: Application of array of structures
#include <stdio.h>typedef struct {
int htno; // Hall ticket number
char name[20];
// Student name
st;
// Test score
int te } student; void main() {
student s[5]; /* Array of structures */ void read(student[], int);
void display(student[], int); void sort(student[], int);
read(s, 5);
printf("\n Student Test Scores:\n");
display(s, 5);
sort(s, 5);
printf("\n Sorted Test Scores:\n");
display(s, 5);
}
void read( student s[], int n ) {
for( int i = 0; i < n; i++ ) // Read data of n students
{
printf("\n HT No: "); scanf("%d", &s[i].htno);
fflush(stdin); // clear the input memory buffer
printf(" Name: ");
gets(s[i].name); printf(" Test marks: "); scanf("%d", &s[i].test ); }
}
void display( student s[], int n ) {
for( int i = 0; i < n; i++ )
printf("\n %d %s\t\t %d", s[i].htno, s[i].name, s[i].test); }
void sort( student s[], int n ) {
int i, j;
student tmp;
for( i = 0; i < n-1; i++ ) // Sort the students on test score for( j = i+1; j < n; j++ )
if( s[i].test < s[j].test )
{ tmp = s[i]; // Swap students
s[i] = s[j];
s[j] = tmp;
} }
Input/Output:
HT No: 1201
Name: Ramu K L
Test marks: 79
HT No: 1202
Name: Rawat Kewal
Test marks: 70
HT No: 1203
Name: Ramya Sharma
Test marks: 85
HT No: 1204
Name: John Paul
Test marks: 47
HT No: 1205
Name: Quereshi Md
Test marks: 59 Student Test Scores: 1201 Ramu K L 79 1202 Rawat Kewal 70 1203 Ramya Sharma 85 1204 John Paul 47 1205 Quereshi Md 59 Sorted Test Scores:
1203 Ramya Sharma 85 1201 Ramu K L 79 1202 Rawat Kewal 70 1205 Quereshi Md 59 1204 John Paul 47
Copying one file to another
28. A program which copies one file to another.
Part-I: A data file, “TEST.DAT” is created.
Part-II: This data file is copied to another file, named “TEST2.DAT”.
Program 28: Copying one file to another file
#include <stdio.h> #include <stdlib.h> void main()
{
FILE *fp1, *fp2; /* declare file pointers */
char ch;
fp1 = fopen( "TEST.DAT", "w");
/* open file: TEST.DAT for writing */
/* read a character from keyboard; press ctrl+Z to end */putc(ch, fp1); /* write a char to file thru file pointer*/
fclose(fp1); /* close file: TEST.DAT */
fp1 = fopen( "TEST.DAT", "r"); fp2 = fopen( "TEST2.DAT", "w");
if( fp1 == NULL )
/* if "TEST.DAT" file does not exist, */
{ printf("\n File not found.");
/* display error message and */
exit(1);
/* exit from the program */
} else
printf("\n File found...\n\n"); /* File found and continue */ while( (ch = getc(fp1)) != EOF )
/* read a character from data file */
{ printf("%c", ch); /* display a character on the monitor */
putc(ch, fp2);
}
fclose(fp1);
/* close files */
fclose(fp2);
}
Output of this program is:
File found . . .
Real-life applications require that the data be written to or read from secondary storage devices. The secondary storage devices are hard disk, compact disk, floppy, and magnetic tape. The data is permanently stored on these devices in the form of data files. Once data is available on these devices, we can access and change it whenever required.
Reverse the first n characters in a file
29. Write a C program to reverse the first n characters in a file.
(Note: The file name and n are specified on the command line.)
Program 29: Copying one file to another file
#include <stdio.h>#include <stdlib.h> #include <string.h>
void main(int argc, char *argv[]) {
FILE *fptr;
// declare file pointer
char ch,
str1[25],
// stores the first n chars of the file
str2[25]; // stores these n chars in reverse order int i, n;n = atoi( argv[1] );
// convert the string to integer
if( fptr == NULL )
// if file does not exist,
{ printf("\n File not found.");// display error message and
exit(1); // exit from the program
} i = 0;
while( i < n )
// read first n character from data file
{ ch = getc(fptr); str1[i] = ch; i++; } str1[i] = NULL;printf("\n First %d characters: %s", n, str1);
strcpy(str2, strrev(str1));
printf("\n Characters reversed: %s", str2);
fclose(fptr);
// close file
}
Let the name of this program is
comline.c
After compilation, the program is:
comline.exe
We have created a data file (by previous program), and its file name is:
TEST.DAT
The content of this data file is as follows:
Real-life applications require that . . .
Execute the program on MS-DOS command line:
C:\>
comline 9 TEST.DAT
where
comline
is the executable program name,
9
is the first n characters of the data file, and
TEST.DAT
is the data file name.
comline
is stored in
argv[0],
9
in
argv[1]
, and
TEST.DAT
in
argv[2]
. “
9
” is a string
which is converted into an integer by
atoi()
function.
The following
output
is generated by the above command line.
First 9 characters: Real-lifeCharacters reversed: efil-laeR