So this is my code so far.
public int getsum (int n){
int num = 23456;
int total = 0;
while (num != 0) {
total += num
I think it's the shortest so far. The input thing is up too you, though.
public static int getSum(int input) { //example: input=246
int sum=0;
if (input%10==input) { //246%10=6;
return input%10; //2%10=2
}
return input%10+getSum((input-input%10)/10); //(246-6)/10=24; 24%10=4
}
Try this:
int getSum(int num)
{
total = total + num % 10;
num = num/10;
if(num == 0)
{
return total;
} else {
return getSum(num);
}
}
int getSum(int N)
{
int totalN = 0;
totalN += (N% 10);
N/= 10;
if(N == 0)
return totalN;
else
return getSum(N) + totalN;
}
Here it is,
//sumDigits function
int sumDigits(int n, int sum) {
// Basic Case to stop the recursion
if (n== 0) {
return sum;
} else {
sum = sum + n % 10; //recursive variable to keep the digits sum
n= n/10;
return sumDigits(n, sum); //returning sum to print it.
}
}
An example of the function in action:
public static void main(String[] args) {
int sum = sumDigits(121212, 0);
System.out.println(sum);
}
#include <iostream>
int useRecursion(int x);
using namespace std;
int main(){
int n;
cout<<"enter an integer: ";
cin>>n;
cout<<useRecursion(n)<<endl;
return 0;
}
int useRecursion(int x){
if(x/10 == 0)
return x;
else
return useRecursion(x/10) + useRecursion(x%10);
}
public static int digitSum (int n)
{
int r = n%10; //remainder, last digit of the number
int num = n/10; //the rest of the number without the last digit
if(num == 0)
{
return n;
} else {
return digitSum (num) + r;
}}