R23 C LAB SOLUTIONS

COMPUTER PROGRAMMING LAB

Exercise 2: Converting algorithms/flowcharts into C Source code
  1. Sum and average of 3numbers.
  2. #include<stdio.h>
    #include<conio.h>
    int main()
    {
        int a, b, c, sum;
        float avg;
        clrscr();
        printf("Enter values of a,b, and c: \n");
        scanf("%d %d %d", &a, &b, &c);
        
        sum = a + b + c;
        
        avg = sum / 3;
       
        printf("Sum = %d \n", sum);
        printf("Average = %.2f", avg);
        return 0;
    }
  3. Conversion of Fahrenheit to Celsius and vice versa.
  4. //Conversion of Fahrenheit to Celsius
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
     float celsius, fahrenheit;
     clrscr();
    
     printf("\n Enter Temp in Fahrenheit : ");
     scanf("%f", &fahrenheit);
    
     celsius = (fahrenheit-32) / 1.8;
     printf("\n Temperature in Celsius : %.2f ", celsius);
    
     getch();
    }
    //Conversion of Celsius to Fahrenheit
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
     float celsius, fahrenheit;
     clrscr();
    
     printf("\n Enter Temp in Celsius : ");
     scanf("%f", &celsius);
    
     fahrenheit = (1.8 * celsius) + 32;
     printf("\n Temperature in Fahrenheit : %.2f ", fahrenheit);
    
     getch();
    }
    
  5. Simple interest calculation.
  6. #include<stdio.h>
    #include<conio.h>
    int main()
    {
    int p,r,t,int_amt;
    clrscr();
    printf("Input principle p, Rate of interest r & time in years t to find simple interest: \n");
    scanf("%d%d%d",&p,&r,&t);
    int_amt=(p*r*t)/100;
    printf("Simple interest = %d",int_amt);
    return 0;
    }


Exercise 3: Simple computational problems using arithmetic expressions.
  1. Finding the square root of a given number.
  2. #include<stdio.h>
    #include<conio.h>
    #include<math.h>
    int main() {
       double number, squareRoot;
       clrscr();
       printf("Enter a number: ");
       scanf("%lf", &number);
       squareRoot = sqrt(number);
       printf("Square root of %.2lf =  %.2lf", number, squareRoot);
       return 0;
    }
  3. Finding compound interest.
  4. #include<stdio.h>
    #include<conio.h>
    #include<math.h>
    int main()
    {
        double principle, rate, time, CI, n;
        clrscr();
        printf("Enter principle (amount): ");
        scanf("%lf", &principle);
    
        printf("Enter time in years: ");
        scanf("%lf", &time);
    
        printf("Enter annual rate of interest: ");
        scanf("%lf", &rate);
        
        printf("Enter the number of times that interest is compounded annually: ");
        scanf("%lf", &n);
    
    	A = principle * pow((1 + rate /(100*n)), n * time);
        printf("final amount with compound interest %lf", A);
        
        /* Calculate compound interest */
        CI = A - principle;
    
        /* Print the resultant CI */
        printf("Compound Interest = %.2lf", CI);
    
        return 0;
    }
    
  5. Area of a triangle using heron’s formulae.
  6. Steps to find the area of a triangle using Heron's formula
    Let A, B and C be the length of three sides of a triangle.
    
    Calculate the semi perimeter of the triangle.
    Semi-Perimeter of triangle(S) = (A + B + C)/2
        
    Now, we can calculate the area of triangle using below mentioned formula.
    Area of Triangle = √ S(S-A)(S-B)(S-C)) 
    Where, S is the semi-perimeter that we calculated in first step.
    
    #include<stdio.h>
    #include<conio.h>
    #include<math.h>
    int main()
    {
        float side1, side2, side3, s, area;
        clrscr();
        printf("Enter the length of three sides of triangle\n");
        scanf("%f %f %f", &side1,&side2,&side3);
        s = (side1 + side2 + side3)/2;
        area = sqrt(s*(s-side1)*(s-side2)*(s-side3));
        printf("Area of triangle : %0.4f\n", area);
        return 0;
    }
  7. Distance travelled by an object.
  8. #include<stdio.h>
    #include<conio.h>
    void main()
      	{
         float u,a,t,v,s;
         clrscr();
         printf("\n Enter initial velocity u: ");
         scanf("%f",&u);
         printf("\n Enter acceleration a: ");
         scanf("%f",&a);
         printf("\n Enter time required t: "); 
         scanf("%f",&t); 
         s=u*t+(1/2)*a*t*t;
         printf("\n The distance traveled is : %f ",s);
         getch();
        }
    


