Sum of All Array Elements – Using Recursion

List Topics
September 1, 2025
No Comments
2 min read

Sum of All Array Elements – Using Recursion

যা শিখবো:

  • কীভাবে recursion ব্যবহার করে array-এর সকল element-এর sum বের করা যায়
  • recursion-এর base case ও recursive call কিভাবে কাজ করে
  • array indexing এবং return statement-এর ব্যবহার

ধাপে ধাপে ব্যাখ্যা:

Step 1: Function তৈরি করা যা sum return করবে

C
int sumArray(int arr[], int n, int index) {
    if(index == n)  // Base case
        return 0;
    return arr[index] + sumArray(arr, n, index + 1); // Recursive call
}

Step 2: ইউজার থেকে array size ইনপুট নেওয়া

C
scanf("%d", &n);

Step 3: ইউজার থেকে array elements ইনপুট নেওয়া

C
for(i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}

Step 4: Function call করে sum বের করা

C
total = sumArray(arr, n, 0);<br><br>

উদাহরণ:

C
#include <stdio.h>

// Function to find sum of array elements using recursion
int sumArray(int arr[], int n, int index) {
    if(index == n)
        return 0;
    return arr[index] + sumArray(arr, n, index + 1);
}

int main() {
    int n, i, total;

    printf("Enter the number of elements: ");
    scanf("%d", &n);

    int arr[n];

    printf("Enter the elements:\n");
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    total = sumArray(arr, n, 0);

    printf("\nSum of all array elements: %d", total);

    return 0;
}

আউটপুট উদাহরণ:

উদাহরণ ১:

C
Enter the number of elements: 5
Enter the elements:
1 2 3 4 5

Sum of all array elements: 15

উদাহরণ ২:

C
Enter the number of elements: 4
Enter the elements:
10 -2 5 7

Sum of all array elements: 20

ব্যাখ্যা:

  • sumArray() → recursion ব্যবহার করে array elements যোগ করে
  • Base Case → যখন index == n, তখন 0 return হয়
  • Recursive Call → arr[index] + sum of remaining elements
  • main() ফাংশনে ইউজারের input নিয়ে function call করা হয় এবং ফলাফল প্রিন্ট করা হয়
©2025 Linux Bangla | Developed & Maintaind by Linux Bangla.