Sie sind auf Seite 1von 33

KAMALA INSTITUTE OF TECHNOLOGY AND SCIENCE, SINGAPUR

COMPUTER SCIENCE AND ENGINEERING


COMPUTER PROGRAMMING IN C LAB
Academic year-2017-18

Prepared by

V. Anil Kumar

Assistant Professor

CSE Department
1. a) Write a C program to find the factorial of a positive integer.
#include <stdio.h>
main()
{
int n, i;
unsigned long long factorial = 1;

printf("Enter an integer: ");


scanf("%d",&n);

// show error if the user enters a negative integer


if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");

else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %llu", n, factorial);
}

}
Output: Enter an integer: 6
Factorial of 6 = 720

b) Write a C program to find the roots of a quadratic equation.

#include<stdio.h>

#include<math.h>

main()

float a, b, c, d, root1, root2;

printf("Enter the values of a, b, c\n");

scanf("%f%f%f", &a, &b, &c);

if(a == 0 || b == 0 || c == 0)
{

printf("Error: Roots can't be determined");

else

d = (b * b) - (4.0 * a * c);

if(d > 0.00)

printf("Roots are real and distinct \n");

root1 = -b + sqrt(d) / (2.0 * a);

root2 = -b - sqrt(d) / (2.0 * a);

printf("Root1 = %f \nRoot2 = %f", root1, root2);

else if (d < 0.00)

printf("Roots are imaginary \n ");

root1 = -b / (2.0 * a) ;

root2 = sqrt(abs(d)) / (2.0 * a);

printf("Root1 = %f +i %f\n", root1, root2);

printf("Root2 = %f -i %f\n", root1, root2);

else if (d == 0.00)

printf("Roots are real and equal\n");

root1 = -b / (2.0 * a);

root2 = root1;

printf("Root1 = %f\n", root1);

printf("Root2 = %f\n", root2);


}

Output: Enter the values of a, b, c

Roots are imaginary

Root1 = -0.600000 +i 0.000000

Root2 = -0.600000 -i 0.000000

2. a) Write a C program to determine if the given number is a prime number or not.

#include <stdio.h>

main() {

int n, i, c = 0;

printf("Enter any number n:");

scanf("%d", &n);

/*logic*/

for (i = 1; i <= n; i++) {

if (n % i == 0) {

c++;

if (c == 2) {

printf("%d is a Prime number",n);

else {

printf("%d is not a Prime number",n);


}

Output: Enter any number n:5

5 is a Prime number

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.

#include<stdio.h>
main()
{
int a = 0, b = 1, n = 0, i, sum = 0;
printf("Enter the length of series \n ");
scanf("%d", &n);
printf("Fibonacci series\n");
printf("%d %d", a, b);
for(i = 2; i < n; i++)
{
sum = a + b;
printf(" %d",sum);
a = b;
b = sum;
}
}
Output: Enter the length of series
7
Fibonacci series
0 1 1 2 3 5 8

3. a) Write a C program to construct a pyramid of numbers.

#include<stdio.h>
main()
{
int i,j,n;
printf("Enter pyramid range:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=0;j<n-i;j++)
printf(" ");
for(j=0;j<i;j++)
printf("%d ",i);
printf("\n");
}
}
Output: Enter pyramid range:3
1
22
333
b) Write a C program to calculate the following Sum:
Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!

# include<stdio.h>
# include<math.h>
main()
{
int i, n ;
float x, val, sum = 1, t = 1 ;
printf("Enter the value for x : ") ;
scanf("%f", &x) ;
printf("\nEnter the value for n : ") ;
scanf("%d", &n) ;
val = x ;
x = x * 3.14159 / 180 ;
for(i = 1 ; i < n + 1 ; i++)
{
t = t * pow((double) (-1), (double) (2 * i - 1)) *
x * x / (2 * i * (2 * i - 1)) ;
sum = sum + t ;
}
printf("\nsum is %f", sum) ;
}
Output: Enter the value for x : 3

Enter the value for n : 5

sum is 0.998630

4. a) The least common multiple (lcm) of two positive integers a and b is the smallest integer
that is evenly divisible by both a and b. Write a C program that reads two integers and
calls lcm (a, b) function that takes two integer arguments and returns their lcm. The lcm
(a, b) function should calculate the least common multiple by calling the gcd (a, b)
function and using the following relation:
LCM (a,b) = ab / gcd (a,b)
#include <stdio.h>
main()
{
int num1, num2, gcd, lcm, remainder, numerator, denominator;
printf("Enter two numbers\n");
scanf("%d %d", &num1, &num2);
if (num1 > num2)
{
numerator = num1;
denominator = num2;
}
else
{
numerator = num2;
denominator = num1;
}
remainder = numerator % denominator;
while (remainder != 0)
{
numerator = denominator;
denominator = remainder;
remainder = numerator % denominator;
}
gcd = denominator;
lcm = num1 * num2 / gcd;
printf("GCD of %d and %d = %d\n", num1, num2, gcd);
printf("LCM of %d and %d = %d\n", num1, num2, lcm);
}

Output: Enter two numbers


5
4
GCD of 5 and 4 = 1
LCM of 5 and 4 = 20

b) Write a C program that reads two integers n and r to compute the ncr value using the
following relation:
ncr (n,r) = n! / r! (n-r)! . Use a function for computing the factorial value of an integer.

