I can't seem to figure out how to get smallest and largest

Write a program that asks the user to enter a series of single digit numbers with nothing
separating them. Read the input as a C-string or a string object. The program should
display the sum of all the single-digit numbers in the string. For example, if the user
enters 2514, the program should display 12, which is the sum of 2, 5, 1, and 4. The
program should also display the highest and lowest digits in the string

#include <iostream>
using namespace std;
int main()
{
const int LENGTH = 100;
char bob[LENGTH];
int total=0, index;
cout << "Enter a series of numbers in a row " << endl;
cin >> bob;
for (index=0; index < strlen( bob );
index++)
{
total += bob[index] - '0';
}

cout << "The total is " << total << endl;


system("PAUSE");
return 0;
}
@jchang1210

Create two variables, like int low, int high. assign them both, the values of bob[0].
To get them to be the actual value of the char array, you subtract 48, like this.
low = int(bob[0] - 48);
The ASCII value of 0, is 48, so subtracting 48, will give the int value of zero.
Run through the index of bob again, like you did to get the value, but check against if the value is lower than the variable low, and let low equal bob[index] if it is. Same with higher.

If you still need a bit more help, show what you are having problems with, and we'll go from there.
Hello :) Maybe there is a better way to do this but what i came up with now is this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int main()
{
	const int LENGTH = 100;
	char bob[LENGTH];
	int total = 0, index;
	cout << "Enter a series of numbers in a row " << endl;
	cin >> bob;
	for (index = 0; index < strlen(bob);
		index++)
	{
		total += bob[index] - '0';
	}

	cout << "The total is " << total << endl;

	//find min
	int min = bob[0] - '0';					//assume min is the first number
	for (index = 0; index < strlen(bob);
		index++)
	{
		if ((bob[index] - '0') < min)
		{
			min = bob[index] - '0';
		}
	}
	cout << "min :" << min << endl;

	//find max
	int max = bob[0] - '0';					//assume max is the first number
	for (index = 0; index < strlen(bob);
		index++)
	{
		if ((bob[index] - '0') > max)
		{
			max = bob[index] - '0';
		}
	}
	cout << "max :" << max << endl;

	system("PAUSE");
	return 0;
}


I hope this was helpful
Topic archived. No new replies allowed.