Pages

Friday, April 4, 2025

Calculate Sum of Digits of a Number in Function in C++

 #include<iostream>

using namespace std;


void sum(int n) {
    int totalSum = 0;
   
    while(n > 0) { // calculates until loop reaches n
    totalSum = totalSum + n; // adds the no. to totalSum
    n--; // decrements n to break the loop at the end
    }
    cout << totalSum << " " << endl;
}

int main(){
    sum(5);

    return 0;
}

OUTPUT-
15

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...