**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 ` |

*chevron_right*

*filter_none*

**Output:**

sum of digits = 21

## Recommended Posts:

- Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
- Sum of digits equal to a given number in PL/SQL
- Count odd and even digits in a number in PL/SQL
- SQL | Procedures in PL/SQL
- SQL | Difference between functions and stored procedures in PL/SQL
- Difference between SQL and T-SQL
- Sum of the first and last digit of a number in PL/SQL
- Sum and average of three numbers in PL/SQL
- Sum Of Two Numbers in PL/SQL
- Print all odd numbers and their sum from 1 to n in PL/SQL
- Finding sum of first n natural numbers in PL/SQL
- SQL COUNT(), AVG() and SUM()
- Reverse a number in PL/SQL
- Check if a number is Palindrome in PL/SQL
- Find the factorial of a number in pl/sql
- Factorial of a number in PL/SQL
- Check Armstrong Number in PL/SQL
- Prime number in PL/SQL
- Check whether a given number is even or odd in PL/SQL
- Greatest number among three given numbers in PL/SQL

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.