C assignment question paper with Answers

DAY-6

1.C program to get minimum number of bits to store an integer number.

 

#include <stdio.h>

 int main()

{

    int num;

    printf("Enter an integer number :");

    scanf("%d",&num);

    int count=0,i;

    if(num==0)

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

    {  

        if( (1 << i) & num)

            count=i;

    }

++count;

 

    printf("\nTotal number of bits required = %d\n",num));

    return 0;

}

2.C program to swap two numbers using bitwise XOR operator

#include <stdio.h>

void swap(int *a, int *b);  //function declaration

int main()

{

int a,b;

printf("Enter first number: ");

scanf("%d",&a);

printf("Enter second number: ");

scanf("%d",&b);

printf("Before swapping: a=%d, b=%d\n",a,b);

swap(&a,&b);

printf("After swapping:  a=%d, b=%d\n",a,b);

return 0;

//function definition

void swap(int *a,int *b)

{

*a  =   *a ^ *b;

*b  =   *a ^ *b;

*a  =   *a ^ *b;

}

3.C program to counter number of 1’s in an integer number.

#include <stdio.h>

 

int count1s(unsigned int num)

{

    unsigned char totalBits=sizeof(num)*8;

    int count=0;

 

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

    {

        if( num & (1<< i) )

            count++;

    }

 

    return count;

}

int main()

{

    unsigned int data=0x58;

    printf("\nTotal number of 1's are : %d\n",count1s(data));

 

    return 0;

}

DAY-7

4.C program to check whether number is Perfect Number or not.

#include <stdio.h>

 

int main()

{

    int num,loop;

    int sum;

 

    printf("Enter an integer number: ");

    scanf("%d",&num);

 

     

    sum=0;

 

    for(loop=1; loop<num;loop++)

    {

        if(num%loop==0)

            sum+=loop;

    }

 

    if(sum==num)

        printf("%d is a perfect number.",num);

    else

        printf("%d is not a perfect number.",num);

 

    return 0;

}

5.C program to check whether number is Perfect Square or not.

#include <stdio.h>

#include <math.h>

 

int main()

{

    int num;

    int iVar;

    float fVar;

 

    printf("Enter an integer number: ");

    scanf("%d",&num);

 

    fVar=sqrt((double)num);

    iVar=fVar;

 

    if(iVar==fVar)

        printf("%d is a perfect square.",num);

    else

        printf("%d is not a perfect square.",num);

     

    return 0;

}

6.C program to count occurrence of a particular digit in a number.

#include <stdio.h>

 

int main()

{

    int num,tNum,digit,cnt;

    int rem;

 

    printf("Enter a number: ");

    scanf("%d",&num);

    printf("Enter digit to search: ");

    scanf("%d",&digit);

 

    cnt=0;

    tNum=num;

 

    while(tNum>0)

    {

        rem=tNum%10;

        if(rem==digit)

            cnt++;

        tNum/=10;

    }

 

    printf("Total occurrence of digit is: %d in number: %d.",cnt,num);

     

    return 0;

}

DAY-8

7.C Program To Find The Roots Of Quadratic Equation

#include<stdio.h>

        #include<math.h>

         

        main()

        {

         int a,b,c;

         float disc,r1,r2;

         for(;;)

         {

          printf("\nEnter the non Zero co-efficients a, b,c\n");

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

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

          {

           printf("\nPlease enter non zero co-efficients \n");

          }else{

           disc=((b*b)-(4*a*c));

           if(disc>0)

           {

            printf("Roots are Real:\n");

            r1=(-b-(sqrt(disc)))/(2.0*a);

            r2=(-b+(sqrt(disc)))/(2.0*a);

            printf("Roots are:%f and %f  \n", r1,r2);

         

           }

           else if(disc<0)

           {

            printf("Roots are Imaginary:\n");

            r1=-b/(2.0*a);

         

            printf("First root: %lf +%fi \n", r1,sqrt(-disc)/(2.0*a));

            printf("Second root:%lf -%lfi\n", r1,sqrt(-disc)/(2.0*a));

           }

           else

           {

            printf("Roots are Equal\n");

            r1= -b/(2.0*a);

            printf("Equal; roots are:%f and %f  \n", r1,r1);

           }

           return 0;

          }

         }

        }

8.C Program to classify the triangle as equilateral, isosceles and scalene

#include<stdio.h>

        #include<math.h>

        

        int main() {

          int a, b, c;

          float s, area;

         

          printf("Enter the values of the sides of the triangle: \n");

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

          if ((a + b > c && a + c > b && b + c > a) && (a > 0 && b > 0 && c > 0)) {

            s = (a + b + c) / 2.0;

            area = sqrt((s * (s - a) * (s - b) * (s - c)));

            if (a == b && b == c) {

              printf("Equilateral Triangle. \n");

              printf("Area of Equilateral Triangle is: %f", area);

            }

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

              printf("Isosceles Triangle. \n");

              printf("Area of an Isosceles Triangle: %f", area);

            }

            else {

              printf("Scalene Triangle. \n");

              printf("Area of Scalene Triangle: %f", area);

            }

          }

          else {

            printf("Triangle formation not possible");

          }

        

          return 0;

        }

