Programming

Programming 1

Hour of Code if you've done it before, help someone else or try a different one.

Python

Assignments

Survey

Write a user survey program named survey.py that asks the user seven questions with a one word answer that you store into variables (ex. What's your favorite color?). They must not be yes or no questions. Your program should respond with the input back to them before the next question (So you like the color blue, I do too.). Each new question should be preceded by a blank line.

GPA

Write a program named gpa.py that asks the user to enter eight numbers (NOT CHARACTERS) representing the grades for each class, where 4 = A, 3 = B, 2 = C, 1 = D and 0 = F. After the grades are entered calculate the grade point average and output it to the console in a user friendly message. Note: sum of grades divided by number of grades equals GPA ((p1+p2…+p8) / 8.0)

Penny

Write a program named penny.py in which the user enters a number of pennies and the program calculates the least number of quarters, dimes, nickels and pennies it is equivalent to. Note: typecasting to an integer truncates the value (ex. int(7 / 3) = 2). Modulus (the percent sign) returns the remainder of division (ex. 7 % 3 = 1). If 41 were entered the answer would be 1 quarter, 1 dime, 1 nickel, and 1 penny.

Rectangle

Write a program named rectangle.py in which the user is prompted for two integers for a rectangle with a width between 1-78 and height between 1-23 until it gets valid entries. It should then use a nested for loop (loop inside another loop) to output the correct rectangle picture.
a sample running of the program should look similar to this, with the blue writing standing for the user input at run time.

Write a program named vowel.py that allows the input of some text then outputs the number of occurrences of each vowel. It should not matter what case the text is input. Also have the program repeat until user wants to quit.

Write a program named money.py that will prompt the user to enter a monthly interest rate, the amount of a monthly deposit and a target value. Then starting with a zero balance, use a loop in which each iteration represents a month and determine the number of years and months needed to reach the target with monthly compounding.

In cryptography, a Caesar cipher is a very simple encryption technique in which each letter in some plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals.

Your task is to implement an encoder/decoder in which a number can be entered as the rotate value and then text can be entered to encode or decode and the result would be output. Once you're done, use your program to decode the following secret message:

Basic text output command is cout and must be followed by double less-than symbols <<. Anything in between quotes is output to the screen. In the example the word text would appear on the screen.cout << "text";

Basic variable output is the same as basic text output but uses a variable that is declared at the beginning of the function.cout << var_name; ← notice no quotes

Combo output variables and text within quotes can be output to the screen by separating them with double less-than symbols.cout << "I'm " << age << " years old.\n";

Input

Basic input command is cin followed by double greater-than symbols >>. The variable must be declared before it is used and must be spelled exactly the same including capitalization.cin >> variable;

Text with spaces input command is used when more than one word of input is desired. Use the command cin.getline(). See below for syntax.cin.getline(variable, #char);The number of characters should be one less than the number declared in the character array.

Operations (math)

+ adds numbers or variables or any combination there of.

- subtracts numbers or variables or any combination there of.

* (the asterisk) multiples numbers or variables or any combination there of.

/ divides numbers or variables or any combination there of.

% (the percent symbol) divides numbers or variables or any combination there of and returns the remainder.

Considerations: calculations are done in the standard order of operations so use parentheses if unsure or to override the standard order.

Decisions

if(condition)
{
//any number of statements or tools can be used within these braces
}
else if(condition)
{
//any number of statements or tools can be used within these braces
}
else
{
//any number of statements or tools can be used within these braces
//notice that no condition is placed after the else.
}

switch(variable)
{
case value1: //a colon follows the case value
//any number of statements or tools can be used within the case
break; //break is used to skip the remaining cases when value is true
case value2:
//any number of statements or tools can be used within the case
//sometimes a break is not used, this is called cascading
default:
//any number of statements or tools can be used within the case
//the default happens if no cases are true
}

Loops

while(condition)
{
//any number of statements or tools can be used within these braces
//these statements repeat until the condition is false
}

do
{
//any number of statements or tools can be used within these braces
//these statements repeat until the condition is false
}while(condition); //a semicolon ends a do loop

for(initial value; condition of exit; action each time thru the loop)
{
//any number of statements or tools can be used within these braces
}

Functions

type name(parameters)
{
//statements
}

The type defines that type of variable returned when the function ends.

The name is made up by the programmer just like a variable name. It should reflect what the function does.

The parameters are values passed to the function when the function is "called" from another place in the program.

Use just one input variable (other variables can be used to store values, count, etc).

Use a loop to input all grades.

Prompt should indicate period number.

Check for valid input and repeat period entry if not.

Allow letter grade entries (uppercase or lowercase) as well as numeric.

Have the program repeat until the user wishes to quit.

Example Run:
This program will ask you to input your grade for each period and then calculate your grade point average.

Please enter your grades (q to exit):
Period 1: A
Period 2: A
Period 3: V
Invalid period 3 grade. Please try again.
Period 3: B
Period 4: C
Period 5: 8
Invalid period 5 grade. Please try again.
Period 5: a
Period 6: a
Period 7: 3
Period 8: 4
Your GPA is 3.5

Create a program called guess.cpp that will play a guess-my-number game with the user. It should repeat until the user chooses to quit. You must include the stdlib.h and time.h library files. The following statement must occur once at the beginning of main to seed the random number generator. It must NOT occur in a loop:srand(time(NULL)); //NULL must be all capitals

Create appropriate variables to hold the number to guess and the user's guess.

Inform the user that they will have 6 chances to guess a random number between 1 and 100.

After each guess let the user know if their guess is high or low.

<your variable name> = rand() will put a random number in your variable. You must figure out how to make it between 1-100 (Hint: modulus).

Dice

Write an interactive program that simulates the roll of two die (see your number guess program for hints). It must use functions and output something that looks like dice with the dots as numbers on them. Make a function to output the dice and allow the user to roll until they choose to quit.

Create a new source file called dice.cpp. There are special characters that will output lines to create the border when added to a string variable. The characters are hexadecimal in which each starts with a zero followed by an x then two characters that are either a digit 0-9 or letter a-f. There are no letter o's following the x. The list below shows which hex code produces which character:

horizontal line - 0xc4

vertical line - 0xb3

upper left corner - 0xda

upper right corner - 0xbf

lower left corner - 0xc0

lower right corner - 0xd9

Example:

• •

• •

•
•
•

You rolled a 7. Roll again? _

Roman Numerals

Write a program that will convert whole numbers less than or equal to 3,999 into Roman Numerals. Your program will prompt for and read in the number from the user and then echo the number back with it's Roman Numeral counterpart.

The easiest way to note down a number is to make that many marks - little I's. Thus I means 1, II means 2, III means 3. However, four strokes seemed like too many…

So the Romans moved on to the symbol for 5 — V. Placing I in front of the V — or placing any smaller number in front of any larger number — indicates subtraction. So IV means 4. After V comes a series of additions — VI means 6, VII means 7, VIII means 8.

means 10. But wait — what about 9? Same deal. IX means to subtract I from X, leaving 9. Numbers in the teens, twenties and thirties follow the same form as the first set, only with X's indicating the number of tens. So XXXI is 31, and XXIV is 24.

means 50. Based on what you've learned, I bet you can figure out what 40 is. If you guessed XL, you're right = 10 subtracted from 50. And thus 60, 70, and 80 are LX, LXX and LXXX.

stands for centum, the Latin word for 100. A centurion led 100 men. We still use this in words like "century" and "cent." The subtraction rule means 90 is written as XC.

stands for 500. As you can probably guess by this time, CD means 400. So CDXLVIII is 448.

is 1,000. You see a lot of Ms because Roman numerals are used a lot to indicate dates. For instance the year 1998 is written as MCMXCVIII. Also the year 2751 is written as MMDCCLI.

Previous text was taken from: http://www.novaroma.org/via_romana/numbers.html

Pig Latin

Write an interactive program called pig.cpp that prompts the user to type in a sentence then your program converts the sentence into Pig Latin. Let the user quit when they want to.
Basically, the Pig Latin system used here works as follows:

Words that start with a vowel (a, e, i, o, u) simply have "way" appended to the end of the word.

Words that start with a consonant have all consonant letters up to the first vowel moved to the end of the word (as opposed to just the first consonant letter), and "ay" is appended('y' is counted as a vowel in this context).

The algorithm incorporates the following features and special case functionality:

Ensures proper capitalization

Correctly translates "qu" (e.g., ietquay instead of uietqay)

Differentiates between "y" as vowel and "y" as consonant
(e.g. yellow = elloyay and style = ylestay) -- (except for a very few exceptions)

In a game of Lingo, there is a hidden word, five characters long. The object of the game is to find this word by guessing, and in return receive two kinds of clues:

characters that are fully correct, with respect to identity as well as to position, and

characters that are indeed present in the word, but which are placed in the wrong position.

Write a program with which one can play Lingo that reads a random word from a file. Use square brackets to mark characters correct in the sense of 1 (in list above), and ordinary parentheses to mark characters correct in the sense of 2. Assuming, for example, that the program conceals the word "tiger", you should be able to interact with it in the following way:

Know the programmers tools (output, input, decision, loops & functions) and in which situation each tool should be used

Programming 2

Review Exercises

Property Tax

Write a program to calculate property tax. Property tax is calculated on 92% of the assessed value of the property. For example, if the assessed value is $100,000 then the property take is on $92,000. Assume that the property tax rate is $1.05 for each $100 of the assessed value.

As part of your program…

Make sure to prompt for the assessed value of the property

Label the results and display them.

Remember to echo everything that has been entered from the user.

Organize your output so that it is easy to read and understand.

Handle the situation where the user enters an invalid value (like a negative value) - display an appropriate error message.

Make sure to display dollars and cents in their proper format. You will need to be in fixed mode, show trailing zeros, and set the precision for the number of digits to the right of the decimal point. To do this include iomanip.h then precede your output line(s) with cout.setf(ios::fixed); and cout.setw(12); and finally <within the output line.

Phone Num Converter

Write a program to convert characters into their corresponding digit on the telephone. So, for example, if you were given the number: 1 800 CS AT BHS, your program would calculate the phone number to be: 1-800-272-8247. Notice that numbers should remain as numbers - only convert characters to numbers. Lower case letters should act the same as upper case letters.

Allow the user to enter new phone numbers as many times as they would like (until they are ready to quit).

Restrictions and hints:

You may not use arrays of characters in this program. You do not need to echo the input with this program!

Only work with one character (or digit) of the phone number at a time. Don't try to read in the entire phone number all at once. Use a loop to do this.

You will need at least 2 loops in your program. One for reading one character of the phone number at a time and one for asking the user if they would like to enter another phone number.

Reducing Fractions

Write a program that asks for a numerator and a denominator for a fraction. Then displays that fraction reduced to lowest terms. Assume for this program that the denominator will always be larger than the numerator and that neither will be larger than 32767. The program should continue until a zero is entered for the numerator.

Your English teacher heard that you know how to write computer programs, and asked you for help. In class, a quiz is given each week, and the teacher likes to write the percentage correct on the top of each student's paper. It is very time consuming to do the math for each student's score, so the teacher would like to have a chart that displays the percentage correct for all the possible scores. Since the total number of possible points is rarely the same from week to week, the teacher needs to be able to generate a new chart for each quiz.

Your teacher would like to be able to see all the percentages (rounded to two decimal places) on a single page ranging from the highest to the lowest score. Write a program that will ask for the total number of points, the highest score, and the lowest score. The program should then create a chart that displays the score and the corresponding percentage for each score from the highest to the lowest. So that more scores can fit on a single screen, the program should display them in columns. No more than twenty scores should appear in any column. If there are more than twenty scores,they should be displayed in the next column to the right. Only the last column should have less than twenty scores. There will never be a quiz with more than 100 possible points, so that there would never need to be more than five columns.

Create a histogram of characters and numbers entered by the user. The histogram should display the "height" of each character. Heights are determined using alphabetical order without regard to case (i.e. z is the highest and a is the lowest. A and a are the same). Your program should prompt the user to "Enter a string of characters:". The string entered will contain 60 or less characters. (some characters may scroll off the screen but that's okay). The Y-axis characters should appear on the left edge and the characters entered should appear as the X-axis at the bottom.

Create a program that will display statistics on text that is entered by the user. Your program should allow the input of a line of text and display a count of the character occurrences. The program should use a function to display the stats for each character and can NOT use any global variables. The display should show each letter followed by the number of times it occurs in the text for all the letters contained in the text. The character string entered should contain 200 or less characters.

Write a game of Hangman, where a random word to guess is read in from a text file. Then a line of periods representing each letter of the word is displayed. The user is then able to enter letter guesses until they guess the word or a complete figure is hung from the gallows. The program should display letters guessed and not allow them to guess the same letter again. It should also replace the corresponding period with the correct letter when it is guessed and show the guesser the word if they don't win. The number of misses should be sent to a function that prints out the gallows.

Input from the User:
User inputs letters until the word is guessed or the person is lynched.

Output to the User:
Display the incorrect letters guessed, the correct letters in their position in the word, and the gallows.

Write a class called deck that has a private array of 52 cards. Also write members (functions) that will load deck with cards (initialize the array of cards to create a deck), shuffle the deck and display all the cards in the deck.

Create a class called hand that allows getting a card and totaling the cards in the hand.

Card Game

Create a card game utilizing the card, deck and hand classes that you've programmed.

Rubics Waffle

Create a new project called waffle and program a waffle class that will simulate the behavior of the waffle puzzle described below.

Rubik's Cube® is a popular puzzle in the shape of a cube with colored face parts that can be independently rotated. You have been hired by the Rubik's people to help test a new product, a kind of 2-dimensional version of the cube called the Rubik's Waffle. The waffle is a flat grid with light-colored squares on one side and dark-colored squares on the other. You can grasp the waffle in your hand and "break" it at some vertical or horizontal division, twisting that part 180 degrees so that the under-side flips over to becomes the top. In the process, the color and orientation of the twisted squares showing on the top will change; see this diagram for an example:
The diagram shows the results of making two twists or moves in sequence, from the upper left to the lower right. On the first move, we break at 2 columns on the right (an "R2" move) and flip them over: note how the darker color from the opposite side now shows on top. In the second move, we flip one row on the top (thus a "T1" move). Here we can see that the two dark squares on the right become light ones on the left. You should write a program which will read in the dimensions of a waffle and a series of moves, and show the final waffle that results (you may show the intermediate steps if you wish). The program should first read the two dimensions (positive integers, say N columns and M rows) and then read in the moves. Each move is a one-letter code for Top, Bottom, Left or Right followed by a positive integer telling how many rows or columns from the specified edge (counting toward the opposite edge) should be turned. For example, if given the dimensions 6 6 and the moves R2 T1, you would show the final waffle as above. More typical examples might involve 10-20 moves like below.