Schedule‎ > ‎

Assignment 3: Strings and Conditions


Objectives

  • Work with sequences of variables
  • Work with different types of data
  • Start declaring and using string variables
  • Start calling (invoking) string member functions
  • Start using if-statements.


Academic Honesty

Read the Scholastic Honesty Policy and Assignment Integrity policies of the syllabus. Here are some clarifications for this particular assignment:

  • You may not give a copy of your code to anyone else.
  • You may not show your completed code to another person or look at another person's code until you complete and submit this assignment.
  • You may get help from people but only if they do not show or tell you the code to type.
  • Remember that the instructor performs similarity tests on programming project submissions, and copied or plagiarized code is usually very easy to detect.
  • Most importantly,  you undermine your own self confidence when you cheat,  because you know you didn't accomplish the assignment without cheating.



Programming Style & Notes

Your solutions to these project must only use techniques we have covered so far.

Programming Style

For all programs, remember to follow all the style rules we covered including:

  1. File block comments.
  2. Placement of curly braces and indentation within curly braces, including if-else-if-else Formatting.
  3. Limiting line length to about 80 characters.

    Notepad++, and most other text editors, tell you both the line and column location, which lets you check the line length.

  4. No tab characters in your code.

    You can remove tab characters by either setting up TextPad correctly (see here) or by running a program named astyle.

  5. Spaces before and after operators.
  6. Meaningful variable names and consistent naming style (caps vs. underbars).


Grading Criteria (30pts + Extra Credit)

For each part:  10 pts: Header Comment 1pt, Compiles 2 pts, Proper Formatting 1 pt,  Works as Specified 6 pts
  1. Project 1: wordwork.cpp (10pts)
  2. Project 2: dragon.cpp (10pts)
  3. Project 3: carbot.cpp (10pts)
  4. Extra Credit: xcwordwork.cpp 
.................................................................................................................................................................


Project 1: Word Worksheet

Use this worksheet to improve your understanding of how to work with strings and if-statements, including:

  • String variables (lesson 3.2.3)
  • String input and output (lesson 3.2.3)
  • Concatenation (lesson 3.2.5)
  • String functions (lesson 3.2.6)
  • Comparing strings (lesson 3.3.3)

Refer to lesson 3 for more information on C++ strings and if-statements. Do not use string functions we have not covered in the lecture notes.

For this worksheet, the user enters two words. You write code to display the computations as specified below.

Project Specifications
  1. Start by copying the worksheet and saving it as wordwork.cpp   Compile and run this to make sure you're starting with a good base.

    Add to the existing code to complete the project. Leave the existing code unchanged, except for comments as instructed.

  2. Add your name and the date to the file comment block at the top of the file.
  3. User input is already coded into the worksheet.

    Do not add any other input commands or change the input order.

  4. Complete each of the following string manipulation problems and code your solutions into the worksheet where indicated by the comments. See the Example Run to verify the correctness of each computation.  Compile and run your program frequently to check your progress.
    1. Measure the length of both words entered by the user and save the length in the related variable. Then use an if-statement to compare the two word lengths and print the word that is the longest.
    2. Concatenate the words and a literal string to produce an output showing the second word followed by ", " followed by the first word. Assign the result of the concatenation operations to variable msg.
    3. Concatenate the first 2 letters of the variable first and the last 3 letters of variable second. Assign the result of the concatenation operations to variable extract.
    4. Remove the first 2 and last 1 character of both words and join them using concatenation. Assign concatenated parts to the variable middles.
    5. Compare the first letter of both words to see which one is the largest (latest in the alphabet). Print the largest letter.
  5. Example Run: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and wording of the output. For the input shown you must get the same output. However, the output must change properly if the inputs are different.
    *** Word Worksheet ***
    Enter two words separated by a space, and press the Enter key
    For example: Hello World!<Enter>: Hello World!
    
    You entered: first = "Hello" and second = "World!"
    Parenthesis below show correct results for example words.
    
    *** Measuring word length ***
    First word length (5): 5
    Second word length (6): 6
    Longest word (World!): World!
    
    *** Concatenating strings ***
    Concatenated (World!, Hello): World!, Hello
    
    *** Extracting substrings ***
    Extracted (Held!): Held!
    
    *** Extracting the middle of strings ***
    Middles (llrld): llrld
    
    *** Comparing first letter of both words ***
    Largest first letter (W): W
    

    In the above example run, the user entered the words shown in italics (for emphasis) to produce the output. Your program does NOT print the characters in italics, nor does the user input appear in italics.

  6. After displaying the output, exit the program.
  7. Submit the source code file wordwork.cpp with the rest of Assignment 3 in Canvas.



Project 2: What's Your Dragon Name?

A dragon is a legendary creature, typically scaled or fire-spewing and with serpentine, reptilian or avian traits, that features in the myths of many cultures around world. Dragons are well known in both Chinese and European folk lore as powerful and fearful creatures. 

