C++ Primer Plus Chapter 4 Exercise 1

c plus plusThe problem with this exercise is that there isn’t really way to complete it without using a method that you have not yet learned in the book. In saying that, there certainly are a few other ways to do this exercise including switch statements and incrementing the ASCII value of a letter grade. But if you are going chapter by chapter in the book, you will not have learned how to do that. I did use cin.getline to store the input sequence to firstName[], allowing for multiple first-names as required.  I posted a simple solution that works for our purposes, and acts as an intro to if statements. Take a look:

1. Write a C++ program that requests and displays information as shown in the following example of output:
What is your first name? Betty Sue
What is your last name? Yew
What letter grade do you deserve? B
What is your age? 22
Name: Yew, Betty Sue
Grade: C
Age: 22
Note that the program should be able to accept first names that comprise more than one word. Also note that the program adjusts the grade downward—that is, up one letter. Assume that the user requests an A, a B, or a C so that you don’t have to worry about the gap between a D and an F.

#include <iostream>

using namespace std;

int main()
char firstName[20];
char lastName[20];
char grade;
char newGrade;
int age;

// Gather input
cout << "What is your first name? ";
cin.getline(firstName, 20);
cout << "What is your last name? ";
cin >> lastName;
cout << "What is the letter grade you deserve? ";
cin >> grade;
cout << "What is your age? ";
cin >> age;

// Increment grade and recognize upper and lowercase input.
if (grade == 'A' || grade == 'a')
newGrade = 'B';
else if (grade == 'B' || grade == 'b')
newGrade = 'C';
else if (grade == 'C' || grade == 'c')
newGrade = 'D';

cout << "name: " << firstName << " " << lastName << endl;
cout << "grade: " << char (newGrade) << endl;
cout << "age: " << age << endl;

return 0;