TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
sum_of_digits.cpp File Reference

A C++ Program to find the Sum of Digits of input integer. More...

#include <cassert>
#include <iostream>
Include dependency graph for sum_of_digits.cpp:

Go to the source code of this file.

Functions

int sum_of_digits (int num)
 
void test1 ()
 
void test2 ()
 
void test ()
 
int main ()
 

Detailed Description

A C++ Program to find the Sum of Digits of input integer.

Copyright 2020

Author
iamnambiar

Definition in file sum_of_digits.cpp.

Function Documentation

◆ main()

int main ( void )

Main Function

Definition at line 68 of file sum_of_digits.cpp.

68 {
69 test();
70 std::cout << "Success." << std::endl;
71 return 0;
72}
void test()

◆ sum_of_digits()

int sum_of_digits ( int num)

Function to find the sum of the digits of an integer.

Parameters
numThe integer.
Returns
Sum of the digits of the integer.

\detail First the algorithm check whether the num is negative or positive, if it is negative, then we neglect the negative sign. Next, the algorithm extract the last digit of num by dividing by 10 and extracting the remainder and this is added to the sum. The number is then divided by 10 to remove the last digit. This loop continues until num becomes 0.

Definition at line 23 of file sum_of_digits.cpp.

23 {
24 // If num is negative then negative sign is neglected.
25 if (num < 0) {
26 num = -1 * num;
27 }
28 int sum = 0;
29 while (num > 0) {
30 sum = sum + (num % 10);
31 num = num / 10;
32 }
33 return sum;
34}
T sum(const std::vector< std::valarray< T > > &A)

◆ test()

void test ( )

Function for testing the sum_of_digits() with all the test cases.

Definition at line 58 of file sum_of_digits.cpp.

58 {
59 // First test.
60 test1();
61 // Second test.
62 test2();
63}
void test2()
void test1()

◆ test1()

void test1 ( )

Function for testing the sum_of_digits() function with a first test case of 119765 and assert statement.

Definition at line 40 of file sum_of_digits.cpp.

40 {
41 int test_case_1 = sum_of_digits(119765);
42 assert(test_case_1 == 29);
43}
int sum_of_digits(int num)

◆ test2()

void test2 ( )

Function for testing the sum_of_digits() function with a second test case of -12256 and assert statement.

Definition at line 49 of file sum_of_digits.cpp.

49 {
50 int test_case_2 = sum_of_digits(-12256);
51 assert(test_case_2 == 16);
52}