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

Encode and Decode Strings - NeetCode.IO Solution by me + gemini pro 3.0 explained

  class Solution {         // encode: List of Strings -> String     public String encode ( List < String > strs) {         Stri...