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 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

26th Sep 2017, 3:39 AM
ishita gupta
ishita gupta - avatar
5 Answers
+ 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.
26th Sep 2017, 5:14 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
0
and yes use for loop
26th Sep 2017, 3:39 AM
ishita gupta
ishita gupta - avatar
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
26th Sep 2017, 4:42 AM
Calviղ
Calviղ - avatar
0
naah
26th Sep 2017, 4:44 AM
ishita gupta
ishita gupta - avatar
0
but I want coding using for loop
26th Sep 2017, 10:29 AM
ishita gupta
ishita gupta - avatar