Problem Statement: Given an array of integers, write a C program to find the sum of all elements in the array.
Example:
Input: arr[] = {1, 2, 3, 4, 5} Output: Sum of elements: 15
Algorithm to find the Sum of Array Elements.
Below are the steps that we need to follow:
Step 1: Initialize a variable sum to 0 to store the sum of elements.
Step 2: Input the size of the array and create an array arr of that size.
Step 3: Input the elements of the array arr.
Step 4: Traverse through the array from the first element to the last element.
- Add each element to the sum variable.
Step 5: Print the value of the sum.
Program to Find Sum of Array Elements.
//C program to find sum of array elements #include <stdio.h> int main() { int n, sum = 0; printf("Enter the size of the array: "); scanf("%d", &n); // Creating an array of size 'n'. int arr[n]; // Input the elements of the array 'arr'. printf("Enter the elements of the array:\n"); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } // calculate the sum of elements. for (int i = 0; i < n; i++) { sum += arr[i]; } printf("Sum of elements: %d\n", sum); return 0; }
Enter the size of the array: 5
Enter the elements of the array:
12 10 5 2 9
Sum of elements: 38
Time Complexity: The time complexity of this code is O(n) since we need to traverse through the entire array once to calculate the sum.
Space Complexity: The space complexity of this code is O(1) because we are not using any extra space to solve this problem except for storing the elements of the input array.
Similar articles:
No comments:
Post a Comment