Programming Exercises


   HelloWorld    Output_a_character_block    Calculate_cents_of_coins    Format_Output    Draw_Square    Draw_Square_Part2    Sum_and_average    Assignment_Turn_in_Policy    Prime_Numbers    The_same_temperature    Credit_Card_Interest    Vending_Machine    Overloading_max    Guessing_Number_Enhancement    Calculate_coins_for_cents    Draw_n_by_n_Square    Tic_Tac_Toe    Selection_Sort_Enhanced    Binary_Search_Enhanced    Decrypt_Secret_Message    Get_Time_From_24-Hour_Format    Another_remove_punct    Swap_with_Pointers    Reverse_String_With_Pointers    How_Pointers_Used_in_this_Example    Min_Max_Number_From_a_File    Word_Count_in_a_File    Student_Grade_Structure    Draw_n_by_n_Square_with_Class    Odometer_Class    Odometer_Class_Enhanced    Odometer_Class_Derived    Draw_Square_with_Operators_Overloaded    Complex_Number_Class    Inherited_From_Person_Class

Hello_World: Your first practice to program in C++

You can download HelloWorld.cpp or creat it yourself as follows:
#include <iostream>
using namespace std;

int main( )
{
    cout << "Hello World!\n";
    return 0;
}

top


Output_a_character_block (Chapter 1, Pr 7)

Write a program that output a character block that contains letters formed as "CS!". Please download and run this ch01_07.exe to make sure that you understand what you are going to create! Your output should look like as this:
*************************************************

         C C C            S S S S          !!
       C       C        S         S        !!
      C                S                   !!
     C                  S                  !!
     C                   S S S S           !!
     C                           S         !!
      C                           S        !!
       C       C       S         S
         C C C           S S S S           00

*************************************************
    Computer Science is Cool Stuff !
Press any key to continue ...

top


Calculate_cents_of_coins (Chapter 1, Pr 8)

Write a program that calculates the monetary value of a number of quarters, dimes, and nickels. please download and play this ch01_08.exe to make sure that you understand what you are going to create! The following is an interactive example and its result:
Enter number of quarters: 5
Enter number of dimes: 3
Enter number of nickels: 7
The monetary value of your coins is 190 cents.
Press Q to Exit . . .
Your code should be in the following format with our Coding Style Guidelines. This is just a sample and you are required to follow the Guidelines in every programming assignment in the class. This time, you can simply copy the following and fill out your code after each comment. Next, you should create your own.
// ============================================================================
// File: ch01_08.cpp
// ============================================================================
// Student:    James 
// Date:       08/18/2009
// Class:      CSCI 123 ("Intro to Programming Using C++")
// Instructor: Mr. Ding
// Program:    Chapter 01 Programming 08: Calculate cents of coins
//
// Description:
//  This program calculates the monetary value of a number of quarters, dimes, 
//  and nickels from the user input. The user is prompted for the numbers of 
//  quarters, dimes, and nickels. Then the sum of all cents of coins is 
//  calculated and displayed to the standard output screen.
//
// Sample output:
//  Enter number of quarters: 5
//  Enter number of dimes: 3
//  Enter number of nickels: 7
//  The monetary value of your coins is 190 cents.
// ============================================================================

#include <iostream>
using namespace std;

// ============================================================================
// Function main: 
//  This main function let us do following:
//   1. Prompt user to input the number of quarters and receive to a variable
//   2. Prompt user to input the number of dimes and receive to a variable
//   3. Prompt user to input the number of nickels and receive to a variable
//   4. Calculate the sum of the total cents
//   5. Display the results to stdout
//
// Input:   none
// Output:  none
// ============================================================================
int main()
{
  int quarters, dimes, nickels, total;

  // Input the number of quarters
  
  // Input the number of dimes
  
  // Input the number of nickels
  
  // Calculate the total
  
  // Output the total

  return 0;
}  // end of "main"
How about adding half dollar and penny? If possible, go ahead to make this enhancement!

top


Format_Output (Chapter 2)

This is practice of formatting outputs. You can first output two lines to descript the forward/back slash. Then, you read into two double values and output their sum with three digits after the decimal point. Using the escape character Tab to align three columns. A sample program Format_Output.exe is available to play like this. Please follow the Coding Style Guidelines shown in the last assignment (ch01_08.cpp).
"/" is a 'forward slash'
"\" is a "back slash"

---------------------------------------
Enter two double values: 1.23456 2
The first       The second      The Sum
1.235           2.000           3.235
Press any key to continue . . .
Try to make the output aligned neatly. But did you find any difficulty to make it aligned always?

top


Draw_Square (Chapter 2)

This program asks the user how to draw a 5 by 5 square based on his input: whether the square is solid or not solid, and which character to draw. The step by step guide is given below. Also you must follow the Coding Style Guidelines shown in the last assignment (ch01_08.cpp).
int main()
{
    // Define variables border and answer as type char

    // Define variable isSolid as type bool

    // Ask if the square is solid and save to the variable answer

    // based on answer, assign isSolid to true or false

    // Ask second question to get a character border to draw

    // Draw five lines based on the value of isSolid and the border character
    
    return 0;
}
Try DrawSquare.exe and the output may look like this:
D:\zdsite\fullcoll\fc123\files>drawSquare
Draw a 5 by 5 square: is it solid? (y/n) y
Give me the character to draw: 1
11111
11111
11111
11111
11111
Press Q to Exit: q

D:\zdsite\fullcoll\fc123\files>drawSquare
Draw a 5 by 5 square: is it solid? (y/n) n
Give me the character to draw: a
aaaaa
a   a
a   a
a   a
aaaaa
Press Q to Exit: q

top


Draw_Square_Part2 (Chapter 2)

Continue with the last program. Now set a loop to let the user repeatedly test the drawing without restarting the program. Your output may look like this:
D:\zdsite\fullcoll\fc123\files>drawSquare
Draw a 5 by 5 square: is it solid? (y/n) y
Give me the character to draw: e
eeeee
eeeee
eeeee
eeeee
eeeee
Try again? (y/n) y
Draw a 5 by 5 square: is it solid? (y/n) n
Give me the character to draw: c
ccccc
c   c
c   c
c   c
ccccc
Try again? (y/n) n
See you later!
Press any key to continue . . .
An enhanced version is to use a different character to draw the inner solid portion of the square. If the user decides to draw a solid one, you have to ask another question to get the second character for inner solid drawing. But if not solid, no such an extra question appears. Please download and play drawSquare2.exe like this:
D:\zdsite\fullcoll\fc123\files>drawSquare2
Draw a 5 by 5 square: is it solid? (y/n) y
Give me the character to draw the border: b
Give me the character to draw the inner solid portion: i
bbbbb
biiib
biiib
biiib
bbbbb
Try again? (y/n) y
Draw a 5 by 5 square: is it solid? (y/n) n
Give me the character to draw the border: e
eeeee
e   e
e   e
e   e
eeeee
Try again? (y/n) n
See you later!

