This blog is under construction
Showing posts with label Function programs. Show all posts
Showing posts with label Function programs. Show all posts

Saturday, 6 July 2013

C program to calculate mean and variance using functions

Write a C program to calculate mean and variance using functions.


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

  /* calculates mean and variance */
  void calculateMeanVariance() {
        float *x, mean = 0, sd, variance;
        int temp, num, i, j;

        /* get the number of entries from user */
        printf("Enter the no of entries:");
        scanf("%d", &num);
        x   = (float *)malloc(sizeof (float) * num);

        /* get n inputs from user */
        printf("Enter your inputs:\n");
        for (i = 0; i < num; i++)
                scanf("%f", &x[i]);

        /* calculate the mean */
        for (i = 0; i < num; i++)
                mean = mean + x[i];
        mean = mean / num;

        /* calculate the varianceiance*/
        for (i = 0; i < num; i++)
                variance = variance + pow((x[i] - mean) , 2);

        variance = variance / num;
        printf("Variance: %f\n", variance);
        printf("Mean: %f\n", mean);
        return;
  }

  int main() {
        calculateMeanVariance();
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the no of entries:5
  Enter your inputs:
  10
  20
  30
  40
  50
  Variance: 200.000000
  Mean: 30.000000



C program to merge two arrays and sort the elements

Write a C program to merge two arrays and sort the elements in merged array.


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

  /* merges two input arrays and sorts the elements in merged array */
  void mergeTwoArrays(int *arr1, int *arr2, int *arr3, int n1, int n2) {
        int temp, n, i, j = 0;

        n = n1 + n2;

        /* merging two arrays */
        for (i = 0; i < n1; i++)
                arr3[j++] = arr1[i];

        for (i = 0; i < n2; i++)
                arr3[j++] = arr2[i];

        /* sorting elements in merged array */
        for (i = 0; i < n - 1; i++) {
                temp = arr3[i];
                for (j = i; j < n; j++) {
                        if (temp > arr3[j]) {
                                temp = arr3[j];
                                arr3[j] = arr3[i];
                                arr3[i] = temp;
                        }
                }
        }
        return;
  }

  int main() {
        int *arr1, *arr2, *arr3, n1, n2, i;

        /* get the no of elements for array1 and array2 */
        printf("Number of elements in first array:");
        scanf("%d", &n1);
        printf("Number of elements in second array:");
        scanf("%d", &n2);

        /* allocate memory to store the input elements */
        arr1 = (int *)malloc(sizeof(int) * n1);
        arr2 = (int *)malloc(sizeof(int) * n2);

        /* allocate memory to store the elements of both arrays */
        arr3 = (int *)malloc(sizeof(int) * (n1 + n2));

        /* get the input for array1 */
        printf("Enter the values for Array1:\n");
        for (i = 0; i < n1; i++) {
                printf("Array1[%d]: ", i);
                scanf("%d", &arr1[i]);
        }

        /* get the input for array2 */
        printf("\nEnter the values for Array2:\n");
        for (i = 0; i < n2; i++) {
                printf("Array2[%d]: ", i);
                scanf("%d", &arr2[i]);
        }

        /* merging two arrays and sort the element */
        mergeTwoArrays(arr1, arr2, arr3, n1, n2);

        /* print the resultant array */
        printf("\nOutput Array:\n");
        for (i = 0; i < (n1 + n2); i++) {
                printf("%d  ", arr3[i]);
        }
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Number of elements in first array:3
  Number of elements in second array:3
  Enter the values for Array1:
  Array1[0]: 100
  Array1[1]: 550
  Array1[2]: 220

  Enter the values for Array2:
  Array2[0]: 110
  Array2[1]: 230
  Array2[2]: 150

  Output Array:
  100  110  150  220  230  550  



C program to pass structure to a function

How to do memory allocation for character double pointer?
char **type;
type = (char **)malloc(sizeof(struct char *), 10);   //equivalent to *type[10]
for (i = 0; i < 10; i++)
     type = (char *)malloc(sizeof(struct char), 10)

Above allocation is equivalent to type[10][10]

Write a C program to pass structure to a function.


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

  struct database {
        int *number;
        char **type;
  };

  /* updates the database */
  void updateDB(struct database *db, int n) {
        int i;
        char **type;

        /* allocate memory to store n numbers */
        db->number = (int *)malloc(sizeof(int) * n);

        /* allocate memory to store the type of number */
        db->type = (char **)malloc(sizeof(char *) * n);
        for (i = 0; i < n; i++) {
                db->type[i] = (char *) malloc(sizeof(char) * 10);
        }

        /* updating the database */
        for (i = 0; i < n; i++) {
                db->number[i] = i + 1;
                if (db->number[i] % 2 == 0) {
                        strcpy(db->type[i], "EVEN");
                } else {
                        strcpy(db->type[i], "ODD");
                }
        }
        return;
  }

  int main() {
        int i = 0, n;
        struct database *db;

        /* get the input n from the user */
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* allocating memory for database */
        db = (struct database *)malloc(sizeof(struct database));

        /* updating database */
        updateDB(db, n);

        /* printing the database */
        printf("Printing the Database:\n");
        for (i = 0; i < n; i++) {
                printf("%d is %s\n", db->number[i], db->type[i]);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:10
  Printing the Database:
  1 is ODD
  2 is EVEN
  3 is ODD
  4 is EVEN
  5 is ODD
  6 is EVEN
  7 is ODD
  8 is EVEN
  9 is ODD
  10 is EVEN



C program to add two matrices using functions

Write a C program to add two matrices using functions.


  #include <stdio.h>

  int rows, columns;

  /* adds two matrices and stores the output in third matrix */
  void matrixAddition(int mat1[][10], int mat2[][10], int mat3[][10]) {
        int i, j;

        for (i = 0; i < rows; i++) {
                for (j = 0; j < columns; j++) {
                        mat3[i][j] = mat1[i][j] + mat2[i][j];
                }
        }
        return;
  }

  int main() {
        int matrix1[10][10], matrix2[10][10];
        int matrix3[10][10], i, j;

        /* get the number of rows and columns from user */
        printf("Enter the no of rows and columns(<=10):");
        scanf("%d%d", &rows, &columns);

        if (rows > 10 || columns > 10) {
                printf("No of rows/columns is greater than 10\n");
                return 0;
        }

        /* input first matrix */
        printf("Enter the input for first matrix:");
        for (i = 0; i < rows; i++) {
                for (j = 0; j < columns; j++) {
                        scanf("%d", &matrix1[i][j]);
                }
        }

        /* input second matrix */
        printf("Enter the input for second matrix:");
        for (i = 0; i < rows; i++) {
                for (j = 0; j < columns; j++) {
                        scanf("%d", &matrix2[i][j]);
                }
        }

        /* matrix addtion */
        matrixAddition(matrix1, matrix2, matrix3);

        /* print the results */
        printf("\nResult of Matrix Addition:\n");
        for (i = 0; i < rows; i++) {
                for (j = 0; j < columns; j++) {
                        printf("%5d", matrix3[i][j]);
                }
                printf("\n");
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the no of rows and columns(<=10):
  3   3
  Enter the input for first matrix:
  10 20 30
  40 54 60
  70 80 90

  Enter the input for second matrix:
  100 110 120
  130 140 150
  160 170 180

  Result of Matrix Addition:
  110  130  150
  170  194  210
  230  250  270



C program to convert binary to decimal using functoins

Write a C program to convert binary to decimal using functions.


  #include <stdio.h>

  /* find 2^findPower value */
  int findPower(int input, int power) {
        int i = 0, result = 1;

        /* 2^0 is 1 */
        if (power == 0)
                return 1;

        /* find 2^findPower value */
        for (i = 0; i < power; i++) {
                result = result * input;
        }

        /* return the calculated value */
        return result;
  }

  /* converts binary value to decimal */
 int binaryToDecimal(int input) {
        int result = 0, rem, i = 0;
        while (input > 0) {
                rem = input % 10;
                result = result + (rem * findPower(2, i));
                input = input / 10;
                i++;
        }
        return (result);

  }

  int main() {
        int input, result = 0, rem;

        /* get the input from the user */
        printf("Enter your input:");
        scanf("%d", &input);

        /* binary to decimal */
        result = binaryToDecimal(input);

        /* print the resultant decimal value */
        printf("Result: %d\n", result);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input:1111
  Result: 15



C program to calculate factorial of a number using functions

Write a C program to calculate factorial of the given number using functions.


  #include <stdio.h>

  /* determines factorial for the given number */
  int factorial(int val) {
        int fact = 1, i;
        /* 0! or 1! is 1 */
        if (val == 0 || val == 1)
                return (1);

        for (i = val; i > 0; i--) {
                fact = fact * i;
        }
        return fact;
  }

  int main() {
        int input, output;

        /* get the input from the user */
        printf("Enter your input:");
        scanf("%d", &input);

        /* wrong input */
        if (input < 0) {
                printf("Wrong input!!\n");
                return 0;
        }

        /* finding factorial */
        output = factorial(input);
        printf("Factorial output: %d\n", output);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input:1111
  Result: 15



C program to sort numbers in descending order using functions

Write a C program to sort numbers in descending order using functions.


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

  /* sorts the input in decending order */
  void decendingOrder(int input[], int num) {
        int i, j, temp;
        for (i = 0; i < num - 1; i++) {
                temp = input[i];
                for (j = i + 1; j < num; j++) {
                        /* swapping small and big */
                        if (temp < input[j]) {
                                temp = input[j];
                                input[j] = input[i];
                                input[i] = temp;
                        }
                }
        }
        return;
  }

  int main() {
        int n, *input, i;
        /* get the number of inputs from the user  */
        printf("Enter the number of inputs:");
        scanf("%d", &n);

        /* allocate memory to hold n elements */
        input = (int *) malloc(sizeof(int) * n);

        /* get n inputs from the user */
        for (i = 0; i < n; i++) {
                printf("input[%d]:", i);
                scanf("%d", &input[i]);
        }
        /* sort the input in decending order */
        decendingOrder(input, n);

        /* print the results after sorting */
        printf("\nAfter sorting:\n");
        for (i = 0; i < n; i++) {
                printf("%d  ", input[i]);
        }
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of inputs:5
  input[0]:10
  input[1]:20
  input[2]:15
  input[3]:25
  input[4]:23

  After sorting:
  25  23  20  15  10  



C program to sort numbers in ascending order using functions

Write a C program to sort numbers in ascending order using functions.


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

  /* sorts the data in ascending order */
  void ascendingOrder(int data[], int n) {
        int i, j, temp;
        for (i = 0; i < n - 1; i++) {
                temp = data[i];
                for (j = i + 1; j < n; j++) {
                        /* swapping big and small */
                        if (temp > data[j]) {
                                temp = data[j];
                                data[j] = data[i];
                                data[i] = temp;
                        }
                }
        }
        return;
  }

  int main() {
        int n, *data, i;
        /* get the number of inputs from the user  */
        printf("Enter the number of inputs:");
        scanf("%d", &n);

        /* allocate memory to hold n elements */
        data = (int *) malloc(sizeof(int) * n);

        /* get n inputs from the user */
        for (i = 0; i < n; i++) {
                printf("data[%d]:", i);
                scanf("%d", &data[i]);
        }

        /* sort the data in ascending order */
        ascendingOrder(data, n);

        /* print the results after sorting */
        printf("\nAfter sorting:\n");
        for (i = 0; i < n; i++) {
                printf("%d  ", data[i]);
        }
        printf("\n");
        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of inputs:5
  data[0]:19
  data[1]:17
  data[2]:29
  data[3]:57
  data[4]:11

  After sorting:
  11  17  19  29  57  



C program to swap two numbers using call by value

Write a C program to swap two numbers without using third variable.


  #include <stdio.h>

  /* swap two numbes without using third variable  */
  void swapTwoNumbers(int num1, int num2) {
        printf("\nValues before swapping:\n");
        printf("num1: %d  num2: %d\n", num1, num2);
        num1 = num1 * num2;
        num2 = num1 / num2;
        num1 = num1 / num2;
        printf("\nValues after swapping:\n");
        printf("num1: %d  num2: %d\n", num1, num2);
        return;
  }

  int main() {
        int val1, val2;

        /* get the inputs from the user */
        printf("Enter your first input:");
        scanf("%d", &val1);
        printf("Enter your second input:");
        scanf("%d", &val2);

        /* swap two numbers using functions */
        swapTwoNumbers(val1, val2);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out 
  Enter your first input:100
  Enter your second input:200

  Values before swapping:
  num1: 100  num2: 200

  Values after swapping:
  num1: 200  num2: 100



C program to add two numbers using functions

Write a C program to add two numbers using function(call by value).


  #include <stdio.h>

  /* function to add two numbers */
  int addTwoNumbers(int num1, int num2) {
        int sum;
        sum = num1 + num2;
        return (sum);
  }

  int main() {
        int num1, num2, sum;

        /* get two numbers from user */
        printf("Enter your first input:");
        scanf("%d", &num1);
        printf("Enter your second input:");
        scanf("%d", &num2);

        /* calling a function to add two numbers */
        sum = addTwoNumbers(num1, num2);

        /* printing the result */
        printf("Sum of %d and %d is %d\n", num1, num2, sum);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:100
  Enter your second input:200
  Sum of 100 and 200 is 300



Monday, 24 June 2013

C program to illustrate function with arguments and return value

C program to illustrate function with arguments and return value.


  #include <stdio.h>

  /*
   * Function with argument and return value.
   * funWithArg - performs addition, subtraction,
   * multiplication and division.
   */
int funWithArg(int a, int b, int ch) {
        int res;
        switch (ch) {
                case 1:
                        res =  a + b;
                        break;
                case 2:
                        res = a - b;
                        break;
                case 3:
                        res = a * b;
                        break;
                case 4:
                        res = a / b;
                        break;
        }
        return res;
  }

  int main() {
        int a, b, ch, res;
        printf("1. Addition\n2. Subtraction\n");
        printf("3. Multiplication\n4. Division\n");
        printf("Enter your choice:");
        scanf("%d", &ch);

        if (ch < 1 || ch > 4) {
                printf("Wrong Option!!\n");
                return 0;
        }

        /* get the inputs from the user */
        printf("Enter your inputs(a & b):");
        scanf("%d%d", &a, &b);

        /* perform arithmetic operation */
        res = funWithArg(a, b, ch);

        /* print the result */
        printf("Output: %d\n", res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  1. Addition
  2. Subtraction
  3. Multiplication
  4. Division
  Enter your choice:1
  Enter your inputs(a & b):100 12345
  Output: 12445



C program to illustrate function with return value and no argument

Write a C program to swap two numbers without using temporary variable.


  #include <stdio.h>

  /* 
   * Function with return value and no args.
   * manipulate() - swaps two numbers without
   * temp variable
   */
  int manipulate()  {
        int a, b;

        /* get the input values from the user */
        printf("Enter your inputs:");
        scanf("%d%d", &a, &b);

        a = a + b;
        b = a - b;
        a = a - b;

        /* print the results */
        printf("After swapping:\n");
        printf("a = %d\nb = %d\n", a, b);
        return 1;
  }

  int main() {
        int flag;
        printf("Program to swap two numbers without temp variable\n");
        flag = manipulate();
        if (flag)
                printf("Operation success\n");
        else
                printf("Operation failure\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Program to swap two numbers without temp variable
  Enter your inputs:100 200
  After swapping:
  a = 200
  b = 100
  Operation success



C program to illustrate function with arguments and no return value

Write a C program to illustrate function with arguments and no return value.


  #include <stdio.h>

  /* 
   * function with arguments and no return value.
   * funWithArg() - performs addition, subtraction,
   * multiplication and division
   */
  void funWithArg(int a, int b, int ch) {
        switch (ch) {
                case 1:
                        printf("Addition output: %d\n", a + b);
                        break;
                case 2:
                        printf("Subtraction output: %d\n", a - b);
                        break;
                case 3:
                        printf("Multiply output: %d\n", a * b);
                        break;
                case 4:
                        printf("Division output: %d\n", a / b);
                        break;
                default:
                        printf("U have entered wrong option\n");
                        break;
        }

  }

  int main() {
        int a, b, ch;
        printf("1. Addition\n2. Subtraction\n");
        printf("3. Multiplication\n4. Division\n");
        printf("Enter your choice:");
        scanf("%d", &ch);

        /* get the input operands from the user */
        printf("Enter your inputs(a & b):");
        scanf("%d%d", &a, &b);

        /* calling function with args and no return value */
        funWithArg(a, b, ch);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  1. Addition
  2. Subtraction
  3. Multiplication
  4. Division
  Enter your choice:4
  Enter your inputs(a & b):100 25
  Division output: 4



C program to illustrate function with no arguments and no return value

Write a C program to illustrate function with no argument and no return value.


  #include <stdio.h>

  /* function with no argument and no return value */
  void funWithNoArg() {
        printf("Function with no argument and no return value\n");
  }

  int main() {
        int i = 0;

        /* calls function funWithNoArg() 5 times */
        while (i <= 5) {
                funWithNoArg();
                i++;
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Function with no argument and no return value
  Function with no argument and no return value
  Function with no argument and no return value
  Function with no argument and no return value
  Function with no argument and no return value
  Function with no argument and no return value



C program to swap two numbers using call by reference

Write a C program to swap two numbers using call by reference.


  #include <stdio.h>

  /* swap two numbers */
  void swap(int *a, int *b) {
        int temp;
        temp = *a;
        *a = *b;
        *b = temp;
  }

  int main() {
        int a, b;

        /* get two numbers from the user */
        printf("Enter the value for a and b:");
        scanf("%d%d", &a, &b);
        printf("Before Swapping:\n");
        printf("a: %d\tb: %d\n", a, b);

        /* call by reference */
        swap(&a, &b);

        /* printing the results after swapping */
        printf("After Swapping:\n");
        printf("a: %d\tb: %d\n", a, b);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for a and b: 100   200
  Before Swapping:
  a: 100 b: 200
  After Swapping:
  a: 200 b: 100