This program should display the sum, the highest and the lowest numbers of the entered C-string. I have no problem finding both the sum and the highest but I can't seem to get the lowest number to work. Thanks for the help!
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
const int length = 1000; // To provide the user with up to 1000 numbers to put in for the series
char sum[length],
highest = sum[0],
lowest = sum[0];
int total = 0,
index,
index2,
index3;
cout << "Enter any series of numbers and I will return the sum, the highest \n";
cout << "and the lowest number: ";
cin >> sum;
// For loop is used to get each individual number from the string and convert
// them to numbers so that they can be added up.
for (index = 0; index < strlen(sum); index++)
{
total += sum[index] - '0';
}
// For loop used for determining the highest number in the series.
for (int index2 = 0; index2 < strlen(sum); index2++)
{
if (sum[index2] > highest)
{
highest = sum[index2];
}
}
// For loop used for determining the lowest number in the series.
for (index3 = 0; index3 < strlen(sum); index3++)
{
if (sum[index3] < lowest)
{
lowest = sum[index3];
}
}
cout << "The sum of the numbers that you provide me with is: " << total << "\n";
cout << "The highest number in the series is: " << highest << "\n";
cout << "The lowest number in the series is: " << lowest << "\n";
return 0;
}
Use std::max_element(sum,sum+strlen(sum)) from #include <algorithm> to get the largest element.
NB. the function returns a pointer to the largest element so you have to deference it to get the actual value.
#include <iostream>
usingnamespace std;
int main()
{
char word[] = "1234";
char max = word[0]; //assume first char to be max
for(int i = 0; i < strlen(word); i++)
{
if(word[i] > max)
max = word[i];
}
cout<<"max is "<<max<<endl;
system("pause");
return 0;
}
Well that's for max. and if you look back at mine I already have that set up but viewed as "highest". My problem is doing lowest, do you have a solution for that?
int main()
{
constint length = 1000; // To provide the user with up to 1000 numbers to put in for the series
char sum[length],
highest = sum[0],
lowest = sum[0];
cout<<static_cast<int>(lowest)<<" "<<static_cast<int>(highest)<<endl;
}
lowest and highest are both negative coz you assume them to sum[o] before sum gets any valid chars.
Hence, no input will be less than the negative lowest but will always be greater than highest.
thats why you get the foreign char for lowest.
so that my lowest variable would be obviously less than sum[length] but that didn't seem to make a difference either; it still resulted in a foreign char, any idea?