top


Sum_and_average (Chapter 2, Pr 10)

In this program, you read ten integer values. Output the sum and average of positive numbers, the sum and average of non-positive numbers, the sum and average of all numbers. Notice that the averages are usually floating point numbers so that it should not be output as an integer. Your output may look like this:
Enter ten numbers:
4 5 -1 3 -4 -3 9 8 7 2
- Sum of Positive numbers is 38
Average of Positive numbers is 5.43
- Sum of NonPositive numbers is -8
Average of NonPositive numbers is -2.67
- Sum of All is 30
Average of All is 3.00
Press any key to continue . . .
An extra work is to let the user control the number of integers to calculate. A sample program is available to play at ch02_10.exe like this:
How many numbers to calculate: 5
Enter 5 numbers:
3 -4 9 8 -1 7
- Sum of Positive numbers is 20
Average of Positive numbers is 6.67
- Sum of NonPositive numbers is -5
Average of NonPositive numbers is -2.50
- Sum of All is 15
Average of All is is 3.00        
Another question: What if all the inputs are positive or non-positive integers?

top


Assignment_Turn_in_Policy (Chapter 3)

Refer to our assignment turn-in policy in Syllabus. How to implement it? You can have your turn-in days as an integer variable TurnInDays. And another variable is FullPoints:
int TurnInDays, FullPoints;
Now you can read in the FullPoints value and check repeatedly with TurnInDays to find the actual maximum available points. The main function simply does:
  1. Prompt the user to enter the Full points that an assignment was worth.
  2. Prompt user to enter the days the assignment was turned in.
  3. Calculate and display the maximum number of points based on the inputs.
  4. Repeat Step2 to Step3, if "Try again".

Try this sample TurnInPolicy.exe and the output can be like this
Enter the full points for each assignment: 100
- Within how many days, you turned in: 5
The Max number of points available is 100
Try again? (y/n) y
- Within how many days, you turned in: 10
The Max number of points available is 80
Try again? (y/n) y
- Within how many days, you turned in: 15
Not acceptable!
Try again? (y/n) n
Press any key to continue . . .
Using either if-then-else or switch-case is fine.

top


Prime_Numbers (Chapter 3, Pr 14)

This program outputs all prime numbers less than 100 using a doubly-nested loop. The following steps are strongly recommended to do your program:
int main()
{
    // define isPrime of bool to remember if a number is prime or not

    // Outter loop: take i from 2 to 100

        // Assume i is prime at first

        // Inner loop: check to see if i is prime    
        // try to divide i by number j from 2 to i/2 

            // if divided evenly (no remainder) 

                // remember i not prime (unnecessary to divide by next)

        // end of inner loop
        
        // if it's prime, output i
          
    // end of outter loop
}
The requirement is to let the user control the count to calculate prime numbers by enterring a maximun integer, and also add a "Try again?" prompt to give a chance to repeatedly test calculations. A sample program is available to play at ch03_14_2.exe like this:
Enter n - show prime numbers less than n: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Try again? (y/n) y

Enter n - show prime numbers less than n: 20
2 3 5 7 11 13 17 19
Try again? (y/n) y

Enter n - show prime numbers less than n: 200
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 
101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 
193 197 199
Try again? (y/n) n
Any imprudent you find could make the program more efficient?

top


The_same_temperature (Chapter 3, Pr 16)

Write a program that finds the temperature that is the same in both Celsius and Fahrenheit. You can set a temperature range for a loop to compute the Fahrenheit value for each Celsius value, stopping when they are equal. The well-known formula is
fahrenheit = 9/5 * celsius + 32
Be careful about the integer division! Notice that you can't use the operator == or != to compare two real values! The textbook's description was a little misleading. It said that using integer may not give an exact value but will not affect its result. Such a guide made it inconsistent and quite confusing, because it give you a false impression by using an incorrect logic to get an expected result to solve this problem.
What is the temperature you get by running your program?

top


Credit_Card_Interest (Chapter 4, Pr 6)

This program computes the interest on a credit card balance. The task is done with a function that accepts initial balance, monthly interest rate, number of months for which the interest must be paid. Interest should be compounded. The value returned is the interest due. This function can be declared like this:
// ============================================================================
// Function:	interest
// Description:	This function calculates the total credit card interest based 
//		on your initial balance, interest, rate and months
//
// Parameter:
//      initBalance [IN]   -- an double value of initial balance received
//      rate [IN]  -- an double value of interest rate like 0.02 as 2%
//      months [IN]   -- the number of months of the integer type
//
// Return:
//      An double value of the final interest amount calculated
// ============================================================================
double interest(double initBalance, double rate, int months);

// The algorithm:
   // declare variable: balance = initBalance
   // initialize variable i = 0 to represent month increment 
   // repetition to update balance by computing compound credit card interest 
   //    Hint: ref to DISPLAY 2.15 Charge Card Program in Chapter 2     
   // the  interest returned should be balance - initBalance
This function is to be called in main() that acquires these values and outputs the interest due. The following is an algorithm in pseudocode:
    1. declare balance, rate, interestEarned, months
    2. repeat the following actions until exit:
         (1). fetch balance, rate, months
         (2). interestEarned = interest(balance, rate, months)
         (3). output interestEarned
Repeat of computation at users option is to be allowed. Your output may look like this:
Credit card interest calculation ...
Enter your initial balance as double: 1000
Enter the monthly interest rate (e.g. for 1.5% per month write 0.015): 0.02
Enter the number of months the bill has run: 12
Interest accumulated = $268.24
Try again? (y/n): y

Credit card interest calculation ...
Enter your initial balance as double: 50
Enter the monthly interest rate (e.g. for 1.5% per month write 0.015): 0.02
Enter the number of months the bill has run: 36
Interest accumulated = $51.99
Try again? (y/n): n

top


Vending_Machine (Chapter 4, Pr 15)

