20_10

Write a program in C to convert a decimal number to binary using recursion.

 Source code:

//Write a program in C to convert a decimal number to binary using recursion.


#include<stdio.h>

long convertB_to_D(int decimal)

{

    static long binary,remainder,multiplier = 1;


    if(decimal != 0)

    {

        remainder = decimal % 2;

        binary = binary + remainder * multiplier;

        multiplier = multiplier * 10;

        convertB_to_D(decimal / 2);

    }

    return binary;

}

int main()

{

    long binary;

    int decimal;

printf("Enter a decimal number: ");

    scanf("%d",&decimal); 


    binary = convertB_to_D(decimal);

    printf("The Binary value is : %ld\n", binary);

    return 0;

}

Output:
program in C to convert a decimal number to binary using recursion


Write a program in C to find GCD of two numbers using recursion.

 Source code:

//Write a program in C to find GCD of two numbers using recursion.


#include<stdio.h>

int GCD_cal(int a,int b)

{

    while(a!=b)

    {

        if(a>b)

            return GCD_cal(a-b,b);

        else

            return GCD_cal(a,b-a);

    }

    return a;

}

int main()

{

int num1, num2, gcd;

printf("Enter the first number: ");

scanf("%d",&num1); /*Enter 1st number */

printf("Enter the second number: ");

scanf("%d",&num2); /*Enter 2nd number */


  gcd = GCD_cal(num1,num2);

  printf("The GCD of %d and %d is: %d\n",num1,num2,gcd);

  return 0;

}

Output:

program in C to find GCD of two numbers using recursion


Write a program in C to count the number of digits of a given number using recursion.

 Source code:

//Write a program in C to count the number of digits of a given number using recursion. 


#include<stdio.h>

int noOfDigits(int n)

{

    static int digit=0;


    if(n!=0)

    {

        digit++;

        noOfDigits(n/10);

    }


    return digit;

}

int main()

{

  int n,digit;

    printf("Enter a number: ");

    scanf("%d",&n); /*Enter Number of digits */


    digit = noOfDigits(n);


    printf("The number of digits in the number is :  %d\n",digit);

    return 0;

}

Output:
count the number of digits of a given number using recursion


Write a C program to print the solution of the series f(n)= (1) + (2*3) + (4*5*6) ... upto n terms using recursion.

 Source code:

/* Program to print the solution of the series  f(n)= (1) + (2*3) + (4*5*6) ... upto n terms using recursion.*/


#include <stdio.h>

int seriesSum(int calculated, int current, int N)

{

    int i, cur = 1;

    // checking termination condition

    if (current == N + 1)

        return 0;


    // product of terms till current

    for (i = calculated; i < calculated + current; i++)

        cur *= i;


    // recursive call for adding terms next in the series

    return cur + seriesSum(i, current + 1, N);

}

int main()

{

    int N;

    printf("Enter the nth term: ");

    scanf("%d", &N); /* Enter number to terms N to be calculated */

    /* Write the function int seriesSum(int calculated, int current, int N) which finds the sum of the series

using recursion.  calculated - number of terms till which sum of terms has 

been calculated; current - number of terms for which sum has to be calculated; N - Number of terms in the function to be calculated */

    printf("The result of the series is: %d\n", seriesSum(1, 1, N));

    return 0;

}

Output:
C program to print the solution of the series  f(n)= (1) + (2*3) + (4*5*6) ... upto n terms using recursion


Write a C program to calculate factorial of a number using recursion.

 Source code:

//Write a C program to calculate factorial of a number using recursion.


#include<stdio.h>

int factorial(int n)

{

    if(n==0)

        return 1;

    else

        return (factorial(n-1)*n);

}

int main()

{

    int num,f;

    printf("Enter a number: ");

    scanf("%d",&num);/*Enter the number whose factorial to be found*/

    f=factorial(num); 

/*Write the factorial(num) function which calculates the function in recursive method and returns f */

    printf("Factorial of %d = %d",num,f);

    return 0;

}

Output:
C program to calculate factorial of a number using recursion


Write a C program to insert an element / item in the sorted array.

 Source code:

/*Write a C program to insert an element / item in the sorted array.  */


#include<stdio.h>

int main( )

