Pages

Thursday, March 27, 2025

code to print sum of digits of numbers using while loop in c++ ((unlocked new BRAIN LEVEL!! - now you can see live process of code like this..! )

#include <iostream>
using namespace std;

// code to print sum of digits of numbers using while loop in c++
int main(){
    int n = 10829;
    int digSum = 0;

    while(n > 0) {
        int lastDig = n % 10;  // gets the last digit
        digSum += lastDig; // adds the lastDig + digSum for e.g:- 9 + 0 = 9
        n = n / 10; // 10829 / 10 -> 9 gets removed, 1082. removes the last digit, keeps the remaining
        cout << "sum = " << digSum << endl; // cout here shows the process from 1st to last of sum
    }

    // cout << "sum = " << digSum << endl;  // shows the result

    return 0;

}



DRY Run -> helps to build deeper understanding of a code.

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