You're online now.

Hurray! you are online now.

Write a C program to find the sum of digitis of a given number

#include <stdio.h>
    int main() {
    	int n, sum = 0;
    	printf("Enter the number : ");
    	scanf("%d", &n);
    	
        while (n != 0){
            int last_digit = n % 10;
            sum += last_digit;
            n = n / 10; // remove last digit
        }
        
        printf("Sum of digits : %d", sum);
    }

Above C code takes the number as input from the user and calculate the sum of the digits. It first initializes the variable ‘sum’ to 0. Then prints or prompts the user to enter an integer using the printf function and reads the input using the scanf function.

The code entters a while loop that loop continues until the value of n becomes 0. In each iteration of the loop, it computes the last digit of 'n' using the modulo operator and adds it to ‘sum’. It then removes the last digit from ‘n’ by dividing it by 10.

Finally, it prints the sum of digits using the printf() function.

Algorithm

  1. Initialize variable ‘n’ and ‘sum’ to 0.
  2. Prompt / print message to the user to enter an integer ‘n’ using printf() and read the input using scanf().
  3. while ‘n’ is not equal to 0, repeate the followig steps:
    a. Compute the last digit of ‘n’ using the modulo operator andd assign it to a variable ‘last_digit’.
    b. Add “last_digit' to ‘sum’.
    c. Remove the last digit from ‘n’ by dividing it by 10.
  4. Print the value of ‘sum’ using printf().
  5. Exit

Pseudocode

1. Set n = 0
    2. Set sum = 0
    3. Display "Enter the number : "
    4. Read integer n from user using scanf
    5. While n is not equal to 0, repeat the following:
       a. Set last_digit = n % 10
       b. Set sum = sum + last_digit
       c. Set n = n / 10
    6. Display "Sum of digits : " followed by the value of sum using printf
    

Learn More Do More. Happy Coding!.

🖤 0
Buy me coffee ☕

Comments

Oops!

No comments here...