{

  int a[20],n=10,item,i;

    printf("Enter the sorted array: ");

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

    {

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

    }

    printf("Enter the item which to be inserted in the array: ");

    scanf("%d", &item);

i = n-1;

    while(item<a[i] && i>=0)

    {

           a[i+1] = a[i];

           i--;

    }

    a[i+1] = item;

    n++;

printf("ITEM to be inserted:%d\n",item);

printf("After insertion array is:\n");

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

    {

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

    }

    return 0;

}

Output:
C program to insert an element or item in the sorted array


Write a C program to find a root of the equation a*x*x + b*x +c using Bi Section method.

 Source code:

/*Numerical Method: Bi Section method to find a root of the equation a*x*x + b*x +c.  The program read should the values of a,b and c and values for starting left and right points. */


#include <stdio.h>

#include <math.h>

double myFunction(double x, double a, double b,double c)

{

  return a*x*x + b*x +c;

}

int main(void){

double a,b,c;

double leftpt, rightpt, midpt, epsilon = .0000001;

double midvalue, rtvalue, root;

printf("Enter the value of 'a','b' and 'c': ");

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

printf("Enter the value of left and right point: ");

scanf("%lf %lf", &leftpt, &rightpt);

do {

        midpt = (leftpt + rightpt)/2;

        rtvalue = myFunction(rightpt,a,b,c);

        midvalue = myFunction(midpt,a,b,c);

        if (rtvalue * midvalue >= 0)

            rightpt = midpt;

        else 

leftpt  = midpt;

} while ((rightpt - leftpt) > epsilon);


root = (rightpt+leftpt)/2;

printf("Root for equation%5.2lf*x**2+%5.2lf*x+%5.2lf is",a,b,c);

printf("%5.2lf\n",root);

return 0;

}

Output:

C program to find a root of the equation using Bi Section method


Write a C program which will generate Fibonacci sequence using recursive function printFibonacci(int n).

 Source code:

/*A recursive procedure or routine is one that has the ability to call itself. Consider a C program which will generate Fibonacci sequence using function printFibonacci(int n). The sequence is characterized by the fact that every number after the first two is the sum of the two preceding ones. By definition, the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two. Here the default is 0,1. So in case of input range 10 it will generate 12 numbers. */


#include<stdio.h>

void printFibonacci(int n){


    static int first=0,second=1,sum;


    if(n>0){

        sum = first + second;

        first = second;

        second = sum;

        printf("%d ",sum);

        printFibonacci(n-1);

    }

}

void printFibonacci(int);


int main(){

    int k,n;

    long int i=0,j=1,f;

    printf("Enter the nth term: ");

    scanf("%d",&n);


printf("%d %d ",0,1);

printFibonacci(n);

    return 0;

}

Output:
C program which will generate Fibonacci sequence using recursive function


Write a program in C to add two numbers using pointers.

 Source code:

/*Write a program in C to add two numbers using pointers. You have to write the fsum() function which accepts the address of two variables and returns the sum of their values to the main function. */


#include <stdio.h>

int fsum(int *n1, int *n2)

{

int sum = 0;

sum = *n1 + *n2;

return(sum);

}

int main()

{

   int no1, no2, sum;

 

   printf(" Input the first number : ");

   scanf("%d", &no1);

   printf(" Input the second  number : ");

   scanf("%d", &no2);   

 

   printf("The sum of the entered numbers is : %d\n",fsum(&no1,&no2));

   return 0;

}

Output:

add two numbers using pointers


Write a C program to swap two integers using pointers.

 Source code:

/*Write a C program to swap two integers using pointers. You have to write a swap function that will accept the address of two integer and swap their values.  */


#include <stdio.h>

void swap(int *a,int *b)

{

    int t;

     t   = *a;

    *a   = *b;

    *b   =  t;

}

int main()

{

    int num1,num2;

    printf("Enter 1st number: ");

    scanf("%d",&num1); /*Enter value of num1 */

    printf("Enter 2nd number: ");

    scanf("%d",&num2); /*Enter value of num2 */

     

    swap(&num1,&num2);

     

    /*print values after swapping */

    printf("num1=%d, num2=%d\n",num1,num2);    

    return 0;

}

Output:

C program to swap two integers using pointers


Write a C Program to find if the given square matrix is skew symmetric or not.

 Source code:

/*A Matrix whose Transpose is negative to that of the original Matrix, it is known as a Skewed Symmetric Matrix. Write a C Program to find if the given square matrix is skew symmetric or not. 

Ex. A^T = -A*/


#include<stdio.h>

void tranpose();

void getmatrix();

int check();

 

int m, n, rows, columns;

