# Sum of digits of a number in PL/ SQL

Prerequisite PL/SQL introduction
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.

Given a number and task is to find the sum of digits of the number.
Examples:

```Input: 123456
Output: 21

Input: 9874
Output: 28
```

Approach is to take a number and getting each digit with MOD function and summing it up.

Below is the required implementation:

 `DECLARE`  ` `  `    ``--Declare variable n, temp_sum   ` `    ``-- and r of datatype number  ` `    ``n        ``INTEGER``;  ` `    ``temp_sum ``INTEGER``;  ` `    ``r        ``INTEGER``;  ` `BEGIN`  `    ``n := 123456;  ` `    ``temp_sum := 0;  ` ` `  `    ``-- here we check condition with the help of while loop  ` `    ``-- here <> symbol represent for not null  ` `    ``WHILE n <> 0 LOOP  ` `        ``r := MOD(n, 10);  ` `        ``temp_sum := temp_sum + r;  ` `        ``n := Trunc(n / 10);  ` `    ``END` `LOOP;  ` `    ``dbms_output.Put_line(``'sum of digits = '`  `                         ``|| temp_sum);  ` `END``;  ` `-- Program End  `

Output:

```sum of digits = 21
```
My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.