Write a function that calculates the sum of digits of an integer using recursion.


Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>

int sumofDigits(int nb)
{
	if (nb == 0)
		return 0;
	return ((nb % 10) + sumofDigits(nb / 10));
}


void main()
{
	int nb;

	printf("Enter an integer: ");
	scanf("%d", &nb);

	printf("Sum of digits of %d = %d", nb, sumofDigits(nb));

	getch();
}

 

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Kth smallest element in an array using QuickSort