int matrix[3][3], transpose[3][3];

void tranpose()

{

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

    {

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

        {

            transpose[columns][rows] = matrix[rows][columns];

        }

    }

}

 

void getmatrix()

{

printf("Enter a matrix:\n");

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

    {

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

        {

            scanf("%d", &matrix[rows][columns]);

        }

    }

}

 

int check()

{

    if(m == n)

    {

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

        {

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

            {

                if(matrix[rows][columns] != -transpose[rows][columns])

                {

                    break;

                }

            }

            if(columns != m)

            {

                break;

            }

        }

    if(rows == m)

        {

            return 0;

        }

    }

    else

    {

        return 1;

    }

}

int main()

{

    int x;

    printf("Enter the number of row:");

    scanf("%d", &m); /*Enter the Number of Rows: */

    printf("Enter the number of column:");

    scanf("%d", &n); /*Enter the Number of Columns: */

    getmatrix();  /*Get the Elements of the Square Matrix from input case */

    tranpose(); /*Function to perform transpose of the matrix */

    x = check(); /*To check if the matrix is a skewed symmetric matrix */

    if(x == 0)

    {

        printf("The Entered Matrix is A Skewed Symmetric Matrix\n");

    }

    else

    {

        printf("The Entered Matrix is Not A Skewed Symmetric Matrix\n");

    }

    return 0;

}

Output:
C Program to find if the given square matrix is skew symmetric or not




Write a C program which will sort number of elements in an ascending by using bubble sort using pointer.

 Source code:

/*Write a C program which will sort number of elements in an ascending by using bubble sort. We will rewrite the algorithm by using pointer. Read 5 elements and sort in ascending order. */


#include<stdio.h>

void bubble(int *ptr,int s)

{

int i,j;

int temp;

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

  {

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

    {

    if(*(ptr+j)>*(ptr+j+1))

    {

      temp=*(ptr+j);

      *(ptr+j)=*(ptr+j+1);

      *(ptr+j+1)=temp;

    }

    }

}

}

int main()

{

int arr[10];

int i;

int size=5;

/* Read Array Elements */

printf("Enter 10 elements: ");

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

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

 

bubble(arr,size);

printf("The sorted elements:\n");

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

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

return 0;

}

Output:
C program which will sort number of elements in an ascending by using bubble sort using pointer


Write a C program which sort strings in lexicographical order.

 Source code:

//Write a C program which sort strings in lexicographical order.


#include<stdio.h>

#include <string.h>

int main()

{

    int i, j;

    char str[10][50], temp[50];

printf("Enter a string: ");

    /* Read 10 elements */

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

        scanf("%s[^\n]",str[i]);

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

        for(j=i+1; j<10 ; ++j)

        {

            if(strcmp(str[i], str[j])>0)

            {

                strcpy(temp, str[i]);

                strcpy(str[i], str[j]);

                strcpy(str[j], temp);

            }

        }

printf("In Lexicographical Order\n");

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

    {

        puts(str[i]);

    }

    return 0;

}

Output:
C program which sort strings in lexicographical order


Write a C program to pass multidimensional array to a function as it's parameter.

 Source code:

/*Consider a program, of passing multidimensional array to a function. Consider an two dimensional array of size 3x3 and write a function. Write a function displayarray() by passing two dimensional array as it's parameter.*/


#include<stdio.h>

void displayarray(int arr[3][3]);

void displayarray(int arr[3][3])

{

    int i, j;

    printf("The complete array is");

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

    {

        printf("\n");

                 

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

        {

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

        }

    }

}

int main()

{

    int arr[3][3], i, j;

    /* Read 9 elements */    

    printf("Enter a matrix:\n");

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

    {

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

        {

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

        }

    }

   /* passing the array as argument */

    displayarray(arr);

    return 0;

}

Output:
C program to pass multidimensional array to a function as it's parameter


Write a C program to find average using findavg() function.

Source code:

 /*Consider the function find average findavg() , which takes an array as an argument along with another argument and based on the passed arguments and it returns the average of the numbers passed through the array. Consider an array of size 10. It reads 5 marks and find the average.  */


#include<stdio.h>

int findavg(int marks[]);

int findavg(int marks[])

{

    int i, sum = 0;

    int avg;

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

        sum += marks[i];

    }

    avg = (sum / 5);

    return avg;

}

int main()