Exercise 4: Simple computational problems using the operator’ precedence and associativity
  1. Evaluate the following expressions.
  2. 1)	Evaluate the following expressions.
    a. A+B*C+(D*E)+F*G
    b. A/B*C-B+A*D/3
    c. A+++B---A
    d. J= (i++) +(++i)
    #include<stdio.h> #include<conio.h> int main() { int A=1,B=2,C=3,D=4,E=5,F=6,G=7,a,b,c,J,i=1; a= A+B*C+(D*E)+F*G; printf("a= %d",a); //if u take float, u will get exact output b=A/B*C-B+A*D/3; printf("\n b= %d",b); c=A+++B---A; printf("\n c= %d",c); J= (i++) +(++i); printf("\n J= %d",J); return 0; }
  3. Find the maximum of three numbers using conditional operator.
  4. #include<stdio.h>
    #include<conio.h>
        void main()
        {
            int a, b, c, big ;
         	clrscr();
            printf("Enter three numbers : ") ;
         
            scanf("%d %d %d", &a, &b, &c) ;
         
            big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;
         
            printf("\nThe biggest number is : %d", big) ;
            getch();
        }
     
  5. Take marks of 5 subjects in integers, and find the total, average in float
  6. #include<stdio.h>
    #include<conio.h>
    int main()
    {
        int eng, phy, chem, math, comp; 
        float total, average, percentage;
    
        /* Input marks of all five subjects */
        printf("Enter marks of five subjects: \n");
        scanf("%d %d %d %d %d", &eng, &phy, &chem, &math, &comp);
    
        /* Calculate total, average and percentage */
        total = eng + phy + chem + math + comp;
        average = total / 5.0;
        percentage = (total / 500.0) * 100;
    
        /* Print all results */
        printf("Total marks = %.2f\n", total);
        printf("Average marks = %.2f\n", average);
        printf("Percentage = %.2f", percentage);
    
        return 0;
    }
     


Exercise 5: Problems using conditional statements.
  1. Write a C program to find the max and min of four numbers using if-else.
  2. #include<stdio.h>
    #include<conio.h>
    int main() {
        int a,b,c,d; 
        printf("Enter the Four Numbers :"); 
        scanf("%d %d %d %d",&a,&b,&c,&d); 
        if(a>b && a>c && a>d) 
        { 
            printf("%d is max \n",a); 
        } 
        else if(b>c && b>d)
        { 
            printf("%d is max \n",b); 
        } 
        else if(c>d)
        { 
            printf("%d is max \n",c); 
        }         
        else
        {
            printf("%d is big \n",d);
        }
        
        if(a<b && a<c && a<d) 
        { 
            printf("%d is min",a); 
        } 
        else if(b<c && b<d)
        { 
            printf("%d is min",b); 
        } 
        else if(c<d)
        { 
            printf("%d is min",c); 
        }         
        else
        {
            printf("%d is min",d);
        }
        return 0;
    }
    
  3. Write a C program to generate electricity bill.
  4.   
    Conditions:
    
        For first 50 units – Rs. 3.50/unit
        For 51 - 150 units – Rs. 4.00/unit
        For 151 -250 units – Rs. 5.20/unit
        For units above 250 – Rs. 6.50/unit
        
    #include<stdio.h>
    int main()
    {
    	float bill, units;
    
    	printf("Enter the units consumed=");
    	scanf("%f",&units);
    
    	if(units<=50 && units>=0)
    	{
    		bill=units*3.50;
    		printf("Electricity Bill=%0.2f Rupees",bill);
    	}
    	else if(units<=150 && units>50)
    	{
    		bill=50*3.50+(units-50)*4;
    		printf("Electricity Bill=%0.2f Rupees",bill);
    
    	}
    	else if(units<=250 && units>150)
    	{
    		bill=50*3.50+100*4+(units-150)*5.20;
    		printf("Electricity Bill=%0.2f Rupees",bill);
    
    	}
    
    	else if(units>250)
    	{
    		bill=50*3.50+100*4+100*5.20+(units-250)*6.50;
    		printf("Electricity Bill=%0.2f Rupees",bill);
    
    	}
    	else
    	{
    	printf("Please enter valid consumed units...");
    	}
    	return 0;
    }    
    
  5. Find the roots of the quadratic equation.
  6.  
    # include<stdio.h>
    # include<math.h>
    #include<conio.h>
    int main () {
        float a,b,c,r1,r2,d;
        clrscr();
        printf ("Enter the values of a b c: ");
        scanf (" %f %f %f", &a, &b, &c);
        
        d= b*b - 4*a*c;
        
        if (d>0) {
            r1 = -b+sqrt (d) / (2*a);
            r2 = -b-sqrt (d) / (2*a);
            printf ("The real roots = %f %f", r1, r2);
        }
        else if (d==0) {
            r1 = -b/(2*a);
            r2 = -b/(2*a);
            printf ("Roots are equal =%f %f", r1, r2);
        }
        else
            printf("Roots are imaginary");
        
        return 0;
    }
     
  7. Write a C program to simulate a calculator using switch case.
  8.  
    #include <stdio.h>
    #include<conio.h>
    int main(){
        char ch;
        int a, b, result;
        clrscr();
        printf("Enter an Operator (+, -, *, /, %): ");
        scanf("%c", &ch);
        printf("Enter two operands: \n");
        scanf("%d %d", &a, &b);
        
        switch(ch){
            case '+':
                result = a + b;
                printf("%d + %d = %d", a, b, result);
                break;
            case '-':
                result = a - b;
                printf("%d - %d = %d", a, b, result);
                break;
            case '*':
                result = a * b;
                printf("%d * %d = %d", a, b, result);
                break;
            case '/':
                result = a / b;
                printf("%d / %d = %d", a, b, result);
                break;
            case '%':
                result = a % b;
                printf("%d mod %d = %d", a, b, result);
                break;
            default:
           		printf("choose proper menu");
                break;
        }
        return 0;
    }
    
  9. Write a C program to find the given year is a leap year or not.
  10.  
    #include <stdio.h>
    #include<conio.h>
        void main() {  
            int year;  
            clrscr();
            printf("Enter a year: ");  
            scanf("%d", &year);  
            if((year%4==0) && ((year%400==0) || (year%100!=0)))  
            {  
                printf("%d is a leap year", year);  
            } else {  
                printf("%d is not a leap year", year);  
            }  
           
        }  
    
    or
    
    #include <stdio.h>
    int main() {
       int year;
       printf("Enter a year: ");
       scanf("%d", &year);
       if (year % 400 == 0) {
          printf("%d is a leap year.", year);
       }
       // not a leap year if divisible by 100
       else if (year % 100 == 0) {
          printf("%d is not a leap year.", year);
       }
       else if (year % 4 == 0) {
          printf("%d is a leap year.", year);
       }
       else {
          printf("%d is not a leap year.", year);
       }
    
       return 0;
    }
    


