Tech Unleashed

Wohoo!! We're on YouTube

Tuesday, 18 January 2022

C program for "if a five digit number is input through the keyboard, write a program to calculate the sum of its digits."

Problem: C program for "if a five digit number is input through the keyboard, write a program to calculate the sum of its digits."

Logic used :
  • Check the number if it is smaller than zero or not.
  • Take the remainder out by modulus operator ( num % 10 ) and store it in a variable.
  • Take another variable with initial value equal to 0.
  • Add the remainder to that variable.
  • Take the quotient out by dividing it to 10 and again store it to the variable which was initially storing the number.
  • Repeat the whole step again until the number becomes less than 0.

Demo :
while ( num > 0 ) {
    m = num % 10;
    sum = sum + m;
    num = num /10 ;
}

C program : 

// Program by Shyam Kanth

#include<stdio.h>

int main(){
    int num,m,sum=0;
    printf("Enter the number : ");
    scanf("%d",&num);
    while(num>0){
        m = num%10;
        sum = sum+m;
        num = num/10;
    }
    printf("%d",sum);
    return 0;
}

Codes used :
  • #include < stdio.h > : Header file for input-output
  • int : Integer data type
  • printf : Function for displaying message
  • scanf : Functio for taking input
  • while : Loop
Do comment, if any doubt
Know about me : Shyam Kanth

No comments:

Post a Comment