Programming exercises



Download 247.83 Kb.
Page1/3
Date08.05.2017
Size247.83 Kb.
#17660
  1   2   3
Chapter1- Introduction to Computing and Programming

PROGRAMMING EXERCISES
1. Write a program that produces the following output. Replace the name

Tyler Howard with your name.

Hello World! My name is Tyler Howard!
2. First develop a prototype, and then write a program that displays the name of

the programming language discussed in this text. You should be more

creative, but one possible design is given here.

3. Print your name, school, and the year you plan to graduate. Place your name

on one line and your graduation year on the second line. Be sure to include

appropriate labels. For example, my information would look like the following,

if I planned to graduate in 2017:

Name: Barbara Doyle

Graduation Year: 2017

School: Jacksonville University
4. Develop an application that produces a banner containing information about

your project. Items you might include are your programming assignment

number, name, date submitted and the purpose of the application. Label each

item. These are items you might want to include as internal documentation

on future programming assignments. Your output for your banner might

look similar to the following:

*********************************************************

** Programming Assignment #4 **

** Developer: Alma King **

** Date Submitted: September 17 **

** Purpose: Provide internal documentation. **

*********************************************************

In addition to printing the output screen banner shown in the preceding code segment, be

sure to include appropriate comments as internal documentation to your program.

Flags are a symbol of unity and invoke special meaning to their followers.

Create a design for a flag, and write a program that displays your design. One

possible design follows.

*******——————————————————————————————————

*******——————————————————————————————————

*******——————————————————————————————————

*******——————————————————————————————————

—————————————————————————————————————————

—————————————————————————————————————————
6. Create an application that produces three different outputs using the same

phrase. Select your own favorite popular saying for the phrase. The phrase

should first be displayed on one line. Use at least three Write( ) methods - but

the output should all appear on a single line.

Then print the phrase on three lines, again using only Write( ) methods. For

your third and final output, print your favorite saying one word per line.

Decide which combination of Write( ) and/or WriteLine( ) would be the

most streamlined approach. Following is an example of what the final output

would look like using a favorite saying of the author:

7. Produce a listing containing information about you. Include items such as,

your name, hometown, major, hobby and/or favorite activity. Label each

piece of information, place each of the items on separate lines and place a

backslash (\) after each entry. Begin and end the entire listing with the |

character. Include the full listing in a box of asterisks. Your output might look

similar to the following:



8. Hangman is a favorite childhood game. Design the stick figure for this game

and produce a printed listing with your stickman. One possible design

follows. You may implement this design or develop an improved version.

(^;^)

|

./ | \.



|

_/ \_
9. Create an application that displays the following patterns. You may use any

character of your choice to construct the pattern. One possible solution

follows.


10. Write your initials in block characters to a standard output device. Design

your prototype using the symbol(s) of your choice. For example, my initials

in block characters are shown below.


BBBBBBBBBBBBBB AA DDDDDDDDDDDDDDDDD

BB BB AA AA DD DD

BB BBBB AA AA DD DD

BB BB AA AA DD DD

BB BB AA AA DD DD

BBBBBB AA AA AA AA AA AA DD DD

BB BB AA AA DD DD

BB BB AA AA DD DD

BB BBBB AA AA DD DD

BB BB AA AA DD DD

BBBBBBBBBBBBBBB AA AA DDDDDDDDDDDDDDDDD

Chapter2. Data Types and Expressions

PROGRAMMING EXERCISES

For each of the exercises, be sure to include appropriate comments, choose meaningful

identifiers, and use proper indentations in your source code.


1. Design an application that converts miles to feet. Declare and initialize miles to

4.5. Show your miles formatted with two positions to the right of the decimal.

Feet and inches should both be shown with no positions to the right of the

decimal. Once you get that portion running, modify your solution so that you

also show the total number of inches. Go into your source code and change the

initialization value for miles. Rerun the application.


2. Write a program that converts a mile into its equivalent metric kilometer

measurement. Test the program by performing a compile-time initialization of

