Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Sum of Digits of a Number in C

Last Updated on May 15, 2023 by Prepbytes

Today, we’ll learn how to answer the most typical C language question i.e. the sum of digits. In order to start coding in the C language and keep up a steady pace, practically everyone must complete this first and most simple program.

Sum of Digits in C

The first step in solving any problem, regardless of the programming language, is always to have an understanding of the problem at hand, In order to solve this problem, we must determine C’s sum of digits. Let’s say we need to execute a number’s digit sum in C, and the number is 257. Therefore, 2+5+7 must be completed. Remember the distinction between C’s sum of numbers and the sum of digits.

We can perform the sum of digits of a number in C in different methods. We will learn all the programs that can be used to execute the sum of digits of a number in C.

Program Using While Loop

In C, we may utilize looping to get a number’s digit sum. We shall employ while statements in this illustration. While the sentence includes a condition that establishes when the loop should end. It has a body that keeps moving till the criteria are met. In this program, the modulus operator (%) returns the remainder.

Algorithm for using While Loop

The algorithm for the program is:

  • Start.
  • Declare variables.
  • Print value on screen.
  • Set and check the condition for a while.
  • Evaluate the sum by adding the initial sum and digit.
  • Divide the number by 10.
  • Execute the code block inside the statement till the condition passes.
  • Print the sum of digits in C on the screen.
  • End.

Let’s look at the code below to find the sum of digits in C using the while statement.

Code Implementation

#include <stdio.h>

// Main body of the program
int main()
{
    // Declare the variables 
    int number, sum = 0;

    printf("Enter the number ");
    scanf("%d", &number);

    printf("The number is = %d\n", number);

    // Loop using a while statement 
    // The loop will run till the number is not equal to 0
    while (number != 0)
    {
        // Sum plus the number divided by 10 to skip a place
        sum += number % 10;

        // Number is divided by 10
        number = number / 10;
    }

    // Print the sum of the number
    printf("Sum: %d\n", sum);

    return 0;
}

Input

12345

Output

15

Program Using Char Input

To find the sum of digits in a number, write a C program that uses a character as input and a while statement without a modulus operator. Similar to the last example, this one does not employ the modulus operator (%). In C, we may utilize looping to get a number’s digit sum.

We shall employ while statements in this illustration. While the sentence includes a condition that establishes when the loop should end. It has a body that keeps moving till the criteria are met. During programming execution, we accept the input as a character and change the number’s data type to an integer.

Algorithm

The algorithm for the program is:

  • Start.
  • Declare number as char input.
  • Accept number input from the user.
  • Set and check the condition for a while.
  • Perform data type conversion from char to int.
  • Evaluate the sum by adding the initial sum and digit.
  • Increment char number input.
  • Execute the code block inside the statement till the condition passes.
  • The print sum of digits in C on the screen.
  • End.

Let’s have a look at the code that uses the while statement and character input to calculate the sum of digits in C.

Code Implementation

#include <stdio.h>
 
int main()
{
   // Declaring variable names    
   int ch, sum, x;
   char num[1000];
   
   // Take number input from the user
   printf("Enter a number\n");
   scanf("%s", num);
 
   sum = ch = 0;
  
   // Loop using a while statement
   while (num[ch] != '\0') {
       
      // Convert character input into an integer 
      x  = num[ch] - '0'; 
      sum = sum + x;
      
      // Increment of character input
      ch++;
   }
 
   printf("Sum of digits of %s = %d\n", num, sum);
   return 0;
}

Input

12345

Output

15

Program Using Recursion

We may also compute the sum of a number’s digits in C using recursion methods. You must comprehend how functions operate in order to comprehend recursion functions. To carry out a certain action or activity, we write a small number of lines of code. Then we assign a name to this set of code blocks. To carry out the action specified in the code block, we may use calls to this name throughout the main body.
A recursive function is one that calls another function from within another function.

Algorithm

The algorithm for the program is:

  • Start.
  • Declare function and variables.
  • Accept number input from the user.
  • Call out the function.
  • The print sum of digits in C on the screen.
  • Define function.
  • Create a base class under the if statement.
  • Create a recursion function under the else statement.
  • End.

Let’s have a look at the C code below that uses the recursion function to calculate the sum of digits.

Code Implementation

#include <stdio.h>

// Declaring a function
int digits_sum(int);

int main()
{
  // Declaring variables  
  int number, result;
  
  // Input from the user
  printf("Enter a number\n");
  scanf("%d", &number);

  // Calling out the function
  result = digits_sum(number);

  printf("The sum is %d\n", result);

  return 0;
}

// Defining the function
int digits_sum(int number) {
    
  // Base case    
  if (number == 0)  
    return 0;
    
  // Recursive function
  return (number%10 + digits_sum(number/10));
}

Input

12345

Output

15

Program Using Loop

In C, we may utilize looping to get a number’s digit sum. We shall utilize "for" expressions in this example. The following is determined by three conditions in the for statement:

  • Starting condition of the loop.
  • Termination condition of the loop.
  • Increment condition of the loop.

It also contains a body that runs till the condition is satisfied. We use the modulus operator (%), which returns the remainder in this program.

NOTE: when we divide two integers in C language, the result is always an integer.

Algorithm

The algorithm for the program is:

  • Start.
  • Declare variables.
  • Accept number input from the user.
  • Use the “for” loop.
  • Skip places in the number using the modulus operator.
  • Evaluate the sum by adding the initial sum and digit.
  • Print the sum of digits in C on the screen.
  • End.

Let’s look at the code below to find the sum of digits in C using the For loop statement.

Code Implementation

#include <stdio.h>
int main()
{
   // Declare the variables
   int n, sum = 0, x;
   printf("Enter a number\n");
   
   // Loop using for
   for (scanf("%d", &n); n != 0; n = n/10) {
       
      // Skip the place by tens using modulus
      x = n % 10;
      
      // Sum of the digits 
      sum = sum + x;
   }

   // Print the output on the screen
   printf("Sum of digits of a number = %d\n", sum);
   return 0;
}

Input

12345

Output

15

Conclusion
We have looked at numerous techniques for performing the digit sum in C. Additionally, we have learned how to calculate the sum of two integers. Here, fundamental syntaxes and codes have been shown. The primary programs discussed in this article aid in the development of our reasoning abilities.

Frequently Asked Questions

Q1. How to add two numbers in C?
Ans. Simple mathematical reasoning may be used to solve more C challenges while remembering to collect fundamental syntaxes.

Q2. What does %d mean in C?
Ans. The writing of integer numbers is what it signifies.

Q3. Can we solve the same problem in subtraction and other mathematical operators?
Ans. Yes, by adjusting the operator sign and other phrases, we may solve the problem.

Q4. Which coding language is mainly required in companies?
Ans. The majority of businesses request Python, Java, and CPP (for machine learning, deep learning, etc.).

Q5. Is C++ harder or C?
Ans. Unlike C, C++ contains new functionalities. The basic language to learn is C, while C++ has certain additional classes and features that are not present in C.

Leave a Reply

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