An Array Sum Program in C is a simple application that demonstrates how to declare and manipulate arrays. The program typically involves summing the elements of an array and outputting the result. This kind of program helps in understanding array handling, loops, and basic input/output operations in C.
Example: Array Sum Program
In this example, we will write a program that allows the user to input a specific number of integers into an array and then calculates the sum of those integers.
C Program to Calculate the Sum of Elements in an Array
Explanation:
Variable Declarations:
int n
: This variable holds the number of elements the user wants to input.int i
: Loop counter for iterating through the array.int sum = 0
: This variable is initialized to0
and will hold the cumulative sum of the array elements.int arr[100]
: Declares an integer array of size 100 to store the elements. The size can be adjusted based on requirements.
Input for Array Size:
- The program prompts the user to enter the number of elements they want to sum and stores this value in
n
.
- The program prompts the user to enter the number of elements they want to sum and stores this value in
Input for Array Elements:
- A
for
loop is used to iterate from0
ton-1
, prompting the user to input each integer, which is stored in the arrayarr
.
- A
Calculating the Sum:
- Another
for
loop iterates over the array elements, adding each element tosum
. The expressionsum += arr[i]
is a shorthand forsum = sum + arr[i]
.
- Another
Output the Result:
- Finally, the program outputs the calculated sum using
printf
.
- Finally, the program outputs the calculated sum using
Sample Output:
Example 1:
Example 2:
Key Points:
- Arrays: The program illustrates how to declare, initialize, and manipulate arrays in C.
- Looping: The use of
for
loops demonstrates how to iterate through an array for both input and processing. - Input/Output: The program utilizes standard input/output functions to interact with the user.
Variations:
You can modify the program to:
- Handle larger arrays dynamically using dynamic memory allocation (with
malloc
). - Calculate the average of the elements in addition to the sum.
- Find the maximum and minimum values in the array.
- Implement error checking to ensure the user inputs valid integers.
This program serves as a foundational exercise for understanding arrays and basic control structures in C programming.