#include <stdio.h>

int main() {
    int n, i; // Declare variables for the number of elements and a loop counter
    int sum = 0; // Variable to hold the sum of the array elements

    // Ask the user for the number of elements in the array
    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    int array[n]; // Declare an array of size n

    // Prompt the user to enter the array elements
    printf("Enter the elements of the array:\n");
    for (i = 0; i < n; i++) {
        printf("Element %d: ", i + 1);
        scanf("%d", &array[i]); // Read each element into the array
    }

    // Calculate the sum of the elements in the array
    for (i = 0; i < n; i++) {
        sum += array[i]; // Add each element to the sum
    }

    // Display the total sum
    printf("The sum of the array elements is: %d\n", sum);

    return 0; // End of the program
}

Explanation of the Program

  1. Include the Standard Library:
    • The line #include <stdio.h> includes the standard input-output library, which allows the use of functions like printf and scanf.
  2. Variable Declarations:
    • int n, i;: Here, n will store the number of elements the user wants in the array, and i is used as a loop counter.
    • int sum = 0;: This initializes the sum variable to zero. It will hold the total of the array elements as we calculate it.
  3. User Input for Array Size:
    • The program prompts the user to enter the number of elements in the array with the line:cCopy codeprintf("Enter the number of elements in the array: ");
    • The input is read using scanf("%d", &n);.
  4. Array Declaration:
    • int array[n];: This declares an array of integers with a size specified by the user.
  5. Input Elements into the Array:
    • The program uses a for loop to prompt the user to enter each element of the array:cCopy codefor (i = 0; i < n; i++) { printf("Element %d: ", i + 1); scanf("%d", &array[i]); }
    • The loop runs from 0 to n-1, and each element is read and stored in the array.
  6. Calculating the Sum:
    • Another for loop calculates the sum of the elements:cCopy codefor (i = 0; i < n; i++) { sum += array[i]; }
    • In each iteration, the current element of the array is added to the sum.
  7. Display the Result:
    • Finally, the program prints the total sum of the elements:cCopy codeprintf("The sum of the array elements is: %d\n", sum);
  8. Program End:
    • The program returns 0, indicating successful completion.

Example Output

Here’s how the program would interact with a user:

User Input:

Enter the number of elements in the array: 5
Enter the elements of the array:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50

output:
The sum of the array elements is: 150

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights