Click here to Skip to main content
15,914,111 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Find the sum of squares of individual digits of a number 'sqdnumber' and store the sum in variable 'sqdNumber_result'. E.g. if the number is 234, the sum is computed as (2*2 + 3*3 + 4*4 = 4 + 9 + 16 = 29)

What I have tried:

i have tried using loops but i cant reach the idea to make this program alive
Posted
Updated 10-Mar-16 21:22pm

once you are able to extract the nth digit from the number, the task is trivial. One way is the following:
C++
while (i)
{
  int d = i % 10; // at each iteration d is one digit extracted from i
  i = i / 10;
}
 
Share this answer
 
The difficult part here is to extract the digits.
You can do this in a single loop.

Extract the digit in the units place by doing a mod 10 -> digit = number % 10.
To continue the loop reduce the number by dividing it by 10 -> number /= 10.

I'm sure you can figure out the rest by yourself.

Tip:
Using the debugger will be a great help.
But if you have trouble doing that, try outputting the values of each variable inside the loop.
 
Share this answer
 
Comments
Bashar Kahwaji 11-Mar-16 3:47am    
thanks, that what i have been thinking of all morning.
We don't do your HomeWork.
Advice:
- Start by learn properly the language, structures, loops, branch ...
- Learn some analyze methods, Dijkstra Top-Down method is a good start.
https://en.wikipedia.org/wiki/Top-down_and_bottom-up_design[^]
https://en.wikipedia.org/wiki/Structured_programming[^]
https://en.wikipedia.org/wiki/Edsger_W._Dijkstra[^]
https://www.cs.utexas.edu/users/EWD/ewd03xx/EWD316.PDF[^]
- Learn the Debugger.
 
Share this answer
 
Comments
Bashar Kahwaji 11-Mar-16 3:44am    
i'm just asking about the idea i didn't ask any one to write the program for me!!
base on char*:
C++
char *base = "234";
int sqdNumber_result = 0;
for(int i = 0; i < strlen(base); i++)
{
   sqdNumber_result += ((base[i]-48) * (base[i]-48)); 
}



based on int:
C++
int base = 234;
int sqdNumber_result = 0;
while(base)
{
   sqdNumber_result += ((base % 10) * (base % 10));
   base /= 10;
}


its in my mind, but i think will work
i don't know what dataype you use as base
 
Share this answer
 
Comments
Richard MacCutchan 11-Mar-16 3:37am    
You do not help people by doing their homework for them. Helping them to think is fine, but doing it for them is not.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900