10 for the miles value. Display the original miles and the formatted converted

value. Go into your source code and change the initialization value and rerun the

application with a new mile value of 3.5. For an additional challenge, include in

your application a kilometer to miles converter.


3. Write a program that converts a temperature given in Celsius to Fahrenheit.

Test the program by performing a compile-time initialization of 32 for the

original Celsius value. Display the original temperature and the formatted

converted value. Go into your source code and change the initialization value

to 0. Rerun the application. Select additional test values and rerun the

application.


4. Write a program that shows the formatted retail price of items when there is a

15% markup. Test the program by performing a compile-time initialization with

Ruggy Shoes, which has a wholesale price of $52.00. Display appropriately2

labeled retail and wholesale values for the shoes. Once you get that running, go

back into your source code, add lines of code that will reassign the memory

location’s values for a Teno Jacket, which has a wholesale price of $71.00. Add

additional lines of code, which will display the new information.
5. Write a program that calculates and prints the take-home pay for a commissioned

sales employee. Perform a compile-time initialization and store the name of

Nesbith Lang in a variable called employeeName. Nesbith earns 7% of her total

sales as her commission. Her federal tax rate is 18%. She contributes 10% to a

retirement program and 6% to Social Security. Her sales this month were

$161,432. Produce a formatted report showing the amount for each of the

computed items. Select appropriate constants. After you finish displaying Nesbith

Lang’s data, change the values and rerun the application.


6. Write a program that computes the average of five exam scores. Declare and

perform a compile-time initialization with the five values. Use a constant to

define the number of scores. Print all scores and the average value formatted

with no digits to the right of the decimal. Rerun the application with different

values.

7. Write a program that prints the number of quarters, dimes, nickels, and



pennies that a customer should get back as change. Run your program once

by performing a compile-time initialization using 92 cents for the value to

be converted. Go into your source code and change the 92 to 27. Rerun the

application.


8. Write a program that computes a weighted average giving the following weights.

Homework: 10%

Projects: 35%

Quizzes: 10%

Exams: 30%

Final Exam: 15%

Do a compile-time initialization with the following values:

Homework: 97; Projects: 82; Quizzes: 60; Exams: 75; Final Exam 80. Display

all values, including the weights, appropriately labeled and formatted. Rerun

the application with different values.


9. Write a program that computes the amount of money the computer club will

receive from the proceeds of their granola project. Each case has 100 bars. The

granola bars sell for $1.50 per bar. Each case costs $100.00. They are required to

give the student government association 10% of their earnings. Display their

proceeds, showing the amount given to the student government association.

Show all the values formatted with currency. Do a compile-time initialization

using 29 for cases sold.

10. In countries using the metric system, many products are sold by grams and

kilograms as opposed to pounds and ounces. Write an application that converts

grams to pounds and will display the price of the product by pound. Test your

application by doing a compile-time initialization of a product called Montreal

Smoked Meat, which sells for $2.09 per 100 grams.



Chapter3. Methods and Behavior

PROGRAMMING EXERCISES


1. Write an application that includes two additional methods in addition to the

Main( ) method. One method should return a string consisting of four or

five lines of information about your school. The other method should return

a string consisting of asterisks. First call the method that returns the string of

asterisks. Call the method that returns the asterisk a second time after you

invoke the method that displays the information about your school. Items

you might include are the name of your school, number of students enrolled,

and school colors. Include appropriate labels. The display should be aesthetically

pleasing so include enough asterisks to surround your listing.
2. Design a message display application. Allow users to enter their name and

favorite saying in a single method that gets invoked two times. First call the

method asking for the person’s name. Send a string argument indicating what

value should be entered. Invoke the method a second time to retrieve the

favorite saying. Return the string values back to the Main( ) method. Call

another method, sending the name and saying. From that method, display the

message showing the person’s name and their saying surrounded by rows of

greater than/less than symbols(<><><>).


3. Write an application that allows a user to input the height and width of a