9.C program to find the value of cos(x) using the series up to the given accuracy (without using user defined function) . Also print cos(x) using library function

#include <stdio.h>

#include <conio.h>

#include <math.h>

#include <stdlib.h>

 

void main()

{

 int  n, x1;

 float  acc, term, den, x, cosx=0, cosval;

 

 clrscr();

 

 printf("Enter the value of x (in degrees)\n");

 scanf("%f",&x);

 

 x1 = x;

 

 /* Converting degrees to radians*/

 

 x = x*(3.142/180.0);

 cosval = cos(x);

 

 printf("Enter the accuary for the result\n");

 scanf("%f", &acc);

 term = 1;

 cosx = term;

 n = 1;

 

 do

 {

  den = 2*n*(2*n-1);

  term = -term * x * x / den;

  cosx = cosx + term;

  n = n + 1;

 } while(acc <= fabs(cosval - cosx));

 

 printf("Sum of the cosine series       = %f\n", cosx);

 printf("Using Library function cos(%d) = %f\n", x1,cos(x));

}

DAY-9

10.C Program to convert a Roman numeral to its decimal equivalent

 

#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<stdlib.h>

 

void main()

{

 

 int *a,len,i,j,k;

 char *rom;

 

 clrscr();

 

 printf("Enter the Roman Numeral:");

 scanf("%s",rom);

 

 len=strlen(rom);

 

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

 {

  if(rom[i]=='I')

   a[i]=1;

  else if(rom[i]=='V')

   a[i]=5;

  else if(rom[i]=='X')

   a[i]=10;

  else if(rom[i]=='L')

   a[i]=50;

  else if(rom[i]=='C')

   a[i]=100;

  else if(rom[i]=='D')

   a[i]=500;

  else if(rom[i]=='M')

   a[i]=1000;

  else

  {

   printf("\nInvalid Value");

   getch();

   exit(0);

  }

 }

 k=a[len-1];

 for(i=len-1;i>0;i--)

 {

  if(a[i]>a[i-1])

   k=k-a[i-1];

  else if(a[i]==a[i-1] || a[i]<a[i-1])

   k=k+a[i-1];

 }

 printf("\nIts Decimal Equivalent is:");

 printf("%d",k);

 getch();

}

11.C program to find the 2’s complement of a binary number.

 

#include <stdio.h>

#include<conio.h>

 

void complement (char *a);

void main()

{

 char a[16];

 int i;

 clrscr();

 printf("Enter the binary number");

 gets(a);

 for(i=0;a[i]!='\0'; i++)

 {

  if (a[i]!='0' && a[i]!='1')

  {

   printf("The number entered is not a binary number. Enter the correct number");

   exit(0);

  }

 }

complement(a);

getch();

}

void complement (char *a)

{

 int l, i, c=0;

 char b[16];

 l=strlen(a);

 for (i=l-1; i>=0; i--)

 {

  if (a[i]=='0')

  b[i]='1';

  else

  b[i]='0';

 }

 for(i=l-1; i>=0; i--)

 {

 if(i==l-1)

 {

  if (b[i]=='0')

  b[i]='1';

  else

  {

   b[i]='0';

   c=1;

  }

 }

 else

 {

  if(c==1 && b[i]=='0')

  {

   b[i]='1';

   c=0;

  }

 else if (c==1 && b[i]=='1')

 {

  b[i]='0';

  c=1;

 }

}

}

b[l]='\0';

printf("The 2's complement is %s", b);

}

