Related to sum of digits

why in some places there is n%10 and in others there is n/10
??

hi @sethyamir5

#include <iostream>
using namespace std;
int main() {
    int n;
    cin>>n;
    int sum = 0;
    while(n > 0){
        int rem = n%10;
        sum += rem;
        n = n/10;
    }
    cout<<sum;
}

so what we are supposed to do is find the sum of all digits in the number…
when we do n%10, we are extracting individual digits… and in n/10, we are reducing the number by one shift…

consider an example say n = 12
when we do first %, we get rem = 2, and by n/10, we reduce it to n = 1…
now again when we do %, we get rem = 1, and on performing n/10, we get n = 0.1
so now n goes less than 0 and while loop breaks…
Hope it clears ur doubt…

hi @sethyamir5
I hope its clear now??

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.