C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Program to print the sum of digits without using modulusIn this program, we have to add the digits of the entry number without the logic of using modulus(%). Example: 149: the sum of its digits (1, 4, 9) is 14. Go through the algorithm to code for this program: Algorithm
Java Programimport java.util.*; class SumOfDigits { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number?"); String str=sc.nextLine(); char[] n = str.toCharArray(); int sum=0; for(int i =0;i<n.length;i++) { sum = sum + ((int)n[i]); sum = sum-48; } System.out.println("sum of digits: "+sum); } } Output: Enter the number? 345 sum of digits: 12 C Program#include <stdio.h> int main() { int c, sum, t; char n[1000]; printf("Enter the number?"); scanf("%s", n); sum = c = 0; while (n[c] != '\0') { t = n[c] - '0'; sum = sum + t; c++; } printf("sum of digits: %d",sum); return 0; } Output: Enter the number? 45 sum of digits: 9 C# Programusing System; public class Sum_Of_Digits { public static void Main() { int sum=0,i; Console.WriteLine("Enter the number?"); string str = Console.ReadLine(); char[] c = str.ToCharArray(); for(i =0;i<c.Length;i++) { sum = sum + ((int)c[i]); sum = sum-48; } Console.WriteLine("sum of digits: "+sum); } } Output: Enter the number? 75 sum of digits: 12 Python Programsum=0 Str = input("Enter the number?"); for i in range(len(Str)): sum = sum + (int(Str[i])) print ("sum of digits: %d"%(sum) ) Output: Enter the number? 175 sum of digits: 13 PHP Program<?php echo("Enter the number?"); $n=readline(); $sum = 0; $c = 0; for($c = 0;$c<strlen($n);$c++){ $t = $n[$c] - '0'; $sum = $sum + $t; } echo("sum of digits:"); echo($sum); ?> Output: Enter the number? 175 sum of digits: 13
Next Topic#
|