40 lines
No EOL
1 KiB
C
40 lines
No EOL
1 KiB
C
/*----------------------------------------------------------
|
|
* HTBLA-Leonding / Class: <your class>
|
|
* ---------------------------------------------------------
|
|
* Title: Sum of Digits
|
|
* Author: Marc Tismonar
|
|
* ----------------------------------------------------------
|
|
* Description:
|
|
* Recursive and iterative implementation of an algorithm that calculates
|
|
* the sum of the digits of a given positive integer.
|
|
* ----------------------------------------------------------
|
|
*/
|
|
|
|
#include "sum_of_digits.h"
|
|
|
|
/*
|
|
Instructions:
|
|
|
|
Define a function sum_of_digits(n) that takes a positive integer `n` as input.
|
|
The sum of digits can be calculated as n mod 10 + sum of digits of n / 10 as long as n is larger than ten.
|
|
|
|
*/
|
|
|
|
int sum_of_digits_recursive(int n) {
|
|
if (n == 0) {
|
|
return 0;
|
|
}
|
|
|
|
return n % 10 + sum_of_digits_recursive(n / 10);
|
|
}
|
|
|
|
int sum_of_digits_iterative(int n) {
|
|
int sum = 0;
|
|
|
|
while (n > 0) {
|
|
sum += n % 10;
|
|
n = n / 10;
|
|
}
|
|
|
|
return sum;
|
|
} |