#include <stdio.h>
int fact(int z);
void main()
{
int n, r, ncr;
printf("\n Enter the value for N and R \n");
scanf("%d%d", &n, &r);
ncr = fact(n) / (fact(r) * fact(n - r));
printf("\n The value of ncr is: %d", ncr);
}
int fact(int z)
{
int f = 1, i;
if (z == 0)
{
return(f);
}
else
{
for (i = 1; i <= z; i++)
{
f = f * i;
}
}
return(f);
}

Output: Enter the value for N and R


5
1
The value of ncr is: 5

5. a) Write C program that reads two integers x and n and calls a recursive function to
compute xn
#include<stdio.h>
#include<math.h>
int power(int x,int n);
main()
{
int n,x,res;
printf("enter values of x,n \n");
scanf("%d%d",&x,&n);
res=pow(x,n);
printf("power of %d ,%d is %d",x,n,res);
}
int power(int x,int n)
{
if(n==0)
return 1;
else if (n==1)
return x;
else
return (x*pow(-x,n-1));
}
Output: enter value of x,n
8
2
power of 8 ,2 is 64

b) Write a C program that uses a recursive function to solve the Towers of Hanoi problem.
#include<stdio.h>
void hanoi(int, char, char, char);
void main()
{
int disks;
char source, destination, aux;
printf("\nEnter No. of Disks:");
scanf("%d",&disks);
printf("\nEnter Source, Destination and Auxillary Disk Names:");
scanf("%s%s%s",source, destination, aux);
hanoi(disks,source,destination,aux);

}
void hanoi(int n, char s, char d, char a)
{
if(n>0)
{
hanoi(n-1,s,a,d);
printf("\n%d is moved from %s to %s",n,s,d);
hanoi(n-1,a,d,s);
}

}
Output
c) Write a C program that reads two integers and calls a recursive function to compute ncr
value.

#include<stdio.h>
int fact(int);
main()
{
int n,r,ncr;
printf("\n enter n and r:");
scanf("%d%d",&n,&r);
ncr=fact(n)/(fact(n-r)*fact(r));
printf("\n combination of %d & %d =%d",n,r,ncr);
}
int fact(int x)
{
if(x==0)
return 1;
else
return(x*fact(x-1));
}

Output: enter n and r: 9


7
combination of 9 & 7 =36

6. a) Write a C program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user using Sieve of Eratosthenes algorithm.
#include <stdio.h>
main()
{
int n,i,j;
int primes[100];
int z = 1;
printf("enter the size");
scanf("%d",&n);
for (i = 2;i < n; i++)
primes[i] = 1;
for (i = 2;i < n; i++)
if (primes[i])
for (j = i; i * j < n; j++)
primes[i * j] = 0;

printf("Prime numbers are : \n");


for (i = 2;i < n; i++)
if (primes[i])
printf("%d\n", i);
}
Output:
enter the size10
Prime numbers are :
2
3
5
7
b) Write a C program that uses non recursive function to search for a Key value in a given
list of integers. Use linear search method.
#include<stdio.h>
void lsearch(int a[],int n,int ele);
main()
{
int a[30],n,i,ele,pos;
printf("enter the size");
scanf("%d",&n);
printf("enter the elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("element to be searched");
scanf("%d",&ele);
lsearch(a,n,ele);
}
void lsearch(int a[],int n,int ele)
{
int i, f=0;
for(i=0;i<n;i++)
if( a[i] == ele)
{
printf("\nThe element %d is present at position %d \n",ele,i);
f=1;
break;
}
if(f==0)
printf("\nThe element is %d is not present \n",ele);
}
Output: enter the size 4
enter the elements
3
1
2
5
element to be searched
3

The element 3 is present at position 0

7. a) Write a menu-driven C program that allows a user to enter n numbers and then choose
between finding the smallest, largest, sum, or average. The menu and all the choices
are to be functions. Use a switch statement to determine what action to take. Display an
error message if an invalid choice is entered.