rectangle and output the area and perimeter. Use methods for entering the

values, performing the computations, and displaying the results. Results

should be formatted and printed in a tabular display.


4. Design an application using methods that convert an integer number of

seconds to an equivalent number of hours, minutes, and seconds. Use

methods for entering the initial seconds, performing the computations, and

displaying the results. Results should be formatted and printed in a tabular

display.
5. Write a program that converts a temperature given in Fahrenheit to Celsius.

Allow the user to enter values for the original Fahrenheit value. Display the

original temperature and the formatted converted value. Use appropriate

methods for entering, calculating, and outputting results.


6. Write a program that can be used to convert meters to feet and inches. Allow

the user to enter a metric meter value in a method. Write appropriate

methods for your solution.

7. Write a program that can be used to determine the tip amount that should

be added to a restaurant charge. Allow the user to input the total, before

taxes and the tip percentage (15% or 20%). Produce output showing the

calculated values including the total amount due for both the 15% and the

20% tips. Tax of 9% should be added to the bill before the tip is determined.

Write appropriate methods for your solution.

8. Write a program that computes the amount of money the computer club

will receive from proceeds of their granola bar sales project. Allow the user

to enter the number of cases sold and the sale price per bar. Each case

contains 12 bars; each case is purchased at $5.00 per case from a local vendor.

The club is required to give the student government association 10% of their

earnings. Display their proceeds formatted with currency. Write appropriate

methods for your solution.


9. Write a program that calculates and prints the take-home pay for a commissioned

sales employee. Allow the user to enter values for the name of the

employee and the sales amount for the week. Employees receive 7% of the

total sales. Federal tax rate is 18%. Retirement contribution is 15%. Social

Security tax rate is 9%. Use appropriate constants. Write input, display, and

calculation methods. Your final output should display all calculated values,

including the total deductions and all defined constants.
10. Write an application that helps landowners determine what their property

tax will be for the current year. Taxes are based on the property’s assessed

value and the annual mileage rate. The established mileage rate for the

current year is $10.03 per $1000 value. Homeowners are given a $25,000

tax exemption, which means they may subtract $25,000 from the assessed

value prior to calculating the taxable value. Enable users to enter the

property address and the prior year’s assessed value. The township has

decided to increase all properties’ assessed value 2.7% for the current year

to add additional monies to the school budget line. Provide methods to

compute and return the new assessed value and the proposed taxes for the

current year. Provide another method that displays the formatted values.

Chapter4. Creating your own classes

PROGRAMMING EXERCISES

1. Create a class representing a student. Include characteristics such as student

number, first and last name, overall GPA, classification, andmajor. Write at least

two constructors. Include properties for each of the data items. Create a second

class that instantiates the first class with information about yourself. In the

second class, create a class method that displays your name and GPA.
2. Create a Motorway class that can be used as extra documentation with

directions. Include data members such as name of motorway, type (i.e.,

Road, Street, Avenue, Blvd., Lane, etc.), direction (i.e., E, W, N, or S),

surface (i.e., blacktop, gravel, sand, concrete), number of lanes, toll or no toll,

and the party that maintains it. Write instance methods that returns the full

name of the motorway, full name of the motorway and whether it is toll or

not, and full name of the motorway and the number of lanes. Also include a

ToString( ) method that returns all data members with appropriate labels.

Include enough constructors to make the class flexible and experiment with

using the class diagram to create the property members.

3. Create an Employee class. Items to include as data members are

employee number, name, date of hire, job description, department, and

monthly salary. The class is often used to display an alphabetical listing of all

employees. Include appropriate constructors and properties. Override the

ToString ( ) method to return all data members. Create a second class

to test your Employee class.


4. Create a Receipt class that could be used by an automobile parts store.

Items to include as data members are receipt number, date of purchase,

customer number, customer name and address, customer phone number,

item number, description, unit price, and quantity purchased. For simplicity

you may assume each receipt contains a single item number. Include

appropriate constructors and properties plus an additional method that

