C Programs to practice- Find the sum of the digits of a given number

 

To find the sum of the digits of a given number, follow the steps given below.

  • Get the input as integer.
  • Check whether the number is greater than zero, repeat the below steps.
  • Use modulation operator, separate the digit and store it to a variable
  • Add the variable value to sum.
  • Divide the number by 10
  • Finally, print the sum value.

The program is given below....

Program: sum.c

#include<stdio.h>

#include<conio.h>

void main()

{

 int a,sum=0,n;

 printf("Enter the number");

 scanf("%d",&a);

 while(a>0)

 {

  n=a%10;

  sum=sum+n;

  a=a/10;

 }

 printf("The sum of the digit is:%d",sum);

 getch();

 }

 

 Output : 

Enter the number 567

The sum of the digit is: 18


Try this:

How to count the number of digits in the given number.

Tip: Use the same logic(sum of the digit) with simple change.

Think about it.

 

Program: “Count.c”

#include<stdio.h>

#include<conio.h>

void main()

{

 int a,count=0,n;

 printf("Enter the number");

 scanf("%d",&a);

 while(a>0)

 {

  n=a%10;

  count++;

  a=a/10;

 }

 printf("The number of the digit is:%d",count);

 getch();

 }

No comments:

Post a Comment