Exercise 6: Problems using control statements.
  1. Find the factorial of given number using any loop
  2. //using while loop
    #include<stdio.h>
    #include<conio.h>
    int main(){
      int f=1,num;
    
      printf("Enter the number : ");
      scanf("%d",&num);
    
      while(num>0)
      {
          f=f*num;
          num--;
      }
      printf("The Factorial is: %d\n",f);
    return 0;
    }
    
    //using for loop
    #include<stdio.h>
    #include<conio.h>
    void main(){
      int i,f=1,num;
    
      printf("Enter the number : ");
      scanf("%d",&num);
    
      for(i=1;i<=num;i++)
      {
          f=f*i;
      }
      printf("The Factorial of %d is: %d\n",num,f);
    }
    
  3. Find the given number is a prime or not.
  4. #include<stdio.h>
    int main() 
    {
      int n, i, flag = 0;
      printf("Enter a positive integer: ");
      scanf("%d", &n);
      if (n == 0 || n == 1)
        flag = 1;
    
      for (i = 2; i <= n / 2; ++i) 
      {
        if (n % i == 0) {
          flag = 1;
          break;
        }
      }
    
      if (flag == 0)
        printf("%d is a prime number.", n);
      else
        printf("%d is not a prime number.", n);
    
      return 0;
    }
    
  5. Compute sine and cos series.
  6.  
    The formula of Sine Series is 
    sin(x) = x - (x*x*x)/3! + (x*x*x*x*x)/5! - (x*x*x*x*x*x*x)/7!
    for Example,
    Let the value of x be 50.
    
    x= 50 * pi/180 = 50 * (3.14/180) = 0.8722
    
    So, Radian value for 50 degree is 0.8722.
    sin(0.8722) = 0.8722 - (0.8722*0.8722*0.8722)/3! + (0.8722*0.8722*0.8722*0.8722*0.8722)/5!...
    
    
    //Compute Sine Series 
    #include<stdio.h>
    int main()
    {
        int i, n;
        float x, sum, t;
        printf(" Enter the value for x : ");
        scanf("%f",&x);
        printf(" \n Enter the value for n : ");
        scanf("%d",&n);
         
        x=x*3.14159/180;
        t=x;
        sum=x;
    
        for(i=1;i<=n;i++)
        {
            t=(t*(-1)*x*x)/(2*i*(2*i+1));
            sum=sum+t;
        }
         
        printf(" The value of Sin(%f) = %.4f",x,sum);
        return 0;
    }
    
    
    The formula of Cosine Series is 
    cos(x) = 1 - (x*x)/2! + (x*x*x*x)/4! - (x*x*x*x*x*x)/6!
    for Example,
    Let the value of x be 50.
    
    x= 50 * pi/180 = 50 * (3.14/180) = 0.8722
    
    So, Radian value for 50 degree is 0.8722.
    cos(0.8722) = 1 - (0.8722*0.8722)/2! + (0.8722*0.8722*0.8722*0.8722)/4!...
    
    
    //Compute Cosine Series 
    #include<stdio.h>
    int main()
    {
        int i, n;
        float x, sum=1, t=1;
        clrscr();
         
        printf(" Enter the value for x : ");
        scanf("%f",&x);
         
        printf(" Enter the value for n : ");
        scanf("%d",&n);
         
        x=x*3.14159/180;
         
        /* Loop to calculate the value of Cosine */
        for(i=1;i<=n;i++)
        {
            t=t*(-1)*x*x/(2*i*(2*i-1));
            sum=sum+t;
        }
         
        printf(" The value of Cos(%f) is : %.4f", x, sum);
        return 0;
    }
    
  7. Checking a number palindrome.
  8. #include<stdio.h>
    int main() {
      int n, rev = 0, rem, org;
        printf("Enter an integer: ");
        scanf("%d", &n);
        org = n;
    
        while (n != 0) {
            rem = n % 10;
            rev = rev * 10 + rem;
            n /= 10;
        }
    
        if (org == rev)
            printf("%d is a palindrome.", org);
        else
            printf("%d is not a palindrome.", org);
    
        return 0;
    }
    
    
  9. Construct a pyramid of numbers.
  10. // Half Pyramid
    #include<stdio.h>>
    int main() {
       int i, j, rows;
       printf("Enter the number of rows: ");
       scanf("%d", &rows);
       for (i = 1; i <= rows; ++i) {
          for (j = 1; j <= i; ++j) {
             printf("%d ", j);
          }
          printf("\n");
       }
       return 0;
    }
    
    
    // Full Pyramid
    #include<stdio.h>>
    
    int main() {
        // Write C code here
        int i,j,k,l;
        for(i=1;i<=5;i++)
        {
            for(k=5;k>=i;k--)
            printf(" ");
            for(j=1;j<=i;j++)
            printf("%d",j);
            for(l=j-2;l>0;l--)
            printf("%d", l);
            printf("\n");
        }
        
    
        return 0;
    }
    


