Pages

Wednesday, March 26, 2025

print sum of N natural numbers in C++

 #include <iostream>

using namespace std;

// code to print sum of first N natural number
int main(){
    int num;

    cout << " enter num : ";
    cin >> num;

    int sum = 0; // sum initialized at 0, stored at 0

    for(int i = 1; i <= num ; i++){
       
        sum += i;
        cout << sum << " ";
    }

   

    return 0;
}

No comments:

Post a Comment

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...