{

    int avg; int marks[10];int i;int n=5;

    /* Read Marks*/

    printf("Enter marks of 5 subject: ");

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

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

    avg = findavg(marks);

    printf("Average=%d", avg);

    return 0;

}

Output:

C program to find average using findavg() function


Write a C program to find out the Sum of the diagonal elements of a matrix.

 Source code:

/*Write a C program to find out the Sum of the diagonal elements of a matrix. Consider a matrix as below:

1 2 3

4 5 6

7 8 9

The Sum of the diagonal elements of the above matrix is 15. */


#include<stdio.h>

int main(){

  int a[3][3],i,j,sum=0,m=3,n=3;


  /* Read the elements of the Matrix a */

printf("Enter a matrix:\n");

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

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

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

  

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

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

          if(i==j)

              sum=sum+a[i][j];

      }

  }

printf("Sum of the Diagonal elements of the matrix=%d",sum);

  return 0;

}

Output:

C program to find out the Sum of the diagonal elements of a matrix


Write a C program to find the transpose of a given matrix.

 Source code:

 /*Write a C program to find the transpose of a given matrix. The transpose of a matrix is a new matrix whose rows are the columns of the original. This makes the columns of the new matrix the rows of the original. Consider a matrix of size 3x3. */

 

#include<stdio.h>

int main(){

  int a[3][3],b[3][3],i,j,k=0,m=3,n=3;


  /* Read an Array a*/

  printf("Enter a matrix:\n");

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

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

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

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

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

          b[i][j]=0;

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

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

            b[i][j]=a[j][i];

      }

  }

printf("Transpose of a Matrix");

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

      printf("\n");

      for(j=0;j<m;j++){

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

      }

  }

  return 0;

}

Output:

C program to find the transpose of a given matrix


Write a C program to perform Multiplication of two matrixes.

 Source code:

/*Multiplication of two matrixes. It is only possible if the first matrix of size i x j and other matrix of size j x k , where I, j and k are any positive integer. Three two dimensional matrices a, b and c each of size [3x3] will be considered here. Read the values of matrix a and matrix b, multiply and put it matrix c. Finally print the value of matrix c. */


#include<stdio.h>

int main()

{

  int a[3][3],b[3][3],c[3][3],i,j,k,sum=0,m=3,n=3,o=3,p=3;

printf("Enter 1st matrix: \n");

/* Read Matrix a */

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

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

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


printf("Enter 2nd matrix: \n");

/* Read Matrix b */

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

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

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

           

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

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

            c[i][j]=0;

      for(i=0;i<m;i++){ /* row of first matrix */

      for(j=0;j<p;j++){  /* column of second matrix */

            sum=0;

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

                sum=sum+a[i][k]*b[k][j];

            c[i][j]=sum;

      }

      }

printf("The multiplication of two matrix is");

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

      printf("\n");

      for(j=0;j<p;j++){

          printf("%d ",c[i][j]);

      }

  }

  return 0;

}

Output:

C program to perform Multiplication of two matrixes


Write a C program which find the student name who obtain the highest marks.

Source code:

//Consider the following program statement:

/*One needs to first input a set of N number of ALPHABETIC Strings each representing a name of a student in an array studname [N] . Assume each string can be Max. 40 Character Long. Subsequently , one needs to input Marks obtained by those students in another array marks [N] . Assume that studname [I] i.e. ith student in the list of student names has obtained Marks [I] in the Marks List.  You need to find out and print the Max Marks obtained by a student and also print the name of the student who has obtained this marks. Considering here both the arrays of size 5. */


#include <stdio.h>

#include <string.h>

typedef char st[10];

int main ()

{

    st studname[10];

    int marks[10];

    int i; int n=5; int imaxpos=1;

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

    {

    printf("Enter name of %d : ",i);

        scanf("%s", studname[i]);

    }

        

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

    {

    printf("Enter marks of %d : ",i);

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

    }


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

    {

        if (marks [i]  > marks [imaxpos] )

        {

            imaxpos = i;

        }

    }

printf ("The largest marks=%d\nObtained by student : %d Name: %s\n", marks[imaxpos] , imaxpos, studname[imaxpos]);

    return(0);

}

Output:

C program which find the student name who obtain the highest marks


Write a C program to sort an array using Bubble sort.

 Source code:

/*Bubble sort is a sorting algorithm that works by repeatedly stepping through lists that need to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. This passing procedure is repeated until no swaps are required, indicating that the list is sorted. Bubble sort gets its name because smaller elements bubble toward the top of the list. Consider an array of size 10. It will be filled it by reading 10 integers. The final output will be sorted output in Ascending Order. */