calculates the total cost using the quantity and unit price. Override the

ToString ( ) method to return the information about the customer (name

and phone number) and the total cost of the item purchased. Create a

second class to test your Receipt class.


5. Create a Date class with integer data members for year, month, and day.

Also include a string data member for the name of the month. Include a

method that returns the month name (as a string) as part of the date. Separate

the day from the year with a comma in that method. Include appropriate

constructors, properties, and methods. Override the ToString ( ) method

to display the date formatted with slashes (/) separating the month, day, and

year.
6. Create a Trip class. Include as data members destination, distance traveled,

total cost of gasoline, and number of gallons consumed. Include

appropriate constructors and properties. Add additional methods that calculates

miles per gallon and the cost per mile. Override the ToString ( )

method. Create a second class to test your Trip class.

7. Create a Money class that has as data members dollars and cents. Include

IncrementMoney and DecrementMoney instance methods. Include constructors

that enable the Money class to be instantiated with a single value

representing the full dollar/cent amount as well as a constructor that enables

you to create an instance of the class by sending two separate integer

values representing the dollar and cent amounts. Include an instance method

that returns as a string the number of dollars, quarters, nickels, dimes, and

pennies represented by the object’s value. Override the ToString( )

method to return the monetary amount formatted with currency symbols.

Create a second class to test your Money class.

8. There are a number of national and state parks available to tourists. Create a

Park class. Include data members such as name of park, location, type of

(i.e., national, state, local) facility, fee, number of employees, number of

visitors recorded for the past 12 months, and annual budget. Write separate

instance methods that a) return a string representing name of the park, the

location and type of park; b) return a string representing the name of the

park, the location and facilities available; c) compute cost per visitor based

on annual budget and the number of visitors during the last 12 months; and

d) compute revenue from fees for the past year based on number of visitors

and fee. Also include a ToString( ) method that returns all data members

with appropriate labels. Create a second class to test your Park class.


9. Write a program that includes an Employee class that can be used to

calculate and print the take-home pay for a commissioned sales employee.

All employees receive 7% of the total sales. Federal tax rate is 18%. Retirement

contribution is 10%. Social Security tax rate is 6%. Write instance

methods to calculate the commission income, federal and social security tax

withholding amounts and the amount withheld for retirement. Use appropriate

constants, design an object-oriented solution, and write constructors.

Include at least one mutator and one accessor method; provide properties for

the other instance variables. Create a second class to test your design.

Allow the user to enter values for the name of the employee and the sales

amount for the week in the second class.
10. Write a program that creates a ProfessorRating class consisting of

professor ID and three ratings. The three ratings are used to evaluate

easiness, helpfulness, and clarity. In a separate implementation class, allow

the user to enter the values. Call the constructor to create an instance of the

ProfessorRating class. Include appropriate properties. Do not allow

the ID to be changed after an object has been constructed. Provide a

method in the ProfessorRating class to compute and return the

overall rating average. Print all ratings and the average rating formatted with

no digits to the right of the decimal from the implementation class. Use a

single class method to enter all data.



Chapter5. Making Decisions

PROGRAMMING EXERCISES

1. Write an application that will enable you to display an aquarium’s pH level. The

pH is a measure of the aquarium water’s alkalinity and is typically given on a 0-14

scale. For most freshwater fish tanks, 7 is neutral. Tanks with a pH lower than 7

are considered acidic. Tanks with a pH higher than 7 are alkaline. Allow the user

to input the pH level number. Display a message indicating the health (i.e.,

acidic, neutral, or alkaline) of the aquarium.


2. Create a Month class that has a single data member of month number. Include

a member method that returns the name of the month and another method that

returns the number of days in the month. The ToString( ) method should

return the name and number of days. Write a second class to test your Month

class. The second class should allow the user to input a month number. Display

the name of the month associated with the number entered and the number of

days in that month. For this exercise, use 28 for February. If the user inputs an

invalid entry, display an appropriate message.

Write a program to calculate and display a person’s Body Mass Index (BMI).

