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

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...