CSci 127 Resources    Coursework    Homework    FAQ



Homework Exercises
CSCI 127: Introduction to Computer Science
Hunter College, City University of New York
Fall 2025


All students registered by Friday, August 22, are sent a Gradescope registration invitation to the email on record on their Brightspace account. If you did not receive the email or would like to use a different account, fill in the form on Brightspace. Include that you not receive a Gradescope invitation, your preferred email, and your EmpID. We will manually generate an invitation. As a default, we use your name as it appears in Brightspace/CUNYFirst (to update CUNYFirst, see changing your personal information). If you prefer a different name for Gradescope, include it, and we will update the Gradescope registration.

General Notes

Learning programming is like learning a foreign language: you will learn more (with less work) if you practice every day. Some of the programs below are easy; some will take more time. We suggest you set aside a block of time most days to work on programming and the course.

The programs build on the concepts and code developed during lecture, lab, and through the reading. Mastery of material is assessed via

While you are encouraged to work with others, all work submitted must be your own. As a rule of thumb, you must do your own typing. If it is not from the book or class webpage and you did not type it, it is plagiarism. For the first incident, your grade will be a 0 for the assignment (even for cases where you typed the program but others submitted it as their own). For the second incident of cheating or plagiarism, your grade will be a 0 for the homework component of the grade (20% of your overall grade). For the third incident, you will fail the class. We report all incidents to the Office of Student Affairs.

Autograder Notes

The majority of the programs this semester are written in Python (see Lab 1 for getting started with Python); it is noted below when other formats or languages are used. For Python programs, the autograder expects a .py file, using only the specified libraries, and does not accept iPython/Jupyter notebooks. Since all assignments are designed to be uploaded as a single file, the autograder is set up for direct file upload instead of Github. If submitting directly (drop-and-drag onto the webpage), the file name is flexible but must have the extension .py, unless otherwise noted. Also, to receive full credit, the code should be compatible with Python 3.10 (the default for the Gradescope autograders).

To get full credit for a program, the file must include in the opening comment:

For example, for the student, Thomas Hunter, his first program might be:

"""
Name:  Thomas Hunter
Email: thomas.hunter1870@hunter.cuny.edu
Date: September 1, 2025
This program prints: Hello, Thomas Hunter
"""

print("Hello, Thomas Hunter")

For each program, the upper right hand side of the description contains the due date, suggested reading, and, when applicable, the available libraries. When testing your Python programs, the autograder uses Python 3.10 and has available the libraries listed. If the available libraries is none, no additional libraries are used (e.g. no import statement is needed in your program).