Exercise 7: Using arrays.
  1. Find the min and max ofa1-D integer array.
  2. #include<stdio.h>>
    int main()
    {
        int A[10], i, max, min, n;
        printf("\n\nFind maximum and minimum element in an array :\n");
        printf("Input the number of elements to be stored in the array :");
        scanf("%d",&n);
       
        printf("Input %d elements in the array :\n",n);
        for(i=0;i<n;i++)
        {
    	  printf("element - %d : ",i);
    	  scanf("%d",&A[i]);
    	}
        max = A[0];
        min = A[0];
    
        for(i=1; i<n; i++)
        {
            if(A[i]>max)
            {
                max = A[i];
            }
    
    
            if(A[i]<min)
            {
                min = A[i];
            }
        }
        printf("Maximum element is : %d\n", max);
        printf("Minimum element is : %d\n\n", min);
    }
    
  3. Perform linear search on 1D array.
  4. #include<stdio.h>>
    int main()
    {
        int A[100], search, i, number;
        printf("Enter the number of elements in array\n");
        scanf("%d",&number);
        printf("Enter %d numbers\n", number);
        for ( i = 0 ; i < number ; i++ )
            scanf("%d",&A[i]);
        printf("Enter the number to search\n");
        scanf("%d",&search);
        for ( i = 0 ; i < number ; i++ )
        {
            if ( A[i] == search )  
            {
                printf("%d is present at location %d.\n", search, i+1);
                break;
            }
        }
        return 0;
    }
    
  5. The reverse of a1D integer array.
  6. #include<stdio.h>>
    int main()
    {
        int n, i,j, A[100];
        
        printf("Enter the number of elements in array\n");
        scanf("%d", &n);
        
        printf("Enter the array elements\n");
        for (i = 0; i < n ; i++)
            scanf("%d", &A[i]);
        printf("reverse elements in array\n");
        for (j = n - 1; j >= 0; j--)
            printf("%d \n",A[j]);
    
  7. Eliminate duplicate elements in an array.
  8. #include<stdio.h>
    int main(){
        int a[10],i,j,k,n;
        printf("Enter size of the array\n");
        scanf("%d",&n);
        printf("Enter Elements of the array:\n");
        for(i=0;i<n;i++){
            scanf("%d",&a[i]);
        }
        printf("Entered element are: \n");
        for(i=0;i<n;i++){
            printf("%d ",a[i]);
        }
        for(i=0;i<n;i++){
            for(j = i+1; j<n; j++){
                if(a[i] == a[j]){
                    for(k = j; k<n; k++){
                        a[k] = a[k+1];
                    }
                    j--;
                    n--;
                }
            }
        }
    printf("\nAfter deleting the duplicate element the Array is:\n");
        for(i=0;i<n;i++){
            printf("%d ",a[i]);
        }
    return 0;
    }
    
  9. Find 2’s complement of the given binary number.
  10. #include<stdio.h>
    int main(){
       char num[10], A[10], B[10],C[10];
       int i,j,k, carry = 1;
       printf("Enter the binary number");
       gets(num);
       for(i = 0; num[i]!= '\0'; i++){
          if(num[i] == '0'){
             A[i] = '1';
          }
          else if(num[i] == '1'){
             A[i] = '0';
          }
       }
       A[i] = '\0';
       printf("1's complement of binary number is %s", A);
       for(j =i - 1; j >= 0; j--){
          if(A[j] == '1' && carry == 1){
             B[j] = '0';
          }
          else if(A[j] == '0' && carry == 1){
             B[j] = '1';
             carry = 0;
          }
          else{
             B[j] = A[j];
          }
       }
       B[i] = '\0';
      // Below code only works if u take all zeros as input 0000
       if(B[0]=='0'&& carry == 1)
          {
          	for(k =0; k<i; k++)
          	{
          		C[k+1]=B[k];
           }
            C[0] = '1';
            C[i+1]='\0';
          printf("\n 2's complement of binary number is %s",C);	 
          }
       else
       {
       printf("\n 2's complement of binary number is %s",B);
       } 
       return 0;
    }
    
Exercise 8: arrays and strings.
  1. Addition of two matrices.
  2. #include<stdio.h>
    int main() {
      int r, c, A[10][10], B[10][10], sum[10][10], i, j;
      printf("Enter the number of rows: ");
      scanf("%d", &r);
      printf("Enter the number of columns: ");
      scanf("%d", &c);
    
      printf("\nEnter elements of A matrix:\n");
      for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
          printf("Enter element a%d%d: ", i + 1, j + 1);
          scanf("%d", &A[i][j]);
        }
    
      printf("Enter elements of 2nd matrix:\n");
      for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
          printf("Enter element b%d%d: ", i + 1, j + 1);
          scanf("%d", &B[i][j]);
        }
    
      // adding two matrices
      for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
          sum[i][j] = A[i][j] + B[i][j];
        }
    
      // printing the result
      printf("\nSum of two matrices: \n");
      for (i = 0; i < r; ++i)
      {
        for (j = 0; j < c; ++j) 
        {
          printf("%d   ", sum[i][j]);
        }  
        printf("\n\n");
      }
    
      return 0;
    }
    
  3. Multiplication of two matrices.
  4. #include<stdio.h>
    #include<conio.h>
    void main()
    {
      int A[50][50],B[50][50],C[50][50],i,j,k,r1,c1,r2,c2,sum=0;
      
      printf("\nInput the rows and columns of first matrix : ");
      scanf("%d %d",&r1,&c1);
      printf("\nInput the rows and columns of second matrix : ");
      scanf("%d %d",&r2,&c2);
      if(c1!=r2){
          printf("Mutiplication of Matrix is not possible.");
          printf("\nColumn of first matrix and row of second matrix must be same.");
      }
      else
          {
           printf("Input elements in the first matrix :\n");
           for(i=0;i<r1;i++)
            {
                for(j=0;j<c1;j++)
                {
    	           printf("element - [%d],[%d] : ",i,j);
    	           scanf("%d",&A[i][j]);
                }
            }   
           printf("Input elements in the second matrix :\n");
           for(i=0;i<r2;i++)
            {
                for(j=0;j<c2;j++)
                {
    	           printf("element - [%d],[%d] : ",i,j);
    	           scanf("%d",&B[i][j]);
                }
            }    
     	 printf("\nThe First matrix is :\n");
      		for(i=0;i<r1;i++)
        		{
          		printf("\n");
          		for(j=0;j<c1;j++)
              	printf("%d\t",A[i][j]);
        		}
      
      	printf("\nThe Second matrix is :\n");
      		for(i=0;i<r2;i++)
        		{
          		printf("\n");
          		for(j=0;j<c2;j++)
          		printf("%d\t",B[i][j]);
        		}
    //multiplication of matrix
          for(i=0;i<r1;i++)
          {
              for(j=0;j<c2;j++)
              {
               C[i][j]=0;
                  for(k=0;k<c1;k++)    
                         {  
                           C[i][j] +=A[i][k]*B[k][j];
                               
                         }
               }
           }
      printf("\nThe multiplication of two matrices is : \n");
      for(i=0;i<r1;i++)
         {
            printf("\n");
            for(j=0;j<c2;j++)
             {
               printf("%d\t",C[i][j]);
             }
         }
      }
    printf("\n\n");
    }
    
  5. Sort array elements using bubble sort.
  6. #include<stdio.h>
    #include<conio.h>
    
    void main()
    {
        int arr1[100];
        int n, i, j, tmp;
    	
    	
           printf("\n\nsort elements of array in ascending order using bubble sort :\n ");
           printf("----------------------------------------------\n");	
    
        printf("Input the size of array : ");
        scanf("%d", &n);
    
           printf("Input %d elements in the array :\n",n);
           for(i=0;i<n;i++)
                {
    	      printf("element - %d : ",i);
    	      scanf("%d",&arr1[i]);
    	    }
    
        for(i=0; i<n; i++)
        {
            for(j=i+1; j<n; j++)
            {
                if(arr1[j] <arr1[i])
                {
                    tmp = arr1[i];
                    arr1[i] = arr1[j];
                    arr1[j] = tmp;
                }
            }
        }
        printf("\nElements of array in sorted ascending order:\n");
        for(i=0; i<n; i++)
        {
            printf("%d  ", arr1[i]);
        }
    	        printf("\n\n");
    }
    
  7. Concatenate two strings without built-in functions.
  8. #include<stdio.h>
    
    int main()
    {
      char str1[10],str2[10],str3[10];
      int i=0,j=0;
      printf("\nEnter First String:");
      gets(str1);
      printf("\nEnter Second String:");
      gets(str2);
      while(str1[i]!='\0')
      {
      str3[i]=str1[i];   
      i++;
      }
      while(str2[j]!='\0')
      {
        str3[i]=str2[j];
        j++;
        i++;
      }
      str3[i]='\0';
      printf("\nConcatenated String is %s",str3);
      return 0;
    }
    
  9. Reverse a string using built-in and without built-in string functions.
  10. With using built-infunction
    #include<stdio.h>
    int main() 
    {
       char str[20] ;
       clrscr();
       printf (“enter a string”);
       gets (str);
       strrev (str);
       printf(“reversed string = %s”,str)
       return 0;
    }
    
    
    
    Without using built-infunction
    #include<stdio.h>
    int main() 
    {
        char str1[20],str2[20],temp;
       int i,j,k,length=0;
       printf("Enter String : ");
       gets(str1);
       for(i=0;str1[i]!='\0';i++)
       {
          length++;
       }
      
       for(j=length-1,k=0;j>=0;j--,k++)
       {
           str2[k]=str1[j];
       }
    	str2[k]='\0';
         printf("Reverse of a string is: %s",str2);
        return 0;
    }
    


