Skip to main content

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS
1. Familiarization of Hardware Components of a Computer
2. Familiarization of Linux environment – Programming in C with Linux
3. Familiarization of console I/O and operators in C
    i) Display “Hello World”
    ii) Read two numbers, add them and display their sum
    iii) Read the radius of a circle, calculate its area and display it
4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution.
Read the values of the variables from the user through console
5. Read 3 integer values, find the largest among them.
6. Read a Natural Number and check whether the number is prime or not
7. Read a Natural Number and check whether the number is Armstrong or not
8. Read n integers, store them in an array and find their sum and average
9. Read n integers, store them in an array and search for an element in the
   array using an algorithm for Linear Search
10.Read n integers, store them in an array and sort the elements in the array
  using Bubble Sort algorithm
11.Read a string (word), store it in an array and check whether it is a
   palindrome word or not.
12.Read two strings (each one ending with a $ symbol),
   store them in  arrays  and  concatenate them without using library functions
13.Read a string (ending with a $ symbol), store it in an array and
   count the   number of vowels, consonants and spaces in it.
14.Read two input each representing the distances between two points in
   the  Euclidean space, store these in structure variables and add the
   two   distance values.
15.Using structure, read and print data of n employees
   (Name, Employee Id and Salary)
16.Declare a union containing 5 string variables
   (Name, House Name, City Name, State and Pin code) each with a length
   of C_SIZE (user defined constant). Then, read and display the address
   of a  person using a variable of the union.
17.Find the factorial of a given Natural Number n using:
    i) a non recursive function
    ii) a recursive function
18.Read a string (word), store it in an array and obtain its reverse by
   using a  user defined function.
19.Write a menu driven program for performing matrix addition,
   multiplication and finding the transpose. Use functions to
   (i) read a matrix, (ii) find the sum of two matrices,
  (iii) find the product of two matrices,(iv) find the transpose of a
   matrix and (v) display a matrix.
20.Do the following using pointers
    i) add two numbers
    ii) swap two numbers using user defined function
21.Input and Print the elements of an array using pointers
22.Compute sum of the elements stored in an array using pointers and
   user defined functions.
23.Create a file and perform the following
    i) Write data to the file
    ii) Read the data in a given file & display the file content on console
    iii) append new data and display on console
24. Open a text input file and count number of characters,
    words and lines in it; and store the results in an output file.

Solutions 
1. Familiarization of Hardware

3.Display Hello World
#include <stdio.h>
int main()
{
system("clear");
printf("Hello World\n");
}
Sum of two numbers
#include <stdio.h>
int main()
{
int a,b,sum;
system("clear");
printf("Enter the two numbers\n");
scanf("%d%d",&a,&b);
sum=a+b;
printf("Sum=%d\n",sum);
}
Area of the circle
#include <stdio.h>
#include <math.h>
int main()
{
float d,r;
system("clear");
printf("Enter the radius\n");
scanf("%f",&r);
printf("area of circle=%.4f\n",M_PI*r*r);
}
4.Evaluating the expression ((a -b / c * d + e) * (f +g))
#include <stdio.h>
int main()
{
float a,b,c,d,e,f,g,exp;
system("clear");
printf("Enter the values a b c d e f in order\n");
scanf("%f%f%f%f%f%f",&a,&b,&c,&d,&e,&f);
exp=((a -b / c * d + e) * (f +g));
printf("Expression value=%f\n",exp);
}
5. Read 3 integer values, find the largest among them.
using if
#include <stdio.h>
int main()
{
    int a, b, c;
    system("clear");
    printf("Enter the numbers a, b and c: ");
    scanf("%d%d%d", &a, &b, &c);

    if (a >= b && a >= c)
        printf("%d is the largest number.\n", a);

    if (b >= a && b >= c)
        printf("%d is the largest number\n", b);

    if (c >= a && c >= b)
        printf("%d is the largest number.\n", c);
}
using if-else
#include <stdio.h>
int main()
{
    int a, b, c;
    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);
    if (a >= b) {
        if (a >= c)
            printf("%d is the largest number.\n", a);
        else
            printf("%d is the largest number.\n", c);
    }
    else {
        if (b >= c)
            printf("%d is the largest number.\n", b);
        else
            printf("%d is the largest number.\n", c);
    }
}
using nested if-else
#include <stdio.h>
int main()
{
    int a, b, c;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    if (a >= b && a >= c)
        printf("%d is the largest number.\n", a);

    else if (b >= a && b >= c)
        printf("%d is the largest number.\n", b);

    else
        printf("%d is the largest number.\n", c);
 }
