Program to find Sum of digits of a number

Program to find Sum of digits of a number

10 May 2023

10 May 2023

Write a program to find Sum of digits of a number



Description about the Program to find Sum of digits of a number

Get a number from user and then find the sum of the digits in the given number.

E.g.  let the number = 341

Sum of digits is 3+4+1= 8

Input

4521

Output

12 

C Program to find Sum of digits of a number

Method 1

#include <stdio.h>

int main()

{

    int num, sum = 0;

    printf("Enter a number: ");

    scanf("%d",&num);

    while(num!=0)

    {

        sum =sum+ num % 10;

        num = num / 10;

    }

    printf("%d",sum);

    return 0;

}

Method 2

#include <stdio.h>

int SumOfDigits(int n, int sum)

{

    if (n==0)

    return sum;

    else

    {

    sum=sum+n%10;

    return SumOfDigits(n/10,sum);

    }    

}

int main()

{

    int num, sum = 0;

    printf("Enter a number: ");

    scanf("%d",&num);

    int result = SumOfDigits(num,sum);

    printf("%d",result);

    return 0;

}

C++ Program to find Sum of digits of a number

#include <iostream>

using namespace std;

int main()

{

    int num, sum = 0;

    cout<<"Enter a number: ";

    cin>>num;

    while(num!=0)

    {

        sum =sum+ num % 10;

        num = num / 10;

    }

    cout<<sum;

    return 0;

}

Java Program to find Sum of digits of a number

import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = sc.nextInt();

int sum= 0;

while(num!=0)

{

sum = sum + num%10;

num = num / 10;

}

System.out.print(sum);

}

}

Python Program to find Sum of digits of a number

num=int(input("Enter a number: "))

Sum=0

while num!=0:

    Sum=Sum+num%10

    num=num//10

print(Sum)


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023


Related Articles

Ask Us Anything !