My assignment is to have the user input an integer, output each digit and then add the sum of the digits. I've outputted the digits, but now I need to know how to get the sum. My digits are char variables and I know I need too change them to int. Thanks
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int num;
int sum = 0;
while(cin){
cout << "Please enter the number:";
cin >> num;
sum += num;
cout << "current sum is " << sum << endl;
}
}
#include <iostream>
usingnamespace std;
int main(int argc, char** argv) {
int maxSize = 25;
int numbers[maxSize];
int sum = 0;
int num;
cout << "Please enter an integer. ";
for (int i = 0; i < maxSize; i++)
{
cin >> numbers[num];
}
for (int i = 0; i < maxSize; i++)
{
cout << numbers[num] << " ";
sum += num;
}
cout << "Sum = " << sum;
return 0;
}
maxSize needs to be declared as constint maxSize = 25;.
On lines 14 and 19, I think you mean numbers[i] instead of numbers[num] (num is never initialized in your code, anyways).
Line 20 should probably also be numbers[i].
Other than that, what your program does is get 25 integers from the user and sum them up. If you were trying to compute the sum of the digits of a number, that's not what this program does (unless you enter one 25-digit number with each digit separated by a space).
Now, if you were planning on having each digit separated by a space, you would need some way to know when the number stops (otherwise you would always have to enter 25 digits).
Perhaps you could implement something where you stop reading input (and summing numbers) when you encounter a -1.
If you just want a sum, you don't even need an array -- just change numbers[num] to just num and combine your two for loops into one. (A for loop might not be appropriate here -- maybe a while loop that goes until you see a -1 or something would be better)
#include <iostream>
#include <vector>
int main()
{
std::vector<int> container;
int number;
int sum = 0;
while(true){
std::cout << "Please enter a number" << std::endl;
std::cin >> number;
container.push_back(number);
sum += number;
std::cout << "The sum of [";
//print all except the last int to get the commas right
for(int i=0; i<container.size()-1; i++){
std::cout << container[i] << ", ";
}
//print the last int
std::cout << container[container.size()-1] << "] is " << sum << std::endl;
}
}
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string num = "";
int total = 0;
cout << "Please enter a number: ";
getline(cin, num);
for (int i = 0; i < num.size(); i++)
{
cout << num.at(i) << ' ';
total += num.at(i) - '0';
}
cout << "\nThe total is: " << total << endl;
cin.ignore();
return 0;
}
include <iostream>
usingnamespace std;
int main()
{
int total = 0;
char temp = '0';
cout << "Please enter a number: ";
while ((temp = cin.get()) != '\n')
{
cout << temp << ' ';
total += temp - '0';
}
cout << endl;
cout << "The total is: " << total << endl;
cin.ignore();
return 0;
}