Array

  1. "Write a program to find the largest and smallest among the given element in an array."
    #include <stdio.h>

    int main() {
        int n;

        // Input the number of elements
        printf("Enter the number of elements: ");
        scanf("%d", &n);

        if (n <= 0) {
            printf("The array must contain at least one element.\n");
            return 1;
        }

        int arr[n];

        // Input the elements
        printf("Enter %d elements:\n", n);
        for (int i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
        }

        // Initialize largest and smallest with the first element of the array
        int largest = arr[0];
        int smallest = arr[0];

        // Find the largest and smallest elements in the array
        for (int i = 1; i < n; i++) {
            if (arr[i] > largest) {
                largest = arr[i];
            }
            if (arr[i] < smallest) {
                smallest = arr[i];
            }
        }

        // Print the largest and smallest elements
        printf("Largest element: %d\n", largest);
        printf("Smallest element: %d\n", smallest);

        return 0;
    }






  2. Write a program to input n number and sort then in descending order.
    #include <stdio.h>

    // Function to sort the array in descending order
    void sortDescending(int arr[], int n) {
        int temp;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (arr[i] < arr[j]) {
                    // Swap the elements
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
    }

    int main() {
        int n;

        // Input the number of elements
        printf("Enter the number of elements: ");
        scanf("%d", &n);

        int arr[n];

        // Input the elements
        printf("Enter %d elements:\n", n);
        for (int i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
        }

        // Sort the array in descending order
        sortDescending(arr, n);

        // Print the sorted array
        printf("Sorted array in descending order:\n");
        for (int i = 0; i < n; i++) {
            printf("%d ", arr[i]);
        }
        printf("\n");

        return 0;
    }







0 Comments had been done yet:

Post a Comment