g | x | w | all
Bytes Lang Time Link
014dc250802T161036ZToby Spe
104GNU sed r250802T154803ZToby Spe
027GNU sed + dc250802T150111ZToby Spe
168Bespoke250802T083118ZJosiah W
024AWK250801T151510Zxrs
006Uiua241123T215544ZErikDaPa
042Clojure240909T174141ZMartin P
014x86 Linux assembly230225T024926Zqwr
057Setanta240908T172428Zbb94
008Perl 5 MListUtil=sum pF240306T011207ZXcali
023Scala230402T024641Z138 Aspe
051Swift230723T232116ZmacOSist
027Java230727T064601ZTop Golf
000Thunno 2 S230611T163728ZThe Thon
021Bash & coreutils230606T112900Zroblogic
027Shasta v0.0.11230605T144819Znoodle p
030Python 3230517T212803ZHunaphu
018C# Visual C# Interactive Compiler230519T041457ZIvan Nee
006Befunge98 PyFunge230303T024500Zyeah ok
056Rockstar230516T114517ZShaggy
018Perl 5 F E230516T205600Zplentyof
031Zsh230515T175116Zroblogic
042Python230515T161103ZThe Empt
025Nibbles230515T135516Zlyxal
095LeafLang230515T050430ZBreadlea
025C gcc230225T095923Zbadatgol
040Lua230409T214638Zbluswimm
030Rust230226T101354Zcorvus_1
039PowerShell230406T133859ZJames Fl
031Java 8 OpenJDK 8230406T123230ZFhuvi
042Javascript230405T213211ZInfigon
005APL230303T032147ZMark Ree
011KAP230405T025303ZElias M&
006vemf230402T043042Z
005K ngn/k230402T023813ZnaffetS
015Trilangle230224T234316ZBbrk24
035bc230311T115706Zroblogic
044Google Sheets230311T072907Zuser1111
015KamilaLisp v0.2230310T194704ZKamila S
010Julia230303T100502ZJacobus
009Vyxal 3.0.0beta.1230224T231735Zlyxal
002Brachylog230227T100429ZFatalize
114Pascal230304T151038ZKai Burg
016Raku230227T214110ZMCLooyve
037Groovy230303T134700ZChristop
009APL230228T030021Zfat peng
nanI saw this and just had to give it a go with Java. I mean230228T081251ZHaakon L
013J230227T182930Z永劫回帰
004Pyth230227T173335ZCursorCo
011GolfScript230227T145126Zemirps
030Excel230225T073148ZJos Wool
087Typescript Type System + hotscript230225T003306Znoodle p
022JavaScript Node.js230227T081221Ztsh
150BrainFlak230227T084333ZRaviRavi
001MathGolf230226T183917ZKevin Cr
019Wolfram Language Mathematica230226T141006ZDavidC
031PowerShell Core230226T163021Zuser3141
023JavaScript Node.js230224T233504Znoodle p
nan230226T135259ZCody Gra
025Hebigo230225T191211Zgilch
030C gcc230225T140455Zc--
003Pip230225T092245ZThe Thon
002Jelly230225T092129ZThe Thon
024Python230225T084238ZThe Thon
003Ly230225T050158Zcnamejj
017Ruby230225T042034ZSuever
043Standard ML230225T032217Zqwr
018Factor + math.unicode230225T014146Zchunes
014Proton230225T012628Zhyperneu
003Charcoal230225T005633ZNeil
006Retina 0.8.2230225T005302ZNeil
019Perl 5 p230225T001716ZKjetil S
015Arturo230225T000547Zchunes
003MATL230224T235403ZSuever
009Pari/GP230224T234044Zc--
00205AB1E230224T233245Zc--
nan230224T233059Znoodle p
001Japt x230224T232248Znoodle p
nanFig230224T230518ZSeggan
000Vyxal s230224T230306Zlyxal

dc, 14 bytes

[A~rd0<x+]dsxx

Try it online!

How it works

The recursive function x divides by 10 (A~) and swaps the results (r) so that the quotient is on top of the stack. The recursion continues until there's nothing left to divide (d0<x), at which point we have a stack made of the digits of the input. We then sum the values (+) as each level of recursion returns.

GNU sed -r, 104 bytes

