Pages

Friday, May 23, 2025

Sum of N natural numbers using Recursion in C++

 #include <iostream>

using namespace std;


// sum of N natural numbers

int sum(int n) {
    if(n==1) {
        return 1;
    }

    return n+sum(n-1);
}

int main() {
   
    cout << sum(5) << endl;
    return 0;
}

No comments:

Post a Comment

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...