int sum=82;
for(int i; i < sum.length; i++)
{
final=sum[i]+final;
}
i need help getting the sum and adding the numbers together. for example 82 would be 8+2.
i keep getting an error on this piece of code and i cant figure it out please help.
First off, sum is an integer. Integers don't have lengths. You are asking the computer to find the length of a number... Number's don't have lengths.
Second, when you start the:
final=sum[i]+final;
The computer doesn't know what final is. You need to specify that final is another integer. You can't actually use "final" though for your integer as that is a word reserved for other things.
Try this:
1 2 3 4 5 6
int sum=82;
int total = 0;
for(int i; i < sum.length /*(<- this is still wrong)*/; i++)
{
total=sum[i]+total;
}
Also, you are trying to do an array access on an integer. To the computer 82 is 82 not an 8 and a 2, just 82. You could make a function that takes in an integer and enters it into an array, then modify your current code to basically do what you where already doing, just with an array instead of with a single int.
//Declare your integers;
//Allow someone to input any integer;
//With a loop, input each of the integers into your array; (82 is moved to an array as [8,2])
//Take the sum of all the numbers in the array with another loop;
//Print out the new sum of the numbers;
If you are looking for a simple answer to your question go with sujitnag above this.
I assumed from:
1 2 3 4 5
int sum=82;
for(int i; i < sum.length; i++)
{
final=sum[i]+final;
}
you were doing a homework assignment where arrays may have been a requirement. If they are not a requirement, using modulus(%) 10 is much simpler, and more efficient. So go with sujitnag's code.