C Programs to practice- Sum of the digits and count the number of digits in a 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 begins....

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 456

The sum of the digit is: 15

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();

 }

The output is shown below....

Enter the number 234

The number of the digit is: 3


No comments:

Post a Comment