#include<stdio.h>
void menu();
int small(int a[],int n);
int large(int a[],int n);
int sum(int a[],int n);
int avg(int a[],int n);
int n,i;
main()
{
menu();
}
void menu()
{
int op,n,o;
int a[50],res;
printf("enter the size of array\n");
scanf("%d",&n);
printf("enter the elements of array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("menu\n");
printf("1.small \t 2.large\t 3.sum \t4. avg \n");
printf("enter ur option \n");
scanf("%d",&op);
switch(op)
{
case 1: res=small(a,n);
printf("small is:%d",res);
break;
case 2: res=lar(a,n);
printf("large is :%d",res);
break;
case 3: res=sum(a,n);
printf("sum is :%d",res);
break;
case 4: res=avg(a,n);
printf("avg is :%d",res);
break;
default:printf("invalid choice");
}
}
int small(int a[],int n)
{
int i;
int sm=a[0];
for(i=1;i<n;i++)
if(sm>a[i])
sm=a[i];
return(sm);
}
int lar(int a[],int n)
{
int i;
int lar=a[0];
for(i=1;i<n;i++)
if(lar<a[i])
lar=a[i];
return(lar);
}
int sum(int a[],int n)
{
int s=0;
for(i=0;i<n;i++)
s=s+a[i];
return(s);
}
int avg(int a[],int n)
{
int s=0;
for(i=0;i<n;i++)
s=s+a[i];
return(s/n);
}

Output:
enter the size of array
4
enter the elements of array
1
2
3
4
menu
1.small 2.large 3.sum 4. avg
enter ur option
2
large is :4

b) Write a C program that uses non recursive function to search for a Key value in a given
sorted list of integers. Use binary search method.

