Write a program to adding a digits from given number in c

28 Dec 2022 Balmiki Mandal 0 C Programming

Adding a digits from given number in c

 

To write a program to add the digits of a given number in C, we can use the following steps:

  1. Declare a variable to store the number that we want to add the digits of.
  2. Declare another variable to store the sum of the digits.
  3. Initialize the sum of the digits to 0.
  4. While the number is greater than 0, do the following:
    • Get the rightmost digit of the number.
    • Add the rightmost digit to the sum of the digits.
    • Divide the number by 10 to remove the rightmost digit.
  5. Print the sum of the digits to the console.

Here is a simple C program to add the digits of a given number:

C Programming
#include <stdio.h>

int main() {
  int number, sum_of_digits;

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

  sum_of_digits = 0;

  while (number > 0) {
    int rightmost_digit = number % 10;
    sum_of_digits += rightmost_digit;
    number /= 10;
  }

  printf("The sum of the digits of %d is %d\n", number, sum_of_digits);

  return 0;
}

Output:

Enter a number: 1234
The sum of the digits of 1234 is 10

This program is simple, but it is effective. It uses a while loop to iterate over the digits of the number and add them to the sum of the digits. Once the loop has finished iterating, the sum of the digits is printed to the console.

Further Reading:

 For further information and examples, Please visit[ C-Programming From Scratch to Advanced 2023-2024]

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.