#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