Exercise 9: Pointers.
  1. Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using malloc( ) function.
  2. #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>
    int main()
    {
        
        int i, n, sum = 0;
        int *p;
    
        printf("Enter number of elements : ");
        scanf("%d", &n);
        p = (int *)malloc(n * sizeof(int));
        for (i = 0; i < n; i++)
        {
            printf("Enter element %d : ", (i + 1));
            scanf("%d", p + i);
            sum += *(p + i);
    
     }
        printf("sum is %d \n", sum);
        free(p);
        return 0;
    }
    
  3. Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using calloc( ) function. Understand the difference between the above two programs
  4. #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>
    int main()
    {
        
        int i, n, sum = 0;
        int *p;
    
        printf("Enter number of elements : ");
        scanf("%d", &n);
        p = (int *)calloc(n, sizeof(int));
        for (i = 0; i < n; i++)
        {
            printf("Enter element %d : ", (i + 1));
            scanf("%d", p + i);
            sum += *(p + i);
    
     }
        printf("sum is %d \n", sum);
        free(p);
        return 0;
    }
    
  5. Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using realloc( ) function. Understand the difference between the above two programs
  6. #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        int *ptr, i , n1, n2;
        clrscr();
        printf("Enter size: ");
        scanf("%d", &n1);
    
        ptr = (int*) malloc(n1 * sizeof(int));
    
        printf("Addresses of previously allocated memory: ");
        for(i = 0; i < n1; i++)
    	 printf("%u\n",ptr + i);
    
        printf("\nEnter the new size: ");
        scanf("%d", &n2);
    
        // rellocating the memory
        ptr = realloc(ptr, n2 * sizeof(int));
    
        printf("Addresses of newly allocated memory: ");
        for(i = 0; i < n2; i++)
    	 printf("%u\n", ptr + i);
    
        free(ptr);
    
        return 0;
    }
    


