0
WAP to read any integer number from the user and display addition of all the digits of that number eg. 124 =1+2+4=7
5 Respostas
+ 4
Here is a simple way, but using a while loop.
int dgt = 0, sum = 0,num;
cin>>num;
while(num!=0)
{
dgt=num%10;
sum += dgt;
num/=10;
}
cout<<sum;
I didn't use a for loop, as I didn't know how many digits were there in the number. So I would have to write a while loop before the for, just to count the number of digits, and then use a for to add every digit, till the counter reaches the number of digits.
0
and yes use for loop
0
Number.prototype.sumDigits = function(){ return Array.from(this+'').map(Number).reduce((a,v)=>a+v);
}
var n = 12568;
var sum = n.sumDigits();
https://code.sololearn.com/Wgr0q924x1Aq/?ref=app
0
naah
0
but I want coding using for loop