C Program to Find Sum of Digits of a Number using Recursion

This C program calculates the sum of the first N natural numbers using a for loop. It iterates from 1 to N and accumulates the sum by adding each number to the previous sum.

Problem Statement

Given a positive integer N, we need to find the sum of the first N natural numbers.

C Program to Find Sum of Digits of a Number using Recursion

#include <stdio.h>

int sumOfDigits(int number);

int main() {
    int number;
    printf("Enter a positive integer: ");
    scanf("%d", &number);

    int sum = sumOfDigits(number);
    printf("Sum of digits of %d = %d\n", number, sum);

    return 0;
}

int sumOfDigits(int number) {
    if (number == 0) {
        return 0;
    } else {
        return (number % 10) + sumOfDigits(number / 10);
    }
}

How it Works:

  1. The user is prompted to enter a positive integer N.
  2. The for loop is used to iterate from 1 to N. The loop variable i is initialized to 1, and the loop continues as long as i is less than or equal to N. After each iteration, i is incremented by 1.
  3. Inside the loop, the current value of i is added to the sum variable. This accumulates the sum of the numbers from 1 to N.
  4. After the loop completes, the final sum is stored in the sum variable.
  5. The main function displays the calculated sum on the screen.

Input/Output:

C Program to Find Sum of Digits of a Number using Recursion

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...