#include<stdio.h>
void bsearch(int a[],int n,int ele);
main()
{
int a[30],n,i,ele,pos;
printf("enter the size\n");
scanf("%d",&n);
printf("enter the elements in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("element to be searched\n");
scanf("%d",&ele);
bsearch(a,n,ele);
}
void bsearch(int a[], int n, int ele)
{
int f=0, l=0,h=n-1;
while(l<=h && f==0)
{
int m=(l+h)/2;
if( a[m] == ele )
{
f=1;
printf(" Element is found at %d position ",m);
}
else if( a[m] > ele)
h=m-1;
else
l=m +1 ;
}
if(f==0)
printf(" Element is not present in that Array !");
}

Output:
enter the size
4
enter the elements in sorted order
10
20
30
40
element to be searched
30
Element is found at 2 position

8 a) Write a C program that implements the Bubble sort method to sort a given list of
integers in ascending order.
#include <stdio.h>
main()
{
int a[100];

int i, j, n, t;

printf("Enter the size of the array \n");

scanf("%d", &n);

printf("Enter the elements \n");

for (i = 0; i < n; i++)


scanf("%d", &a[i]);

printf("Input array is \n");

for (i = 0; i<n; i++)

printf("%d\n", a[i]);

for(i = 0; i < n; i++)


{
for(j = 0; j < (n - i - 1); j++)
{
if (a[j] > a[j + 1])

{
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < n; i++)
{
printf("%d\n", a[i]);
}
}
Output:
Enter the size of the array
3
Enter the elements
40
10
50
Input array is
40
10
50
Sorted array is...
10
40
50

b) Write a C program that reads two matrices and uses functions to perform the following:
i) Addition of two matrices
ii) Multiplication of two matrices
#include<stdio.h>
main()
{
int ch,i,j,m,n,p,q,k,r1,c1,a[10][10],b[10][10],c[10][10];
printf("\n\t\tMENU");
printf("\n[1]ADDITION OF TWO MATRICES");
printf("\n[2]MULTIPLICATION OF TWO MATRICES");
printf("\n[0]EXIT");
printf("\n\tEnter your choice:\n");
scanf("%d",&ch);
if(ch<=2 & ch>0)
{
printf("Valid Choice\n");
}
switch(ch)

{
case 1:
printf("Input rows and columns of A & B Matrix:");

scanf("%d%d",&r1,&c1);

printf("Enter elements of matrix A:\n");

for(i=0;i<r1;i++)
{

for(j=0;j<c1;j++)

scanf("%d",&a[i][j]);

printf("Enter elements of matrix B:\n");

for(i=0;i<r1;i++)

for(j=0;j<c1;j++)

scanf("%d",&b[i][j]);

printf("\n =====Matrix Addition=====\n");

for(i=0;i<r1;i++)
{

for(j=0;j<c1;j++)

printf("%d\t",a[i][j]+b[i][j]);

printf("\n");

break;

case 2:

printf("Input rows and columns of A matrix:");

scanf("%d%d",&m,&n);

printf("Input rows and columns of B matrix:");

scanf("%d%d",&p,&q);

if(n==p)

printf("matrices can be multiplied\n");

printf("resultant matrix is %d*%d\n",m,q);

printf("Input A matrix\n");

read_matrix(a,m,n);

printf("Input B matrix\n");

/*Function call to read the matrix*/

read_matrix(b,p,q);

/*Function for Multiplication of two matrices*/

printf("\n =====Matrix Multiplication=====\n");

for(i=0;i<m;++i)

for(j=0;j<q;++j)

c[i][j]=0;

for(k=0;k<n;++k)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}

printf("Resultant of two matrices:\n");

write_matrix(c,m,q);

/*end if*/

else

printf("Matrices cannot be multiplied.");

/*end else*/

break;

case 0:

printf("\n Choice Terminated");

break;

default:

printf("\n Invalid Choice");

/*Function read matrix*/


int read_matrix(int a[10][10],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
return 0;

/*Function to write the matrix*/

int write_matrix(int a[10][10],int m,int n)

{
int i,j;

for(i=0;i<m;i++)

for(j=0;j<n;j++)

printf("%d\t",a[i][j]);

printf("\n");

return 0;

}
Output:

MENU
[1]ADDITION OF TWO MATRICES
[2]MULTIPLICATION OF TWO MATRICES
[0]EXIT
Enter your choice:
2
Valid Choice
Input rows and columns of A matrix:
2
2
Input rows and columns of B matrix:
2
2
matrices can be multiplied
resultant matrix is 2*2
Input A matrix
1
2
3
4
Input B matrix

1
2
3
4

=====Matrix Multiplication=====
Resultant of two matrices:
7 10
15 22
9. a) Write a C program that uses functions to perform the following operations:
i) to insert a sub-string into a given main string from a given position.

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[200], str2[200];
int l1, l2, n, i;
puts("Enter the string 1\n");
gets(str1);
l1 = strlen(str1);
puts("Enter the string 2\n");
gets(str2);
l2 = strlen(str2);
printf("Enter the position where the string is to be inserted\n");
scanf("%d", &n);
for(i = n; i < l1; i++)
{
str1[i + l2] = str1[i];
}
for(i = 0; i < l2; i++)
{
str1[n + i] = str2[i];
}
str2[l2 + 1] = '\0';
printf("After inserting the string is %s", str1);
}
Output:
Enter the string 1

sachin
Enter the string 2

tendulkar
Enter the position where the string is to be inserted
5
After inserting the string is sachitendulkarn

ii) to delete n characters from a given position in a given string

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str[20];
int i, n, l, pos;

puts("Enter the string\n");


gets(str);
printf("Enter the position where the characters are to be deleted\n");
scanf("%d", &pos);
printf("Enter the number of characters to be deleted\n");
scanf("%d", &n);
l = strlen(str);
for(i = pos + n; i < l; i++)
{
str[i - n] = str[i];
}
str[i - n] = '\0';
printf("The string is %s", str);

}
Output
Enter the string
sachin
Enter the position where characters are to be deleted
2
Enter the number of characters to be deleted
2
The string is sain