using ternary operator ?:
#include <stdio.h>
int main()
{
    int a, b, c, largest;
    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);
    largest = a > b ? (a > c ? a : c) : (b > c ? b : c);
    printf("%d is the largest number.\n", largest);
}
6. Read a Natural Number and check whether the number is prime or not
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}
 #include <stdio.h>
int main()
{
    int n, i, flag = 1;
    printf("Enter a number: \n");
    scanf("%d", &n);
    for (i = 2; i <= n / 2; i++)
        {
        // check for factors from 2 to n/2, no factors other than 1 and n ,its a prime number
        if (n % i == 0) {
            flag = 0;
            break;
        }
    }
    if (flag == 1)
        printf("%d is a prime number\n", n);
    else
        printf("%d is not a prime number\n", n);
}
7. Read a Natural Number and check whether the number is Armstrong or not
A positive integer of n digits is called an Armstrong number of order n (order is number of digits)
 if.abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
Example:
Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153
Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9
Input : 1253
Output : No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723
Input : 1634
Output : Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n, i,nd,d,sum=0,temp;
char str[100];
printf("Enter a number: \n");
scanf("%d", &n); //finding number of digits(nd) in the number
//by converting into string and find the length
sprintf(str,"%d",n);
nd=strlen(str);
temp=n;
while(temp!=0)
{ d=temp%10;
  sum=sum+pow(d,nd);
  temp=temp/10;
}
if ( n==sum)
    printf("%d is an Armstrong number\n", n);
else
    printf("%d is not a Armstrong number\n", n);
}
 
8. Read n integers, store them in an array and find their sum and average
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int n, i,a[100];
    float sum=0,avg;
    printf("Enter  number of elemnts: \n");
    scanf("%d", &n);
    printf("Enter the elements..\n");
    for(i=0;i<n;i++)
    {
         scanf("%d",&a[i]);
         sum=sum+a[i];
   }
    avg=sum/n;
   printf("Sum=%f Average=%f\n",sum,avg);
}

9.Read n ntegers, store them in an array and search for an element in the array using an algorithm for Linear Search.
#include <stdio.h>
int main()
{
    int n, i,a[100],key,flag=-1;
    printf("Enter number of elements: \n");
    scanf("%d",&n);
    printf("Enter the list of elements..\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("Enter the element to search..\n");
        scanf("%d",&key);
    for (i=0;i<n;i++)
        if (a[i]==key)
         { flag=1;break;}
   if(flag==1)
         printf("Element is found at index %d\n",i);
   else
         printf("Element is not found\n");  
}

10.Read n integers, store them in an array and sort the elements in the array using Bubble Sort algorithm
#include <stdio.h>
int main()
{
    int n, i,j,a[100],temp,flag;
    printf("Enter number of elements: \n");
    scanf("%d",&n);
    printf("Enter the list of elements..\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    for(i = 0; i < n; i++)
    {
      for(j = 0; j < n-i-1; j++)
       {
            // introducing a flag to monitor swapping
        flag = 0;
        if( a[j] > a[j+1])
          {
                // swap the elements
                temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
                // if swapping happens update flag to 1
                flag = 1;
            }
      }
      if ( flag==0) break;// if no swapping the list is sorted
     }
     printf("The sorted list is ...\n");
     for(i=0;i<n;i++)
      printf("%d\n",a[i]);
}
11.Read a string (word), store it in an array and check whether it is a
   palindrome word or not.
#include <stdio.h>
#include <string.h>
int main()
{
    char str[100],rstr[100];
    int i,j,ln;
    printf("Enter the string(word): ");
    scanf("%s",str);
    ln=strlen(str);// reversing the string
    for(i=ln-1,j=0;i>=0;i--,j++)
          rstr[j]=str[i];
    rstr[j]='\0';
    if(strcmp(rstr,str)==0)
       printf("Palindrome\n");
    else
       printf("Not Palindrome\n");
 }

Not using any library function
#include <stdio.h>
#include <string.h>
int main()
{
    char str[100];
    int i,j,flag=1;
    printf("Enter the string(word): ");
    scanf("%s",str);
    for(j=0;str[j]!='\0';j++);//  finding length j
    for(i=0,--j;i<j;i++,j--)
          if(str[i]!=str[j]) { flag=0;break;}
    if(flag==0)
       printf("Not Palindrome\n");
    else
       printf("Palindrome\n");
 }

12.Read two strings (each one ending with a $ symbol),   store them in  arrays  and  concatenate them without using library functions

#include <stdio.h>
#include <string.h>
int main()
{
    char str1[100],str2[100];
    int i,j;
    printf("Enter the string1: ");
    fgets(str1,100,stdin);
    printf("Enter the string2: ");
    fgets(str2,100,stdin);
        for(i=0;str1[i]!='$';i++);
    for(j=0;str2[j]!='$';j++,i++)
      str1[i]=str2[j];
    str1[i]='\0';
    printf("conatenated string is \n");
    printf("%s\n",str1);
 }
 13.Read a string  store it in an array and  count the   number of vowels, consonants , digits and spaces in it.
#include <stdio.h>
int main()
{
    char str[150];
    int i, vowels, consonants, digits, spaces;
    vowels =  consonants = digits = spaces = 0;
    printf("Enter a  string: ");
    scanf("%[^\n]", str);
    for(i=0; str[i]!='\0'; ++i)
    {
        if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
           str[i]=='o' || str[i]=='u' || str[i]=='A' ||
           str[i]=='E' || str[i]=='I' || str[i]=='O' ||
           str[i]=='U')
        {
            ++vowels;
        }
        else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z'))
        {
            ++consonants;
        }
        else if(str[i]>='0' && str[i]<='9')
        {
            ++digits;
        }
        else if (str[i]==' ')
        {
            ++spaces;
        }
    }
    printf("Vowels: %d",vowels);
    printf("\nConsonants: %d",consonants);
    printf("\nDigits: %d",digits);
    printf("\nWhite spaces: %d\n", spaces);
}

Note: we can use builtin functions to check for alphabets,digits and spaces.
check the link for usage of built in functions 
http://cprogramktu.blogspot.com/2020/01/character-processing.html
14.Read two input each representing  points in the  Euclidean space, store these in structure variables and add the two  point values.
#include <stdio.h>
struct Point
{
int x;
int y;
}p1,p2,p3;
int main()
{
  printf("Enter the first point(x1,y1)\n"); 
  scanf("%d,%d",&p1.x,&p1.y);
  printf("Enter the second point(x2,y2)\n"); 
  scanf("%d,%d",&p2.x,&p2.y);
  p3.x=p1.x+p2.x;
  p3.y=p1.y+p2.y;
  printf("new point after addition\n");
  printf("(%d,%d)\n",p3.x,p3.y);
}
15.Using structure, read and print data of n employees  (Name, Employee Id and Salary)

#include <stdio.h>
struct Employee
{
int empid;
char name[50];
int salary;
}emp[50];
int main()
{ int n,i;
  system("clear");
  printf("Enter the number of employees\n"); 
  scanf("%d",&n);
  for(i=0;i<n;i++)
  {
    printf("Enter the employee details-%d\n",i+1);
    printf("Employee id:");
    scanf("%d",&emp[i].empid);
    getchar();
    printf("Employee name:");
    scanf("%[^\n]",emp[i].name);
    printf("Employee salary:");
    scanf("%d",&emp[i].salary);
 }
  //printing the details
  printf("Employee Details\n");
  printf("Employee id---Employee name---Employee salary\n");
   for(i=0;i<n;i++)
       printf("%-15d %-15s %10d\n",emp[i].empid,emp[i].name,emp[i].salary);
} 
16.Declare a union containing 5 string variables
   (Name, House Name, City Name, State and Pin code) each with a length of C_SIZE (user defined constant). Then, read and display the address of a  person using a variable of the union.
#include <stdio.h>
#include <string.h>
#define C_SIZE 50
union Address
{
        char name[C_SIZE];
        char hname[C_SIZE];
        char cityname[C_SIZE];
        char state[C_SIZE];
        char pin[C_SIZE];
};

int main()
{
    union Address record1;
  
    printf("Enter name:");
    scanf("%[^\n]",record1.name);
    getchar();
    printf("Enter house name:");
    scanf("%[^\n]",record1.hname);
    getchar();
    printf("Enter city name:");
    scanf("%[^\n]",record1.cityname);
    getchar();
    printf("Enter state name:");
    scanf("%[^\n]",record1.state);
    getchar();
    printf("Enter pin:");
    scanf("%[^\n]",record1.pin);

    printf("Union record1 values ....\n");
    printf(" Name          : %s \n", record1.name);
    printf(" House Name    : %s \n", record1.hname);
    printf(" City Name       : %s \n\n", record1.cityname);
    printf(" State name    : %s \n", record1.state);
    printf(" Pin       : %s \n\n", record1.pin);
 }
Note: it is noted that the program will print only Pin because the union will hold only one value at a time .
You can read one value and print at a time
int main()
{
    union Address record1;
  
    printf("Enter name:");
    scanf("%[^\n]",record1.name);
    printf("Union record1 values ....\n");
    printf(" Name          : %s \n", record1.name);
    getchar();
    printf("Enter house name:");
    scanf("%[^\n]",record1.hname);
    printf(" House Name    : %s \n", record1.hname);
    getchar();
    printf("Enter city name:");
    scanf("%[^\n]",record1.cityname);
    getchar();
     printf(" City Name       : %s \n\n", record1.cityname);
    printf("Enter state name:");
    scanf("%[^\n]",record1.state);
    getchar();
    printf(" State name    : %s \n", record1.state);
    printf("Enter pin:");
    scanf("%[^\n]",record1.pin);
    printf(" Pin       : %s \n\n", record1.pin);
    }


17.Find the factorial of a given Natural Number n using:
    i) a non recursive function
    ii) a recursive function