12.C program to convert the given Binary number into its equivalent Decimal,Octal and Hexadecimal numbers.

#include <stdio.h>

#include<string.h>

void hexadecimal();

void main()

{

 int   num, bnum, dec = 0, base = 1, rem ,dec1=0,oct[25],dec2=0,flag=0,i=0,counter=0,j;

 

 

 printf("Enter the binary number(1s and 0s)\n");

 scanf("%d", &num);          

 

 bnum = num;

 

 while( num > 0)

 {

  rem = num % 10;

  if((rem==0) || (rem==1))

  {

   dec = dec + rem * base;

   num = num / 10 ;

   base = base * 2;

   flag=1;

  }

  else

  {

   flag=0;

   printf("\nEnter binary number\n");

   break;

  }

 }

 if(flag==1)

 {

  printf("The Binary number is = %d\n", bnum);

  printf("Its decimal equivalent is =%d\n", dec);

  dec1=dec;

  dec2=dec1;

  while(dec>0)

  {

   rem=dec%8;

   oct[i]=rem;

   dec=dec/8;

   i++;

   counter++;

 

  }

  counter--;

  printf("\n Its octal equivalent is:");

  while(counter>=0){

   printf("%d" ,oct[counter]);

   counter--;

  }

 

  printf("\nIts Hexa Decimal  equivalant is:  ");

  hexadecimal(dec2);

 

 }

}

void hexadecimal(long n)

{

 long i;

 if(n>0)

 {

  i=n%16;

  n=n/16;

  hexadecimal(n);

  if(i>=10)

  {

   switch(i)

   {

   case 10:

    printf("A");

    break;

   case 11:

    printf("B");

    break;

   case 12:

    printf("C");

    break;

   case 13:

    printf("D");

    break;

   case 14:

    printf("E");

    break;

   case 15:

    printf("F");

    break;

   }

  }

  else

   printf("%ld",i);

 }

}

DAY-10

13.C program to print following Pyramid:

        *

       * *

      * * *

     * * * *

    * * * * *

    * * * * *

     * * * *

      * * *

       * *

        *

#include<stdio.h>

 

#define MAX 5

 

int main()

{

    int i,j;

    int space=4;

    /*run loop (parent loop) till number of rows*/

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

    {

        /*loop for initially space, before star printing*/

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

        {

            printf(" ");

        }

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

        {

            printf("* ");

        }

         

        printf("\n");

        space--;

    }

    /*repeat it again*/

    space=0;

    /*run loop (parent loop) till number of rows*/

    for(i=MAX;i>0;i--)

    {

        /*loop for initially space, before star printing*/

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

        {

            printf(" ");

        }

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

        {

            printf("* ");

        }

         

        printf("\n");

        space++;

    }

    return 0;

}

14.C program to print following pyramid

1A2B3C4D5E

1A2B3C4D

1A2B3C

1A2B

1A

#include <stdio.h>

 

int main()

{

    int i,j,k;

     

    /*Run parent loop*/

    for(i=5; i>=1; i--)

    {

        for(j=1, k='A'; j<=i; j++,k++)

        {

            printf("%d%c",j,k);

        }

             

        printf("\n");

    }

 

    return 0;

}

15.C Program For Draw A Perfect Christmas Tree

 

#include<stdio.h>

#include<conio.h>

//#include<iostream>

//using namespace std;

int main()