#include <stdio.h>

int main()

{

  int array[10], n=10, i, j, swap;


 /* Read array elements */

printf("Enter the array: ");

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

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

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

  {

    for (j = 0 ; j < n - i - 1; j++)

    {

      if (array[j] > array[j+1]) /* For decreasing order use < */

      {

        swap       = array[j];

        array[j]   = array[j+1];

        array[j+1] = swap;

      }

    }

  }

printf("Sorted list in ascending order:\n");


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

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

  return 0;

}

Output:
C program to sort an array using Bubble sort


Write a C program to sort an array using Insertion sort.

 Source code:

/*Insertion sort is a sorting algorithm in which the elements are transferred one at a time to the right position. Here the first element in the array is considered as sorted, even if it is an unsorted array. Then each element in the array is checked with the previous elements, resulting in a growing sorted output list. With each iteration, the sorting algorithm removes one element at a time and finds the appropriate location within the sorted array and inserts it there. The iteration continues until the whole list is sorted. First an array of size 10 will be taken. We will fill it by reading 10 integers. You need to write the logic of Selection Sort. The final output will be sorted output in Ascending Order.*/


#include <stdio.h>

int main()

{

  int n=10, array[10], i, j, t;


  /* Read Array Elements*/

printf("Enter the array: ");

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

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

  }

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

    j = i;


    while ( j > 0 && array[j-1] > array[j]) {

      t = array[j];

      array[j] = array[j-1];

      array[j-1] = t;

    j--;

    }

}

printf("The sorted output in ascending order:\n");

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

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

  }

  return 0;

}

Output:
C program to sort an array using Insertion sort


Write a C program to sort an array using Selection Sort.

Source code:

 /*The Selection Sort works by finding the smallest unsorted item in the list and swapping it with the item in the current position. The algorithm works as follows:

1. Set first position as current position.

2. Find the minimum value in the list

3. Swap it with the value in the current position

4. Set next position as current position

5. Repeat Steps 2-4 until you reach end of list 


First an array of size 10 will be taken. We will fill it by reading 10 integers. The final output will be sorted output in Ascending Order.*/


#include <stdio.h>

int main()

{

    int array[10], n=10, i, j, index, swap;


   /* Read Array Elements */

printf("Enter the array:");

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

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

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

    {

    index = i;

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

        {

        if ( array[index] > array[j] )

            index = j;

        }

      if ( index != i )

      {

        swap = array[i];

        array[i] = array[index];

        array[index] = swap;

        }

    }

printf("The sorted output in ascending order:\n");

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

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

    return 0;

}

Output:
C program to sort an array using Selection Sort


Write a C program to search a number in an array using Linear search algorithm.

Source code:

 /*A Linear search is a searching algorithm which is used to find whether a given number is present in an array. It is also known as sequential search. It is straightforward and keep on comparing each element with the element to search until it is found or the list ends. First an array of size 10 will be taken. We will fill it by reading 10 integers. Then the key integer to be searched will be given as input.   The test case total number of values are 11. The first 10 values are to fill up the array. If it is found then output would return it and it's position.  */


#include <stdio.h>

int main()

{

    int array[10], search, i, n=10;


  /* Read array */

printf("Enter the array:");

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

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


  /* Read the interger to be searched */

printf("Enter the search element:");

    scanf("%d", &search);

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

    {

    if (array[i] == search)     /* if required element found */

        {

        printf("%d is found at position %d.", search, i+1);

          break;

      }

    }

    if (i == n)

    printf("%d is not there in the array.", search);

return 0;

}

Output:

C program to search a number in an array using Linear search algorithm




Write a C program to search a number in an array using Binary search algorithm.

 Source code:

/*A Binary search is an efficient algorithm for finding an item from an ordered list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until it is narrowed down the possible locations to just one. First an array of size 10 will be taken. We will fill it by reading 10 integers. Then the key integer to be searched will be given as input.  */


#include <stdio.h>

int main()

{

int i, n=10, first, last, middle, search, array[10];


   /* Fill Array */

    printf("Enter the array: ");

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

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


   /* Read the value of the integer to be searched */

printf("Enter the number which to be search:");

    scanf("%d", &search);

    first = 0;

    last = n - 1;

    middle = (first+last)/2;


    while (first <= last) {

        if (array[middle] < search)

        first = middle + 1;

        else if (array[middle] == search) {

        printf("%d found at position %d.", search, middle+1);

        break;

      }

      else

          last = middle - 1;


      middle = (first + last)/2;

    }

    if (first > last)

    printf("%d is not there in the list.", search);

return 0;

}

