A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://TheAlgorithms.github.io/C-Plus-Plus/d4/d83/sum__of__digits_8cpp.html below:

TheAlgorithms/C++: math/sum_of_digits.cpp File Reference

Loading...

Searching...

No Matches

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

#include <cassert>
#include <iostream>

Go to the source code of this file.

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

Copyright 2020

Definition in file sum_of_digits.cpp.

◆ main()

Main Function

Definition at line 68 of file sum_of_digits.cpp.

68 {

70 std::cout << "Success." << std::endl;

71 return 0;

72}

◆ sum_of_digits() int sum_of_digits ( int num )

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

Parameters
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

25 if (num < 0) {

26 num = -1 * num;

27 }

29 while (num > 0) {

31 num = num / 10;

32 }

34}

T sum(const std::vector< std::valarray< T > > &A)

◆ test() ◆ 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 {

42 assert(test_case_1 == 29);

43}

int sum_of_digits(int num)

◆ 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 {

51 assert(test_case_2 == 16);

52}


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4