{

 //Program By Ghanendra Yadav

int i,j;

int  no,abc;

char last;

 printf("Enter The Value 30 For Perfact Chrismas Treen\n\n ");

 scanf("%d",&no);

 printf("\n");

 do//Do-While Loop Start From Here

  {

  abc=no/4;

  for(i=1; i<=no/4; i++)

   {

   printf("\t\t  ");

   for(j=1; j<abc; j++)

    printf(" ");

    abc--;

     for(j=1; j<=2*i-1; j++)

      printf("*");

       printf("\n");

 }

 abc=no/3;

 for(i=3; i<=no/3; i++)

  {

  printf("\t     ");

   for(j=1; j<abc; j++)

    printf(" ");

    abc--;

     for(j=1; j<=2*i-1; j++)

      printf("*");

      printf("\n");

  }

 abc=no/2;

 for(i=4; i<=no/2; i++)

  {

  printf("\t");

   for(j=1; j<abc; j++)

    printf(" ");

    abc--;

     for(j=1; j<=2*i-1; j++)

      printf("*");//Enter The AnyThing In Place Of ( * ) Like Any Key For Change Pattern

      printf("\n");

  }

 for(i=0;i<no/3;i++)

  {

  printf("\t\t      ");//Extra Space For Maintain Tree

  printf("*****");//Enter The AnyThing In Place Of ( * ) Like Any Key For Change Pattern

  printf("\n");

  }

 

  printf("\t\t  *************");//Enter The AnyThing In Place Of ( * ) Like Any Key For Change Pattern

  printf("\nPress Y Or y Number For Again Print Tree N Or Other Key For Exit :");

  scanf("%c",&last);

 }

 while(last=='Y'||last=='y');

 getch();

 return 0;

DAY-11

16.C program to find sum of following series:

        1+ 1/2 + 1/3 + 1/4 + 1/5 + .. 1/N

#include<stdio.h>

     

int main()

{

    int i,N;

    float sum;

     

    /*read value of N*/

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

    scanf("%d",&N);

     

    /*set sum by 0*/

    sum=0.0f;

     

    /*calculate sum of the series*/

    for(i=1;i<=N;i++)

        sum = sum + ((float)1/(float)i);

     

    /*print the sum*/

     

    printf("Sum of the series is: %f\n",sum);

     

    return 0;

}

17.C program to find sum of following series:

        1 + 3^2/3^3 + 5^2/5^3 + 7^2/7^3 + ... till N terms

#include<stdio.h>

#include<math.h>

     

int main()

{

    int i,N;

    float sum;

    int count;

     

     

    /*read value of N*/

    printf("Enter total number of terms: ");

    scanf("%d",&N);

     

    /*set sum by 0*/

    sum=0.0f;

     

    /*calculate sum of the series*/

    count=1;

    for(i=1;i<=N;i++)

    {

        sum = sum +  ( (float)(pow(count,2)) / (float)(pow(count,3)) );

        count+=2;

    }

     

    /*print the sum*/

     

    printf("Sum of the series is: %f\n",sum);

     

    return 0;

}

18.C program to find sum of the square of all natural numbers from 1 to N.

        Series: 1^2+2^2+3^2+4^2+..N^2

#include<stdio.h>

     

int main()

{

    int i,N;

    unsigned long sum;

     

    /*read value of N*/

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

    scanf("%d",&N);

     

    /*set sum by 0*/

    sum=0;

     

    /*calculate sum of the series*/

    for(i=1;i<=N;i++)

        sum= sum+ (i*i);

     

    /*print the sum*/

     

    printf("Sum of the series is: %ld\n",sum);

     

    return 0;

}

DAY 12 & 13

19.C program to replace all EVEN elements by 0 and Odd by 1 in One Dimensional Array.

void readArray(int arr[], int size)

{

    int i =0;

 

    printf("\nEnter elements : \n");

 

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

    {

        printf("Enter arr[%d] : ",i);

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

    }

}

 

/** funtion :   printArray()

    input   :   arr ( array of integer ), size

    to display ONE-D integer array on standard output device (moniter).

**/

void printArray(int arr[], int size)

{

    int i =0;

 

    printf("\nElements are : ");

 

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

    {

        printf("\n\tarr[%d] : %d",i,arr[i]);

    }

    printf("\n");

}

 

/** funtion :   replaceEvenOdd()

    input   :   arr ( array of integer ), size

    to replace EVEN elements by 0 and ODD elements by 1.

**/

void replaceEvenOdd(int arr[], int size)

{

    int i=0;

 

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

    {

        if( arr[i] % 2 == 0 )

            arr[i] = 0 ;

        else

            arr[i] = 1 ;

    }

}

 

int main()

{

    int arr[10];

 

    readArray(arr,10);

     

    printf("\nBefore replacement : ");

    printArray(arr,10);

 

    replaceEvenOdd(arr,10);

 

    printf("\nAfter replacement : ");

    printArray(arr,10);

}

20.C program to swap adjacent elements of a one dimensional array

#include <stdio.h>

#define MAX 100

int main()

{

    int arr[MAX],n,i;

    int temp;

     

    printf("Enter total number of elements: ");

    scanf("%d",&n);

     

    //value of n must be even

    if(n%2 !=0)

    {

        printf("Total number of elements should be EVEN.");

        return 1;

    }

    //read array elements

    printf("Enter array elements:\n");

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

    {

        printf("Enter element %d:",i+1);

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

    }

    //swap adjacent elements

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

    {

        temp    = arr[i];

        arr[i]  = arr[i+1];

        arr[i+1]= temp;

    }

     

    printf("\nArray elements after swapping adjacent elements:\n");

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

    {

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

    }

    return;

}

21.C program to cyclically permute the elements of an array.

#include <stdio.h>

 

void main ()

{

 int i,n,number[30];

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

 scanf ("%d", &n);

 printf ("Enter the numbers\n");

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

 {

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

 }

 number[n] = number[0];

 

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

 {

  number[i] = number[i+1];

 }

 printf ("Cyclically permted numbers are given below \n");

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

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

}

DAY-14 & 15

 22.C program to count upper case, lower case and special characters in a string.

#include<stdio.h>

 

int main()

{

    char text[100];

    int i;

    int countL,countU,countS;

     

    printf("Enter any string: ");

    gets(text);

 

    //here, we are printing string using printf

    //without using loop

    printf("Entered string is: %s\n",text);

     

    //count lower case, upper case and special characters

    //assign 0 to counter variables

    countL=countU=countS=0;

     

    for(i=0;text[i]!='\0';i++)

    {

        //check for alphabet

        if((text[i]>='A' && text[i]<='Z') || (text[i]>='a' && text[i]<='z'))

        {

            if((text[i]>='A' && text[i]<='Z'))

            {

                //it is upper case alphabet

                countU++;

            }

            else

            {

                //it is lower case character

                countL++;

            }

        }

        else

        {

            //character is not an alphabet

            countS++; //it is special character

        }

    }

     

    //print values

    printf("Upper case characters: %d\n",countU);

    printf("Lower case characters: %d\n",countL);

    printf("Special characters: %d\n",countS);

     

    return 0;

}

23.C program to convert string in upper case and lower case

#include<stdio.h>

 

int main()

{

    char text[100];

    int i;

     

    printf("Enter any string: ");

    gets(text);

     

    printf("Entered string is: %s\n",text);

     

    //convert into upper case

    for(i=0;text[i]!='\0';i++)

    {

        if(text[i]>='a' && text[i]<='z')

            text[i]=text[i]-0x20;

    }

    printf("String in Upper case is: %s\n",text);

     

    //convert into lower case

    for(i=0;text[i]!='\0';i++)

    {

        if(text[i]>='A' && text[i]<='Z')

            text[i]=text[i]+0x20;

    }

    printf("String in Lower case is: %s\n",text);

 

    return 0;

}

24.C program to toggle case of all characters of string.

#include<stdio.h>

 

int main()

{

    char text[100];

    int i;

     

    printf("Enter any string: ");

    gets(text);

     

    printf("Entered string is: %s\n",text);

     

    //convert into upper case

    for(i=0;text[i]!='\0';i++)

    {

        //check character is alphabet or not

        if((text[i]>='A' && text[i]<='Z')||(text[i]>='a' && text[i]<='z'))

        {

            //check for upper case character

            if(text[i]>='A' && text[i]<='Z')

                text[i]=text[i]+0x20;

            else

                text[i]=text[i]-0x20;

        }

    }

     

    printf("String after toggle case: %s\n",text);

 

    return 0;

}

DAY-16

25.C program to count vowels and consonants in a string using pointer

/*C program to count vowels and consonants in a string using pointer.*/

#include <stdio.h>

int main()

{

    char str[100];

    char *ptr;

    int  cntV,cntC;

     

    printf("Enter a string: ");

    gets(str);

     

    //assign address of str to ptr

    ptr=str;

     

    cntV=cntC=0;

    while(*ptr!='\0')

    {

        if(*ptr=='A' ||*ptr=='E' ||*ptr=='I' ||*ptr=='O' ||*ptr=='U' ||*ptr=='a' ||*ptr=='e' ||*ptr=='i' ||*ptr=='o' ||*ptr=='u')

            cntV++;

        else

            cntC++;

        //increase the pointer, to point next character

        ptr++;

    }

     

    printf("Total number of VOWELS: %d, CONSONANT: %d\n",cntV,cntC);        

    return 0;

}

26.C Program to Access Elements of an Array Using Pointer.

#include <stdio.h>

int main()

{

   int data[5], i;

   printf("Enter elements: ");

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

     scanf("%d", data + i);

   printf("You entered: \n");

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

      printf("%d\n", *(data + i));

   return 0;

}

27. C program for Attempting to modify data through a  non constant pointer to constant data.

#include<stdio.h>

Void f (const int *xPtr);

Int main(void)

{

Int y;

f(&y);

return o;

}

Void f(const int xPtr)

{

*xPtr=100;

}

DAY-18

28.C program to add two distances in feet and inches using structure

#include <stdio.h>

struct distance{

    int feet;

    int inch;

};

void addDistance(struct distance d1,struct distance d2){

    struct distance d3;

    d3.feet= d1.feet + d2.feet;

    d3.inch= d1.inch + d2.inch;

   

    d3.feet= d3.feet + d3.inch/12; //1 feet has 12 inches

    d3.inch= d3.inch%12;

   

    printf("\nTotal distance- Feet: %d, Inches: %d",d3.feet,d3.inch);

}

int main()

{

    struct distance d1,d2;

    printf("Enter first distance in feet & inches:");

    scanf("%d%d",&d1.feet, &d1.inch);

   

    printf("Enter second distance in feet & inches:");

    scanf("%d%d",&d2.feet, &d2.inch);

    /*add two distances*/

    addDistance(d1,d2);

    return 0;

}

29.Calculate Difference Between Two Time Periods

#include <stdio.h>

struct TIME

{

  int seconds;

  int minutes;

  int hours;

};

void differenceBetweenTimePeriod(struct TIME t1, struct TIME t2, struct TIME *diff);

int main()

{

    struct TIME startTime, stopTime, diff;

    printf("Enter start time: \n");

    printf("Enter hours, minutes and seconds respectively: ");

    scanf("%d %d %d", &startTime.hours, &startTime.minutes, &startTime.seconds);

    printf("Enter stop time: \n");

    printf("Enter hours, minutes and seconds respectively: ");

    scanf("%d %d %d", &stopTime.hours, &stopTime.minutes, &stopTime.seconds);

    // Calculate the difference between the start and stop time period.

    differenceBetweenTimePeriod(startTime, stopTime, &diff);

    printf("\nTIME DIFFERENCE: %d:%d:%d - ", startTime.hours, startTime.minutes, startTime.seconds);

    printf("%d:%d:%d ", stopTime.hours, stopTime.minutes, stopTime.seconds);

    printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds);

    return 0;

}

