#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
- Include the Standard Library:
- The line
#include <stdio.h>
includes the standard input-output library, which allows the use of functions likeprintf
andscanf
.
- The line
- Variable Declarations:
int n, i;
: Here,n
will store the number of elements the user wants in the array, andi
is used as a loop counter.int sum = 0;
: This initializes thesum
variable to zero. It will hold the total of the array elements as we calculate it.
- User Input for Array Size:
- The program prompts the user to enter the number of elements in the array with the line:cCopy code
printf("Enter the number of elements in the array: ");
- The input is read using
scanf("%d", &n);
.
- The program prompts the user to enter the number of elements in the array with the line:cCopy code
- Array Declaration:
int array[n];
: This declares an array of integers with a size specified by the user.
- 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
ton-1
, and each element is read and stored in the array.
- The program uses a
- 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
.
- Another
- Display the Result:
- Finally, the program prints the total sum of the elements:cCopy code
printf("The sum of the array elements is: %d\n", sum);
- Finally, the program prints the total sum of the elements:cCopy code
- Program End:
- The program returns
0
, indicating successful completion.
- The program returns
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