#include <stdio.h>
long int factnr(int n)
{ int i;
  long int f=1;
  for(i=1;i<=n;i++)
       f=f*i;
  return f;
}
long int factr(int n)
{
  if(n==0) return 1;
  else
  return (n*factr(n-1));
}
int main()
{int n;
  system("clear");
  printf("Enter the number \n");
  scanf("%d",&n);
  printf("Factorial using non recursive function  %d !=%ld\n",n,factnr(n));
  printf("Factorial using     recursive function  %d !=%ld\n",n,factr(n));
}
18.Read a string (word), store it in an array and obtain its reverse by
   using a  user defined function.
#include <stdio.h>
#include <string.h>
void reversestr(char str[])
{ int i,l;
  char c;
  l=strlen(str); //instead of strlen we can use this code ----  l=0; while ( str[l]!='\0') l++;
  for(i=0;i<l/2;i++)
    {   c=str[i];
         str[i]=str[l-1-i];
         str[l-1-i]=c;
     }
}
int main()
{
  char str[100];
  system("clear");
  printf("Enter the string \n"); 
  scanf("%[^\n]",str);
  reversestr(str);
  printf("Reversed string is=%s\n",str);
}

19.Write a menu driven program for performing matrix addition,
   multiplication and finding the transpose. Use functions to
   (i) read a matrix, (ii) find the sum of two matrices,
  (iii) find the product of two matrices,(iv) find the transpose of a
   matrix and (v) display a matrix.
 #include <stdio.h>
#include <stdlib.h>
void readmatrix(int a[][100],int m,int n)
{
 int i,j;
 printf("enter the elements row by row\n");
 for(i=0;i<m;i++)
   for(j=0;j<n;j++)
    scanf("%d",&a[i][j]);
}
void displaymatrix(int a[][100],int m,int n)
{
 int i,j;
 for(i=0;i<m;i++)
 {
  for(j=0;j<n;j++)
    printf("%5d",a[i][j]);
  printf("\n");
  }
}
void addmatrix(int a[][100],int b[][100],int m,int n)
{
 int i,j,c[100][100];
 for(i=0;i<m;i++)
   for(j=0;j<n;j++)
    c[i][j]=a[i][j]+b[i][j];
 printf("Sum of matrix...\n");
 displaymatrix(c,m,n);
}
void transpose(int a[][100],int m,int n)
{
 int i,j,c[100][100];
 for(i=0;i<m;i++)
   for(j=0;j<n;j++)
    c[j][i]=a[i][j];

 displaymatrix(c,n,m);
}
void multmatrix(int a[][100],int b[][100],int m1,int n1,int n2)
{
 int c[100][100],i,j,k;
// Multiply the two
    for (i = 0; i < m1; i++) {
        for (j = 0; j < n2; j++) {
            c[i][j] = 0;
            for (k = 0; k < n1; k++)
                c[i][j] += a[i][k] * b[k][j];
        }
    }
 printf("Product of matrix...\n");
 displaymatrix(c,m1,n2);
}
int main()
{ int a[100][100],b[100][100],m1,n1,m2,n2,op;
  system("clear");
  printf("Enter the size of the matrix A row,column\n");
  scanf("%d%d",&m1,&n1);
  printf("Enter Matrix A\n");
  readmatrix(a,m1,n1);
  printf("Enter the size of the matrix B row column\n");
  scanf("%d%d",&m2,&n2);
  printf("Enter Matrix B\n");
  readmatrix(b,m2,n2);
  system("clear");
  printf("Matrix A..\n");  
  displaymatrix(a,m1,n1);
  printf("Matrix B..\n");  
  displaymatrix(b,m2,n2);
  while(1)
  {
   printf("\n************************************\n");
   printf("1.add  2.multiply  3.transpose 4.exit \n");
   printf("Enter the option.....:");
   scanf("%d",&op);
   switch(op)
   {
    case 1: if(m1==m2 && n1==n2)
                   addmatrix(a,b,m1,n1);
                else
                   printf("Incompatable matrix...cannot add..\n");
                 break;
    case 2: if(n1==m2)
                   multmatrix(a,b,m1,n1,n2);
               else
                   printf("Incompatable matrix...cannot mutliply..\n");
                break;
    case 3: printf("Transpose of A..\n");
                transpose(a,m1,n1);
                printf("Transpose of B..\n");
                transpose(b,m2,n2);
                break;
    case 4: exit(0);
   } 
   }
}
20.Do the following using pointers
    i) add two numbers
    ii) swap two numbers using user defined function