b) Write a C program that uses a non recursive function to determine if the given string is a
palindrome or not.

#include <conio.h>
#include <string.h>
main()
{
char str[20];
int i, l, f = 0;

printf("Enter any string\n");


gets(str);
l = strlen(str);
for(i = 0; i <= l - 1; i++)
{
if(str[i] == str[l - 1 - i])
f = f + 1;
}
if(f == l)
{
printf("The string is palindrome");
}
else
{
printf("The string is not a palindrome");
}
}
Output:
Enter any string
malayalam
The string is a palindrome

10. a) Write a C program to replace a substring with another in a given line of text.

#include <stdio.h>
#include <string.h>
#include<conio.h>
main()
{
char text[100],word[10],rpwrd[10],str[10][10];
int i=0,j=0,k=0,w,p;

printf("PLEASE WRITE ANY TEXT.\n");


gets(text);
printf("\nENTER WHICH WORD IS TO BE REPLACED\n");
scanf("%s",word);
printf("\nENTER BY WHICH WORD THE %s IS TO BE REPLACED\n",word);
scanf("%s",rpwrd);
p=strlen(text);

for (k=0; k<p; k++)


{

if (text[k]!=' ')
{
str[i][j] = text[k];
j++;
}
else
{
str[i][j]='\0';
j=0; i++;
}
}
str[i][j]='\0';
w=i;
for (i=0; i<=w; i++)
{
if(strcmp(str[i],word)==0)
strcpy(str[i],rpwrd);

printf("%s ",str[i]);
}

Output:
PLEASE WRITE ANY TEXT.
hello how are you

ENTER WHICH WORD IS TO BE REPLACED


hello

ENTER BY WHICH WORD THE hello IS TO BE REPLACED


Hai

hai how are you

b) Write a C program that reads 15 names each of up to 30 characters, stores them in an


array, and uses an array of pointers to display them in ascending (ie. alphabetical) order.

#include <stdio.h>
#include <string.h>
main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;

printf("Enter the value of n \n");


scanf("%d", &n);
printf("Enter %d names" ,n);
for (i = 0; i < n; i++)
{
scanf("%s", name[i]);
strcpy(tname[i], name[i]);
}
for (i = 0; i < n - 1 ; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf("\n----------------------------------------\n");
printf("Input \t NamestSorted names\n");
printf("------------------------------------------\n");
for (i = 0; i < n; i++)
{
printf("%s\t\t%s\n", tname[i], name[i]);
}
printf("------------------------------------------\n");
}
Output:
Enter the value of n
10
Enter 10 names
raju
anil
hello
kiran
ram
rahul
akhil
amar
kumar
ramesh

----------------------------------------
Input NamestSorted names
------------------------------------------
raju akhil
anil amar
hello anil
kiran hello
ram kiran
rahul kumar
akhil rahul
amar raju
kumar ram
ramesh ramesh

11. a) 2s 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 2s complement of
11100 is 00100. Write a C program to find the 2s complement of a binary number.
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main()
{
char a[20];
int i, carry, l;
printf("Enter the binary number \n");
scanf("%s", &a);
l = strlen(a);
for(i = 0; i < l; i++)
{
if(a[i] == '0')
{
a[i] = '1';
}
else
{
a[i] = '0';
}
}
printf("The 1's compliment of the binary number is %s \n", a);
i = strlen(a) - 1;
while(i >= 0)
{
if(a[i] == '0')
{
a[i] = '1';
carry = 0;
break;
}
else
{
a[i] = '0';
carry = 1;
i = i - 1;
}
}
printf("The 2's compliment of the binary number is ");
if(carry == 1)
{
printf("1");
}
printf("%s", a);
}
Output:
Enter the binary number
11100
The 1's compliment of the binary number is 00011
The 2's compliment of the binary number is 00100

b) Write a C program to convert a positive integer to a roman numeral. Ex. 11 is converted


to XI.

#include<stdio.h>
void predigits(char c1,char c2);
void postdigits(char c,int n);
char roman_Number[1000];
int i=0;

