Write a program to find the sum of all elements of the array.
Used function
Used recursion
Used function
- #include <stdio.h>
- int element(int arr[], int n)
- {
- int sum = 0;
- for(int i = 0; i < n; i++) {
- sum = sum + arr[i];
- }
- return sum;
- }
- int main()
- {
- int arr[100];
- int total = 0;
- int i, n;
- printf("Enter the number of elements to be stored in the array : ");
- scanf("%d", &n);
- printf("Enter %d elements in the array :\n", n);
- for(i=0; i<n; i++) {
- printf("Element - %d : ", i);
- scanf("%d", &arr[i]);
- }
- total = element(arr, n);
- printf("Sum of all elements of array is : %d", total);
- return 0;
- }
Used recursion
- #include <stdio.h>
- int element(int arr[], int n, int i)
- {
- if(i<n)
- return arr[i]+element(arr, n, ++i);
- return 0;
- }
- int main()
- {
- int arr[100];
- int total = 0;
- int i, n;
- printf("Enter the number of elements to be stored in the array : ");
- scanf("%d", &n);
- printf("Enter %d elements in the array :\n", n);
- for(i=0; i<n; i++) {
- printf("Element - %d : ", i);
- scanf("%d", &arr[i]);
- }
- total = element(arr, n, 0);
- printf("Sum of all elements of array is : %d", total);
- return 0;
- }
একটি মন্তব্য পোস্ট করুন