
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- Write a Golang program to find the factorial of a given number (Using Recursion)
- C++ Program to Sum the digits of a given number
- Golang Program to find the parity of a given number.
- Write a Golang program to calculate the sum of elements in a given array
- Golang Program to Count the Number of Digits in a Number
- Write a Golang program to reverse a number
- 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))
- Program to find the sum of all digits of given number in Python
- Write a program in Python to count the number of digits in a given number N
- Write a Golang program to find prime numbers in a given range
- Write a Golang program to find duplicate elements in a given array
- Write a Golang program to find duplicate elements in a given range
- Write a Golang program to find pairs with given sum in an array(O(nlogn))
- C Program to sum the digits of a given number in single statement
Advertisements