Sum of Digits Calculation

CCBeginner
Practice Now

Introduction

In this lab, we will learn to write a program to calculate the sum of digits of a given number in C programming language.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Define variables and take input from user

In this step, we will define three variables - n, sum, and remainder. We will take user input in the variable n using the scanf() function.

#include<stdio.h>

int main()
{
    int n, sum = 0, remainder;

    printf("Enter the number you want to add digits of:  ");
    scanf("%d", &n);

    // code for sum of digits

    return 0;
}

Calculate the sum of digits

In this step, we will use a while loop to calculate the sum of digits of the given number.

while(n != 0)
{
    remainder = n % 10;
    sum += remainder;
    n = n / 10;
}

The above code uses modulus operator (%) to get the remainder of a number when divided by 10. This remainder is added to the variable sum. We then divide the number by 10 to remove the last digit of the number. We repeat this process until the number becomes zero.

Display the sum

In this step, we will display the sum of digits calculated above to the user using the printf() function.

printf("\n\nSum of the digits of the entered number is  =  %d\n\n", sum);
printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");

Write the full program

Now, we will combine all the above steps and write the full program to calculate the sum of digits of a number.

#include<stdio.h>

int main()
{
    int n, sum = 0, remainder;

    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");

    printf("Enter the number you want to add digits of:  ");
    scanf("%d", &n);

    while(n != 0)
    {
        remainder = n % 10;
        sum += remainder;
        n = n / 10;
    }

    printf("\n\nSum of the digits of the entered number is  =  %d\n\n", sum);
    printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");

    return 0;
}

Summary

In this lab, we learned to write a program to calculate the sum of digits of a given number in C programming language. We used modulus operator and while loop to calculate the sum.

Other C Tutorials you may like