# Write a program to find Sum of digits of a number

12 May 2022

Write a program to find Sum of digits of a number

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

# Description

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

# 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

#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

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

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