#include <iostream>
using namespace std;
int main( )
{
cout << "Hello World!\n";
return 0;
}
|
D:\Teaching\CSCI123\...\Projects>g++ HelloWorld.cpp -o hw D:\Teaching\CSCI123\...\Projects>dir ... ... 08/06/2009 07:39 AM 111 HelloWorld.cpp 08/06/2009 09:42 PM 462,404 hw.exe D:\Teaching\CSCI123\...\Projects>hw Hello World! |
zuoliu@zuoliu-VirtualBox:~$ ssh fccsci.fullcoll.edu -p 5150 -l zding
********************************************************************************
Welcome to Fullerton College Computer Science
NOTICE TO USERS WARNING! The use of this system is restricted to authorized users,
... ...
services this system provides.
********************************************************************************
zding@fccsci.fullcoll.edu's password:
Linux fccsci.fullcoll.edu 2.6.26-2-686 #1 SMP Thu Jan 27 00:28:05 UTC 2011 i686
... ...
Last login: Sat Aug 6 11:53:05 2011 from pool-173-67-105-16.lsanca.dsl-w.verizon.net
zding@fccsci:~$ dir
cppHw
zding@fccsci:~$ cd cppHw
zding@fccsci:~/cppHw$ dir
helloworld.cpp hw hw2
zding@fccsci:~/cppHw$ g++ helloworld.cpp -o hw3
zding@fccsci:~/cppHw$ ./hw3
Hello World!
zding@fccsci:~/cppHw$ vi helloworld.cpp
... ...
zding@fccsci:~/cppHw$ exit
|
D:\Teaching\ssh>psftp fccsci.fullcoll.edu -P 5150 The server's host key is not cached. You have no guarantee ... ... Store key in cache? (y/n) y login as: zding Welcome to ... ... This system is used for educational purposes only. zding@fccsci.fullcoll.edu's password: ************ Remote working directory is /home/jding psftp> dir Listing directory /home/jding ... ... psftp> mkdir ch1 mkdir /home/jding/ch1: OK psftp> cd ch1 Remote directory is now /home/jding/ch1 psftp> put D:\Teaching\CSCI123\Projects\ch01\HelloWorld.cpp local:D:\Teaching\CSCI123\Projects\ch01\HelloWorld.cpp => remote:/home/jding/ch1/HelloWorld.cpp psftp> get HelloWorld.cpp d:\temp\HelloWorld2.cpp remote:/home/jding/ch1/HelloWorld.cpp => local:d:\temp\HelloWorld2.cpp |
login as: zding Welcome to FCSCSI! This system is used for educational purposes only. zding@fccsci.fullcoll.edu's password: Last login: Sun Jul 26 21:51:06 2009 from pool-98-119-126-68.lsanca.dsl-w.verizon.net [zding@fccsci ~]$ dir ... ... [zding@fccsci ch1]$ exit |
*************************************************
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 ...
|
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 . . . |
// ============================================================================
// 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"
|
"/" 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 . . . |
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 |
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 . . . |
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! |
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 . . . |
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 |
int TurnInDays, FullPoints; |
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 . . . |
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
}
|
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 |
fahrenheit = 9/5 * celsius + 32 |
// ============================================================================ // 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 |
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
|
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 |
const int TWINKIE_PRICE = 350; |
int accept_money(); |
int compute_change(int total_paid); |
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;
} |
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 |
double myMax(double x, double y); double myMax(double x, double y, double z); |
double d1 = 3.2, d2 = 4.5, maxVal; maxVal = myMax(d1, d2); double d3 = myMax(8.1, 7, maxVal); |
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); |
char c = myMax('A', 66);
|
bool NumberGuessing(int last); |
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? ... |
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? ... |
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 . . . |
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. |
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 |
void Compute_Coins(int coinValue, int& numbers, int& left); |
// 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; |
void GetSquareInfo(bool& isSolid, char& border, char& inner, int& size); void DrawSquare(bool isSolid, char border, char inner, int n); |
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;
}
|
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: |
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! |
// 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!
}
|
bool CheckWin(char board[]); |
void sort2(int a[], int number_used, bool ascending); |
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 |
int BinarySearch2(int a[], int first, int last, int value, bool ascending); |
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 |
void decrypt(const char encoded[], char decoded[], int key); |
void decrypt(char message[], int key); |
If (OriginalChar + Key > 126) then
EncryptedChar = OriginalChar + Key -127 +32
else
EncryptedChar = OriginalChar + Key;
|
If (EncryptedChar - Key < 32) then
OriginalChar = EncryptedChar - Key + 127 -32
else
OriginalChar = EncryptedChar - Key;
|
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 . . . |
string GetTimeFrom24HourFormat(const string& time); |
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) |
string remove_punct(const string& s, const string& punct); |
string pure_str = remove_punct2(str, ",;:.?!'\" "); |
string remove_punct(const string& s); |
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? |
void SwapWithPtr(int* ptr1, int* ptr2); |
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 . . . |
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
}
|
cout << "Enter a string before reversing: "; cin >> str1; reverse(str1); cout << "This is the string reversed: " << str1 << endl; |
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 |
#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;
}
|
ptrA = xbc ptrB = yc ptrC = z |
#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
}
|
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 |
Enter a file name: f6_20.txt The file contains 50 words. Press any key to continue . . . |
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);
|
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;
}
|
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 |
// 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[]); |
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 ... ... |
class Square
{
public:
void GetSquareInfo();
void DrawSquare();
private:
int size;
bool isSolid;
char border;
char inner;
};
|
sqr.GetSquareInfo(); sqr.DrawSquare(); |
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;
};
|
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
}
|
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 . . . |
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
};
|
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
}
|
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 |

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;
};
|
// 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()
|
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 |
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;
};
|
... ... cin >> square2; ... ... cout << square1 << endl << square2 << endl; ... ... cout << square1+square2; ... ... |
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;
};
|
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 . . . |
#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
}
|
- 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 ... ... |

// 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
|
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 |