Output:



Write C code to check the number is a Perfect Number. A function isPerfect is used here.

 Source code:

/*A perfect number is a positive integer which is equal to the sum of it's positive divisors excluding the number itself e.g 6 is first perfect number because it's proper divisors are 1,2 and 3 so sum 1+2+3=6.  Using a function, write C code to check the number is a Perfect Number. A function isPerfect is used here.  */


#include <stdio.h>

int isPerfect(int num);

int isPerfect(int num)

{

    int i, sum, n;

    sum = 0;

    n = num;


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

    {

        /* If i is a divisor of num */

        if(n%i == 0)

        {

            sum += i;

        }

    }

    return (num == sum);

}


int main()

{

int num;

printf("Enter a number:");

    scanf("%d", &num);

    

    if(isPerfect(num))

    {

        printf("%d is Perfect Number", num);

    }

    else

    {

        printf("%d is not Perfect Number", num);

    }

    return 0;

}

Output:


Write a C code to read a number and check whether it is prime. A function isPrime() is used here.

 Source code:

/A Prime number is a natural number greater than 1 which has no positive divisors other than 1 and itself. Write a C code to read a number and check whether it is prime. A function isPrime() is used here.*/

#include <stdio.h>

int isPrime(int num);

int isPrime(int num)

{

    int i;

    for(i=2; i<=num/2; i++)

    {

      /* If the number is divisible by any number

         other than 1 and self then it is not prime */


        if(num%i == 0)

        {

            return 0;

}

    }

    return 1;

}


int main()

{

    int num;

printf("Enter a number:");

    scanf("%d", &num);

    

    if(isPrime(num))

    {

        printf("%d is Prime Number", num);

    }

    else

    {

        printf("%d is not Prime Number", num);

    }

return 0;

}

Output:

C code to read a number and check whether it is prime


Write a C code to add and subtract two one dimensional array of size 5 using function addarray() and subtractarray().

 Source code:

/*Write a C code to add and subtract two one dimensional array of size 5 using function addarray() and subtractarray().*/

#include<stdio.h>

#define size 5

void readarraya(int a[],int );

void readarrayb(int b[],int );

void addarray(int a[],int b[],int add[], int );

void subarray(int a[], int b[], int sub[], int );

void printarrayadd(int add[], int );

void printarraysub(int sub[], int );

void readarraya(int a[],int n)

{

    int i;

    printf("Enter the value of the array 'a':");

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

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

}

void readarrayb(int b[],int n)

{

    int i;

    printf("Enter the value of the array 'b':");

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

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

}

 void addarray(int a[],int b[],int add[],int n)

{

    int i;

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

        add[i]=a[i]+b[i];

}

void subarray(int a[],int b[],int sub[],int n)

{

    int i;

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

        sub[i]=a[i]-b[i];

void printarrayadd (int add[],int n)

    int i;

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

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

}           

void printarraysub (int sub[],int n)

{

  int i;

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

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

}

int main()

{

    int i,n;

    int a[size],b[size],add[size],sub[size];

       

    /* Read Array a */

    readarraya(a,size);


    /* Read Array b */   

    readarrayb(b,size);


    /* add two arrays*/

    addarray(a,b,add,size);


    /* subtract two arrays*/

    subarray(a,b,sub,size);


    printf("After adding\n");

    printarrayadd(add,size);


    printf("After subtracting\n");

    printarraysub(sub,size);


    return 0;

}

Output:

C code to add and subtract two one dimensional array using function


Write a C code to compare two strings.

 Source code:

/*Write a C code to compare two strings e.g. str1 and str2 and check whether strings are equal and str1 is greater than str2 or less, without using standard string library. */

#include <stdio.h>

#include <string.h>

int main(){

    char str1[20],str2[20];

    int c=0,d=0;

printf("Enter 1st string:");

    //Read String 1

    scanf("%s", &str1);

printf("Enter 2nd string:");

    //Read String 2

    scanf("%s", &str2);

int i=0;

while (str1[i] != '\0')

{

c++;

i++;

}

i=0;

while (str2[i] != '\0')

{

d++;

i++;

}

if (c==d)

{

        printf ("Strings are equal");

}

else if (c>d)

{

        printf ("String 1 is greater than String 2");

}

else

{

        printf ("String 1 is less than String 2");

}

return 0;

}