void differenceBetweenTimePeriod(struct TIME start, struct TIME stop, struct TIME *diff)

{

    if(stop.seconds > start.seconds){

        --start.minutes;

        start.seconds += 60;

    }

    diff->seconds = start.seconds - stop.seconds;

    if(stop.minutes > start.minutes){

        --start.hours;

        start.minutes += 60;

    }

    diff->minutes = start.minutes - stop.minutes;

    diff->hours = start.hours - stop.hours;

}

30.C Program to Add Two Distances (in inch-feet) System Using Structures

#include <stdio.h>

struct Distance

{

    int feet;

    float inch;

} d1, d2, sumOfDistances;

int main()

{

    printf("Enter information for 1st distance\n");

    printf("Enter feet: ");

    scanf("%d", &d1.feet);

    printf("Enter inch: ");

    scanf("%f", &d1.inch);

    printf("\nEnter information for 2nd distance\n");

    printf("Enter feet: ");

    scanf("%d", &d2.feet);

    printf("Enter inch: ");

    scanf("%f", &d2.inch);

    sumOfDistances.feet = d1.feet+d2.feet;

    sumOfDistances.inch = d1.inch+d2.inch;

    // If inch is greater than 12, changing it to feet.

    if (sumOfDistances.inch>12.0)

    {

        sumOfDistances.inch = sumOfDistances.inch-12.0;

        ++sumOfDistances.feet;

    }

    printf("\nSum of distances = %d\'-%.1f\"",sumOfDistances.feet, sumOfDistances.inch);

    return 0;

}

