Write the functions in C for the following: (a) To find the square of any number. (b) To find the absolute difference between two integers. (c) To convert a decimal number to its equivalent binary number. (d) To find the largest element in a given array of n elements.

, , No Comments

 Certainly! Below are the C functions for the given tasks:


 (a) To find the square of any number:


```c

include <stdio.h>


int square(int num) {

    return num * num;

}


int main() {

    int num;

    printf("Enter a number: ");

    scanf("%d", &num);


    int result = square(num);


    printf("Square of %d is %d\n", num, result);


    return 0;

}

```


 (b) To find the absolute difference between two integers:


```c

include <stdio.h>


int absoluteDifference(int num1, int num2) {

    return num1 > num2 ? num1 - num2 : num2 - num1;

}


int main() {

    int num1, num2;

    printf("Enter two integers: ");

    scanf("%d %d", &num1, &num2);


    int result = absoluteDifference(num1, num2);


    printf("Absolute difference: %d\n", result);


    return 0;

}

```


(c) To convert a decimal number to its equivalent binary number:


```c

include <stdio.h>


void decimalToBinary(int decimal) {

    int binary[32];

    int i = 0;


    while (decimal > 0) {

        binary[i] = decimal % 2;

        decimal /= 2;

        i++;

    }


    printf("Binary equivalent: ");

    for (int j = i - 1; j >= 0; j--) {

        printf("%d", binary[j]);

    }

    printf("\n");

}


int main() {

    int decimal;

    printf("Enter a decimal number: ");

    scanf("%d", &decimal);


    decimalToBinary(decimal);


    return 0;

}

```


 (d) To find the largest element in a given array of n elements:


```c

#include <stdio.h>


int findLargest(int arr[], int n) {

    int largest = arr[0];


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

        if (arr[i] > largest) {

            largest = arr[i];

        }

    }


    return largest;

}


int main() {

    int n;

    printf("Enter the number of elements in the array: ");

    scanf("%d", &n);


    int arr[n];

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

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

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

    }


    int result = findLargest(arr, n);


    printf("Largest element in the array: %d\n", result);


    return 0;

}

```


These C programs demonstrate the functions to perform the specified tasks. You can run these programs and test the functions with different inputs.

0 टिप्पणियाँ:

Post a Comment