Output:
C code to compare two strings e.g. str1 and str2 and check whether strings are equal and str1 is greater than str2 or less, without using standard string library


Write a C code to concatenate two strings.

Source code:

 //Write a C code to concatenate two strings

#include <stdio.h>

#include <string.h>

int main(){

    char str1[20],str2[2];

    printf("Enter 1st string:");

    //Read String 1

    scanf("%s", str1);

printf("Enter 2nd string:");

    //Read String 2

    scanf("%s", str2);

int i,j,temp;

i=j=0;

while (str1[i] != '\0')

        i++;

    for (j = 0; str2[j] != '\0'; i++, j++)

      str1[i] = str2[j];

    str1[i] = '\0';

printf("The concatenated output:%s",str1);

return 0;

}

Output:

C code to concatenate two strings


Write a C code to reverse a string without using any string library functions.

 Source code:

/*Write a C code to reverse a string without using any string library functions , e.g. '12345' should be '54321'. */

#include <stdio.h>

#include <string.h>

int main(){

    char str[20];

printf("Enter a string:");

    //Read String

    scanf("%s", str);

int temp;

int i=0,j=0,length;


while (str[j] != '\0')

        j++;

        j--;

    while (i<j) {

        temp=str[i];

        str[i]=str[j];

        str[j]=temp;

        i++;

        j--;

}

printf("The reverse string:%s",str);

return 0;

}

Output:

C code to reverse a string without using any string library functions


Write a C code to check whether a given string is palindrome or not.

Source code:

 /*A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, e.g. madam 123321 etc. Write a C code to check whether a given string is palindrome or not. */

#include <stdio.h>

#include <string.h>

int main(){

    char string[20];

    int flag = 0;

    printf("Enter a string:");

    //Read a String

    scanf("%s", string);

int i, length; 

length = strlen(string);

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

        if(string[i] != string[length-i-1]){

            flag = 1;

            break;

    }

}

  if (flag) {

        printf("The given string %s is not palindrome", string);

    }

    else {

        printf("The given string %s is palindrome", string);

    }

    return 0;

}

Output:

C code to check whether a given string is palindrome or not


Write a C code to find the difference between two matrices of any order and print the result in matrix format.

 Source code:

/*Write a C code to find the difference between two matrices of any order and  print the result in matrix format.*/

#include <stdio.h>

int main()

{

        int row, col, i, j, first[10][10], second[10][10], difference[10][10]; 

printf("Enter the number of row & column:");

        scanf("%d %d", &row, &col);  

printf("Enter the 1st matrix:\n");

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

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

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

  printf("Enter the 2nd matrix:\n");

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

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

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

/* Find the difference of entered matrices and store it in difference[10][10] */

 

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

    for (j = 0; j < col; j++) {

        difference[i][j] = first[i][j] - second[i][j];

     

    }

/*printing the difference array */

printf("Subtraction of two matrix is:\n");

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

{

    for (j = 0 ; j < col; j++){

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

}

printf("\n");

    }

return 0;

}

Output:

C code to find the difference between two matrices of any order and  print the result in matrix format


Write a C program to count total number of vowel or consonant in a string.

Source code:

//Write a C program to count total number of vowel or consonant in a string 

#include <stdio.h>

#include <string.h>

int main()

{

    char s[1000],ch;

    int i=0, vowel, consonant;

    printf("Enter your sentence:");

    while(ch != '\n')    /* terminates if user hit enter */

    {

        ch = getchar();

        s[i] = ch;

        i++;

    }

    s[i-1] = '\0';       /* inserting null character at end */

int len;

vowel = 0;

    consonant = 0;

    len = strlen(s);


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

    {

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

        {


            if(s[i] =='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u' ||

               s[i] =='A' || s[i]=='E' || s[i]=='I' || s[i]=='O' || s[i]=='U'  )

                vowel++;

            else

                consonant++;

        }

    }

printf("Total number of vowel = %d\n", vowel);

    printf("Total number of consonant = %d\n", consonant);

return 0;

}

Output:

C program to count total number of vowel or consonant in a string


Write a C program to find the transpose of a matrix.

Source code:

 //Write a C program to find the transpose of a matrix 

#include <stdio.h>

int main()