DAY-18

31. A program to declare a member of an union as a structure data type and to display the contents of the union

#include<stdio.h>

#include<conio.h>

void main()

{

  struct date

  {

    int day;

    int month;

    int year;

  };

  union value

  {

    int i;

    float f;

    struct date bdate;

  };

  union value x;

    x.i=10;

    x.f=-1234.45;

    x.bdate.day=12;

    x.bdate.month=4;

    x.bdate.year=2009;

    printf("First member=%d\n",x.i);

    printf("Second member=%d\n",x.f);

    printf("Structure:\n");

    printf("%d / %d / %d",x.bdate.day,x.bdate.month,x.bdate.year);

}

32.C program to Demonstrate union

#include <stdio.h>

#include <string.h>

 

union Data {

   int i;

   float f;

   char str[20];

};

 

int main( ) {

   union Data data;        

   printf( "Memory size occupied by data : %d\n", sizeof(data));

   return 0;

}

33.C program for entering the marks and grade of students by using Union

#include<stdio.h>

union marks        \\ A

    {

    float perc;    \\ B

    char grade;    \\ C

    }

main ( )

   {

    union marks student1;    \\ E

    student1.perc = 98.5;    \\ F

    printf( “Marks are %f   address is  %16lu\n”, student1.perc, &student1.perc);  \\ G

    student1.grade = ‘A’’;    \\ H    

    printf( “Grade is  %c  address is  %16lu\n”, student1.grade, &student1.grade);    \\ I

   }