BMI is an internationally used measure of obesity. Depending on where you live,

either use the Imperial BMI formula or the Metric Imperial Formula. Once the

BMI is calculated, display a message of the person’s status. Prompt the user for

both their weight and height. The BMI status categories, as recognized by the

U.S. Department of Health & Human Services, are shown in the table below:

BMI Weight Status

Below 18.5 Underweight

18.5 - 24.9 Normal

25 - 29.9 Overweight

30 & above Obese
4. Write a program that calculates the take-home pay for an employee. The two

types of employees are salaried and hourly. Allow the user to input the employee

first and last name, id, and type. If an employee is salaried, allow the user to input

the salary amount. If an employee is hourly, allow the user to input the hourly rate

and the number of hours clocked for the week. For hourly employees, overtime is

paid for hours over 40 at a rate of 1.5 of the base rate. For all employees’ takehome

pay, federal tax of 18% is deducted. A retirement contribution of 10% and a

Social Security tax rate of 6% should also be deducted. Use appropriate constants.

Design an object-oriented solution. Create a second class to test your design.

5. A large Internet merchandise provider determines its shipping charges based on

the number of items purchased. As the number increases, the shipping charges

proportionally decrease. This is done to encourage more purchases. If a single

item is purchased the shipping charge is $2.99. When customers purchase

between 2 and 5 items, they are charged the initial $2.99 for the first item and

then $1.99 per item for the remaining items. For customers who purchase more

than 5 items but less than 15, they are charged the initial $2.99 for the first item,

$1.99 per item for items 2 through 5, and $1.49 per item for the remaining items.

If they purchase 15 or more items, they are charged the initial $2.99 for the first

item, $1.99 per item for items 2 through 5, and $1.49 per item for items 6

through 14 and then just $0.99 per item for the remaining items. Allow the user

to enter the number of items purchased. Display the shipping charges.
6. Write an application that computes the area of a circle, rectangle, and cylinder.

Display a menu showing the three options. Allow users to input which figure

they want to see calculated. Based on the value inputted, prompt for appropriate

dimensions and perform the calculations using the following formulas:


Area of a circle = pi * radius2

Area of a rectangle = length * width

Surface area of a cylinder = 2 * pi * radius * height + 2 * pi * radius2
Write a modularized solution, which includes class methods for inputting data

and performing calculations.

Create an application with four classes. Three of the classes should contain data

and behavior characteristics for circle, rectangle, and cylinder. The fourth class

should allow the user to input a figure type from a menu of options. Prompt for

appropriate values based on the inputted figure type, instantiate an object of the

type entered, and display characteristics about the object.
8. Design a solution that prints the amount of profit an organization receives based

on it sales. The more sales documented, the larger the profit ratio. Allow the user

to input the total sales figure for the organization. Compute the profit based on

the following table. Display the sales and profit formatted with commas, decimals,

and a dollar symbol. Display the profit ratio formatted with a percent

symbol.


0 - $1000: 3%

$1000.01_$5000: 3.5%

$5000.01_$10000: 4%

over $10000: 4.5%

Be sure to design your solution so that all possible situations are accounted for and

tested. Use the decimal data type for your solution. What values did you enter and

test to verify your program’s correctness?
9. Two fuel stops, CanadianFuel and AmericanFuel, are positioned near the U.S.–

Canadian border. At the Canadian station, gas is sold by the liter. On the

American side, it is sold by the gallon. Write an application that allows the user

to input information from both stations and make a decision as to which station

offers the most economical fuel price. Test your application with 1.259 per liter

against 4.50 per gallon. Once the decision is made, display the equivalent prices.


10. Write a program that takes a decimal value between 1 and 10 and displays its

equivalent roman numeral value. Display an error message if the value entered is

outside of the acceptable range. Write a two class solution. The second class

should allow the user to input a test value.




Download 247.83 Kb.

Share with your friends:
  1   2   3




The database is protected by copyright ©ininet.org 2024
send message

    Main page