Write the code to simulate a person putting money into a vending machine for a deep-fried twinkie, $3.50 each. The following are implementation suggestions: Use cents for all monetary values to let us work with integer, rather than floating-point, variables.
const int TWINKIE_PRICE = 350;
This is a function to prompt the user to insert coins repeatedly until enough has been paid to buy a twinkie. A switch statement is suggested to use in the function. The total amount inserted, in cents, is returned as integer.
int accept_money();
You may create another to get the change back from total_paid
int compute_change(int total_paid);
The main() function can work like this as suggested:
int main()
{
    // Define variable money_entered for the amount of money that the 
    // user enters, along with change that is to be returned to him.
    ... ...
    
    // Make sure that monetary values we output are formatted with
    // two digits after the decimal point.
    ... ...
    
    // Call your function accept_money to collect money from the user.
    money_entered = accept_money();

    // Figure out how much change to return to the user.
    change = compute_change(money_entered);

    // Dispense the twinkie to the user with change back.
    ... ...    

    return 0;
}
Now the work is simple that you only need to define the function accept_money() and create the above main(). A sample program is available at ch04_15.exe and can be run like this:
Please insert coins:
 n - Nickel
 d - Dime
 q - Quarter
 D - Dollar
A fried twinkie costs $3.50. You have inserted $0.00.
Next coin: D

Please insert coins:
 n - Nickel
 d - Dime
 q - Quarter
 D - Dollar
A fried twinkie costs $3.50. You have inserted $1.00.
Next coin: a

'a' is not recognized as a coin. 
Please insert coins:
 n - Nickel
 d - Dime
 q - Quarter
 D - Dollar
A fried twinkie costs $3.50. You have inserted $1.00.
Next coin: q

Please insert coins:
 n - Nickel
 d - Dime
 q - Quarter
 D - Dollar
A fried twinkie costs $3.50. You have inserted $1.25.
Next coin: D

Please insert coins:
 n - Nickel
 d - Dime
 q - Quarter
 D - Dollar
A fried twinkie costs $3.50. You have inserted $2.25.
Next coin: d

Please insert coins:
 n - Nickel
 d - Dime
 q - Quarter
 D - Dollar
A fried twinkie costs $3.50. You have inserted $2.35.
Next coin: D

Please insert coins:
 n - Nickel
 d - Dime
 q - Quarter
 D - Dollar
A fried twinkie costs $3.50. You have inserted $3.35.
Next coin: D

Enjoy your deep-fried twinkie. Your change is $0.85

top


Overloading_max (Chapter 4, Pr 12)

To be different from the max in C Run-Time Library, define overloaded functions myMax that returns the largest of all the arguments received like the following
double myMax(double x, double y);
double myMax(double x, double y, double z);
You can call them like these examples, the results of maxVal is 4.5 and d3 is 8.1:
double d1 = 3.2, d2 = 4.5, maxVal; 
maxVal = myMax(d1, d2);
double d3 = myMax(8.1, 7, maxVal);
Further, you may try to define some of the following or more.
double myMax (int x, double y);
int myMax (int x, int y);
char myMax (char x, char y);
double myMax (double x, int y, double z);
int myMax (int x, int y, int z, int n4);
The purpose is to understand how they are working when being called? Which one gets called or the compiler can't find one? As an example, see what if your want to call this:
char c = myMax('A', 66);

top


Guessing_Number_Enhancement (Supplied)

This is an enhancement for the Guessing Number program, based on the code demo in the class. Add the last number input by the user to give more flexibility and add error handling to make the game more intelligent. You can download here the original demo function bool NumberGuessing( ) conveniently as a start point.

- Step 1: Let the user enter the last number by simply add a parameter named last:
bool NumberGuessing(int last);
Now you can call NumberGuessing in main() like the following examples assuming that the number to guess is 7. But you entered a wrong 'y' or 'n', either accidentally or intentionally
Game starts:
I can guess a number [1..n] in your mind. Enter n you want: 10
Is it 5? n
Is it bigger than 5? y
Is it 8? n
Is it bigger than 8? n
Is it 6? n
Is it bigger than 6? y
Is it 7? n
Is it bigger than 7? n
Is it 6? 
...
or
Game starts:
I can guess a number [1..n] in your mind. Enter n you want: 10
Is it 5? n
Is it bigger than 5? y
Is it 8? n
Is it bigger than 8? n
Is it 6? n
Is it bigger than 6? n
Is it 5? n
Is it bigger than 5? y
Is it 5?
...
Unfortunately, the game can't recognize the error or cheating happened in processing. In the first example, you answer NO to the only choice of 7, but the game asks 6 at the second time again. This is definitely not a logic deduction. In the second example, you answer NO to 6 and continue to choose less than 6, a cheating obviously. Again, the game can't detect it and be stupid to ask 5 at the second time.

- Step 2: As we can see, the function NumberGuessing() doesn't return any meaningful false value. Now we can make use of this false value to indicate an error. We need to let the game detect the invalid input. So you have to add error handling of above situations in NumberGuessing(). It returns true if working fine to win, false if an error or cheating detected. You can have different ways to deal with it. The following are two alternatives, still assuming that the number to guess is 7.

You can make it like this when call NumberGuessing():
Game starts:
I can guess a number [1..n] in your mind. Enter n you want: 10
Is it 5? n
Is it bigger than 5? y
Is it 8? n
Is it bigger than 8? n
Is it 6? n
Is it bigger than 6? y
Is it 7? n
You are cheating, bye.
Press any key to continue . . .

I can guess a number [1..n] in your mind. Enter n you want: 10
Is it 5? n
Is it bigger than 5? y
Is it 8? n
Is it bigger than 8? n
Is it 6? n
Is it bigger than 6? n
You are cheating, bye.
Press any key to continue . . .
A smarter NumberGuessing() should ask 7 immediately after you say No to 6:
Game starts:
I can guess a number [1..n] in your mind. Enter n you want: 10
Is it 5? n
Is it bigger than 5? y
Is it 8? n
Is it bigger than 8? n
Is it 6? n
Is it 7? n
You are cheating, bye.
A sample program is available at NumberGuessing2.exe

top


Calculate_coins_for_cents (Chapter 5, Pr 5)

This program tells what coins to give out for any amount of cents. You can use coin denominations of 25 cents (quarters), 10 caents (dimes), 5 cents (nickles), and 1 cent (pennies). The algorithm can be found from an example like this with 92 cents: So for 92 cents, you have 3 quarters, 1 dime, 1 nickle, and 2 pennies. A sample program is available at ch05_05.exe and can be run like this:
Input total cents: 92
3 Quarters
1 Dime
1 Nickel
2 Pennies
Try again? (y/n) y

