{ }codelper
remainderinteger divisionwhile loopP0006

Sum of digits

A non-negative integer N is given.
Print the sum of all its digits.

Input
0 ≤ N ≤ 1,000,000,000
Output
sum of the digits
Example 1 · stdin
1234
stdout
10
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

Two approaches: treat it as text and convert each character (Python sum(map(int, s)), C-family c - '0'), or treat it as a number, taking the last digit with % 10 and shrinking with / 10.
In Craykon and JS / is fractional, so you need Math.Floor (Math.floor).

Pythonmain.py · 2 lines
s = input().strip()print(sum(map(int, s)))
JavaScriptmain.js · 2 lines
const s = require("fs").readFileSync(0, "utf8").trim();console.log([...s].reduce((t, c) => t + Number(c), 0));
TypeScriptmain.ts · 3 lines
import { readFileSync } from "node:fs";const s: string = readFileSync(0, "utf8").trim();console.log([...s].reduce((t, c) => t + Number(c), 0));
JavaMain.java · 10 lines
import java.util.Scanner; public class Main {    public static void main(String[] args) {        String s = new Scanner(System.in).next();        int total = 0;        for (char c : s.toCharArray()) total += c - '0';        System.out.println(total);    }}
C#Main.cs · 12 lines
using System; class Program{    static void Main()    {        string s = Console.ReadLine().Trim();        int total = 0;        foreach (char c in s) total += c - '0';        Console.WriteLine(total);    }}
C++main.cpp · 10 lines
#include <iostream>#include <string> int main() {    std::string s;    std::cin >> s;    int total = 0;    for (char c : s) total += c - '0';    std::cout << total << '\n';}
Cmain.c · 13 lines
#include <stdio.h> int main(void) {    long long n;    scanf("%lld", &n);    int total = 0;    do {        total += n % 10;        n /= 10;    } while (n > 0);    printf("%d\n", total);    return 0;}
Craykonmain.cray · 8 lines
n = Console.ReadLine().ToNumber();total = 0;while (n > 0){    total += n % 10;    n = Mathf.Floor(n / 10);}Console.WriteLine(total);