Some people believe they have an inner dragon, which protects them but also needs to be tamed or trained. In this project, we give a name to your inner dragon.   

Project Specifications
  1. Write a program that gives the user a "dragon name."
  2. Name the source code file dragon.cpp and include all your code in this single file.

    Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.

  3. Ask the user for the following inputs (and no other input) in this order, as shown in the Example Run below:
    1. first name
    2. last name
    3. mother's first name
    4. father's first name
  4. Use the following algorithm to generate the "dragon name":
    The first two letters of your last name
    + last two letters of your first name
    + a space
    + the first two letters of your mother's name
    + the last letter of your father's name
    
  5. Display the result to the user with the following format:
    Your "dragon name" is: "<dragon name>"
    

    Make sure to include the double-quote marks (") in the output for full credit.

  6. Example Run: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and wording of the output. For the input shown you must get the same output. However, the output must change properly if the inputs are different.
    Want to learn your "dragon name?"
    Please enter your first and last name: Edward Parrish
    Please enter your mother's first name: Cassandra
    Please enter your father's first name: Stewart
    Your "dragon name" is: "Pard Cat"
    

    In the above example run, the user entered the values shown in italics (for emphasis) to produce the output. Your program does NOT print the characters in italics, nor does the user input appear in italics.

  7. After displaying the output, exit the program.
  8. Submit the source code file dragon.cpp with the rest of the assignment as described in Deliverables.
Hints:
  • Use an escape character \" to print double quote marks.
References and More Information
  1. Dragon: from Wikipedia




Project 3:  Car Chat

For this programming assignment, we are going to write a basic chatbot program. For fun, try having a conversation with an online chatbot here or here. The chatbot we are going to design wants to know a few things about you, such as:                                                                                                                                                                                                                                                                             Tesla Model X (Silver)   image source

  1. What is your name?
  2. Where are you from?
  3. What is your favorite number?
  4. What is your dream car?
  5. How much does your dream car cost?
Project Specifications
  1. Write a chatbot program that interacts with the user as described in the Interaction section below.
  2. Name the source code file carbot.cpp and include all your code in this single file.                                                                                                                                                 
  3. Interaction: Interact with the user with the following inputs in the order given (and no other input) and responses as follows (see the sample output below):   Compile and run your code after each step.                                                                          
    1. Open the conversation with the name of your bot and find out the name of the user (string). Reply with a greeting that displays the user's name, like "It's so nice to meet you <user's name>!".
    2. Find out where the user is from (string). Reply with a positive statement that says the location, like "<location> sounds like a nice place to be from!".
    3. Find out the user's favorite number (integer). Reply with a value that relates the user's favorite number to your favorite number, like "Your favorite number (<user's favorite number>) is 1.5 times as big as my favorite number, which is (7).
    4. Find out the user's dream car (string). Reply with a comment that expresses interest in the car and states the car name, like "Wow, I've always wanted a <car> too!"
    5. Find out how much the dream car costs (double). Then start a conversation about the cost of the car:
      1. A comment that restates the cost, like "Wow, <cost> is spendy."
      2. Find out how much of a down payment the user can afford, like "How much of a down payment can you afford?".
      3. Use an if-statement to test if the down payment is greater than or equal to the cost. If so, then exit the program with a reply like "Awesome! It must be nice to be rich!"
      4. Otherwise, find out how many months the user would want to take out a loan to pay for <car> (integer)
      5. Find out what annual interest rate (percent) the user expects to get for <car> (double)
      6. Reply with the expected monthly payment and total amount of money the user would pay for <car> (car price + interest), like "Your monthly payment for the <car> is <monthly payment>, which is a total of <total car cost>!.
    6. Say goodbye to <user's name>.

    Make sure to restate the input where indicated by the word "reply".

  4. Assume the user enters only valid data.
  5. For calculating monthly payments, use the following formula:

    `mPymt = {r(P)} / {1 - (1 + r)^{-n}}` 
    Where:

    • rr is the monthly interest rate
    • PP is the cost of the car
    • nn is the number of monthly payments

    Calculate rr by converting the interest rate the user enters to a decimal (divide by 100) and then dividing by 12 (12 months in a year).

  6. Numbers may not display with exactly two decimal places, which is fine. Display the output using the default formatting and precision for the numbers - do NOT add any formatting statements to the code.
  7. Example Runs: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and wording of the output. For the input shown you must get the same output. However, the output must change properly if the inputs are different.
    My name is Mombot.
    What is your name? Ed
    It's nice to meet you Ed.
    Where are you from? Santa_Cruz
    Santa_Cruz sounds like a nice place to be from!
    What is your favorite number? 42
    Your number (42) is 6 times as big as my favorite number, which is (7).
    What is your dream car? Tesla_Model_3
    Wow, I've always wanted a Tesla_Model_3 too.
    How much does a Tesla_Model_3 cost? 35000
    Wow, 35000 is spendy.
    How much of a down payment can you afford? 100
    With a down payment of $100 you will need a loan.
    How many months would do you need for the loan? 60
    For a 60 months loan, what is the annual interest rate you can get (%)? 3.11
    If you bought the Tesla_Model_3 with a down payment of 100,
      you would have a monthly payment of $628.815.
    Over 60 months that is a total of $37728.9!
    After you graduate and get a job as a software engineer,
      maybe you will buy your dream car.
    Well, gotta go study now. Goodbye Ed.
    
    My name is Mombot.
    What is your name? Richie$Rich
    It's nice to meet you Richie$Rich.
    Where are you from? Chicago
    Chicago sounds like a nice place to be from!
    What is your favorite number? 1000000
    Your number (1000000) is 142857 times as big as my favorite number, which is (7).
    What is your dream car? Tesla_Roadster
    Wow, I've always wanted a Tesla_Roadster too.
    How much does a Tesla_Roadster cost? 250000
    Wow, 250000 is spendy.
    How much of a down payment can you afford? 250000
    Awesome! It must be nice to be rich!
    Since rich people just got a huge tax break you can buy your dream car anytime!
    Well, gotta go study now. Goodbye Richie$Rich.
    

    In the above example runs, the user entered the values shown in italics (for emphasis) to produce the output. Your program does NOT print the characters in italics, nor does the user input appear in italics.

    Note: Your output does not have to exactly match mine above. It needs to be correct, but you are free to give your chatbot his/her own personality. Make sure the inputs are in the same order and that you reply to the data entered by the user as shown. Otherwise, have fun with it!

  8. After displaying the output, exit the program.
  9. Submit the source code file carbot.cpp with the rest of the Assignment 3.
Hints:
  • Verify your loan calculation using a car loan calculator like this one.


Extra Credit

The following are worth extra credit points.  xcwordwork.cpp

  1. Add an additional interesting and useful string manipulation like those done in wordwork.cpp making use of both input variables and a string function that we have covered. (2 points: 1 for completing with a string function and 1 for interest or usefulness.)
    1. Submit the source code with the extra string manipulation in a file named xcwordwork.cpp.
    2. Describe the purpose of the string manipulation in the header comment.
    3. Include the data input section of the original wordwork.cpp file.
    4. Follow the output format of the previous problems by:
      1. Printing a title for the problem surrounded by asterisks (*) like, "*** Comparing last letter of both words ***".
      2. On the next line print a label for the problem like, "Largest last letter",
      3. followed by the expected value inside parenthesis when entering "Hello World!" like, "(o)",
      4. followed by a colon and the output of the string manipulation like, ": o".

      Example Extra Credit Output
      *** Extra Credit Word Worksheet ***
      Enter two words separated by a space, and press the Enter key
      For example: Hello World!: Hello World!
      
      You entered: first = "Hello" and second = "World!"
      Parenthesis below show correct results for example words.
      
      *** Comparing last letter of both words ***
      Largest last letter (o): o
      


SOLUTION CODE:

Project 1: wordwork.cpp

/**
    CS-11 Asn 3, wordwork.cpp
    Purpose: Work with string concatenation and functions.

    @author Sharon Strelitz
    @version 1.0 02/09/2018
*/
#include <iostream>
using namespace std;

int main() {
    // Do NOT change the next few lines
    // Read words from stdin and print their values to stdout.
    cout << "*** Word Worksheet ***\n";
    string first, second;
    cout << "Enter two words separated by a space, and press the Enter key";
    cout << "\nFor example: Hello World!<Enter>: ";
    cin >> first >> second;
    cout << "\nYou entered: first = \"" << first << "\" and second = \""
         << second << "\"\n";
    cout << "Parenthesis below show correct results for example words.\n\n";
    // Make changes after this line where stated in comments.

    // a. Length (lesson 3.2.6 + 3.3.1)
    cout << "*** Measuring word length ***\n";
    int firstLength, secondLength;
    // Find length of both words and assign to firstLength and secondLength.
    firstLength = first.length(); // Measure length of first word on this line.
    secondLength = second.length(); // Measure length of second word on this line.
    cout << "First word length (5): " << firstLength << endl;
    cout << "Second word length (6): " << secondLength << endl;
    cout << "Longest word (World!): ";
    // Add if-statements to test word length and print longest (lesson 3.3.1).
    if (firstLength > secondLength) {
        cout << first;
    }  else {
        cout << second;
    }
    cout << endl << endl; // Add if-statements before this line.

    // b. Concatenation (lesson 3.2.5)
    cout << "*** Concatenating strings ***\n";
    string msg;
    // Concatenate second followed by ", " followed by first and assign to msg.
    msg = second + ", " + first; // Assign concatenated parts on this line.
    cout << "Concatenated (World!, Hello): " << msg << endl << endl;

    // c. Extracted first and last parts using substr() (lesson 3.2.5 + 3.2.6)
    cout << "*** Extracting substrings ***\n";
    // Concatenate first 2 letters of first and last 3 letters of second.
    string extract = first.substr(0,2) + second.substr(second.length()-3,3); // Assign concatenated parts on this line.
    cout << "Extracted (Held!): " << extract << endl << endl;

    // d. Show concatenated middles (lesson 3.2.5 + 3.2.6)
    cout << "*** Extracting the middle of strings ***\n";
    // Remove the first 2 and last 1 characters of both words and join them.
    string middles = first.substr(2,first.length()-3) + 
        second.substr(2,second.length()-3);  // Assign concatenated parts on this line.
    cout << "Middles (llrld): " << middles << endl << endl;

    // e. Comparing string letters (lesson 3.3.3)
    cout << "*** Comparing first letter of both words ***\n";
    cout << "Largest first letter (W): ";
    // Add if-statements to test first letter of each word and print largest.
    if (first.substr(0,1) > second.substr(0,1))  {
        cout << first.substr(0,1);
    } else {
        cout << second.substr(0,1);
    }
    cout << endl << endl; // Add if-statements before this line.

    return 0;
}

Project 2:  dragon.cpp

/**
    CS-11 Asn 3, Project 2: dragon.cpp
    Purpose: Generates an inner dragon name for the user

    @author Sharon Strelitz
    @version 1.0 02/09/2018
*/
#include <iostream>
using namespace std;

int main() {
    cout << "Want to learn your \"dragon name\"?" << endl;
    string first = "", last = "", mother = "", father = "";
    cout << "Please enter your first and last name: ";
    cin >> first >> last;
    cout << "Please enter your mother's first name: ";
    cin >> mother;
    cout << "Please enter your father's first name: ";
    cin >> father;
    cout << "Your dragon name is: ";
    /*  dragon name algorithm:  
        The first two letters of your last name
        + last two letters of your first name
        + a space
        + the first two letters of your mother's name
        + the last letter of your father's name
    */  
    string dragonName = "";
    dragonName = last.substr(0,2) + first.substr(first.length()-2,2) + " " 
        + mother.substr(0,2) + father.substr(father.length()-1,1);
    cout << dragonName << endl;
    return 0;
}

Project 3:  carbot.cpp

/**
    CS-11 Asn 3, Project 3: carbot.cpp
    Purpose: Car chatbox

    @author Sharon Strelitz
    @version 1.0 02/09/2018
*/
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << "Hello, my name is MomBot" << endl;
    string name = "", location = "", car = "";
    int number = 0, months = 0;
    double cost = 0.0, total = 0.0;
    double downPayment = 0.0, annualInterest = 0.0;
    double monthlyPayment = 0.0, monthlyInterest = 0.0;
    cout << "What is your name? ";
    cin >> name;
    cout << "Hi " << name << ", it's so nice to meet you!" << endl;
    cout << "Where are you from? ";
    cin >> location;
    cout << "oh! " << location << " sounds like a nice place to be from!" << endl;
    cout << "What is your favorite number? ";
    cin >> number;
    cout << endl << "Your number(" << number << ") " << "is " << number <<
          " times bigger than my favorite number, which is (1)." << endl;
    cout << "What is your dream car? ";
    cin >> car;
    cout << "aaaah,  I've always wanted a " << car << " too!" << endl;
    cout << "How much does a " << car << " cost? ";
    cin >> cost;
    cout << "Wow, $" << cost << " is a lot of money!" << endl;
    cout << "How much of a down payment can you afford? ";
    cin >> downPayment;
    if (downPayment < cost)  {
        cout << "With a down payment of $" << downPayment 
              << " you will need a loan." << endl;
        cout << "How many months do you want to take out a loan? ";
        cin >> months;
        cout << "For a " << months << " months loan, what is the annual " 
             << "interest rate you can get (%)? ";
        cin >> annualInterest;
        monthlyInterest = (annualInterest/100)/12;
        monthlyPayment = (monthlyInterest * cost)/(1 - pow(1 + monthlyInterest,-months));
        cout << "If you bought the " << car << " with a down payment of $"
             << downPayment << ", " << endl;
        cout << "you would have a monthly payment of $" << monthlyPayment 
             << "." << endl;
        total = monthlyPayment * months;
        cout << "Over " << months << " months that is a total of $" <<
             total << endl;
    
    }  else  {
        cout << "Awesome! It must be nice to be rich!";   
    }  
        cout << "Goodbye " << name << ", it was nice chatting with you!" << endl;
        return 0;     
    return 0;
}
Subpages (1): wordwork
Comments