Homework 3 Solution UCR CS10: Introduction to Computer Science Winter Quarter 2004, Lecturer: Kris Miller Due Thursday, January 29 before 2:00pm by web turnin. ------------------------------------------------------------------------------- Note: Collaboration policy for this homework assignment Collaboration on this homework is strongly ENCOURAGED. The homework is intended for practice, not assessment -- most people who turn in decent work should get most if not all points for this assignment. Forming study groups is strongly encouraged. You shouldn't simply copy answers from any source -- each other, the book, the web, other books, previous solutions, etc. But you can certainly discuss how to solve the problems, look over each others solutions and help "debug" them, compare answers and redo problems if you determine your answer is wrong, and most importantly, explain concepts related to the problems and solutions. ------------------------------------------------------------------------------- Solutions for the Self-test Exercises are in the back of each chapter. 6. Write a program that reads in characters from the user. The program should continue to read in characters one at a time until it reads in the character, z. (Hint: Use a while loop that reads in one character. The program should break out of the while loop when it reads in a 'z'). #include using namespace std; int main() { const char STOP_CHAR = 'z'; char next_char; cout << "Enter as many characters as you want.\n" << "Hit return when you want to send those characters to the program." << "\nWhen you want to stop, enter the character " << STOP_CHAR << endl; do { cin >> next_char; }while (next_char != STOP_CHAR); return 0; } This program doesn't do a whole lot. But, for example, if you wanted to count how many characters the user typed up to and including the z, you could just add one to a counter variable in the do-while loop and then output the counter's value after the loop ends. Then the program would look something like: #include using namespace std; int main() { const char STOP_CHAR = 'z'; char next_char; int cnt = 0; cout << "Enter as many characters as you want.\n" << "Hit return when you want to send those characters to the program." << "\nWhen you want to stop, enter the character " << STOP_CHAR << endl; do { cin >> next_char; cnt++; }while (next_char != STOP_CHAR); cout << "You entered " << cnt << " characters up to and including the " << STOP_CHAR << endl; return 0; }