- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a Golang program to find the sum of digits for a given number
Examples
- num = 125 => 1 + 2 + 5 = 8
- num = 101 => 1 + 0 + 1 = 2
- num = 151 => 1 + 5 + 1 = 7
Approach to solve this problem
Step 1: Define a function that accepts numbers(num); type is int.
Step 2: Start a true loop until num becomes 0 and define res:=0.
Step 3: Find modulo and add to res.
Step 4: Divide num by 10.
Step 5: Return res.
Program
package main import "fmt" func findDigitSum(num int) int { res := 0 for num>0 { res += num % 10 num /= 10 } return res } func main(){ fmt.Println(findDigitSum(168)) fmt.Println(findDigitSum(576)) fmt.Println(findDigitSum(12345)) }
Output
15 18 15
- Related Articles
- C++ Program to Sum the digits of a given number
- Write a Golang program to find the factorial of a given number (Using Recursion)
- Program to find the sum of all digits of given number in Python
- Write a Golang program to calculate the sum of elements in a given array
- C Program to sum the digits of a given number in single statement
- Write a program in Python to count the number of digits in a given number N
- Golang Program to find the parity of a given number.
- Golang Program to Count the Number of Digits in a Number
- C# program to find the sum of digits of a number using Recursion
- Java Program to Find Sum of Digits of a Number using Recursion
- C program to find sum of digits of a five digit number
- Haskell Program to Find Sum of Digits of a Number using Recursion
- Write a Golang program to find pairs with the given sum in an array(O(n2))
- Write a Golang program to find pairs with the given sum in an array(O(n))
- Python Program to Find the Sum of Digits in a Number without Recursion

Advertisements