Works with version 4.2 but not with 4.9 (which doesn't support empty labels, nor backrefs in search strings):

s/0//g
:
s/[2-9]/1&/g
y/123456789/x12345678/
t
:a
s/x/<<123456789x01>/
s/(.)<.*\1(x?.).*>/\2/
ta
s/^$/0/

Try it online!

How it works

# Convert each digit to unary
s/0//g
:u
s/[2-9]/1&/g
y/123456789/x12345678/
tu

# Add 'em all up - see https://codegolf.stackexchange.com/a/235144/39490
:a
s/x/<<123456789x01>/
s/(.)<.*\1(x?.).*>/\2/
ta

# Special-case zero
s/^$/0/

GNU sed + dc, 27 bytes

s/./&+/g
s/.*/dc -e'0 &p'/e

Creates a simple dc program of the form 0 ₁+₂+₃+...+p (where ₁₂₃... are the input digits) and executes it.

Try it online!

Bespoke, 168 bytes

now,in this summation decimal numbers(ASCII)go to some full sum
we can subtract"zero"for an easy handling
starting value is higher(actually nonzero)because EOF equals-I

Input is a series of digit characters. (I tried a version that takes input as a number and does math to it, but it turned out to be 197 bytes.)

AWK, 24 bytes

{for(;i++<NF;)x+=$i}$0=x

Attempt This Online!

Uiua, 6 bytes

/+≡⋕°⋕

Explanation:

/+≡⋕°⋕
  ≡⋕°⋕ => number to list of each digit
/+     => sum

Try this online!

Clojure, 42 bytes

#(apply +(map parse-long(map str(str %))))

x86 Linux assembly, 18 15 14 bytes

Custom calling convention because I remembered lodsb exists. Takes input as a null-terminated string in esi, because that's the only way to handle numbers with 100 digits. It turns out the answer is nearly identical to Cody Gray's now, except he cleverly used ah instead of 0 in cmp. Oh well. lea is 4 bytes, the same as sub al,'0'/add edx,eax.

I copied his listing format too because it's nicer to look at than an objdump.

-1 byte from using cdq instead of xor.

sum_digits:                                 ; input: null-terminated string in esi
  31 C0         xor     eax, eax            ; clear upper bits of eax
  99            cdq                         ; zero edx (sum)
.L:                                         ; do
  AC            lodsb                       ; al c = *str++
  8D 54 02 D0   lea     edx, [edx-48+eax]   ; sum += c - '0'
  80 3E 00      cmp     BYTE [esi], 0       ; while (*str)
  75 F6         jne     .L
  C3            ret                         ; return in edx

Setanta, 57 bytes

gniomh(n){s:=0le i idir(0,fad@n)s+=go_uimh(n[i])toradh s}

try-setanta.ie link

Version for native number type (up to \$2^{53}\$), 35 bytes

gniomh f(n){toradh n&n%10+f(n//10)}

try-setanta.ie link

Perl 5 -MList::Util=sum -pF, 8 bytes

$_=sum@F

Try it online!

Scala, 23 bytes

Try it online!

x=>x.map(_.asDigit).sum

Swift, 51 bytes

let s={String($0+0).reduce(0){Int("\($1)")!+$0}}

Java, 27 bytes

for(s=0;n>0;s+=n%10,n/=10);

Input as Integer (n)

Thunno 2 S, 0 bytes

Attempt This Online!

No bytes, that's right.

Thunno 2, 1 byte

S

Attempt This Online!

Alternatively, have a built-in.

Bash & coreutils, 21 bytes

fold -1|paste -sd+|bc

Try it online!

Shasta v0.0.11, 27 bytes

{(eval(join(split$"")"+"))}

{...} Function of argument $

(eval ...) Evaluate as JavaScript

(join ... "+") Join on "+"

(split $ "") Characters of the input string

Alternative 27 bytes:

{(sum(map(split$"")number)}

The sum of mapping each character of the input string to number.

Online interpreter will be set up very soon; for now, you can test this by following instructions from the README on GitHub.

Python 3, 33 (35!) 30 bytes

-5 thanks to c--. No strings

f=lambda n:n and n%10+f(n//10)

Try it online!

C# (Visual C# Interactive Compiler), 18 bytes

s=>s.Sum(a=>a-48);

Try it online!

Befunge-98 (PyFunge), 9 7 6 bytes

~c%+#q

Try it online!

Having read through the Default I/O thread, it seems my "fun extra" answer is actually valid as a submission. Note that since the output in this version is an exit code, POSIX-compatible systems (including TIO; please let me know if there's a better site for this) will only care about the least significant byte and as such display the result mod 256 (as per the Funge-98 spec).

Explanation

~: Read next character.

c%: Push 12, then take input character mod 12. This gives the number represented. Suggested by Jo King (previous iteration subtracted 48 from the number with '0-).

+: Add that to the current total (initially implicitly 0).

#q: Do nothing if control flow is LTR, quit and return top of stack as exit code if RTL.

Due to wrapping, this is a loop. At EOF, ~ reflects, thus executing the last portion RTL.

Previous version

~'0-+2j@.

Try it online!

Explanation

As above, but replace #q with:

2j@.: Jumps over the exit and print if control flow is LTR, prints top of stack as an integer then exits if RTL (push 2, jump, exit, print).

Rockstar, 75 65 56 bytes

listen to N
cut N
X's 0
while N
let X be+roll N-0

say X

Try it here (Code will need to be pasted in)

listen to N     :Read input string into variable N
cut N           :Split to an array
X's 0           :Initialise X as 0
while N         :While N is not empty
let X be+       :  Increment X by
  roll N        :    Pop the first element from N
  -0            :    Subtract an 0 to cast it to an integer
                :End while loop
say X           :Output X

Perl 5 -F -E, 18 bytes

$s+=$_ for@F;say$s

Try it online!

Zsh, 31 bytes

for i (${(s::)1})((n+=i));<<<$n

Try it online!

Python, 42 Bytes

lambda x:sum(int(y) for y in list(str(x)))

Try this code online

Nibbles, 2.5 bytes

+`@10

Attempt This Online!

Explained

+`@10
+      # Sum of
 `@    # input converted to
   10  # base 10 (basically, list of digits)

Leaf-Lang, 95 bytes

macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p 1p s print

Explaination

Leaf Lang is a lang I made in my free time in college. It is a stack-based programming language. It can be hard to understand, so I wrote a step-by-step golf of my solution.

The readable solution

"" input splitString # split input into array of strings
0 : sum              # sum = 0
"" = 0 =             # loop condition
while
        pop pop pop pop      # clean stack of condition
        toNumber sum + : sum # sum = sum + toNumber
        "" = 0 =             # loop condition
stop

pop pop pop pop # clean stack of condition
pop             # clean stack of stop condition

sum # add sum to stack
print

Compressed readable solution, 109 bytes

""input splitString 0:sum""=0=while pop pop pop pop toNumber sum+:sum""=0=stop pop pop pop pop pop sum print

Macro optimization #1, 98 bytes

macro p pop end""input splitString 0:s""=0=while p p p p toNumber s+:s""=0=stop p p p p p s print

This uses a macro to shorten the long chains of pop calls.

Macro optimization #2, 96 bytes

macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p pop s print

The final golf code, 95 bytes

macro p pop pop end""input splitString 0:s""=0=while p p toNumber s+:s""=0=stop p p 1p s print

The final code abuses my parser to push a 1 to the stack then call the p macro to essentially make a single pop call.

C (gcc), 29 27 25 bytes

f(i){i=i?i%10+f(i/10):0;}

Try it online!

-2 bytes thanks to Giuseppe

-2 bytes thanks to c--

Takes input as int.

C's int isn't large enough for the last test case.

The bracket around the ternary is truly awful. Wish I could remove that. Thanks c-- again.

C (gcc), 38 36 bytes (no recursion).

a;f(i){for(a=0;i;i/=10)a+=i%10;a=a;}

Try it online!

-2 bytes thanks to Giuseppe

Takes input as int.

C's int isn't large enough for the last test case.

C (gcc), 56 bytes (no recursion) (outgolfed by c-- using recursion).

a,n;f(char*s){for(a=0,n=strlen(s);n--;++s)a+=*s-48;a=a;}

Takes input as string

Try it online!

Lua, 40 bytes

a=0(...):gsub('.',load'a=...+a')print(a)

Try it online!

Rust, 54 47 30 bytes

|n|n.map(|b|b as u64-48).sum()

A function that takes a std::str::Bytes and returns a u64. For the purpose of this challenge, I consider std::str::Bytes to be an iterator of ASCII-characters, which meets our general criteria for a string.

Previous versions:

|mut n|{let mut s=0;while n>0{s+=n%10;n/=10;}s}
|n|n.to_string().bytes().map(|d|u64::from(d)-48).sum()

PowerShell, 39 bytes

param([string]$i)($i|% t*y)-join"+"|iex

Try it online!

Java 8 (OpenJDK 8), 31 bytes

Very classic answer in Java

s->s.chars().map(e->e-48).sum()

Try it online!

Javascript, 42 bytes

This new and improved version supports BigInt, as well as numbers and strings. It uses tsh's idea, but it first changes the type and uses the ES10 BigInt. (It also happens to be the shortest I could come up with!)

a=n=>eval("x=BigInt(n);x&&x%10n+a(x/10n)")

I also tried playing around and created these functions:

// BigInt/String/Number
b=n=>eval("l=0;(n+[]).split('').forEach(t=>l+=+t);l")
// String only
c=n=>eval("l=0;n.split('').forEach(t=>l+=+t);l")
// BigInt only
d=n=>n&&n%10n+d(n/10n)
// String/Number
e=n=>+n&&+n%10+e(+n/10|0)

APL, 5 bytes

+/⍎¨⍞

Explanation:

Try it online!

KAP, 7 characters, 11 bytes:

+/@0-⍨⍕

Try it online.

It appears that one needs bigint support to properly answer this question. If strings are allowed then the last character can be removed from the answer.

vemf, 6 bytes

ª-:48+

Input is a number literal.

try it online, uses :314159 as example

Explanation

ª      ' represent as a codepage string
 -:48  ' subtract 48 from each codepoint
       ' (so the codepoints are all now 0-9)
     + ' sum list

K (ngn/k), 5 bytes

+/10\

Try it online!

Trilangle, 15 bytes

'0.<"@(+>i(^-<!

Test it on the online interpreter!


Roughly equivalent to this C code:

#include <stdio.h>

int main() {
    int total = 0;
    int i;
    while ((i = getchar()) != EOF) {
        total += i - '0';
    }
    printf("%d\n", total);
}

Control flow is kinda weird so it actually calls getchar() a couple times even after EOF is reached.


Unfolds to this:

    '
   0 .
  < " @
 ( + > i
( ^ - < !

With code paths highlighted:

Control flow starts at the north corner heading southwest (on the red path). Instructions are executed as follows:

If the value is positive (any character that isn't EOF), the IP takes the green path:

Once EOF is read, the IP takes the blue path, printing out the stored value... eventually. As you can see from the image it takes the scenic route.

bc, 35 bytes

for(;i<length(a);i++)b+=a/10^i%10;b

Try it online!

Using the default scale=0 i.e. no decimals, divide by 1,10,100,... successively (a/10^i), and %10 to add only the last digit to b. When the for loop finishes, print the sum. ;b

Google Sheets, 44 bytes

=QUERY(,"select "&REGEXREPLACE(A1,"\B","+"))

KamilaLisp v0.2, 15 (APL SBCS)

$(⌿.← +)∘:⊙⍫∘⍫∧

Equivalent to $(foldl1 +)@:parse-number@str:explode.

Julia, 12 10 bytes

Tacit Julia strikes again!

sum∘digits

Explanation:

digits: take an integer and return a vector of its digits in base 10 (default)
∘: function composition
sum: sum a collection

Try it online!

-2 thanks to MarcMush

Vyxal 3.0.0-beta.1, 9 bytes

'%%O48-/+

Try it online! (link is to literate version)

Unlike my v2 answer, there is no sum flag, sum built-in, cast to int or cast to string built in in this version of vyxal (because it's a beta release - what do you expect?).

Explained

'%%O48-/+
'%%        ## Format the input as a string
   O48-    ## get the ordinal value of each character and subtract 48 to get the digit value
       /+  ## fold by addition

Brachylog, 2 bytes

ẹ+

Try it online!

Explanation

is a pretty disgusting built-in for a declarative logic language, but it’s useful. A "better" alternative would be ∋ᶠ (find all elements) but it’s longer.

ẹ     Split into a list of elements
 +    Sum

Pascal, 114 bytes

This is a full program according to ISO standard 7185 “Standard Pascal”. The built-in data type integer comprises (at least) all integral values in the range −maxInt..maxInt. The value of maxInt is implementation-defined. In order to successfully test values up to and including one googol you will need a processor (this refers to the specific combination of machine, compiler, OS, etc.) defining maxInt ≥ 10100.

program p(input,output);var x,y:integer;begin y:=0;read(x);repeat y:=y+x mod 10;x:=x div 10 until x=0;write(y)end.

Ungolfed:

program digitSum(input, output);
    var
        x, digitSum: integer;
    begin
        digitSum := 0;
        read(x);
        
        repeat
        begin
            digitSum := digitSum + x mod 10;
            x := x div 10;
        end
        until x = 0;
        
        write(digitSum);
    end.

Because in Pascal mod is defined to always yield a non-negative result, digitSum works incorrectly for negative inputs. Injecting an x := abs(x); prior the loop will resolve this issue.


Another method is of course to process characters. In Pascal it is guaranteed that the characters '0' through '9' are in ascending order and consecutive, thus ord('9') − ord('0') is guaranteed to yield the integer value 9.

program p(input,output);var x:integer;begin x:=0;while not EOF do begin x:=x+ord(input^)-ord('0');get(input)end;write(x)end.

Input must not be followed by a newline, or replace the EOF by EOLn. This program is ≥ 124 bytes

Raku, 19 16 bytes

say [+] get.comb

Try it online!

get(): gets a single line from stdin (parens not required)

`.univals()`: maps a string of numerical unicode chars to a list of their values. I'm just using it in place of `.split("")`, which would be 2 bytes longer.

.comb: splits out to list of characters (thanks @Mark Reed)

[+]: reduces the list by addition.

say: writes to stdout

Groovy, 37 bytes

def c={("$it"as List).sum{it as int}}

Try it online!

APL, 9 bytes (?)

sd←+/⊥⍣¯1

Some characters take probably more than 1 byte, but I am not sure how many...

I saw this and just had to give it a go with Java. I mean, I'm not going to win, but it's in good fun, right? Using loops, assuming that we can have multiple inputs, including 0:

class D{public static void main(String[]a){int s=0;for(String t:a)for(char c:t.toCharArray())s+=c-48;System.out.println(s);}}

That gives 125 bytes, but if we assume some assumptions, we can surely get it lower. If we assume one and only input, we don't have to loop, so we can shorten it down further. But if we also stream, we get:

class D{public static void main(String[]a){System.out.println(a[0].chars().map(i->i-48).sum());}}

Which clocks in at 97 bytes.

That's not too bad for Java.

J, 13 bytes

[: +/ 48 -~ a. I. ]

Pyth, 4 bytes

ssMz

Try it online!

Alternatively there's sjQT or just ssM if we're allowed to have quotes around the input.

GolfScript, 11 bytes

`1/{~}%{+}*

Try it online!

A function which takes a single integer as input. Link includes test cases.

Explanation

`1/{~}%{+}* # whole function
`           # convert the input into a string
  /         # split into groups of size
 1          # 1
   { }%     # for each value in the split groups...
    ~       # eval it
       {+}* # sum this `eval`ed array

Excel, 32 31 30 bytes

=SUM(0+(0&MID(A1,ROW(A:A),1)))

Input in cell A1.

Thanks to user117069 and EngineerToast for the two bytes saved.

Typescript Type System + hotscript, 92 87 bytes

import{Pipe,S,T}from"hotscript"
type _<U>=Pipe<U,[S.Split<"">,T.Map<S.ToNumber>,T.Sum]>

I just found out about this library that basically turns the Typescript Type System into a full-on functional programming language and it's amazing

Saved 5 bytes by taking input as a string instead of a number

TS Playground Link

import{Pipe,S,T}from"hotscript"
type _<U>=           // define hotscript lambda with string argument U
Pipe<U,[             // pipe U to:
  S.Split<"">,       //   split on "" (= character list)
  T.Map<S.ToNumber>, //   map each letter to number
  T.Sum              //   sum 
]>                   // end pipe

JavaScript (Node.js), 22 bytes

f=n=>n&&n%10+f(n/10|0)

Try it online!


JavaScript (Node.js), 21 bytes

f=n=>n&&n*9%9-f(n/~9)

Try it online!

It is shorter, but with floating point errors...

Brain-Flak, 150 bytes

{(({})<><((()()()()()){})>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}{})<>({}<((()()()()()){})>(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)}<>

Not sure if this counts, because it exceeds TIO's 60s time limit for the 3141592653589793238462643383279502884197169399375105820974944592 test case, as its' time complexity is linear. Theoretically, given enough time, it should output the right answer. This answer is extremely similar in format to my answer here.

{                                                                               #  loop while top of left stack is not 0
(({})<><((()()()()()){})>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}{})<>    #  add the result of modulo 10 of the top value of the left stack to the top value on the right stack
({}<((()()()()()){})>(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)          #  integer division by 10 on left stack
}                                                                               #  end loop
<>                                                                              #  switch to right stack
                                                                                #  implicit output of active (right) stack

Try it online!

MathGolf, 1 byte

Σ

Try it online.

Explanation:

Σ  # Sum the digits of the (implicit) input-integer
   # (after which the entire stack is output implicitly as result)

Wolfram Language (Mathematica), 19 bytes

Total@IntegerDigits

Try it online!

Total@IntegerDigits@3141592653589793238462643383279502884197169399375105820974944592

315

PowerShell Core, 31 bytes

%{$s=0;$_|% *ay|%{$s+="$_"};$s}

Input comes from the pipeline

Try it online!

%{$s=0;$_|% *ay|%{$s+="$_"};$s}
%{                            } # % is an alias for the cmdlet ForEach-Object; input (the string containing the number) comes from the pipeline and will be in $_
  $s=0;                         # initialize the final sum
       $_|% *ay                 # takes the input string and passes it to "ForEach-Object -MemberName ToCharArray": turns the string into an array of characters. This is shorter than a cast using [char[]]$_
               |%{$s+="$_"};    # pass the single characters to yet another ForEach-Object which sums up the total. The current character in $_ must be turned into a single-char string by wrapping it in double quotes;
                                # without that, PS would add up the character's byte code since the left operand (the sum) is an integer.
                            $s  # output the sum

JavaScript (Node.js), 23 bytes

n=>eval([...n].join`+`)

Try it online!

Takes input as a string

JavaScript (Node.js), 26 bytes

n=>eval([...""+n].join`+`)

Try it online!

Takes input as a number, doesn't work if the number is too large for JavaScript to stringify naturally

NOTE: Since many/most of the answers seem to ignore the requirement in the question that the input must be taken from stdin and the output must be sent to stdout, I suppose it is reasonable if I do so, too. I think that's a silly and arbitrary requirement, because it makes many languages non-competitive. The standard on Code Golf is to allow functions, and to allow functions taking input via arguments and outputting via their return value(s), so this is what I will follow.

x86-64 Assembly, standard Linux calling convention, 17 bytes

64 31 C0 0F B6 0F E3 09 48 FF C7 8D 44 01 D0 EB F2 C3   

Try it online!

This is a minor, iterative improvement on qwr's answer, which is 18 bytes.

It saves 1 byte by using the relatively-obscure JECXZ instruction (actually JRCXZ, since this is 64-bit mode), which jumps if the value of the rcx register is zero.

It also improves on qwr's original (arguably fixes a bug?) in that it supports the case where the input is an empty string, returning a sum of zero. (To be fair, the challenge doesn't specify whether it is required to handle this, so maybe it cannot be termed a "bug", and, in fact, my next attempt will have this same "bug", so I can hardly ding qwr for taking advantage of it, too!)

SumDigits:
  31 C0         xor    eax, eax
Loop:
  0F B6 0F      movzx  ecx, BYTE PTR [rdi]
  E3 09         jrcxz  End
  48 FF C7      inc    rdi
  8D 44 01 D0   lea    eax, [rcx + rax - '0']
  EB F2         jmp    Loop
End:
  C3            ret    ; result is in eax

x86-64 Assembly, fully custom calling convention, 14 bytes

64 31 C0 31 D2 AC 8D 54 02 D0 38 26 75 F7 C3   

Try it online!

This is a variation on the same theme (it still takes the input as a pointer to the beginning of a NUL-terminated ASCII string), but it pulls out all the stops to really optimize for size:

SumDigits:
  --          ; cld                           ; can assume DF is always clear on Linux)
  31 C0         xor    eax, eax               ; eax  = 0 (al = 0, ah = 0)
  31 D2         xor    edx, edx               ; edx  = 0 (holds result)
Loop:
  AC            lods                          ; al   = BYTE PTR [rsi]
  8D 54 02 D0   lea    edx, [rdx + rax - '0'] ; edx += (eax - '0')
  38 26         cmp    BYTE PTR [rsi], ah     ; is BYTE PTR [rsi] == ah (which is 0)?
  75 F7         jne    Loop                   ; loop back if not equal (non-zero)
  C3            ret                           ; result is in edx

The custom calling convention is a pretty major "cheat" here, but it's not unusual in the "real world" to use a custom calling convention when writing code in assembly. If you're going to call it from C, you need to take steps to match the standard C calling convention, but who says we're calling it from C?! We don't need no stinkin' C! :-)

Hebigo, 25 bytes

print:sum:map: int input:

(It compiles to the following Python.)

print(
  sum(
    map(
      int,
      input())))

C (gcc), 30 bytes

f(int*s){s=*s?*s-48+f(s+1):0;}

Try it online!

C (clang), 31 bytes

f(*s){return*s?*s-48+f(s+1):0;}

Try it online!

C89, 35 bytes

f(char*s){return*s?*s-48+f(s+1):0;}

Try it online!

Pip, 3 bytes

$+a

Attempt This Online!

$+    sum of
      (the digits of)
  a   the input

Jelly, 2 bytes

DS

Try it online!

D    digits
 S   sum

Python, 24 bytes

lambda n:sum(map(int,n))

Attempt This Online!

Input as a string.

Python, 29 bytes

lambda n:sum(map(int,str(n)))

Attempt This Online!

Input as an integer.

Ly, 3 bytes

S&+

Try it online!

Breaks STDIN into digits and pushes onto the stack, then uses &+ to sum them. Prints the stack as a number be default when the code exits.

Ruby, 17 bytes

->x{x.digits.sum}

This defines an anonymous function that accepts a single input (a number), breaks it up into an array of digits, then sums this array and returns the result

Standard ML, 43 bytes

(foldl op+ 0)o map(fn x=>ord x-48)o explode

Lack of sum function strikes again

Factor + math.unicode, 18 bytes

[ >dec 48 v-n Σ ]

Attempt This Online!

Proton, 14 bytes

digits(10)+sum

Try it online!

digits(x, y) converts y into digits in base x and sum performs sum. Therefore, digits(10) is a partial function that becomes y => digits(10, y) and + sum chains it with sum so an input will be called with digits(10)(...) first, and then the result is called with sum(...).

This is 6 bytes shorter than the straightforward x=>sum(digits(10,x)).

Charcoal, 3 bytes

IΣN

Try it online! Link is to verbose version of code. Explanation:

  N Input number
 Σ  Sum of digits
I   Cast to string
    Implicitly print

Retina 0.8.2, 6 bytes

.
$*
1

Try it online! Link includes test cases. Explanation:

.
$*

Convert each digit to unary.

1

Convert the sum to decimal.

Perl 5 -p, 19 bytes

s/./$s+=$&/ge;$_=$s

Try it online!

Arturo, 15 bytes

$=>[∑digits&]

Try it

Even though the question says input and output must be via standard IO, the author of the question said functions are allowed in the comments. So this is a function.

MATL, 3 bytes

!Us

Try it out at MATL Online

Explanation

      % Implicitly read in first input, a 1 x N string
!     % Flip it so that it is N x 1 character array (one character per row)
U     % Convert each row from a string to a number
s     % Sum the resulting N x 1 numeric array
      % Implicitly display the result

Pari/GP, 9 bytes

sumdigits

Try it online!

05AB1E, 2 bytes

SO

Try it online!

Thunno, \$2 \log_{256}(96)\approx\$ 1.646 bytes

dS

Attempt This Online!

d    digits of input
 S   calculate sum

Japt -x, 1 byte

ì

Try it

ì gets the digits of the number, the -x flag sums the resulting array

Fig, \$1\log_{256}(96)\approx\$ 0.823 bytes

S

Try it online!

Builtin

Vyxal s, 0 bytes


Try it Online!

That's right. No bytes needed.

Alternatively

Vyxal, 1 byte

Try it Online!

Just the built-in that works on numbers