Exercise 10: Structures and union.
  1. Write a C program to find the total, average of n students using structures
  2. #include <stdio.h>>
    
    // Define a structure for a student
    struct Student {
        char name[50];
        int marks;
    };
    
    int main() {
        int i,n, total = 0;
        float average;
        struct Student students[10];
        printf("Enter the number of students: ");
        scanf("%d", &n);
    
        // Input student names and marks
        for (i = 0; i < n; i++)
         {
    	printf("Enter name of student %d: ", i + 1);
    	scanf("%s", students[i].name);
    	printf("Enter marks of student %d: ", i + 1);
    	scanf("%d", &students[i].marks);
    	total += students[i].marks;
        }
    
        // Calculate average
        average = (float)total / n;
    
        printf("\nStudent Information:\n");
        printf("Name\t\tMarks\n");
        for (i=0;i<n;i++)
        {
    	printf("%s\t\t%d\n", students[i].name, students[i].marks);
        }
    
        printf("\nTotal marks: %d\n", total);
        printf("Average marks: %.2f\n", average);
    
        return 0;
    }
    
  3. Write a C program to illustrate Union
  4. #include <stdio.h>>
    
    // Define a union for a student
    union Student {
        char name[50];
        int marks;
    };
    
    int main() {
        int i,n, total = 0;
        float average;
        union Student students[10];
        printf("Enter the number of students: ");
        scanf("%d", &n);
    
        // Input student names and marks
        for (i = 0; i < n; i++)
         {
    	printf("Enter name of student %d: ", i + 1);
    	scanf("%s", students[i].name);
        printf("%s\n",students[i].name);
    	printf("Enter marks of student %d: ", i + 1);
    	scanf("%d", &students[i].marks);
        printf("%d\n",students[i].marks);
    	total += students[i].marks;
        }
    
        // Calculate average
        average = (float)total / n;
        printf("\nTotal marks: %d\n", total);
        printf("Average marks: %.2f\n", average);
    
        return 0;
    }
    