Input total cents: 128
5 Quarters
3 Pennies
Try again? (y/n) n
Notice that if zero of a coin type, it will not appear for display. Also, the singular and plural are indicated. According to the project requirement (see Page 298), you have to define the following function
void Compute_Coins(int coinValue, int& numbers, int& left);
Notice that the numbers and left here are Reference Parameters. You csn use it in the calculations of quarter, dime, and nickle repeatedly. The following explains how to call Compute_Coins() with the same example as illustrated before
// left is 92 cents     
Compute_Coins(25, total, left);  
// total is 3, left is 17
nQuarters = total;                 

// left is 17 cents     
Compute_Coins(10, total, left);
// total is 1, left is 7
nDimes = total;

// left is 7 cents     
Compute_Coins(5, total, left);
// total is 1, left is 2
nNickels = total;
pennies = left;
Looks interesting? Try it now and have fun!

top


Draw_n_by_n_Square (Chapter 5)

Now you can draw an n by n square with any size n received from the user input. The following are such functions to be called in main()
void GetSquareInfo(bool& isSolid, char& border, char& inner, int& size);
void DrawSquare(bool isSolid, char border, char inner, int n);
The main() function can work like this:
int main()
{
    ... ...
    
    // Receive the square data entered by the user
    GetSquareInfo(isSolid, border, inner, size);
   
    // Now prepared all arguments, call this to Draw a Square based on isSolid, border, inner, and size
    DrawSquare(isSolid, border, inner, size);

    ... ...
    return 0;
}
A sample program is available at drawSquare3.exe and can be run like this:
Draw an n by n square: Enter the size n: 5
Is the square solid? (y/n) n
Give me the character to draw the border: A
AAAAA
A   A
A   A
A   A
AAAAA
Y or y continues, any other character terminates: y

Draw an n by n square: Enter the size n: 8
Is the square solid? (y/n) y
Give me the character to draw the border: e
Give me the character to draw the inner solid portion: x
eeeeeeee
exxxxxxe
exxxxxxe
exxxxxxe
exxxxxxe
exxxxxxe
exxxxxxe
eeeeeeee
Y or y continues, any other character terminates:

top


Tic_Tac_Toe (Chapter 7, Pr 10)

This program plays tic-tac-toe using a one dimensional array to represent the board. This program is to ask for moves alternately between player A and B with marks X and O. The players enter their moves by entering a number corresponding to the place to be marked. After each move, the program displays the changed board. A sample program is available at ch07_10.exe and can be run like this:
Start Game:
-----
1 2 3
4 5 6
7 8 9
-----
Player A, Please Enter move: 5
-----
1 2 3
4 X 6
7 8 9
-----
Player B, Please Enter move: 3
-----
1 2 O
4 X 6
7 8 9
-----
Player A, Please Enter move: 1
-----
X 2 O
4 X 6
7 8 9
-----
Player B, Please Enter move: 5
That space is taken, try again.
-----
X 2 O
4 X 6
7 8 9
-----
Player B, Please Enter move: 0
Invalid move, try again.
-----
X 2 O
4 X 6
7 8 9
-----
Player B, Please Enter move: 9
-----
X 2 O
4 X 6
7 8 O
-----
Player A, Please Enter move: 6
... ...
... ...
Player A, Please Enter move: 7
-----
O X O
X X O
X O X
-----
Game over! 
You can start your program with the following steps. Make sure you understand each step and entire logic. It does not require to check for a win at this moment, since the main purpose is to practice with an array. You may try if you want.
// This function displays a board on the screen. It outputs each
// character in the array, putting a newline every three characters.

void showBoard(char board[])
{
    cout << "-----" << endl;
    for (int i=0; i<9;i++)
    {
        cout << board[i] << " ";
        if ((i+1) % 3 == 0) 
            cout << endl;
    }
    cout << "-----" << endl;
}

// ====================
//     main function
// ====================

int main()
{
  char board[9];                 // Holds digits, X, or O
  int move, numMoves = 0;        // Number of moves
  char whoseTurn = 'X', player;  // Current player's move

  // Initialize board to character digits 1-9

  // Loop to Get a move until all 9 moves used

      // showBoard

      // Decide Who is the player A or B to prompt

      // Receive move

      // Check if the move is not valid, 
           // let the player try again
      
      // if the move is valid, 1 to 9
      
          // Update move to index, as the array is 0 based, not 1 based

          // if board[move] is filled by X or O, let the player try again
          
          // if the move is OK to fill
          
              // Assign 'X' or 'O' in whoseTurn to board[move]

              // Switch turns - change whoseTurn

              // Update numMoves
              
  // End of Loop 
  
  // showBoard
  // Say Game over! 
}
At this moment, if you are comfortable with all, go next to the challenging job by checking winner at each time you update the board. The suggested function is
bool CheckWin(char board[]);
A sample program available at ch07_10ex.exe can be run just for fun. Notice that additionally You can implement some of them as interested. Good luck!

top


Selection_Sort_Enhanced (Chapter 7)

Write a program that implements the enhanced selection sorting. Let the user choose ascending or descending order by answering the question. Then you must save this order flag and pass it to a revised sorting function that can be defined like this:
void sort2(int a[], int number_used, bool ascending);
Based on this ascending true or false, you make the different comparisons to fit ascending or descending order. Just make use of either fill_array or fill_array_Rand to initialize your test data. A sample program is available at SelSortEx.exe and can be run like this:
An enhanced version of Selection Sort: Do you want an ascending order? (y/n) y
Fill out 20 Random numbers:
 32 78 16 22 77 23 55 80 23 43 12 37 52 32 76 1 76 81 2 20
In sorted order the numbers are:
 1 2 12 16 20 22 23 23 32 32 37 43 52 55 76 76 77 78 80 81
Try Again? (y/n) y

An enhanced version of Selection Sort: Do you want an ascending order? (y/n) n
Fill out 20 Random numbers:
 54 81 62 25 43 11 74 57 32 75 77 46 84 84 82 95 94 86 49 85
In sorted order the numbers are:
 95 94 86 85 84 84 82 81 77 75 74 62 57 54 49 46 43 32 25 11
Try Again? (y/n) n

top


Binary_Search_Enhanced (Chapter 14)