i) add two numbers
#include <stdio.h>
int main()
    {
       int first, second, *p, *q, sum;
       printf("Enter two integers to add\n");
       scanf("%d%d", &first, &second);
       p = &first;
       q = &second;
       sum = *p + *q;
       printf("Sum of the numbers = %d\n", sum);
     }
ii) swap two numbers using user defined function
#include <stdio.h>
// This function swaps values pointed by xp and yp
void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
    swap(&x, &y);
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;

21.Input and Print the elements of an array using pointers
#include <stdio.h>
int main()
{
    int arr[100];
    int n, i;
    int * ptr = arr;    // Pointer to arr[0]
    printf("Enter size of array: ");
    scanf("%d", &n);

    printf("Enter elements in array:\n");
    for (i = 0; i < n; i++)
    {
        // (ptr + i) is equivalent to &arr[i]
        scanf("%d", (ptr + i)); 
    }

    printf("Array elements: \n");
    for (i = 0; i < n; i++)
    {
        // *(ptr + i) is equivalent to arr[i]
        printf("%d\n", *(ptr + i));
    }
  }
Note: You can use dynamic memory allocation  for array using pointers
using the following definition int *ptr=(int *)malloc(sizeof(int));
22.Compute sum of the elements stored in an array using pointers and
   user defined functions.
#include <stdio.h>
#include <stdlib.h>
int arraysum(int *ptr,int n)
{
 int sum=0,i;
for (i = 0; i < n; i++)
    {
        // *(ptr + i) is equivalent to arr[i]
        sum=sum+ *(ptr + i);
    }
 return sum;
}
int main()
{
    int arr[]={4,5,6,7,8,9,10,1,2,3};
    int  sum;
    sum=arraysum(arr,10);
    printf("Array elements sum=:%d \n",sum);
}

23.Create a file and perform the following
    i) Write data to the file
    ii) Read the data in a given file & display the file content on console
    iii) append new data and display on console
 i) Write data to the file( char by char using putc/fputc function)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
fp=fopen("a.txt","w");
if(fp==NULL)
  {
  printf("Error opening file..");
  exit(1);
   }
do{
   ch=getchar();
   if (ch=='$') break;
   putc(ch,fp); // fputc(ch,fp)
  }
while(1);
fclose(fp);
}
i) Write data to the file( as strings using fputs function)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
char t[80];
fp=fopen("a.txt","w");
if(fp==NULL)
  {
  printf("Error opening file..");
  exit(1);
   }
printf("Enter strings...type end to stop\n");
do{
   fgets(t,80,stdin);
   if(strcmp(t,"end\n")==0 ) break;
   fputs(t,fp);
  }
while(1);
fclose(fp);
}
 i) Write data to the file( as strings using fprintf)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp=fopen("a.txt","w");
if (fp==NULL)
  {
    printf("error opening file..\n");
    exit(1);
   }
else
  {
   fprintf(fp,"%s","Welcome\n");
   fprintf(fp,"%s","to file handling in C\n");
   }