DAY-19

37.C program to read a one dimensional array, print sum of all elements along with inputted array elements using Dynamic Memory Allocation.

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

    int *arr;

    int limit,i;

    int sum=0;

     

    printf("Enter total number of elements: ");

    scanf("%d",&limit);

     

    /*allocate memory for limit elements dynamically*/

    arr=(int*)malloc(limit*sizeof(int));

     

    if(arr==NULL)

    {

        printf("Insufficient Memory, Exiting... \n");

        return 0;

    }

     

    printf("Enter %d elements:\n",limit);

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

    {

        printf("Enter element %3d: ",i+1);

        scanf("%d",(arr+i));

        /*calculate sum*/

        sum=sum + *(arr+i);

    }

     

    printf("Array elements are:");

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

        printf("%3d ",*(arr+i));

     

     

    printf("\nSum of all elements: %d\n",sum);

     

    return 0;    

}

38.C program to read and print the student details using structure and Dynamic Memory Allocation.

#include <stdio.h>

#include <stdlib.h>

 

/*structure declaration*/

struct student

{

    char name[30];

    int roll;

    float perc;

};

 

int main()

{

    struct student *pstd;

     

    /*Allocate memory dynamically*/

    pstd=(struct student*)malloc(1*sizeof(struct student));

     

    if(pstd==NULL)

    {

        printf("Insufficient Memory, Exiting... \n");

        return 0;

    }

     

    /*read and print details*/

    printf("Enter name: ");

    gets(pstd->name);

    printf("Enter roll number: ");

    scanf("%d",&pstd->roll);

    printf("Enter percentage: ");

    scanf("%f",&pstd->perc);

     

    printf("\nEntered details are:\n");

    printf("Name: %s, Roll Number: %d, Percentage: %.2f\n",pstd->name,pstd->roll,pstd->perc);

     

    return 0;

}

 

39.C program to read and print the N student details using structure and Dynamic Memory Allocation.

#include <stdio.h>

#include <stdlib.h>

 

/*structure declaration*/

struct student

{

    char name[30];

    int roll;

    float perc;

};

 

int main()

{

    struct student *pstd;

    int n,i;

     

    printf("Enter total number of elements: ");

    scanf("%d",&n);

     

    /*Allocate memory dynamically for n objetcs*/

    pstd=(struct student*)malloc(n*sizeof(struct student));

     

    if(pstd==NULL)

    {

        printf("Insufficient Memory, Exiting... \n");

        return 0;

    }

     

    /*read and print details*/

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

    {

        printf("\nEnter detail of student [%3d]:\n",i+1);

        printf("Enter name: ");

        scanf(" "); /*clear input buffer*/

        gets((pstd+i)->name);

        printf("Enter roll number: ");

        scanf("%d",&(pstd+i)->roll);

        printf("Enter percentage: ");

        scanf("%f",&(pstd+i)->perc);

    }

     

    printf("\nEntered details are:\n");

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

    {

        printf("%30s \t %5d \t %.2f\n",(pstd+i)->name,(pstd+i)->roll,(pstd+i)->perc);

    }

     

    return 0;

}