You may submit your assignments up to three weeks before the due date and are encouraged to work ahead. To receive credit, assignments must be submitted by the deadline to Gradescope. For more information on using Gradescope, see Lab 1. Since Gradescope gives limited feedback, run your program first locally (on your computer or a lab computer) where the compiler messages will pinpoint errors and help debug your code. For example, if Gradescope gives you a "The autograder failed to execute..." error, it means your program has an error (in this case, it's usually the file contains non-Python commands.). The local Python compiler will give the line of your file with the error, where Gradescope will only say that there's a general problem. For more information on installing Python on your computer, see the installation guides.





Homework Exercises


  1. Due Date: 5pm, Tuesday, September 2
    Reading: Chapter 1 & Lab 1
    Available Libraries: none

    Hello

    Write a program that prints Hello followed by your name to the screen. For example, if your name is Thomas Hunter, when your program is run, it would print:

    Hello, Thomas Hunter
  2. Due Date: 5pm, Wednesday, September 3
    Reading: Chapter 4 & Lab 1
    Available Libraries: turtle

    Triangle

    Write a program that draws a triangle using the turtle library.
    program 2

    Note: Whenever submitting a turtle program, choose a name for your file that is not turtle.py. When executing the import turtle statement, the computer first looks in the folder where the file is saved for the turtle module and then in the libraries (and other places on the path). If you name your file turtle.py, it thinks the module is itself, causing all kinds of errors. To avoid this, name your program something like myTurtle.py or program2.py.

  3. Due Date: 5pm, Thursday, September 4
    Reading: Chapter 4 & Lab 1
    Available Libraries: turtle

    Turtle Drawing

    Write a program that implements the incomplete code (start right from the red spot and return to there). The initial part of the code is provided if you like. The colors are green, blue, cyan, and red, respectively.

    """
    Your Name
    Your Email		
    """
    import turtle
    
    t = turtle.Turtle()
    t.pensize(5)
    t.shape("circle")
    
    """
    TODO: finish the rest of the program
    Hint:  The distance for a long line is 300.
    The distance for a short line is 100.
    """

    The result should look as follows:

  4. Due Date: 5pm, Friday, September 5
    Reading: Chapter 1 & Lab 1
    Available Libraries: none

    Multiple Greetings

    Write a program that will print Welcome! multiple times. The number of times depends on your EmplID number. Take the last 2 digits of your EmplID number and add 10. For example, if your EmplID ends in 13, the number of times you repeat the message is 13+10 = 23.

    For example, with an EmplID ending in 02, you would repeat the message 12 times:

    Welcome!
    Welcome!
    Welcome!
    Welcome!
    Welcome!
    Welcome!
    Welcome!
    Welcome!
    Welcome!
    Welcome!
    Welcome!
    Welcome!
  5. Due Date: 5pm, Tuesday, September 9
    Reading: Chapter 4 & Lab 1
    Available Libraries: turtle

    Flower

    Write a program that implements the pseudocode ("informal high-level description of the operating principle of a computer program or other algorithm") below:

    Change the pen to blue.
    Repeat 50 times: 
      Repeat 5 times: 
        Walk forward 100 steps.  
        Turn right 72 degrees. 
      Turn right 70 degrees.

    Your output should look like this:


  6. Due Date: 5pm, Wednesday, September 10
    Reading: Chapter 2 & Lab 2
    Available Libraries: none

    Upper & Lower

    Using the string commands introduced in Lab 2, write a Python program that prompts the user for a message, and then prints the message, the message in lower case letters, and the message in upper case letters.

    A sample run of your program should look like:

    Enter a message:  Mihi cura futuri
    Mihi cura futuri
    mihi cura futuri
    MIHI CURA FUTURI

    Another run:

    Enter a message:  I love Python!
    I love Python!
    i love python!
    I LOVE PYTHON!
    

    Hint: Your program should be able to take any phrase the user enters and prints it, prints it in lower case letters, and prints it in upper case letters. To do that, you need to store the phrase in a variable and print variations of the stored variable. See "More Useful String Methods" in Lab 2.

  7. Due Date: 5pm, Thursday, September 11
    Reading: Chapter 2 & Lab 2
    Available Libraries: none

    Lowercase ASCII

    Write a program that prompts the user to enter a phrase, converts the phrase to lowercase, and then prints out each lowercase character and its corresponding ASCII code.

    A sample run of your program should look like:

    Enter a phrase: abc
    a 97
    b 98
    c 99

    And another sample run:

    Enter a phrase: ABC
    a 97
    b 98
    c 99

    Another run, with a longer phrase:

    Enter a phrase:  I love Python!
    i 105
      32
    l 108
    o 111
    v 118
    e 101
      32
    p 112
    y 121
    t 116
    h 104
    o 111
    n 110
    ! 33
    

    Hint: The first step is to ask the user for input (see Section 2 of Lab 2). If c is a character, ord(c) returns its ASCII code. For example, if c is 'i', then ord(c) returns 105. See Lab 2 for more on ASCII and characters.

  8. Due Date: 5pm, Friday, September 12
    Reading: Chapter 2 & Lab 2
    Available Libraries: none

    Counting by 17's

    Write a program that prints out the numbers from 850 to 1700, counting by seventeens.

    The output of your program should be:

    850
    867
    884
    901
    918
    935
    952
    969
    986
    1003
    1020
    1037
    1054
    1071
    1088
    1105
    1122
    1139
    1156
    1173
    1190
    1207
    1224
    1241
    1258
    1275
    1292
    1309
    1326
    1343
    1360
    1377
    1394
    1411
    1428
    1445
    1462
    1479
    1496
    1513
    1530
    1547
    1564
    1581
    1598
    1615
    1632
    1649
    1666
    1683
    1700
  9. Due Date: 5pm, Tuesday, September 16
    Reading: Chapter 4 & Lab 2
    Available Libraries: turtle

    Expanding Hexadecagon

    Write a program, using the turtle library, that implements the pseudocode below:

    For i = 60, 62, 64, 26, ... ,110:
      Turn pen red.
      Walk forward i steps.
      Turn left 45 degrees.
      Turn pen blue.		
      Walk forward i steps
      Turn right 90 degrees

    Your output should look similar to:


    Hint: See examples of range(start,stop,step) in Section 4 of Lab 2.

  10. Due Date: 5pm, Wednesday, September 17
    Reading: Chapter 2 & Lab 2
    Available Libraries: none

    Acronyms

    Write a program that prompts the user for a phrase and creates an acronym, consisting of the first letters of each word, in uppercase.

    To approach a problem, it is useful to break it into steps:

    1. Prompt for a phrase & read it into a variable.
    2. Make the phrase upper case.
    3. Print the phrase.
    4. Split up the phrase into words.
    5. Take the first letter of each word (keep in mind that split() returns a list of the words ), concatenate and make an acronym of it.
    6. Print the acronym.

    Now translate the above pseudocode (informal but detailed description of the steps in a program) into python and test that your program works as follows:

    Enter a phrase:  City University New York
    Your phrase in capital letters:  CITY UNIVERSITY NEW YORK
    Acronym:  CUNY

    And another run:

    Enter a phrase:  Hunter College
    Your phrase in capital letters:  HUNTER COLLEGE
    Acronym:  HC

    Hint: See examples of looping throught strings in Section 4 of Lab 2.


  11. Due Date: 5pm, Thursday, September 18
    Reading: Chapter 4 & Lab 3
    Available Libraries: turtle

    Shades of Blue

    Modify the program from Lab 3 to show the shades of blue.

    Your output should look similar to:

  12. Due Date: 5pm, Friday, September 19
    Reading: Chapter 2 & Lab 2
    Available Libraries: none

    Word Count

    Write a program that asks the user for a phrase, and prints out the number of words in the phrase. Your program should repeat this for 4 more phrases (a total of 5 phrases):

    The output of your program should be:

    Enter phrase: This is my letter to the World
    7
    Enter phrase: That never wrote to Me-
    5
    Enter phrase: The simple News that Nature told-
    6
    Enter phrase: With tender Majesty
    3
    Enter phrase: Emily Dickinson
    2
  13. Due Date: 5pm, Thursday, September 25
    Reading: Chapter 2, Chapter 4 & Lab 3
    Available Libraries: turtle

    Color Stamps

    Write a program that asks the user for a color in hexadecimal notation, moves a turtle forward 20 steps, and then stamps out a turtle shape that color. Your program should repeat this for 4 more colors in hexadecimal notation (a total of 5 turtle stamps and moves forward).

    For example, if you ran your program and the user entered:

    Enter color (as hex): #0000FF
    Enter color (as hex): #0000B8
    Enter color (as hex): #000087
    Enter color (as hex): #000043
    Enter color (as hex): #000011

    The output would be:

  14. Due Date: 5pm, Friday, September 26
    Reading: Section 2.8, Chapter 4, Lab 2 & Lab 4
    Available Libraries: turtle

    Turning Turtle

    Write a program that asks the user for 5 whole (integer) numbers. For each number, turn the turtle left the degrees entered and then the turtle should move forward 100.

    A sample run of your program should look like:

    Enter a number: 270
    Enter a number: 100
    Enter a number: 190
    Enter a number: 200
    Enter a number: 80

    and the output should look similar to:

  15. Due Date: 5pm, Monday, September 29
    Reading: Lecture 2 & Chapter 2
    Available Libraries: none

    Caesar Cipher


    (The cipher disk above shifts 'A' to 'N', 'B' to 'O', ... 'Z' to 'M', or a shift of 13. From secretcodebreaker.com)

    Write a program that prompts the user to enter a word and then prints out the word with each letter shifted right by 13. That is, 'a' becomes 'n', 'b' becomes 'o', ... 'y' becomes 'l', and 'z' becomes 'm'.

    Assume that all inputted words are in lower case letters: 'a',...,'z'.

    A sample run of your program should look like:

    Enter an all-small-letter string: zebra
    Enter a non-negative int to shift: 13
    Encoded string: mroen

    Here is another sample run of your program.

    Enter an all-small-letter string: owqfka
    Enter a non-negative int to shift: 6
    Encoded string: ucwlqg

    Hint: See the example programs from Lecture 2.


  16. Due Date: 5pm, Tuesday, September 30
    Reading: Lecture 3, Section 9.7 & Lab 2
    Available Libraries: none

    Slicing Loop

    Implement the following piece of pseudocode as a complete program:
    1.  Prompt the user to enter a string and call it s.
    2.  Let ls be the length of s.
    3.  For i in 0, 1, ..., ls-1:
    4.     Print s[:i]
    5.  For i in 0, 1, ..., ls-1:
    6.     Print s[i:]
    5.  Print a closing statement
    	

    A sample run of your program should look like:

    Enter string: a man a plan a canal panama
    

    which would output:

    a
    a
    a m
    a ma
    a man
    a man
    a man a
    a man a
    a man a p
    a man a pl
    a man a pla
    a man a plan
    a man a plan
    a man a plan a
    a man a plan a
    a man a plan a c
    a man a plan a ca
    a man a plan a can
    a man a plan a cana
    a man a plan a canal
    a man a plan a canal
    a man a plan a canal p
    a man a plan a canal pa
    a man a plan a canal pan
    a man a plan a canal pana
    a man a plan a canal panam
    a man a plan a canal panama
    man a plan a canal panama
    man a plan a canal panama
    an a plan a canal panama
    n a plan a canal panama
    a plan a canal panama
    a plan a canal panama
    plan a canal panama
    plan a canal panama
    lan a canal panama
    an a canal panama
    n a canal panama
    a canal panama
    a canal panama
    canal panama
    canal panama
    anal panama
    nal panama
    al panama
    l panama
    panama
    panama
    anama
    nama
    ama
    ma
    a
    
    Thank you for using my program!
  17. Due Date: 5pm, Friday, October 3
    Reading: Chapter 2, Chapter 7 & Lab 4
    Available Libraries: none

    DNA

    We can store DNA sequences as strings. These strings are made up of the letters A, C, G, and T. For a given DNA string, the GC-content is the percent of the string that is C or G, written as a decimal.

    Write a program that prompts the user for a DNA string, and then prints the length and GC-content of that string.

    A sample run of the program:

    Enter a DNA string:  ACGCCCGGGATG
    Length is 12
    GC-content is 0.75

    Hint: See Lab 4. You can use a for-loop to go through each character in the string, and count each time you encounter a 'C' or 'G'. You can use an if-statment to check what kind of character the loop is currently on. Alternatively, you can use the count() method introduced in Lab 2 to get the total occurrences of 'C' and 'G' in the string.

  18. Due Date: 5pm, Tuesday, October 7
    Reading: Lab 4 & Numpy Tutorial
    Available Libraries: matplotlib, numpy

    Grayscale Image

    Write a program that asks the user for a name of an image .png file and the name of an output file. The program then converts the image to grayscale and saves the grayscale image to the specified output file.

    There are many ways to convert color images to grayscale (see Grayscale Algorithms for a nice overview).

    For this program, we are setting each channel of a pixel to its green value. That is, your program should then set the red channel values to the green channel values, as well as the blue channel values to the green channel values. For example, a single pixel at (i,j) of the image img would be changed to:
    img[i,j,0] = img[i,j,1]  #change value of red channel to value of green channel
    img[i,j,2] = img[i,j,1]  #change value of blue channel to value of green channel
    

    A sample run of your program should look like:

    Enter name of the input file:  csBridge.png
    Enter name of the output file:  gray_bridge.png

    The sample input file and the resulting grayscale image:

    Note: before submitting your program for grading, remove the commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.

    Hint: See Lab 3. Think about how you can uses numpy slices to change every pixel.

  19. Due Date: 5pm, Wednesday, October 8
    Reading: Section 8.11, Lab 4 & Numpy Tutorial
    Available Libraries: matplotlib, numpy

    Topographic Map

    Modify the map-making program from Lab 4 to create a topographic map (highlighting the points that have elevations that are multiples of 10) and the coastline. Your program should ask the user for the amount of intensity (a floating point number between 0.0 and 1.0), the name of the output image, and create a new image with that name and with the pixels colored as follows:

    • If the elevation is less than or equal to 0, the pixel should be colored blue (0% red, 0% green, and 100% blue).
    • If the elevation is not 0 but divisible by 10, color the pixel gray (amt red, amt green, and amt blue) where amt is the amount of intensity entered by the user.
    • Otherwise, the pixel should be colored white (100% red, 100% green, and 100% blue).

    A sample run of your program should look like:

    What intensity for the topo lines:  0.5
    What is the output file:  med_topo.png
    Thank you for using my program!
    Your map is stored med_gray_topo.png.

    Your resulting map should look like:

    and be saved to a file called med_gray_topo.png.

    Another run with darker lines:

    What intensity for the topo lines:  0.0
    What is the output file:  dark_lines_topo.png
    Thank you for using my program!
    Your map is stored dark_lines_topo.png.

    Your resulting map should look like:

    and be saved to a file called dark_lines_topo.png.

    Note: before submitting your program for grading, remove the commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.

  20. Due Date: 5pm, Thursday, October 9
    Reading: Section 10.23, Chapter 4 & Lab 4
    Available Libraries: none

    Two-Part Numbers

    Write a program that identifies all two-part numbers from a string and returns a list of those numbers. In the input string, each number is separated by a comma followed by a space: ', ', and two-part numbers contain a '-'.

    For example, if you ran your program and the user entered:

    Enter numbers, separated by commas: twenty, four, thirty-one, sixty-six, eight
    A list of the two-part numbers:  ["thirty-one", "sixty-six"]

    Hint: See Section 4 in Lab 4.


  21. Due Date: 5pm, Friday, October 10
    Reading: Section 8.11, Lab 4 & Numpy Tutorial
    Available Libraries: numpy, matplotlib

    Logo

    Write a program that creates a 'U' logo for university on a 30x30 grid. Your program should ask the user for the red, green, and blue for the color of their logo, and the file to save the image.

    A sample run using Hunter College Purple (Pantone 267):

    Enter amount of red:  0.373
    Enter amount of green:  0.145
    Enter amount of blue:  0.624
    Enter file name:  hunterPurple_U.png
    

    The resulting file is:

    The grading script is expecting:

    • The grid to be 30 x 30.
    • The color of the 'U' is the amount of red, blue, and green specified, as a value between 0 and 1.0.
    • The left side of the 'U' should be the left third of the image; the bottom part of the 'U' should be the bottom third of the image; and the right part of the 'U' should be the the right third of the image.
    • The remaining pixels in the image should be white (100% red, 100% green, and 100% blue).

    Note: before submitting your program for grading, remove the commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.

  22. Due Date: 5pm, Tuesday, October 14
    Reading: Burch's Logic & Circuits & Lab 5
    Available Libraries: N/A

    NAND Circuit

    Build a circuit that has the same behavior as a nand gate (i.e. for the same inputs, gives identical output) using only and, or, and not gates.

    Save your expression to a text file. See Lab 5 for the format for submitting logical expressions to Gradescope.

  23. Due Date: 5pm, Wednesday, October 15
    Reading: Burch's Logic & Circuits & Lab 5
    Available Libraries: N/A

    Majority Circuit

    Write a logical expression that is equivalent to the circuit that computes the majority of 3 inputs, called in1, in2, in3:

    • If two or more of the inputs are True, then your expression should evaluate to True.
    • Otherwise (two or more of the inputs are False), then your expression should evaluate to False.

    Save your expression to a text file. See Lab 5 for the format for submitting logical expressions to Gradescope.

    Hint: See Lab 5.

  24. Due Date: 5pm, Thursday, October 16
    Reading: Chapter 7, Chapter 11, & Lab 4
    Available Libraries: turtle

    Turtle String

  25. The program turtleString.py takes a string as input and uses that string to control what the turtle draws on the screen (inspired by code.org's graph paper programming). Currently, the program processes the following commands:

    For example, if the user enters the string FLFLFLFL^FFFvFLFLFLFL, the turtle would move forward and then turn left. It repeats this 4 times, drawing a square. Next, it lifts the pen and move forward 3, puts the pen back down and draw another square.

    Modify this program to allow the user also to specify with the following symbols:

    An example with the new symbols and string SrFTFFFBBBbtFLFFF would create the image:

  26. Due Date: 5pm, Tuesday, October 21
    Reading: Burch's Logic & Circuits & Lab 5
    Available Libraries: N/A

    Binary Number Incrementer

    Logical gates can be used to do arithmetic on binary numbers. For example, we can write a logical circuit whose output is one more than the inputted number. Our inputs are in1 and in2 and the outputs are stored in out1, out2, and out3.


    Here is a table of the inputs and outputs:
    InputsOutputs
    Decimal
    Number
    in1in2Decimal
    Number
    out1out2out3
    000 1001
    101 2010
    210 3011
    311 4100

    Submit a text file with each of the outputs on a separate line:

    """
    Name:  YourNameHere
    Date:  March 2025
    Logical expressions for a 4-bit incrementer
    """
    
    out1 = ...
    out2 = ...
    out3 = ...
    		
    Where "..." is replaced by your logical expression (see Lab 5 for hints and formatting help).

    Note: here's a quick review of binary numbers.


  27. Due Date: 5pm, Wednesday, October 22
    Reading: Lecture 4, Lab 4
    Available Libraries: none

    Fares by Time

    Write a program that will ask for the time in 24 hour format (e.g. 2034 is 8:34pm) and, prints out:

    • "Peak Fare (Morning Rush)" if the time is between 6am (e.g. 600) and 10am (e.g. 1000), inclusive,
    • "Peak Fare (Evening Rush)" if the time is between 4pm (e.g. 1600) and 8pm (e.g. 2000), inclusive, and
    • "Non-Peak Fare" otherwise.

    A sample run:

    Enter time:  1750
    Peak Fare (Evening Rush)

    Note: "Inclusive" for a range of numbers means that it includes the endpoints. For example, "between 4 and 8, inclusive" means all values that are greater than or equal to 4 and are also less than or equal to 8.

  28. Due Date: 5pm, Thursday, October 23
    Reading: 10-mins to Pandas, DC Pandas, Lab 6
    Available Libraries: pandas

    Minimal Temperatures

    In Lab 6, we wrote a program that computed the average rainfall from Australian weather data. Modify the program to ask the user for the name of a CSV file and then to print out, using the data from the CSV file:

    • The lowest temperature recorded across all locations and dates.
    • The lowest temperature for each location across all dates.

    For example, running the program on rain_A.csv (a smaller version of the CSV file from the lab that's contains only the cities that start with 'A'):

    Enter CSV file name: rain_A.csv
    Overall min temp: -5.2
    
    Minimum temperature by location:
    Location
    Adelaide        0.7
    Albany          1.8
    Albury         -2.8
    AliceSprings   -5.2		
    
  29. Due Date: 5pm, Monday, October 27
    Reading: 10-mins to Pandas, DC Pandas, Lab 6
    Available Libraries: pandas

    Triple Recipe

    Using pandas, write a program that asks the user for a recipe (in comma separated value (CSV) format), reads in the corresponding CSV file and prints out quantities and ingredients needed to make a triple batch. Assume that the CSV files have the columns: "Amount", "Measurement", and "Ingredient".

    For example if the CSV file, meringues.csv, contained:

    AmountMeasurementIngredient
    150gramschocolate chips
    4whites ofeggs
    .25teaspoonvanilla
    .25teaspooncream of tartar

    A sample run of your program would be:

    Enter recipe name: meringues.csv
    Double your recipe is:
       Amount Measurement       Ingredient
    0   450.0       grams  chocolate chips
    1    12.0   whites of             eggs
    2    0.75    teaspoon          vanilla
    3    0.75    teaspoon  cream of tartar
    
  30. Due Date: 5pm, Tuesday, October 28
    Reading: GitHub Guide, Lab 6
    Available Libraries: N/A

    GitHub

    In Lab 6, you created a GitHub account. Submit a text file with the name of your account. The grading script is expecting a file with the format:

    """
    Name:  Your_name
    Email: Your_eamil
    Account name for my GitHub account
    """"
    
    AccountNameGoesHere
    

    Note: it takes a few minutes for a newly created GitHub account to be visible. If you submit to Gradescope and get a message that the account doesn't exist, wait a few minutes and try again.

  31. Due Date: 5pm, Wednesday, October 29
    Reading: Lab 6, Ubuntu Terminal
    Available Libraries: N/A

    Hello (Shell Script)

    Write a shell script that prints Hello, Shell to the screen.

    Submit a single text file containing your Unix shell commands. See Lab 6 for details.

    Note: for comments, shell scripts use # in front of lines (instead of the block comments surrounded by """ """) and the first line is the "shebang" line. For a proper shell script, your file should start:

    #!/bin/bash
    #Name:  YourNameHere
    #Email: YourEmailHere
    

  32. Due Date: 5pm, Thursday, October 30
    Reading: Lab 7 & Section 6.8
    Available Libraries: none

    Hello Two Ways

    Write a Python program that contains a function called, main(). Your function should print out a greeting to you by name. For example, if your name is Thomas Hunter, invoking main() would print:

    Hello, Thomas Hunter

    You should use conditional execution, so your file can be run as a standalone program or imported so the function can be used elsewhere.

    To test your program, we will run it two ways:

    1. We will run it as a stand-alone program and see that it outputs the greeting. If your program is called, student.py, then we would run it, python3 student.py, to see that it prints the greeting.
    2. We will import your file and directly call the function. If your program is called, student.py, we would import it into a Python program, import student, and in that program, call your function, student.main(), to see that it prints the greeting.

    Hint: See Section 4 of Lab 7 for details on conditional execution.

  33. Due Date: 5pm, Friday, October 31
    Reading: Think CS Chapter 6, Chapter 7, Lab 4 & Numpy Tutorial
    Available Libraries: matplotlib, numpy

    Image Shrinking

    Write a function shrink() that takes a numpy array that contains an image and returns an image that is half the width and half the length. The returned image should have every other pixel of the inputted image, starting from the upper left corner.

    For example, using the file csBridge.png as the input file, the following code, using your function:

    bridge_img = plt.imread('csBridge.png')
    small_bridge = shrink(bridge_img)
    plt.imsave('small_bridge.png',small_bridge)
    

    The resulting image is:

    Another example, this time, repeatedly applying our function to the Octocat.png

    #Vanishing cat...
    cat_img = plt.imread('Octocat.png')
    for i in range(5):
        cat_img = shrink(cat_img)
        file_name = 'cat'+str(i)+'.png'
        plt.imsave(file_name,cat_img)
    

    which would have as input and outputs, preserving relative size:

    If we look at them all at the same scale, we can see the taking every other pixel (repeatedly) loses definition:

    Note: before submitting your program for grading, remove any commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.

  34. Due Date: 5pm, Monday, November 3
    Reading: Section 7.4, Lab 4 and Lab 7
    Available Libraries: none

    Number to String

    Write the function string2num() which takes a string and returns the corresponding number as an integer.

    1. If user gives a string that does not correspond to a number between 1 and 99, your function should return: -1.
    2. Numbers larger than 20 are separated by a space. For example, "twenty one" or "ninety nine".

    A sample call of the function:

    print("Converting fourteen to", string2num("fourteen"))

    would print:

    Converting fourteen to 14

    And another example call of the function:

    num_str = "sixty six"
    print("Converting", num_str, "to", string2num(num_str))

    would print:

    Converting sixty six to 66

    Note: The grading script does not run the whole program, but instead tests your function separately ('unit tests') to determine correctness. As such, the function name must match exactly (else, the scripts cannot find it). Before submitting your program for grading, remove any commands that are outside a function definition. To test the function you wrote, we import your file and then call the function directly. Code outside of function definitions will give compilation errors and prevents the tests from completing (giving a grade of 0). If you have extra code for testing and such, either comment it out before submitting, or use conditional execution (see Lab 7).

    Hint: See Lecture 8 for related programs.

  35. Due Date: 5pm, Tuesday, November 4
    Reading: Section 6.8, Section 7.4 & Lab 7
    Available Libraries: none

    URL Domains

    Write a program, using function main() that input a website URL like www.apple.com or hunter.edu. Find out the website name and its top level domain type. If top level domain is com, print "commercial", otherwise, if top level domain is edu, print "education", otherwise, if top level domain is org, print "organization", otherwise, if top level domain is gov, print "government", otherwise, print "other". See Lab 7.

    A sample input/output is as follows.

    Enter a website URL: chat.openai.com
    website name: openai
    commercial

    Another sample input/output is as follows.

    Enter a website URL: hunter.edu
    website name: hunter
    education

    Yet another sample input/output using the air force website as an example.

    Enter a website URL: www.af.mil
    website name: af
    other

    Hint: You may need to consider a website can be in either form: www.websiteName.com or websiteName.com, so use the negative index (e.g. count from the end, instead of the beginning) to extract website or domain after split by '.'.

  36. Due Date: 5pm, Wednesday, November 5
    Reading: 10-mins to Pandas, DC Pandas, Lab 7
    Available Libraries: pandas

    Ticket Binning

    Modify the parking ticket program from Lab 7 to do the following:

    • Ask the user for the name of the input file.
    • Ask the user for the attribute (column header) to search by.

    A sample run:

    Enter file name:  Parking_Violations_Jan_2016.csv
    Enter attribute:  Vehicle Color
    The 10 worst offenders are:
    WHITE    2801
    WH       2695
    GY       1420
    BK       1153
    BLACK    1054
    BROWN     727
    BL        656
    GREY      574
    SILVE     450
    BLUE      412
    Name: Vehicle Color, dtype: int64
    

    And another run:

    Enter file name:  Parking_Violations_Jan_2016.csv
    Enter attribute:  Vehicle Year
    The 10 worst offenders are:
    0       3927
    2015    1265
    2014    1143
    2013    1105
    2012     772
    2011     666
    2007     643
    2008     559
    2010     509
    2006     499
    Name: Vehicle Year, dtype: int64
    

  37. Due Date: 5pm, Thursday, November 6
    Reading: Think CS Chapter 6, Lab 4, Lab 8, & Numpy Tutorial
    Available Libraries: matplotlib, numpy

    Averaging Images

    Fill in the missing functions:

    • average(region): Takes a region of an image and returns the average red, green, and blue values across the region.
    • setRegion(region,r,g,b): Takes a region of an image and red, green, and blue values, r, g, b. Sets the region so that all points have red values of r, green values of g, and blue values of b.

    The functions are part of a program that averages smaller and smaller regions of an image until the underlying scene is visible (inspired by the elegant koalas to the max).

    For example, if you inputted our favorite image, you would see (left to right):

    and finally:

    A template program, averageImage.py, is available here. You should use this file to get started with your program.

    The grading script does not run the whole program, but instead runs each of your functions separately ('unit tests') to determine correctness. As such, the names of the functions must match exactly the ones listed above (else, the scripts cannot find them).

  38. Due Date: 5pm, Friday, November 7
    Reading: 10-mins to Pandas, DC Pandas, Lab 7
    Available Libraries: pandas

    School Enrollment

    Download csv file from 2013 to 2018 Demographic Snapshot Borough. Your program should ask the user for the borough, an name for the output file, and then display the fraction of Grade K to 6 enrollment that has lived in that borough, over time. Then print out the minimum, maximum, median, mean, and stand deviation of total enrollment in that borough (round to 3 decimal numbers).

    A sample run of the program:

    
    Enter borough name:  Bronx
    Enter output file name:  bronxFraction.png
    minimum of total enrollment for Bronx is 233588
    maximum of total enrollment for Bronx is 241986
    median of total enrollment for Bronx is 239955.0
    mean of total enrollment for Bronx is 239283.0
    stand deviation of total enrollment for Bronx is 3407.191
    

    The file bronxFraction.png:

    Hint: First create a column that calculate the fraction of Grade K to 6 vs. Total Enrollment. Then get borough data usig either groupby and get_group function or query method. You can test both approaches. Suppose the original data frame is saved in variable df and the input borough name is put in variable borough.

    borough_data = df.query("Borough == '" + borough + "'")

    Then borough_data has data for the specific borough. Plot fraction using this data.

    Note: before submitting your program for grading, remove the commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.

  39. Due Date: 5pm, Monday, November 10
    Reading: Think CS Chapter 6 & Lab 8
    Available Libraries: turtle

    Polygons

    Write function polygon, which takes four parameters: a turtle, number of edges, edge length, and color as a string. The functionality of polygon uses turtle object to draw a polygon with number of edges, each edge has edge length, the polygon is in color, where color can be specified in name like "red" or using a hexadecimal representation such as "#00ffff" (green + blue = cyan).

    The code of function main to test polygon is as follows:

    def main():
    	tess = turtle.Turtle()
    	polygon(tess, 5, 100, "green")
    	polygon(tess, 6, 60, "#ff00ff")
    	polygon(tess, 7, 70, "#ff0000")
    	turtle.done()
    
    if __name__ == '__main__':
    	main()
    
    The above main function produces the following figure.

    Hint: See Lecture 1 for the general recipe for drawing polygons.

  40. Due Date: 5pm, Tuesday, November 11
    Reading: Chapter 12 & Lab 8
    Available Libraries: none

    Unique Entries

    When students visit the lab, their EmpID is stored as an 8-digit string. Many students visit multiple times, but we are interested in the total number of unique visitors to the lab. Write a function unique_visitors() that takes a list of 8-digit strings and returns the number of unique strings that occur.

    For example:

    ids = ['12345678','11223344','12312323','12345678']
    print("The number of unique visitors is ", unique_visitors(ids))
    
    would print:
    The number of unique visitors is 3
    since there are 4 entries but the first and fourth entries are duplicates of each other.

    Note: The grading script does not run the whole program, but instead tests your function separately ('unit tests') to determine correctness. As such, the function name must match exactly (else, the scripts cannot find it). Before submitting your program for grading, remove any commands that are outside a function definition. To test the function you wrote, we import your file and then call the function directly. Code outside of function definitions will give compilation errors and prevents the tests from completing (giving a grade of 0). If you have extra code for testing and such, either comment it out before submitting, or use conditional execution (see Lab 7).

    Hint: Use a dictionary to store the IDs and return the length of the dictionary.

  41. Due Date: 5pm, Wednesday, November 12
    Reading: Chapter 12 & Lab 8
    Available Libraries: none

    Most Common Word

    Write a function most_common() that takes a string and returns the word that occurs most often. You may assume that:

    • There is exactly one word that occurs most often.
    • All punctuation has been removed and words are separated by spaces (' ') and all letters are lower-case.

    For example:

    phrase = "MORE:  The more that you read, the more things you will know. The more that you learn, the more places you'll go. --Dr. Seuss" 
    phrase = phrase.lower()
    punctuation_list = ['.',',','!','?',':',';','\n','\t','-','  ']
    for pun in punctuation_list:
    	phrase = phrase.replace(pun,' ')
    print('Phrase unpunctuated:', phrase)
    print('Most common word:', most_common(phrase))
    would print:
    Phrase unpunctuated: more the more that you read the more things you will know the more that you learn the more places you'll go dr seuss
    Most common word: more	
    

    since 'more' occurs five times in the phrase, more than any other.

    Note: The grading script does not run the whole program, but instead tests your function separately ('unit tests') to determine correctness. As such, the function name must match exactly (else, the scripts cannot find it). Before submitting your program for grading, remove any commands that are outside a function definition. To test the function you wrote, we import your file and then call the function directly. Code outside of function definitions will give compilation errors and prevents the tests from completing (giving a grade of 0). If you have extra code for testing and such, either comment it out before submitting, or use conditional execution (see Lab 7).

    Hint: Use a dictionary to count how many times you see each name. When you add a name to the dictionary a second time, also append the name to a list of duplicated names.


  42. Due Date: 5pm, Thursday, November 13
    Reading: Think CS Chapter 6 & Lab 8
    Available Libraries: turtle

    Tree Drawing

    Write the function draw_tree() that implements the pseudocode below, using the turtle library:

    Function draw_tree()
    Inputs:  a turtle, the branch length, the leaf color and the trunk color
    
    1.  Change the color to the trunk color.
    2.  If branch length <= 20
    3.     Change the color to leaf color.
    4.     Move forward the branch length.
    5.     Move backward the branch length.
    6.     Change the color to trunk color. 
    7.  Else:
    8.     Move forward 80% of the branch length.
    9.     Turn 30 degrees to the left.
    10.    Call the function with 80% of the branch length, and the same turtle & colors.
    11.    Turn 60 degrees to the right.
    12.    Call the function with 80% of the branch length, and the same turtle & colors.
    13.    Turn 30 degrees to the left.
    14.    Move backward 80% of the branch length.
    

    For example:

    tess = turtle.Turtle()
    tess.left(90)
    tess.pensize(2)
    draw_tree(tess,50,"green","brown")
    

    will draw:

    While increasing the starting branch length and changing the branch and trunk colors:

    tess = turtle.Turtle()
    tess.left(90)
    tess.pensize(2)
    draw_tree(tess,100,"indigo","black")
    

    will draw:

    The grading script does not run the whole program, but instead tests your function separately ('unit tests') to determine correctness. As such, the function name and input parameter order must match exactly (else, the scripts cannot find it).

  43. Due Date: 5pm, Friday, November 14
    Reading: Lab 9
    Available Libraries: none

    Finding Errors




    Lab 9 works through finding and fixing errors in a Python program. Fix all of the errors in the file errorsHex.py and then upload the file to Gradescope.



  44. Due Date: 5pm, Monday, November 17
    Reading: Think CS Chapter 6 & Lab 9
    Available Libraries: turtle, pandas

    Hurricane Tracker

    This program asks that you fill in the missing function to animate hurricane data (inspired by the 2018 Nifty Hurricane Program by Phil Ventura). Your function, animate(t,lat,lon,wind) takes as input:

    • t: a turtle,
    • lat: an integer storing the current latitude,
    • lon: an integer storing the current longitude, and
    • wind: the current wind speed in miles per hour.

    Your function should move to the turtle to the current location (longitude, latitude), and then based on the Saffir-Simpson Hurricane Wind Scale, change the turtle to be:

    • red and pen size 5 for Category 5 (windspeed > 157 mph)
    • orange and pen size 4 for Category 4 (windspeed in 130-156 mph)
    • yellow and pen size 3 for Category 3 (windspeed in 111-129 mph)
    • green and pen size 2 for Category 2 (windspeed in 96-110 mph)
    • blue and pen size 1 for Category 1 (windspeed in 74-95 mph)
    • white and pen size 1 if not hurricane strength

    Download the template program, hurricane.py. You will also need to download the background image, mapNASA.gif (link here), and put it in the same directory as hurricane.py.

    The grading script does not run the whole program, but instead runs each of your functions separately ('unit tests') to determine correctness. As such, the names of the functions must match exactly the ones listed above (else, the scripts cannot find them).

    Two test files (irma.csv and jose.csv) are from the Nifty site. Additional CSV files are available there.

    Hint: You may find the following turtle commands useful: color(), goto(), and pensize().

  45. Due Date: 5pm, Tuesday, November 18
    Reading: 10-mins to Pandas,
    DC Pandas, Plotly Maps, Lab 9

    Available Libraries: pandas, plotly

    Collisions Map

    Using Plotly Express (see Lab 9), write a program that asks the user for the name of a CSV file, name of the output file, and creates a map with markers for all the traffic collisions from the input file. When the user hovers over the marker, the time of the accident should appear in the pop-up box.

    A sample run:

    Enter CSV file name:  collisions.csv
    Enter output file:  myMap.html

    which would produce the HTML file:

    This assignment uses collision data collected and made publicly by New York City Open Data. A sample file, collisionsThHunterBday.csv from 18 October 2016 was downloaded and can be used to test your program.

    When running your program locally, you need to check that the "LATITUDE" and "LONGITUDE" values are non-empty. You can drop any row where there's empty values with:

    df_cleaned = df.dropna()

    Note: For this data set, the names of the columns are "LATITUDE" and "LONGITUDE" (unlike the previous maps from the lab, where the data was stored with "Latitude" and "Longitude").

  46. Due Date: 5pm, Wednesday, November 19
    Reading: 10-mins to Pandas, DC Pandas, Lab 6 & 8
    Available Libraries: pandas

    Address DataFrame

    Write a function, make_addr_df() that has 3 input parameters:

    • last_names: a string containing last names, separated by spaces,
    • first_names: a string containing first names, separated by spaces,
    • emails: a string containing emails, separated by spaces,
    and returns a dataframe with columns labeled: Last, First, and Email and includes the information entered for each. The data for each category is in a string, separated by spaces.

    For example:
    hc_last = "Hunter Raab Kirschner Cantor"
    hc_first = "Thomas Jennifer Anne Nancy"
    hc_email = "th1870@hunter.cuny.edu jr2001@hunter.cuny.edu ak2023@hunter.cuny.edu nc2024@hunter.cuny.edu"
    print(make_addr_df(hc_last, hc_first, hc_email))
    

    will output:

    	Last     First                  emails
    0     Hunter    Thomas  th1870@hunter.cuny.edu
    1       Raab  Jennifer  jr2001@hunter.cuny.edu
    2  Kirschner      Anne  ak2023@hunter.cuny.edu
    3     Cantor     Nancy  nc2024@hunter.cuny.edu
    

    The grading script does not run the whole program, but instead runs your function separately ('unit tests') to determine correctness. As such, the name of the functions must match exactly the one listed above (else, the scripts cannot find it).

    Hint: Use split() to create lists of each category entered. See Lab 8 for creating dataframes with dictionaries.


  47. Due Date: 5pm, Thursday, November 20
    Reading: Think CS: Chapter 8 & Lab 10
    Available Libraries: random

    Random Walk

    Modify the program from Lab 10 that makes a turtle walk 250 times. Each "walk" is 5 steps forward and the turtle can turn 0,45,90,135,...330,345 degrees (chosen randomly) at the beginning of each walk.

    A sample run of your program:

  48. Due Date: 5pm, Friday, November 21
    Reading: Think CS: Chapter 8 & Lab 10
    Available Libraries: none

    Validating Input

    Write a program that asks the user to enter a string. If the user enters an empty string, your program should continue prompting the user for a new string until they enter a non-empty string with 10 characters or less. Your program should then print out the string entered.

    A sample run of your program:

    Enter a string with 1 to 10 characters:
    That string is the wrong length.  Try again.
    Enter a string with 1 to 10 characters: Mihi cura futuri
    That string is the wrong length.  Try again.
    Enter a string with 1 to 10 characters: Hunter
    You entered: Hunter
    
    
  49. Due Date: 5pm, Monday, November 24
    Reading: 10-mins to Pandas, DC Pandas,
    Plotly Maps, Lab 9

    Available Libraries: pandas, plotly

    Housing Map

    Using Plotly Express (see Lab 9), write a program that asks the user for the name of a CSV file, choice of unit size, and name of the output file, and creates a map with scaled markers for all the housing of that size from the input file. When the user hovers over the marker, the name of the property, the number of units of that size and the coordinates. The overall title for the map should include the housing type.

    The housing data is available from NYC Open Data listing affordable and market rate housing by building location. We created a smaller file, of just 2023 housing units, Affordable_Housing_Production_by_Building_2023.csv.

    If the user enters for size:

    • 0: use the column: "Studio Units"
    • 1: use the column: "1-BR Units"
    • 2: use the column: "2-BR Units"
    • 3: use the column: "3-BR Units"
    • 4: use the column: "4-BR Units"
    • 5: use the column: "5-BR Units"
    • Otherwise use the column: "6-BR+ Units"

    A sample run:

    
    Enter input file: Affordable_Housing_Production_by_Building_2023.csv
    Enter number of bedrooms (0 for studio, 1 for one bedroom,...): 2
    Enter output file name: two_bed_2023.html
    
    

    which would produce the HTML file:

    Since the data includes all permits, the information for some private residences is not shared (marked 'Confidential' in the "Project Name" column). Since those lack information, drop those rows before plotting:

    housing_df = housing_df[ housing_df['Project Name'] != 'Confidential']

    Once the user has specified the housing type, you should make sure that you only plot rows that have information about that housing size (e.g. that are not null ). For example, if they are interested in 1 bedroom apartments:
    df = housing_df[ housing_df["1-BR Units"].notnull() ]
  50. Due Date: 5pm, Tuesday, November 25
    Reading: Lab 10, Lab 11, & Ubuntu Terminal
    Available Libraries: N/A

    Counting Script

    Using Unix shell commands, write a script that counts the number of .py files in current working directory.

    Submit a single text file containing your shell commands. See Lab 10.

    Note: for comments, shell scripts use # in front of lines (instead of the block comments surrounded by """ """) and the first line is the "shebang" line. For a proper shell script, your file should start:

    #!/bin/bash
    #Name:  YourNameHere
    #Email: YourEmailHere
  51. Due Date: 5pm, Wednesday, November 26
    Reading: Think CS Chapter 9 & Lab 9
    Available Libraries: none

    Decimal to Binary Converter

    Write a function dec2bin() that takes as input a positive integer and returns a string containing the corresponding binary number. Your function should implement the pseudocode:

    dec2bin( dec_num ):
    1. Set bin_str = "".
    2. While dec_num != 0:
    3.   Let rem be the remainder of dividing dec_num by 2.
    4.   Add rem to the beginning of bin_str.
    5.   Let dec_num be dec_num divided by 2 (integer division).
    6. Return bin_str.
    

    For example, calling your function:

    print("5 in binary is", dec2bin(5))

    would print:

    5 in binary is 101

    And another example:

    num = 15
    print(num, "in binary is", dec2bin(num))

    would print:

    15 in binary is 1111

    Note: The grading script does not run the whole program, but instead tests your function separately ('unit tests') to determine correctness. As such, the function name must match exactly (else, the scripts cannot find it). Before submitting your program for grading, remove any commands that are outside a function definition. To test the function you wrote, we import your file and then call the function directly. Code outside of function definitions will give compilation errors and prevents the tests from completing (giving a grade of 0). If you have extra code for testing and such, either comment it out before submitting, or use conditional execution (see Lab 7).

    Hint: Remember to add a number to a string, you need to cast the number to be a string first: e.g. bin_str = str(rem) + bin_str.


  52. Due Date: 5pm, Monday, December 1
    Reading: MIPS Wikibooks & Lab 11
    Available Libraries: N/A

    Machine Language Hi

    Write a simplified machine language program that prints: Hi World!

    See Lab 11 for details on submitting the simplified machine language programs.

    Hint: You may find the following table useful:


    (Image from wikimedia commons)

    Hint: The grading scripts are matching the phrase exactly, so, you need to include the spacing and punctuation.

  53. Due Date: 5pm, Tuesday, December 2
    Reading: MIPS Wikibooks & Lab 11
    Available Libraries: N/A

    Machine Language Loop

    Write a simplified machine language program that has register $s0 loop through the numbers 10, 9, 8, ..., 2, 1, 0.

    See Lab 11 for details on submitting the simplified machine language programs.

  54. Due Date: 5pm, Wednesday, December 3
    Reading: Lab 12
    Available Libraries: C++

    C++ Hello

    Write a C++ program that prints "Hello, C++!" and also prints Hello followed by your name. These greetings should be printed on two separate lines to the screen. For example, if your name is Thomas Hunter, when your program is run, it would print:

    Hello, C++!
    Hello, Thomas Hunter

    Hint: See Lab 12 for getting started with C++.

  55. Due Date: 5pm, Thursday, December 4
    Reading: Lab 4 & Lab 12
    Available Libraries: C++

    Loop Practice

    Write a C++ program that asks for the number of repetition, print Practice makes perfect. that many times.

    A sample run of your code is as follows.

    Enter repetition time: 5
    Practice makes perfect.
    Practice makes perfect.
    Practice makes perfect.
    Practice makes perfect.
    Practice makes perfect.

  56. Due Date: 5pm, Friday, December 5
    Reading: Lab 4 & Lab 12
    Available Libraries: C++

    Temperature Converter

    Write a C++ program that converts fahrenheit to celsius. Your program should prompt the user for the temperature in fahrenheit and then print out the corresponding temperature in celsius.

    A useful formula: celsius = (5/9)* (fahrenheit - 32).

    See Lab 4 for designing Input-Process-Output programs and Lab 12 for getting started with C++.


  57. Due Date: 5pm, Monday, December 8
    Reading: Lab 12 & Lab 13
    Available Libraries: C++

    Stripes

    Write a C++ program program that asks the user for a number and draws stripes of that height and width using 'character graphics'.

    A sample run:

    Enter a number:  6
    +-+-+-
    +-+-+-
    +-+-+-
    +-+-+-
    +-+-+-
    +-+-+-

    Another sample run:

    Enter a number:  3
    +-+
    +-+
    +-+
  58. Due Date: 5pm, Tuesday, December 9
    Reading: Lab 12 & Lab 13
    Available Libraries: C++

    Credit Classification

    Write a C++ program that asks the user for the current number of credit hours and prints

    • "freshman" if the given hours is lower than 30.
    • "sophomore" if the given hours is at least 30 and less than 61.
    • "junior" if the given hours is at least 61 and less than 91.
    • "senior" if the given hours is 91 degrees or greater.

    A sample run:

    Enter number of credit hours taken: 12
    freshman	
    

    Another sample run:

    Enter number of credit hours taken: 96
    senior	
    
  59. Due Date: 5pm, Wednesday, December 10
    Reading: Lab 12 & Lab 13
    Available Libraries: C++

    Validating Input (C++)

    Write a C++ program that asks the user for a year, and continue asking until the number entered that is 2025 or later. Once an appropriate year has been entered, your program should then print the year entered.

    A sample run:

    Enter year: 2020
    Year must be 2025 or later
    Enter year: 1990
    Year must be 2025 or later
    Enter year: 2030
    You entered:  2030
    

    Hint: See Lab 10 for similar programs in Python. Rewrite in C++.

  60. Due Date: 5pm, Thursday, December 11
    Reading: Lab 12 & Lab 13
    Available Libraries: C++

    Population Growth

    Write a complete C++ program that prints the change in population of the the United States:

    p = p + Bp - Dp
    where p is the population, B is the birth rate of 12.4 births for every 1000 people (12.4/1000) each year, and D is the death rate of 8.4 for every 1000 people (8.4/1000). In 2017, the population of United States was 325.7 million. Your program should ask the user for the number of years and print expected population over those years starting from 2017. Each line should have: the year and the population (in millions).

    A sample run:

    Please enter the number of years: 10
    Year 2017  325.70
    Year 2018  327.00
    Year 2019  328.31
    Year 2020  329.62
    Year 2021  330.94
    Year 2022  332.27
    Year 2023  333.60
    Year 2024  334.93
    Year 2025  336.27
    Year 2026  337.61

    Note: if you would like to make the output a bit prettier, you can include the library (#include <iomanip>) which has a command to limit the number of places after the decimal point printed to 2 before you print:

    cout << setprecision(2) << fixed;
  61. Due Date: 5pm, Friday, December 12
    Reading: Lab 12 & Lab 13
    Available Libraries: C++

    Twos' Complement

    Write a C++ program that asks the user for a whole number between -31 and 31 and prints out the number in "two's complement" notation, using the following algorithm:

    1. Ask the user for a number, n.
    2. If the number is negative, print a 1 and let x = 32 + n.
    3. If the number is not negative, print a 0 and let x = n.
    4. Let b = 16.
    5. While b > 0.5:
      1. If x >= b then print 1, otherwise print 0
      2. Let x be the remainder of dividing x by b.
      3. Let b be b/2.
    6. Print a new line ('\n').

    A sample run:

    Enter a number:  8
    would output:
    001000

    Another run:

    Enter a number: -1
    would output:
    111111