Exercise 11: Using functions.
  1. Write a C function to calculate NCR value.
  2. #include <stdio.h>>
     
    int fact(int a);
     
    int 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 a)
    {
        int f = 1, i;
        if (a == 0)
        {
            return(f);
        }
        else
        {
            for (i = 1; i <= a; i++)
    	{
                f = f * i;
    	}
        }
        return(f);
    }
    
  3. Write a C function to find the length of a string.
  4. #include <stdio.h>>
    int length(char str[]);
    int main()
    {
        char str[100];
        int i;
    	
        printf("Enter a string: ");
        scanf("%s", str);
    	printf("The length of the string is: %d\n", length(str));
     return 0;   
    }
    int length(char str[])
    {
    	int i,l = 0;
        for (i = 0; str[i] != '\0'; i++)
        {
            l++;
        }
    
        return l;
    }
    
  5. Write a C function to transpose of a matrix.
  6. #include <stdio.h>>
    void transpose(int A[10][10], int r, int c, int B[10][10])     
    {
        for(int i=0;i<r;i++)     
        {
            for(int j=0;j<c;j++)
            {
                B[j][i]=A[i][j];     
            }
        }
        printf("\nAfter transpose the elements are...\n");
        for(int i=0;i<c;i++)      
        {
            for(int j=0;j<r;j++)
            {
                printf("%d ",B[i][j]);
            }
            printf("\n");
        }
    }
    int main()
    {
        int r,c,A[10][10],B[10][10];                 
        printf("Enter the number of rows and column: \n");
        scanf("%d %d",&r,&c);      
        printf("\nEnter the elements of the matrix: \n");
        for(int i=0;i<r;i++)    
        {
            for(int j=0;j<c;j++)
            {
                scanf("%d",&A[i][j]);
            }
        }
        transpose(A,r,c,B);
        return 0;
    }
    
      


Exercise 12: Using Recursion Function.
  1. Write a recursive function to generate Fibonacci series.
  2. #include <stdio.h>>
    
    int fibonacci(int num)
    {
        if (num == 0)
        {
            return 0; 
        }
        else if (num == 1)
        {
            return 1; 
        }
        else
        {
           return fibonacci(num-1) + fibonacci(num-2); 
        }
    }
    
    int main()
    {
        int num; 
        printf("Enter the number of elements to be in the series : ");
        scanf("%d", &num); 
        int i;
        for (i = 0; i < num; i++)
        {
            printf("%d,",fibonacci(i)); 
        }
    
        return 0;
    }
    
    
  3. Write a recursive function to find the LCM of two numbers.
  4. #include <stdio.h>>
    int lcmCalculate(int a, int b);
     
    int main()
    {
        int n1, n2, lcmOf;
    	printf("\n\n Recursion : Find the LCM of two numbers :\n");
    	printf("----------------------------------------------\n");
        printf(" Input 1st number for LCM : ");
        scanf("%d", &n1);
        printf(" Input 2nd number for LCM : ");
        scanf("%d", &n2);
        if(n1 >  n2)
            lcmOf = lcmCalculate(n2, n1);
        else
            lcmOf = lcmCalculate(n1, n2);
        printf(" The LCM of %d and %d :  %d\n\n", n1, n2, lcmOf);
        return 0;
    }
    int lcmCalculate(int a, int b)
    {
        static int m = 0;
        m += b;
        if((m % a == 0) && (m % b == 0))
        {
            return m;
        }
        else
        {
            lcmCalculate(a, b);
        }
    }
    
    
  5. Write a recursive function to find the factorial of a number.
  6. #include <stdio.h>>
    long int fact(int n);
    int main() {
        int n;
        printf("Enter a positive integer: ");
        scanf("%d",&n);
        printf("Factorial of %d = %ld", n, fact(n));
        return 0;
    }
    
    long int fact(int n) 
    {
        if (n>=1)
            return n*fact(n-1);
        else
            return 1;
    }
    
    