DAY-20

34.C program to print contents in reverse order of a file.

#include <stdio.h>

#include <string.h>

 

int main(int argc, char *argv[])

{

    FILE *fp1;

     

    int cnt = 0;

    int i   = 0;

     

    if( argc < 2 )

    {

        printf("Insufficient Arguments!!!\n");

        printf("Please use \"program-name file-name\" format.\n");

        return -1;

    }

     

    fp1 = fopen(argv[1],"r");

    if( fp1 == NULL )

    {

        printf("\n%s File can not be opened : \n",argv[1]);

        return -1;

    }

     

    //moves the file pointer to the end.

    fseek(fp1,0,SEEK_END);

    //get the position of file pointer.

    cnt = ftell(fp1);

     

    while( i < cnt )

    {

        i++;

        fseek(fp1,-i,SEEK_END);

        printf("%c",fgetc(fp1));

    }

    printf("\n");

    fclose(fp1);

     

    return 0;

}

35.C program to copy number of bytes from specific offset to another file.

#include <stdio.h>

#include <string.h>

 

int main(int argc,char *argv[])

{

    FILE *fp1;

    FILE *fp2;

     

    int count       = 0;

    int location    = 0;

    int totBytes    = 0;

     

    unsigned char data[1024];

     

    if( argc < 5 )

    {

        printf("Insufficient Arguments!!!\n");

        printf("Please use \"program-name source-file-name target-file-name offset N\" format.\n");

        return -1;

    }

     

    fp1 = fopen(argv[1],"r");

    if( fp1 == NULL )

    {

        printf("\n%s File can not be opened : \n",argv[1]);

        return -1;

    }

     

    fseek(fp1,0,SEEK_END);

     

    count    = ftell(fp1);

    location = atoi(argv[3]);       // offset of source file to copy

    totBytes = atoi(argv[4]);       // number of bytes to copy

     

    if( count < (location  + totBytes) )

    {

        printf("\nGiven number of bytes can not be copy, due to file size.\n");

        return -1;

    }

     

    fp2 = fopen(argv[2],"w");

    if( fp2 == NULL )

    {

        printf("\n%s File can not be opened\n",argv[2]);

        return -1;

    }

 

    fseek(fp1,location,SEEK_SET);

     

    fread(data,totBytes,1,fp1);

 

    fwrite(data,totBytes,1,fp2);

     

    data[totBytes]=0;

     

    printf("\nCopied content is : \"%s\"\n",data);

 

    fclose(fp1);

    fclose(fp2);

 

    return 0;

}

36.C program to Convert All Characters in Upper Case of a File using C Program.

#include <stdio.h>

#include <ctype.h>

 

int main(){

 

    //file nane

    const char *fileName="sample.txt";

    //file pointers

    FILE *fp,*fp1;

    //to store read character

    char ch;

     

    //open file in read mode

    fp=fopen(fileName,"r");

    if(fp==NULL){

        printf("Error in opening file.\n");

        return -1;

    }

    //create temp file

    fp1=fopen("temp.txt","w");

    if(fp1==NULL){

        printf("Error in creating temp file.\n");

        return -1;

    }  

    //read file from one file and copy

    //into another in uppercase

    while((ch=fgetc(fp))!=EOF){

        if(islower(ch)){

            ch=ch-32;

        }

        //write character into temp file

        putc(ch,fp1);                  

    }

    fclose(fp);

    fclose(fp1);

    //rename temp file to sample.txt

    rename("temp.txt","sample.txt");

    //remove temp file

    remove("temp.txt");

     

    //now, print content of the file

    //open file in read mode

    fp=fopen(fileName,"r");

    if(fp==NULL){

        printf("Error in opening file.\n");

        return -1;

    }

    printf("Content of file\n");

    while((ch=getc(fp))!=EOF){

        printf("%c",ch);

    }

    printf("\n");

    fclose(fp);

    return 0;

}