#include <iostream>
#include <string>
constunsigned num_to_compare = 15;
bool IsEqual(int num, unsigned num_to_compare = num_to_compare);
int main()
{
constint array_size = 10;
int array[array_size] = { 19, 32, 69, -44, 5, 63, -7, 8, -29, 906 };
for (unsigned loop = 0; loop < array_size; loop++)
{
if (IsEqual(array[loop]))
{
std::cout << array[loop] << " sums to " << num_to_compare << "\n\n";
}
else
{
std::cout << array[loop] << " does NOT sum to " << num_to_compare << "\n\n";
}
}
}
bool IsEqual(int num, unsigned num_compare)
{
// get the absolute (positive) value of the passed number
unsigned abs_num = abs(num);
// turn it into a string
std::string num_str = std::to_string(abs_num);
unsigned sum = 0;
// use a C++11 for loop to walk through the string
for (auto loop: num_str)
{
// obtain each individual stringized digit
std::string temp_str = { loop };
// covert each digit to an integer and add to the sum
sum += std::stoi(temp_str);
// printout the ongoing sum for testing purposes
// you can remove this if you want
std::cout << "\t" << temp_str << "\t" << sum << "\n";
}
// compare the complete sum with the number to compare
if (sum == num_compare)
{
returntrue;
}
else
{
returnfalse;
}
}
1 1
9 10
19 does NOT sum to 15
3 3
2 5
32 does NOT sum to 15
6 6
9 15
69 sums to 15
4 4
4 8
-44 does NOT sum to 15
5 5
5 does NOT sum to 15
6 6
3 9
63 does NOT sum to 15
7 7
-7 does NOT sum to 15
8 8
8 does NOT sum to 15
2 2
9 11
-29 does NOT sum to 15
9 9
0 9
6 15
906 sums to 15
It might be better to rewrite the array to being a vector, it maintains its own count of elements so no need to have a separate array size variable:
#include <iostream>
#include <string>
#include <vector>
constunsigned num_to_compare = 15;
bool IsEqual(int num, unsigned num_to_compare = num_to_compare);
int main()
{
std::vector<int> array = { 19, 32, 69, -44, 5, 63, -7, 8, -29, 906 };
for (unsigned loop = 0; loop < array.size(); loop++)
{
if (IsEqual(array[loop]))
{
std::cout << array[loop] << " sums to " << num_to_compare << "\n\n";
}
else
{
std::cout << array[loop] << " does NOT sum to " << num_to_compare << "\n\n";
}
}
}
bool IsEqual(int num, unsigned num_compare)
{
// get the absolute (positive) value of the passed number
unsigned abs_num = abs(num);
// turn it into a string
std::string num_str = std::to_string(abs_num);
unsigned sum = 0;
// use a C++11 for loop to walk through the string
for (auto loop: num_str)
{
// obtain each individual stringized digit
std::string temp_str = { loop };
// covert each digit to an integer and add to the sum
sum += std::stoi(temp_str);
// printout the ongoing sum for testing purposes
// you can remove this if you want
std::cout << "\t" << temp_str << "\t" << sum << "\n";
}
// compare the complete sum with the number to compare
if (sum == num_compare)
{
returntrue;
}
else
{
returnfalse;
}
}
If you don't want to do the string manipulation there is ways to parse out the individual digits using the modulo operator: