Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please help. I can\'t get the sum and the largest and lowest digit to show up ri

ID: 3658558 • Letter: P

Question

Please help. I can't get the sum and the largest and lowest digit to show up right. Could you please tell me what I have done wrong. Here is the programming challenge Write a program that asks the user to enter a series of single digit number 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 lowest digits in the string. Here is the program that I wrote #include #include //Needed for strings #include //Needed for atoi using namespace std; int main () { const int DIGITS = 15; //Array size char num[DIGITS]; //To hold input int count = 0; //Loop counter /*Variables to convert string to interger*/ int number, largest, lowest; //To convert string to integers while (num[DIGITS] != '') count++; number = atoi(num); //Get numbers entered cout << "Enter a series of single digits with no spaces in between "; cin.getline(num, DIGITS); //Display sum of the numbers entered int sum = 0; //Inititalize accumulator for(int count = 0; count < DIGITS; count++) sum += num[count]; //Display the largest number entered largest = num[0]; for(count = 1; count < DIGITS; count++) { if(num[count] > largest) largest = num[count]; } //Display the lowest number entered lowest = num[0]; for(count = 1; count < DIGITS; count++) { if(num[count] < lowest) lowest = num[count]; } cout << "The sum of the numbers entered is " << sum; cout << endl; cout << "The largest number entered is " << largest; cout << endl; cout << "The lowest number entered is " << lowest; cout << endl; system ("pause"); return 0; }

Explanation / Answer

while (num[DIGITS] != '') count++; - This is not correct because num is array of size DIGITS and hence you cannot acces beyond num[DIGITS-1]. It should be while(num[count]!='') count++;