int main(){

int j;
long int number;

printf("Enter any natural number: ");


scanf("%d",&number);

if(number <= 0){


printf("Invalid number");
return 0;
}

while(number != 0){

if(number >= 1000){


postdigits('M',number/1000);
number = number - (number/1000) * 1000;
}
else if(number >=500){
if(number < (500 + 4 * 100)){
postdigits('D',number/500);
number = number - (number/500) * 500;
}
else{
predigits('C','M');
number = number - (1000-100);
}
}
else if(number >=100){
if(number < (100 + 3 * 100)){
postdigits('C',number/100);
number = number - (number/100) * 100;
}
else{
predigits('L','D');
number = number - (500-100);
}
}
else if(number >=50){
if(number < (50 + 4 * 10)){
postdigits('L',number/50);
number = number - (number/50) * 50;
}
else{
predigits('X','C');
number = number - (100-10);
}
}
else if(number >=10){
if(number < (10 + 3 * 10)){
postdigits('X',number/10);
number = number - (number/10) * 10;
}
else{
predigits('X','L');
number = number - (50-10);
}
}
else if(number >=5){
if(number < (5 + 4 * 1)){
postdigits('V',number/5);
number = number - (number/5) * 5;
}
else{
predigits('I','X');
number = number - (10-1);
}
}
else if(number >=1){
if(number < 4){
postdigits('I',number/1);
number = number - (number/1) * 1;
}
else{
predigits('I','V');
number = number - (5-1);
}
}
}

printf("Roman number will be: ");


for(j=0;j<i;j++)
printf("%c",roman_Number[j]);

return 0;

void predigits(char c1,char c2){


roman_Number[i++] = c1;
roman_Number[i++] = c2;
}

void postdigits(char c,int n){


int j;
for(j=0;j<n;j++)
roman_Number[i++] = c;

}
Output:
Enter any natural number: 11
Roman number will be: XI

12. a) Write a C program to display the contents of a file to standard output device
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *fptr;

char filename[100], c;

printf("Enter the filename to open \n");


scanf("%s", filename);

// Open file
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}

// Read contents from file


c = fgetc(fptr);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}

fclose(fptr);
return 0;
}
Output:
Enter the filename to open
a.txt
/*Contents of a.txt*/

b) Write a C program which copies one file to another, replacing all lowercase characters
with their uppercase equivalents.

#include<stdio.h>
#include<ctype.h>
main()
{
FILE *p,*q;
char s[10],d[10],ch;
printf(" Enter The Source FileName :: ");
gets(s);
printf("Enter The Target FileName :: ");
gets(d);
p=fopen(s,"r");
if(p==NULL)
{
printf("\nFile Not Found");
exit(1);
}
q=fopen(d,"w");
if(q==NULL)
{
printf("\nFile Creating Error");
exit(1);
}
while( (ch=getc(p))!=EOF)
{
if(islower(ch))
putc(toupper(ch),q);
else
if(isdigit(ch))
putc(ch,q);
else
putc(ch,q);
}
printf("\n\nThe Convertion Is Successfull!\n");
fclose(p);
fclose(q);
printf("\n\nThe Content Of File %s Is ::\n",s);
p=fopen(s,"r");
while( (ch=getc(p))!=EOF)
printf("%c",ch);
fclose(p);
printf("\n\nThe Content Of File '%s' Is ::\n",d);
q=fopen(d,"r");
while( (ch=getc(q))!=EOF)
printf("%c",ch);
fclose(q);
}
Output:
Enter The Source FileName :: p1a.c
Enter The Target FileName :: aa.txt
/*Contents of aa.txt*/

13. a) Write a C program to count the number of times a character occurs in a text file. The file
name and the character are supplied as command-line arguments.

#include <stdio.h>
#define M 20
int main()
{
char filename[M];
printf("Enter the file name ");
scanf("%s", filename);
char ch;
printf("Enter the character to be counted ");
scanf(" %c", &ch);
FILE* f;
f = fopen(filename, "r");

char tmp;
int freq = 0;
while(!feof(f))
{
tmp = fgetc(f);
if (tmp == ch)
freq++;
}

printf("File '%s' has %d instances of letter '%c'", filename, freq, ch);


}

Output:
a.txt
hello
hai
how are you
anil

Enter the file name a.txt


Enter the character to be counted a
File 'a.txt' has 3 instances of letter 'a'

b) Write a C program to compare two files, printing the first line where they differ.

#include <stdio.h>
#include <string.h>