Continuing with the previous enhanced selection sorting, write a program that implements the enhanced Binary Search. Pass the ascending or descending order flag to a revised Binary Search function that can be defined like this:
int BinarySearch2(int a[], int first, int last, int value, bool ascending);
Based on this ascending true or false, you update your first or last index to go next half of array to continue Binary Search. If make fill_array_Rand to initialize your test data, a sample program bSearchEx.exe and can be run like this:
An enhanced version of Selection Sort: Do you want an ascending order? (y/n) y
Fill out 20 Random numbers:
 10 93 73 58 70 77 97 67 77 66 84 34 37 3 66 22 70 49 97 56
In sorted order the numbers are:
 3 10 22 34 37 49 56 58 66 66 67 70 70 73 77 77 84 93 97 97
Binary Search: Enter a number to search for (-1 to exit): 77
77 is indexed at 14
Binary Search: Enter a number to search for (-1 to exit): 66
66 is indexed at 9
Binary Search: Enter a number to search for (-1 to exit): -1
Try Again? (y/n) y

An enhanced version of Selection Sort: Do you want an ascending order? (y/n) n
Fill out 20 Random numbers:
 78 27 75 2 97 88 74 6 71 12 56 46 16 46 15 53 90 89 44 35
In sorted order the numbers are:
 97 90 89 88 78 75 74 71 56 53 46 46 44 35 27 16 15 12 6 2
Binary Search: Enter a number to search for (-1 to exit): 97
97 is indexed at 0
Binary Search: Enter a number to search for (-1 to exit): 2
2 is indexed at 19
Binary Search: Enter a number to search for (-1 to exit): 22
22 is not on the list.
Binary Search: Enter a number to search for (-1 to exit): -1
Try Again? (y/n) n

top


Decrypt_Secret_Message (Chapter 8, Pr 12 - Using C-String)

This program decodes the secret message ":mmZ\dxZmx]Zpgy", by trying all 99 possible keys in the decryption algorithm. You can define one of the following functions decrypt. This function decrypts the input C-string encoded using the key and puts it back into the C-string decoded
void decrypt(const char encoded[], char decoded[], int key);
or this function decrypts the input C-string message using the key and puts the result back to the C-string message itself.
void decrypt(char message[], int key);
We have already intercepted the enemy's encoding method as shown in the textbook and learned that the value of Key was below 100:
If (OriginalChar + Key  > 126) then
    EncryptedChar = OriginalChar + Key -127 +32
else
    EncryptedChar = OriginalChar + Key;
As opposed to encoding, we would like to use the decoding formula like this to get back the decrypted original characters:
If (EncryptedChar - Key  < 32) then
    OriginalChar = EncryptedChar - Key + 127 -32
else
    OriginalChar = EncryptedChar - Key;
Implementation considerations: Your program can be run like this:
Enter your encoded message: :mmZ\dxZmx]Zpgy