{

int array1[10][10], array2[10][10];

int i,j,row,col;

printf("Enter the number of row:");

scanf("%d",&row); 

printf("Enter the number of column:");

scanf("%d",&col); 

  printf("Enter the matrix:\n");

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

    {

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

        {

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

        }

    }

 /*Transpose a matrix */

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

    {

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

        {

            array2[i][j] = array1[j][i];    /*exchange elements*/

        }

    } 

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

    {

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

        {

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

        }

printf("\n");

    }

    return 0;

}

Output:
C program to find the transpose of a matrix


Write a C program to find number of blank space in a sentence(Do not use the strlen() function).

Source code:

 //Write a C program to find number of blank space in a sentence

#include <stdio.h>

int main()

{

    char s[1000], ch;

    int i = 0, count=0; /*i is array index and count is to count blank */

printf("Enter your sentence:");

    while(ch != '\n')    /* terminates if user hit enter */

    {

        ch = getchar();

        s[i] = ch;

        i++;

    }

    s[i-1] = '\0';       /* inserting null character at end */

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

    {

    if (s[i] == ' ')

    count += 1; 

    }   

    

printf("No. of blank space = %d", count);

return 0;

}

Output:

C program to find number of blank space in a sentence


Write a C program to count frequency of each element of an array.

 Source code:

/*Write a C program to count frequency of each element of an array. Frequency of a particular element will be printed once.*/

#include <stdio.h>

int main()

{

    int arr[50], freq[50]; /* Array arr[50] stores the elements and freq[50] stores the no. of times the element occurs */

    int size, i, j, count;

printf("Enter the size of array:");

    scanf("%d", &size);


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

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

    {

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

        freq[i] = -1; 

/* all frequencies are initialized to -1 which will be changed to specific value after counting no. of occurrence */

/* for the element which is already counted the corresponding frequency will be made 0 */ 

    }

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

    {

        count = 1;

        for(j=i+1; j<size; j++)

        {

            /* If duplicate element is found */

            if(arr[i]==arr[j])

            {

                count++;

                /* Make sure not to count frequency of same element again */

                freq[j] = 0;

            }

        }


        /* If frequency of current element is not counted */

        if(freq[i] != 0)

        {

            freq[i] = count;

        }

    }


   /* Print frequency of each element */


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

    {

        if(freq[i] != 0) /* The element with corresponding frequency 0 means duplicate occurrence of the element */

        {

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

        }

    }

return 0;

}

Output:
C program to count frequency of each element of an array


Write a C program which reads a square matrix a[n][n] and print only the elements that falls in the diagonal starting from a[0][0] to a[n][n] and all other elements printed as 0 (zero).

 Source code:

/*Write a C program which reads a square matrix a[n][n] and print only the elements that falls in the diagonal starting from a[0][0] to a[n][n] and all other elements printed as 0 (zero).*/

#include<stdio.h>

int main()

{

int n, i, j;

int a[10][10];

printf("Enter the number of row = column:");

scanf("%d", &n); /*Number of Rows = Column = n */

printf("Enter the matrix:\n");

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

{

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

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

}

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

{

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

{

if(i!=j)

a[i][j]=0;

}

}

/* printing the matrix in matrix format*/

printf("The diagonal matrix is:\n");

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

{

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

printf("%d\t",a[i][j]); /* print the row elements with one tab space */

printf("\n");

}

return 0;

}

 Output:

C program to make a diagonal matrix


Write a C code which computes and prints the sum of each rows of a 2D Matrix.

 Source code:

//Write a C code which computes and prints the sum of each rows of a 2D Matrix. 

#include <stdio.h>

int main()

{

    int matrix[10][10];

    int i,j,r,c; 

    int sum[10]; /* Sum of each row is kept in this array */

printf("Enter the number of row:\n");

    scanf("%d",&r); /* Input no. of rows */

printf("Enter the number of column:\n");

    scanf("%d",&c); /* Input no. of columns */

printf("Enter the matrix:\n");

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

    {

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

        {

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

        }

    }

    /*sum of all rows*/

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

    {

    sum[i]=0;

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

        {

            sum[i] = sum[i] +  matrix[i][j];

        }

    }

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

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

return 0;

}

Output:

C code which computes and prints the sum of each rows of a 2D Matrix


Write a program in C to convert a decimal number to binary using recursion.

 Source code: //Write a program in C to convert a decimal number to binary using recursion. #include<stdio.h> long convertB_to_D(int d...