fclose(fp);
}
ii) Read the data in a given file & display the file content on console
(reading character by character using getc/fgetc function)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
fp=fopen("a.txt","r");
if(fp==NULL)
  {
  printf("Error opening file..");
  exit(1);
   }
do{
  ch=getc(fp); // ch=fgetc(fp);
  if (ch!=EOF) putchar(ch);
}
while(ch!=EOF);
fclose(fp);
}
reading line by line using fgets function
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char t[100];
fp=fopen("a.txt","r");
if(fp==NULL)
  {
  printf("Error opening source file..");
  exit(1);
   }
while((fgets(t,sizeof(t),fp)!=NULL))
{
printf("%s",t);
}
fclose(fp);
}
reading word by word using fscanf function
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char t[100];
fp=fopen("a.txt","r");
if(fp==NULL)
  {
  printf("Error opening source file..");
  exit(1);
   }
while(fscanf(fp,"%s",t)==1)
{
printf("%s\n",t);
}
fclose(fp);
}
iii Append data to a file and display the contents to console
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char t[100];
fp=fopen("a.txt","a");
if(fp==NULL)
  {
  printf("Error opening source file..");
  exit(1);
   }
printf("Enter the contents to append.................\n");
while(1)
{
 fgets(t,sizeof(t),stdin);
 if(strcmp(t,"end\n")==0) break;
 fputs(t,fp);
}
fclose(fp);
fp=fopen("a.txt","r");
printf("File contents after appending...\n");
printf("********************************\n");
while(fgets(t,sizeof(t),fp)!=NULL)
{
printf("%s",t);
}
fclose(fp);
}

24. Open a text input file and count number of characters,
    words and lines in it; and store the results in an output file.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char fname[50];
int ch;
int nl=0,nc=0,nw=0;
printf("Enter the file name....\n");
scanf("%[^\n]",fname);
fp=fopen(fname,"r");
if(fp==NULL)
  {
  printf("Error opening file..");
  exit(1);
   }
ch=getc(fp);
while(ch!=EOF)
{
if (ch=='\n') nl++;
if(ch==' ') nw++;
nc++;
ch=getc(fp);
}
fclose(fp);
printf("Number of lines=%d Number of words=%d ,Number of characters = %d,\n",nl,nc,nw+nl);
printf("results are written into result.dat file..\n");
fp=fopen("result.dat","w");
fprintf(fp,"Number of lines=%d Number of words=%d ,Number of characters = %d,\n",nl,nc,nw+nl);
fclose(fp);
}

Comments

  1. This comment has been removed by the author.

    ReplyDelete

  2. MN Park manages the common infrastructure, landscaping, water utilities and treatment plants of resident companies of Synergy Square 2, like Sami Labs, ISSAR, Hylasco, AMRI, Genotex and Biomax.
    Email: - atul@lc-reit.com
    Call now:-7989572171
    Know More:- Lab Space for Rent | Laboratory Space for Rent

    ReplyDelete



  3. There are numerous cases in which students need instant Programming Homework Help.Fortunately, you can also get the immediate assignment help. Moreover, with the help of this, you can submit the assignments within the deadlines and clear with high grades. Instant assignments is a worthy quality service that helps students in their studies. Therefore, you get excellent grades in the assignment.

    ReplyDelete
  4. At MN Park, you will find national and multinational tenants working, so you can seek healthy networking opportunities to share the resources and knowledge to create something better for this world. https://www.mn-park.com/

    ReplyDelete
  5. factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
    factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. Keep sharing!

    laboratory information system software

    ReplyDelete
  8. It’s really great information for becoming a better Blogger. Keep sharing, Thanks.
    Atal Tinkering Lab

    ReplyDelete
  9. pikashow Picasso Apps is a video streaming platform from where you can watch TV Shows, Web Series, IPL Live, and the Latest Movies for free.

    pikashow Picasso Apps is a video streaming platform from where you can watch TV Shows, Web Series, IPL Live, and the Latest Movies for free.

    What is the Factorial of One Hundred Before diving into the depths of the factorial of one hundred, let us first grasp the concept of factorials.

    ReplyDelete
  10. Really I am very impressed with this post. Just awesome, I haven’t any word to appreciate this post.
    language lab hardware

    ReplyDelete

Post a Comment

Popular posts from this blog

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper EST 102 Programmin in C University Question Papers  and evaluation scheme   EST 102 Programming in C  Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboar