Search
 
SCRIPT & CODE EXAMPLE
 

CPP

sum of digits in c++

int x, s = 0;
   cout << "Enter the number : ";
   cin >> x;
   while (x != 0) {
      s = s + x % 10;
      x = x / 10;
   }
Comment

C++ sum the digits of an integer

// sum the digits of an integer
int getSum(long long n) {
  int sum = 0;
  int m = n;
  while(n > 0) {    
    m = n % 10;    
    sum = sum + m;    
    n = n / 10;    
  } 
  return sum;
}
Comment

digit sum c++

//1
	int n = 12345, sum = 0;
    while(n) {
        sum+=n%10;
        n/=10;
    }
    cout << sum; //15
//2
	int n = 12345, sum = 0;
    for (sum = 0; n > 0; sum += n % 10, n /= 10);
    cout << sum; //15
Comment

c++ Program for Sum of the digits of a given number

// C program to compute sum of digits in
// number.
#include <iostream>
using namespace std;
 
/* Function to get sum of digits */
class gfg {
public:
    int getSum(int n)
    {
        int sum = 0;
        while (n != 0) {
            sum = sum + n % 10;
            n = n / 10;
        }
        return sum;
    }
};
 
// Driver code
int main()
{
    gfg g;
    int n = 687;
    cout << g.getSum(n);
    return 0;
}
// This code is contributed by Soumik
Comment

PREVIOUS NEXT
Code Example
Cpp :: convert integer to string c++ 
Cpp :: how to get the first element of a map in c++ 
Cpp :: c++ print string 
Cpp :: set was not declared in this scope 
Cpp :: c vs c++ 
Cpp :: c++ isalphanum 
Cpp :: ViewController import 
Cpp :: size of pointer array 
Cpp :: reading file c++ 
Cpp :: c++ remove last character from string 
Cpp :: c++ vectors 
Cpp :: c++ loop vector 
Cpp :: checking if a string has only letters cpp 
Cpp :: c++ public class syntax 
Cpp :: concat two vectors c++ 
Cpp :: cpp string slice 
Cpp :: sorting using comparator in c++ 
Cpp :: modulo subtraction 
Cpp :: anagram solution in c++ 
Cpp :: how to add external library in clion 
Cpp :: sleep in c++ 
Cpp :: setw c++ 
Cpp :: letter occurrence in string c++ 
Cpp :: cpp string find all occurence 
Cpp :: how to cout in c++ 
Cpp :: input full line as input in cpp 
Cpp :: create matrix cpp 
Cpp :: rotate an array of n elements to the right by k steps 
Cpp :: accumulate vector c++ 
Cpp :: preorder 
ADD CONTENT
Topic
Content
Source link
Name
8+3 =