Key: 1 Decoded message: 9llY[cwYlw\Yofx
Key: 2 Decoded message: 8kkXZbvXkv[Xnew
... ... ...
Key: 99 Decoded message: 6iiVX`tVitYVlcu
Press any key to continue . . .
Among all those lines, only one of the decoded messages makes sense while all others are as gibberish. You can recognize it at once. What are the message and its key? Tell your commander immediately without delay!

top


Get_Time_From_24-Hour_Format (Chapter 8, Using C++ string class)

This program converts a 24-Hour Format time to the normal time. The argument should be a C++ string in "HH:MM" 24-hour format. The result will be a C++ string written as "HH:MM AM" or "HH:MM PM" in 12-hour format with AM or PM. The following is the function suggested to receive a 24-hour time and return the converted 12-hour time.
string GetTimeFrom24HourFormat(const string& time);
Using C++ string is required, not using C-string. A program can be run like this:
Enter a time 'HH:MM' in 24-Hour-Format: 11:02
11:02 is converted to 11:02 AM
Try Again? (y/n) y
Enter a time 'HH:MM' in 24-Hour-Format: 12:30
12:30 is converted to 12:30 PM
Try Again? (y/n) y
Enter a time 'HH:MM' in 24-Hour-Format: 15:22
15:22 is converted to 03:22 PM
Try Again? (y/n) y
Enter a time 'HH:MM' in 24-Hour-Format: 00:20
00:20 is converted to 12:20 AM
Try Again? (y/n)
See 24-hour clock at Wikipedia for detailed descriptions.

top


Another_remove_punct (Chapter 8, supplied)

As learned from the DISPLAY 8.8 Palindrome Testing Program, we understand the function
string remove_punct(const string& s, const string& punct);  
removing all punctuation marks and spaces by calling
string pure_str = remove_punct2(str, ",;:.?!'\" ");		
During the class discussion, Michael Poole proposed another way to do this simply by using the CRT function isalpha(). This assignment is just let you create such an implementation with a function like:
string remove_punct(const string& s);
Let the user enter a sentence. Your program can be run like this:
Enter a sentence with punctuation marks and spaces:
Madam, I'm a dam.
After removing punctuation marks and spaces:
MadamImadam
Try again? y

Enter a sentence with punctuation marks and spaces:
 cout << endl << "Enter a sentence with punctuation marks and space:\n";
After removing punctuation marks and spaces:
coutendlEnterasentencewithpunctuationmarksandspacen
Try again?
Implementation considerations:

top


Swap_with_Pointers (Chapter 9)

This program is to simply practice the function parameter type called by pointers. A function SwapWithPtr() could be defined as:
void SwapWithPtr(int* ptr1, int* ptr2);
You have to call it twice. Think of how to pass an integer argument and how to pass a pointer argument to SwapWithPtr(). When test your code, the result should be like this:
Enter n1 and n2: 111 222
After the first swap call using n1 and n2:
  n1=222, n2=111
After the second swap call using p1 and p2:
  n1=111, n2=222
  *p1=111, *p2=222
Press any key to continue . . .

top


Reverse_String_With_Pointers (Chapter 9, Pr04)

This program reverses a C-String using pointers to manipulate the values in memory. Not acceptable if you use array indexes. The function should be defined like this
void reverse(char *s)
{
    // Define two char pointers front and rear

    // front starts at left side of the string

    // rear start at right side of the string

    // Loop when front does not meet rear

        // Exchange the characters pointed to by front and rear with help of a temp char

        // Update front and rear pointing to the next character 
        
    // End of Loop 
}
Simply call it in main() like this
 cout << "Enter a string before reversing: ";
 cin >> str1;
 reverse(str1);
 cout << "This  is  the  string  reversed: " << str1 << endl;
A sample program can be like this:
Enter a string before reversing: abcde
This  is  the  string  reversed: edcba
Try aganin? (y/n)y
Enter a string before reversing: 12345678
This  is  the  string  reversed: 87654321
Try aganin? (y/n)n

top


How_Pointers_Used_in_this_Example (Chapter 9, Research)

A toy program is written as below. The purpose of this code is to show how to pass a pointer to a function and get different results back with the pointer features.
#include <iostream>    
using namespace std;

void funcA(char *s) 
{
    s[0] = 'x';        
    s++; 
}

void funcB(char* &s) 
{ 
    *(s+1) = 'y';
    s++; 
}

void funcC(char** s) 
{ 
    *((*s)+1) = 'z';
    (*s)++; 
}

int main()
{
    char str[] = "abc";
    char *ptrA = str, *ptrB = str;

    funcA(ptrA);
    cout << "ptrA = " << ptrA << endl;

    funcB(ptrB);
    cout << "ptrB = " << ptrB << endl;

    char* ptrC = ptrB;
    funcC(&ptrC);
    cout << "ptrC = " << ptrC << endl;
}
It can be run to display the following results:
ptrA = xbc
ptrB = yc
ptrC = z
Write some paragraphs for: Hint: trace the code in VS by watching memory. You may need to find other resources outside the textbook, in order to answer the question.

top


Min_Max_Number_From_a_File (Chapter 6, Pr 1)

Search a file of int numbers and write the largest and smallest to the screen and an output file. The input file is space and newline delimited integers. A sample text file is available at f6_01.txt or you can create a test file yourself. Remember, this data file must be under the directory where your program executable can access it.

You can start your program with the following steps:
#include <iostream>    // for streams
#include <fstream>     // for files
using namespace std;

int main()
{   
    int input;
    int largest =  INT_MIN;     //initialize largest to min int, -2,147,483,648
    int smallest = INT_MAX;     //initialize smallest to max int, 2,147,483,647

    char file_name [80];  
    // Prompt to ask for a file name to save in file_name 

    // Creat an ifstream variable and open the file

    // Check if this file is opened correctly

    // Set a loop to read an input from the ifstream variable
    //     - get an input (You can output each to the screen)
    //     - compare the input to the current largest and smallest
    //     - if necessary, update the largest and smallest with the input
    // end of the loop

    // Output the largest and smallest to the screen

    // if above correct, then write code here to save your results to an output file
}
A sample program is available at ch06_01.exe and can be run like this:
Enter a file name: f6_01.txt
Numbers in f6_01.txt:
333333
-1
4444444
-22
55555555
-1
-333
999999
-4444

The smallest = -4444, the largest = 55555555
Notice the last comment: if above correct, add code to save your results to an output file
Where is your test files located?

top


Word_Count_in_a_File (Chapter 6, Pr 20)

Write a program that inputs the name of a text file and then outputs the number of words in the file. You can consider a “word” to be any text that is surrounded by whitespace (e.g. a space, carriage return, newline) or borders the beginning or end of the file. A sample text file is available at f6_20.txt or you can create a test file yourself. Remember, this data file must be under the directory where your program executable can access it. Although it's easy to use the extraction operator >>, the purpose of this this program is to practice using the input stream's get() function.

A sample program is available at ch06_20.exe and can be run like this:
Enter a file name: f6_20.txt
The file contains 50 words.
Press any key to continue . . .
This result should be the same as the Word Count from Windows Word:

The Word Count from Windows Word

Hint: As a practice, using infile_stream.get(ch) and isspace(ch) is strongly recommended.

top


Student_Grade_Structure (Chapter 10, Pr 1, Modified)

This program requires you to create a student grade structure named StudentRecord. Using this StudentRecord type, input the students' data, calculate the numeric average and letter grade, and output the student record. The scores are simply the average of quiz, midterm, and final points. To help you in this exercise, the following are suggested:
struct StudentRecord
{
  int studentNumber;       // as ID
  double quiz;             // from input	
  double midterm;          // from input
  double final;            // from input
  double average;          // calculated and output
  char grade;              // calculated and output
};

//prompts for input for one student, sets the structure variable members.
void input(StudentRecord& student);

//calculates the numeric average and letter grade.
void computeGrade(StudentRecord& student);

//outputs the student record.
void output(const StudentRecord& student);
Step 1: You have to implement above three functions. Then you can call them as follows, where the constant CLASS_SIZE can be set a small number for your test. A programming stratagem is to deal with a single student first, and then extend to treat an array of CLASS_SIZE students.
int main()
{
  StudentRecord studentAry[CLASS_SIZE];
  int i;
  cout << "Input " << CLASS_SIZE << " students' Data please...\n\n";
  for(i = 0; i < CLASS_SIZE; i++)
     input(studentAry[i]);

// Use the similar loop to call computeGrade() and output() by passing studentAry[i]   

  return 0;
}
Your program should be run like this:
Input 2 students' Data please...

Enter the student number: 10001
Enter three grades of quiz, midterm and final (Max 100 each): 80 90 70

Enter the student number: 10003
Enter three grades of quiz, midterm and final (Max 100 each): 60 73 82

The record for student number: 10001
Three grades of quiz, midterm and final are: 80.00 90.00 70.00
The numeric average is: 80.00
The letter grade assigned is B

The record for student number: 10003
Three grades of quiz, midterm and final are: 60.00 73.00 82.00
The numeric average is: 71.67
The letter grade assigned is C
Step 2: Now the enhancement is to detect the duplicate, if a student number is entered before. To implement this feature, you can redefine the input function like this below, where the array parameter students contains all the previous students' record that you can check duplicates.
// Input:   index points to the current student element in the students array 
// Output:  the students array at index should contain the student date entered without duplicating 
void input2(int index, StudentRecord students[]);
When implementing it, you can call input2 in main(), and now run your program to catch it
Input 10 students' Data please...

Enter the student number: 10001
Enter three grades of quiz, midterm and final (Max 100 each): 80 79 90

Enter the student number: 10001
This student number is entered already. Try another...
Enter the student number: 10002
Enter three grades of quiz, midterm and final (Max 100 each): 60 73 86
... ...

top


Draw_n_by_n_Square_with_Class (Chapter 10)

Now you can draw an n by n square with a Square class as defined:
class Square
{
public:
   void GetSquareInfo();
   void DrawSquare();

private:
   int size;
   bool isSolid;
   char border;
   char inner;
};
You can simply migrate your previous code in Chapter 5 to Square's member functions. In your main(), just call them in the "Try again" loop:
sqr.GetSquareInfo();
sqr.DrawSquare();
Where sqr is a Square object. The program will be run with the output exactly as Draw_n_by_n_Square (Chapter 5)

top


Odometer_Class (Chapter 10, Pr11, Modified)

This program defines an Odometer class to track fuel and mileage. It stores the miles driven and fuel efficient and includes a function to calculate the number of gallons of gasoline consumed. The class should be defined like this
class Odometer
{
public:
    void setFuelEfficiency(double newEfficiency);   // Sets the fuel efficiency in miles per gallon     
    void reset();                                   // Resets the odometer reading
    void logMiles(int additionalMiles);             // Logs additional miles to the odometer
    double gasConsumed();                           // Calculates the gallons of gas consumed on the trip

private:
    int miles;
    double fuel_efficiency;
};
You can create an Odometer object and call its member functions in main():
int main()
{
  // Define the object trip1 of Odometer
  // Define mpg for efficiency in miles per gallon

  // Receive mpg from the user

  // Reset the odometer reading with trip1

  // Sets the fuel efficiency mpg with trip1

  // Log initial 100 miles to the odometer with trip1 and output the gas consumed

  // Log additional 50 miles to the odometer with trip1 and output the gas consumed

  // Reset the odometer reading with trip1 and let the user enter another mpg

  // Log again 50 miles to the odometer with trip1 and output the gas consumed
}
The program should be run like this:
For your Car, Enter your Fuel Efficiency (Miles/Gallon): 30
Driving 100 miles, 3.33333 gallons used.
Driving next 50 miles, 5 gallons used.

Now reset your car odometer:
Change your Car to the Fuel Efficiency (Miles/Gallon): 25
Driving again 50 miles now, 2 gallons used.
Press any key to continue . . .

top


Odometer_Class_Enhanced (Chapter 10)

This program is based on the previous Odometer class by adding more OOP features. The purpose is to practice the dynamic memory allocation for the class and objects with the following suggested: Now the class can be defined like this:
class OdometerEnhanced
{
public:
// Default constructor
    OdometerEnhanced();

// One parameter constructor to set the fuel efficiency in miles per gallon  
// allocate the dynamic array with milesRecordPtr and size MAX_RECORDS 
    OdometerEnhanced(double Efficiency);	

// Release the dynamic array
    ~OdometerEnhanced();

// Logs additional miles to the OdometerEnhanced. Also update milesRecordPtr and numberOfRecords
    void logMiles(int additionalMiles);      

// Loop through the array milesRecordPtr to show miles logged in each record
    void OutputMilesRecord();

// Other member functions, refer to the last class definition to add any methods you needed:
//  ... ...    
                        
private:
    int miles;
    double fuel_efficiency;

    int* milesRecordPtr;		// the dynamic array
    int numberOfRecords;		// the current size of trip record
};
You can test this OdometerEnhanced object just by adding some calls below in main():
int main()
{
  // Receive mpg from the user
 
  // Define the object trip1 of OdometerEnhanced with the one parameter constructor 

  // Log initial 100 miles to the trip1 and output the gas consumed

  // Output record for 100 miles by calling OutputMilesRecord  

  // Log additional 50 miles and output the gas consumed

  // Output record for 100 and 50 miles by calling OutputMilesRecord  

  // Reset the trip1 and and let the user enter another mpg
 
  // Log again 50 miles to the trip1 and output the gas consumed 

  // Output record for 50 miles by calling OutputMilesRecord  
} 
The program should be run like this:
For your Car, Enter your Fuel Efficiency: (Miles/Gallon) 30
Driving 100 miles, 3.33333 gallons used.
The miles logged: 100
Driving next 50 miles, 5 gallons used.
The miles logged: 100 50

Now reset your car odometer:
Change your Car to the Fuel Efficiency: (Miles/Gallon) 25
Driving again 50 miles now, 2 gallons used.
The miles logged: 50
You can test this class by an OdometerEnhanced object as the requirement.

Optionally, if everything works and you want to try more, you can dynamically create an OdometerEnhanced object in main(), call its members, and finally releasing it. Recall what are the differences between an static object and a dynamically created one.

top


Odometer_Class_Derived (Chapter 10)

This program is based on the previous Odometer_Class (Chapter 10, Pr11, Modified) by adding a derived class to get the same result as Odometer_Class_Enhanced. The purpose is to practice how to reuse an existing class and add more functionality by derivation. The base class and its derived are as follows:
Odometer Class Derived image

The suggestions and comments below can help you to understand: Now by modifying Odometer and implement OdometerDerived, you can test this OdometerDerived object. The main() calls should be similar to that of Odometer_Class_Enhanced while the output should be the same as that of Odometer_Class_Enhanced

top


Draw_Square_with_Operators_Overloaded (Chapter 11)

- Step 1: Now you can use the previous Square class by overloading two operators:
class Square
{
    // ============================================================================
    // Function: operator+
    // Type:     friend
    // Description: Overload plus sign operator+. like sq1 + sq2
    //
    // Parameter: Square:  [in] sqr1 and sqr2 of constant Square reference
    // Return: The resulted Square object with
    //         size: the sum of the size of sqr1 and sqr2
    //         border: the average of border ASCII code of sqr1's and sqr2's; 
    //                e.g., if 'A' for sqr1 and 'C' for sqr2, the result is 'B'
    //         inner: set to '+', regardless of any previous inner of sqr1 and sqr2     
    // ============================================================================
    friend Square operator+ (const Square& sqr1, const Square& sqr2);

    // ============================================================================
    // Function: operator==
    // Type:     friend
    // Description: Overload plus sign operator==. like sq1 == sq2
    //
    // Parameter: Square:  [in] sqr1 and sqr2 of constant Square reference
    // Return: true if three fields size, border, and inner equal of sqr1 and sqr2 
    //         false: any one field not equal between two objects
    // ============================================================================
    friend bool operator== (const Square& sqr1, const Square& sqr2);

public:
    Square();                                   // Default constructor
    Square(int size, char brdr, char inr=' ');  // Initialize square 
                    
    void GetSquareInfo();
    void DrawSquare();

private:
    int size;
    char border;
    char inner;
};
You can simply start from your previous Square class code in Chapter 10. Just remove the isSolid field and implement two constructors and two friend operator functions. In your main(), just call them:
// 1. prompt the user to enter data for square1
    // Initialize square1 by a non-default constructor

// 2. Receive square2's data entered by the user
    // Call square2's GetSquareInfo()

// 3. Draw two squares
    // Call square1 and square2's DrawSquare()

// 4. Check equality of two squares and output result
    // Use square1 == square2

// 5. Call square1+square2 and draw the resulted square
    // Use square1 + square2 and then DrawSquare()
The program will be run like this:
1. To initialize the first square by calling the constructor
Enter the size, border char, and inner char: 3 a H

2. For the second square by calling the member GetSquareInfo()
Draw an n by n square: Enter the size n: 5
Is the square solid? (y/n) y
Give me the character to draw the border: e
Give me the character to draw the inner solid portion: f

3. Draw two squares:
aaa
aHa
aaa

eeeee
efffe
efffe
efffe
eeeee

4. Check equality: The square1 and the square2 are not equal.
5. Call square1+square2 and draw the resulted square
cccccccc
c++++++c
c++++++c
c++++++c
c++++++c
c++++++c
c++++++c
cccccccc
- Step 2: If you feel comfortable with all above, you can be ready to overload the extraction (>>) and the insertion (<<) operators. To overload the extraction (>>), simply call GetSquareInfo() and to overload the insertion (<<), simply call DrawSquare(). This is the hint to help you think about the modified class:
class Square
{
    friend Square operator+ (const Square& sqr1, const Square& sqr2);
    friend bool operator== (const Square& sqr1, const Square& sqr2);

    friend istream& operator >>(istream& ins, Square& sqr);
    friend ostream& operator <<(ostream& outs, const Square& sqr);

public:
    Square();                                   // Default constructor
    Square(int size, char brdr, char inr=' ');  // Initialize square 
                    
private:
    void GetSquareInfo(istream& ins);
    void DrawSquare(ostream& outs) const;

    int size;
    char border;
    char inner;
};
Notice that GetSquareInfo() and DrawSquare() are now private. We can receive the square info and draw squares by this:
... ...
   cin >> square2;
... ...
   cout << square1 << endl << square2 << endl;
... ...
   cout << square1+square2;
... ...    

top


Complex_Number_Class (Chapter 11, Pr 6, Modified)

Define a class for complex numbers with a form of a+bi where a and b are of type double in this assignment. Implement operator overloading for +, -, *, ==, !=, [], >>, and <<. A class can be defined as follows:
class complex
{
public:
// Constructors a destructor
  complex (double r = 0, double i = 0);
  ~complex ();
  complex (const complex&);
  complex& operator= (const complex&);

// Overload the following seven operators. Choose a friend or member function to implement for each:
   
  // complex addition: operator +
  // complex subtraction: operator -
  // complex multiplication: operator *
  // complex extraction: operator>>
  // complex insertion: operator<<
  // complex equality check: operator ==
  // complex inequality check: operator !=

// Overload index operator to return values based on ValueType 
  enum ValueType {Absolute, Real, Imaginary};
  double operator [] (const ValueType);       // ref: Appendix 6

private:
   double re, im;
};
You have to implement above functions. Then you can test every operator in main(). Your program should be run like this:
1. Test default, one-parameter, and two-parameter constructors for x, y, z
Output a complex object by consecutive '<<' calls...
 x is 0+0i, y is 3+0i, z is -3.2+2.1i

2. Test the assignment operator by changing x and y...
 x is 3+(-4)i, y is -2+3i

3.Test the arithmetic operator+...
 z = x + y is 1+(-1)i

4. Test automatic conversion with the operator-...
Enter a variable d of double: 2.3
 z = x - d is 0.7+(-4)i
 z = d - y is 4.3+(-3)i

5. Test getting data from cin by '>>'...
Input the first complex x ...
Enter a complex number (real and imaginary):3 -4
Input the second complex y ...
Enter a complex number (real and imaginary):5 6

6.Test the arithmetic operator*...
 x*y is (3+(-4)i)*(5+6i)=39+(-2)i

7. Test equal or not equal by x==y or x!=y...
 x is not equal to y

8. Test the index operator[]...
 x[complex::Real] is 3
 x[complex::Imaginary] is -4
 x[complex::Absolute] is 5

All test passed
Press any key to continue . . .
Optional: Now you can monitor your execution of the constructors, destructor, and assignment operator by adding trace outputs in these functions. For example in debug mode, simply add a private helper ShowComplex() to the complex class and then add it to the constructor like this:
#ifdef _DEBUG
void complex::ShowComplex() const
{
    if (!re && !im) cout <<" default";
    else
    {
        if (re) cout << " re=" << re;
        if (im) cout << " im=" << im;
    }
    cout << endl;
}
#endif

complex:: complex(double r, double i) : re (r), im (i) 
{	
#ifdef _DEBUG
    cout << "  Constructor called,";
    ShowComplex();
#endif
}
You can see the verbose display like
- Test default, one-parameter, and two-parameter constructors for x, y, z
  Constructor called, default
  Constructor called, re=3
  Constructor called, re=-3.2 im=2.1
- Test output a complex object by consecutive '<<' calls...
 x is 0+0i,  y is 3+0i, z is -3.2+2.1i

- Test the assignment operator by changing x and y...
  Constructor called, re=3 im=-4
  Assignment called, default
  Destructor called, from re=3 im=-4
  Constructor called, re=-2 im=3
  Assignment called, re=3
  Destructor called, from re=-2 im=3
 x is 3+(-4)i, y is -2+3i
 ... ... 

top


Inherited_From_Person_Class (Chapter 15)

The purpose of this program is to practice the concept of inheritance. You create the base class called Person and then derive several classes, Student, CompSciStudent, and Instructor, as shown in the following hierarchy:
Person Inherited hierachy image

Now you can use these class types to create objects and call their mamber functions suggested as the following steps:
// Create a Computer Science Student with the name of Bob Smith and id of 101
    // - by calling the CompSciStudent constructor, which in turn, calling the Student constructor
// Display Bob's Name, ID and Major to verify
// Set the course CSCI 123 to Bob

// Create an Instructor with the name of James Hope and id of 999 at Computer Science Dept. 
    // - by calling the Instructor constructor 
// Display James' information to verify
  
// Let James assign grade 100 to Bob 
    // - by calling the Instructor's function that will assign a grade to the student object passed in
// Display Bob's Name, grade, and course to verify
The expected result would be like this:
Create a Computer Science Student object.
Name: Bob Smith, ID: 101, Major: CS
Set the course CSCI 123 to Bob.

Create an Instructor object.
Name: James Hope, ID: 999, in Computer Science

James assigned grade 100 to Bob.
Now Bob Smith received the grade 100 in CSCI 123

top