#define MAXNAME 20
#define MAXLINE 100

FILE *first, *second;

int main()
{
char f[MAXNAME], s[MAXNAME], str1[MAXLINE], str2[MAXLINE];

printf("type the names of the compared files\n");


printf("first: ");
gets(f);
printf("second: ");
gets(s);
if((first = fopen(f, "r")) == NULL)
{
perror(f);
return 1;
}
else if((second = fopen(s, "r")) == NULL)
{
perror(s);
return 1;
}
else
printf("files open\n\n");
while(!feof(first) && !feof(second))
{
fgets(str1, MAXLINE-1, first);
fgets(str2, MAXLINE-1, second);
if(strcmp(str1,str2) != 0)
{
printf("first different strings:\n\n");
printf("%s\n%s\n", str1, str2);
break;
}
}
fclose(first);
fclose(second);
return 0;
}

Output:
a.txt
hello
hai
how are you
anil
b.txt
ggg
hello

type the names of the compared files


first: a.txt
second: b.txt
files open

first different strings:

hello

ggg

14. a) Write a C program to change the nth character (byte) in a text file. Use fseek function.
#include<stdio.h>

int main() {

FILE *fp;
char ch;
int num;
long length;

printf("Enter the value of num : ");


scanf("%d", &num);

fp = fopen("a.txt", "r");
if (fp == NULL) {
puts("cannot open this file");
exit(1);
}

fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, (length - num), SEEK_SET);

do {
ch = fgetc(fp);
putchar(ch);
} while (ch != EOF);

fclose(fp);
return(0);
}
Output:
a.txt
hello
hai
how are you
anil

Enter the value of num : 6


anil

b) Write a C program to reverse the first n characters in a file. The file name and n are
specified on the command line. Use fseek function.

#include<stdio.h >
main()
{

FILE *fp,*fp1;
char ch;
int c,n;
fp=fopen("a.txt","r");
fp1=fopen("b.txt","w");
printf("enter n value");
scanf("%d",&n);
n--;
c=n;
fseek(fp,n,SEEK_SET);
while(c>=0)
{
ch=fgetc(fp);
fputc(ch,fp1);
fseek(fp,-2,SEEK_CUR);
c--;
}
fseek(fp,n+1,0);
while(!feof(fp))
{
ch=fgetc(fp);
fputc(ch,fp1);
}
fclose(fp);
}
Output:
a.txt
hello
hai
how are you

enter n value5

b.txt
olleh
hai
how are you

15. a) Write a C program to merge two files into a third file (i.e., the contents of the firs t file
followed by those of the second are put in the third file).

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *fs1, *fs2, *ft;

char ch, file1[20], file2[20], file3[20];


printf("Enter name of first file\n");
gets(file1);

printf("Enter name of second file\n");


gets(file2);

printf("Enter name of file which will store contents of two files\n");


gets(file3);

fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");

if( fs1 == NULL || fs2 == NULL )


{
perror("Error ");
printf("Press any key to exit...\n");
getch();
exit(EXIT_FAILURE);
}

ft = fopen(file3,"w");

if( ft == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}

while( ( ch = fgetc(fs1) ) != EOF )


fputc(ch,ft);

while( ( ch = fgetc(fs2) ) != EOF )


fputc(ch,ft);

printf("Two files were merged into %s file successfully.\n",file3);

fclose(fs1);
fclose(fs2);
fclose(ft);

return 0;
}
Output:
a.txt
hello
hai
how are you

b.txt
olleh
hai
how are you

Enter name of first file


a.txt
Enter name of second file
b.txt
Enter name of file which will store contents of two files
c.txt
Two files were merged into c.txt file successfully.

c.txt
hello
hai
how are you

olleh
hai
how are you
b) Define a macro that finds the maximum of two numbers. Write a C program that uses
the macro and prints the maximum of two numbers.

#include <stdio.h>
#define MAX(x,y) ((x>y)?x:y)

int main()
{
int a,b,max;

printf("Enter first number: ");


scanf("%d",&a);
printf("Enter second number: ");
scanf("%d",&b);

max=MAX(a,b);
printf("Maximum number is: %d\n",max);

return 0;
}
Output:

Enter first number: 20


Enter second number: 40
Maximum number is: 40

Das könnte Ihnen auch gefallen