Exercise 13: Simple functions using Call by reference, Dangling pointers.
  1. Write a C program to swap two numbers using call by reference.
  2.   #include <stdio.h>>
        void swap(int *, int *);    
        int main()  
        {  
            int a = 10;  
            int b = 20;   
            printf("Before swapping the values in main a = %d, b = %d\n",a,b); 
            swap(&a,&b);  
            printf("After swapping values in main a = %d, b = %d\n",a,b); 
        }  
        void swap (int *a, int *b)  
        {  
            int temp;   
            temp = *a;  
            *a=*b;  
            *b=temp;  
            printf("After swapping values in function a = %d, b = %d\n",*a,*b); 
        }  
    
  3. Demonstrate Dangling pointer problem using a C program.
  4. #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int *ptr;
        
    	ptr = (int *)malloc(sizeof(int)); 
    
        *ptr = 10;
    // memory block deallocated using free() function
        free(ptr);
        
    // here ptr acts as a dangling pointer
        printf("%d", *ptr);
        
        // prints garbage value in the output console
    
        return 0;
    }
    
  5. Write a C program to copy one string into another using pointer.
  6. #include <stdio.h>
    
    void copy_string(char*, char*);
    
    main()
    {
        char source[100], target[100];    
        printf("Enter source string\n");    
        gets(source);    
        copy_string(target, source);    
        printf("Target string is \"%s\"\n", target);    
        return 0;
    }
    
    void copy_string(char *target, char *source)
    {
        while(*source)
        {
            *target = *source;        
            source++;        
            target++;
        }    
        *target = '\0';
    }
    
  7. Write a C program to find no of lowercase, upper case, digits and other characters using pointers.
  8. #include <stdio.h>
    void stringcount(char *str)
    {
    int i,upper=0,lower=0,digits=0,specialchars=0;
    for(i=0;str[i];i++)  
    {
    if(str[i]>='A' && str[i]<='Z')
    	upper++;
    else if(str[i]>='a' && str[i]<='z') 
    	lower++;
    else if(str[i]>=48 && str[i]<=57)
        digits++;
    else
        specialchars++;
    }
    printf("Upper case letters = %d\n",upper);
    printf("Lower case letters = %d\n",lower);
    printf("Digits = %d\n",digits);
    printf("Special characters = %d", specialchars);
    }
    
    int main()
    {
    char s[100];  
    
    printf("Enter  the string: ");
    gets(s);
        
    stringcount(s);
    }
    


Exercise 14: File handling
  1. Write a C program to write and read text in to a file.
  2. #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
       char str[100];
       FILE *fptr;
    
       fptr = fopen("999.txt","w");
    
       if(fptr == NULL)
       {
          printf("Error!");   
          exit(1);             
       }
    
       printf("Entered data is: ");
       gets(str);
    
       fprintf(fptr,"%s",str);
       
       
       if ((fptr = fopen("999.txt","r")) == NULL){
           printf("Error! opening file");
    
           exit(1);
       }
    
       fscanf(fptr,"%s", str);
    
       printf("data avilable in ext file is n=%s", str);
       fclose(fptr);
    
       return 0;
    }
    
  3. Copy the contents of one file to another file.
  4. #include <stdio.h>
    #include <stdlib.h> // For exit() 
    
    int main() 
    { 
    	FILE *fptr1, *fptr2; 
    	char filename[100], c; 
    
    	printf("Enter the filename to open for reading \n"); 
    	scanf("%s", filename); 
    
    	// Open one file for reading 
    	fptr1 = fopen(filename, "r"); 
    	if (fptr1 == NULL) 
    	{ 
    		printf("Cannot open file %s \n", filename); 
    		exit(0); 
    	} 
    
    	printf("Enter the filename to open for writing \n"); 
    	scanf("%s", filename); 
    
    	// Open another file for writing 
    	fptr2 = fopen(filename, "w"); 
    	if (fptr2 == NULL) 
    	{ 
    		printf("Cannot open file %s \n", filename); 
    		exit(0); 
    	} 
    
    	// Read contents from file 
    	c = fgetc(fptr1); 
    	while (c != EOF) 
    	{ 
    		fputc(c, fptr2); 
    		c = fgetc(fptr1); 
    	} 
    
    	printf("\nContents copied to %s", filename); 
    
    	fclose(fptr1); 
    	fclose(fptr2); 
    	return 0; 
    }
    
    
  5. Find no. of lines, words and characters in a file.
  6. #include <stdio.h>
    #include <stdlib.h>
    
    int main() 
    { 
        FILE *fptr; 
        char ch; 
        int wrd=0,charctr=0,line=0;
        char fname[100];
        printf("\n\n Count the number of words, characters and lines in a file :\n");
    	printf("---------------------------------------------------------\n"); 
    	printf(" Input the filename to be opened : ");
    	scanf("%s",fname);    
    
        fptr=fopen(fname,"r"); 
        if(fptr==NULL) 
         { 
             printf(" File does not exist or can not be opened."); 
          } 
        else 
            { 
              ch=fgetc(fptr); 
              //printf(" The content of the file %s are : ",fname); 
              while(ch!=EOF) 
                { 
                    printf("%c",ch); 
                    if(ch==' '||ch=='\n')
                        { 
                            wrd++; 
                            if(ch=='\n')
                            line++;
                        }
                        else
                        {
                            charctr++; 
                        }
                    ch=fgetc(fptr); 
                }
            printf("\n The number of words in the  file %s are : %d\n",fname,wrd); 
            printf(" The number of characters in the  file %s are : %d\n",fname,charctr);  
    		printf(" The number of lines in the  file %s are : %d\n",fname,line);        
            } 
        fclose(fptr); 
    }
    
    


All The Best

No comments:

Post a Comment