Programming exercises


Chapter6. Repeating Instructions



Download 247.83 Kb.
Page2/3
Date08.05.2017
Size247.83 Kb.
#17660
1   2   3

Chapter6. Repeating Instructions

PROGRAMMING EXERCISES

1. Write a program that generates 1000 random numbers between 0 and 100000.

Display the number of odd values generated as well as the smallest and the largest

of values. Output should be displayed in a Windows message box.
2. Create an application that contains a loop to be used for input validation.

Valid entries are positive integers less than 100. Test your program with values

both less than and greater than the acceptable range as well as non-numeric

data. When the user is finished inputting data, display the number of valid and

invalid entries entered.
3. Write a program to calculate the average of all scores entered between 0 and

100. Use a sentinel-controlled loop variable to terminate the loop. After

values are entered and the average calculated, test the average to determine

whether an A, B, C, D, or F should be recorded. The scoring rubric is as

follows:

A—90-100; B—80-89; C—70-79; D—60-69; F < 60.

4. Create an application that determines the total due including sales tax and

shipping. Allow the user to input any number of item prices. Sales tax of

7.75% is charged against the total purchases. Shipping charges can be determined

based on the number of items purchased. Use the following chart to determine

the shipping charge. Display an itemized summary containing the total purchase

charge, number of items purchased, sales tax amount, shipping charge, and grand

total.

fewer than 3 items $3.50



3 to 6 items $5.00

7 to 10 items $7.00

11 to 15 items $9.00

more than 15 items $10.00


5. Write a program that allows the user to input any number of hexadecimal

characters. Sum the values and display the sum as a hexadecimal value. Within

the loop, convert each character entered to its decimal equivalent. Treat each

single inputted character as a separate value. Display the original hex value and

the corresponding decimal value. For example, if the user inputs F, 15 would be

displayed as the decimal equivalent. Use a sentinel value to control the loop.

After all values are entered, display the sum of values entered in both hexidecimal

and decimal notation.


6. Write an application that will enable a vendor to see what earnings he can expect

to make based on what percentage he marks up an item. Allow the user to input

the wholesale item price. In a tabular form, show the retail price of the item

marked up at 5%, 6%, 7%, 8%, 9% and 10%.


7. Write a program that produces a multiplication table with 25 rows of computations.

Allow the user to input the first and last base values for the

multiplication table. Display a column in the table beginning with the first

base inputted value. The last column should be the ending base value entered.

The first row should be for 1 times the beginning base, 1 times the (beginning

base value + 1), through 1 times the ending base value. The last row should

be for 25 times the beginning base, 25 times the (beginning base value + 1),

through 25 times the ending base value. Base values can range from 2 through

8. Display an error message if an invalid base is entered. Display an aesthetically

formatted multiplication table. An example of output produced when 2

and 8 are entered appears in Figure 6-22.

8. Prompt the user for the length of three line segments as integers. If the three lines

could form a triangle, print the integers and a message indicating they form a

triangle. Use a state-controlled loop to allow users to enter as many different

combinations as they want.
9. Write an application that calculates a student’s GPA on a 4.0 scale. Grade point

average (GPA) is calculated by dividing the total amount of grade points earned

by the total amount of credit hours attempted. For each hour, an A receives 4

grade points, a B receives 3 grade points, a C receives 2 grade points, and a D

receives 1 grade point.

Allow the user to input any number of courses and associated grades. Display

the number of hours earned and the GPA.

Chapter7. Arrays

PROGRAMMING EXERCISES

1. Write a program that reads data into an array of type int. Valid values are from 0

to 10. Your program should display how many valid values were inputted as well

as the number of invalid entries. Output a list of distinct valid entries and a count

of how many times that entry occurred.

Use the following test data:

1 7 2 4 2 3 8 4 6 4 4 7


2. The Ion Realty Sales Corporation would like to have a listing of their sales over

the past few months. Write a program that accepts any number of monthly sales

amounts. Display the total of the values. Display a report showing each original

value entered and the percentage that value contributes to the total. You may

prompt the user for the number of values to be inputted.
3. Write a temperature application. Your solution should be a two class application

that has a one-dimensional array as a data member. The array stores temperatures

for any given week. Provide constructors for instantiating the class and methods

to return the highest temperature, lowest temperature, average temperature, and

the average temperature excluding the lowest temperature. Provide a method

that accepts as an argument a temperature and returns the number of days the

temperatures were below that value. Override the ToString( ) method to

return a listing of all the temperatures in three column format and the temperature

range for the given week. Write a second class to test your class.
4. Create three arrays of type double. Do a compile-time initialization and place

different values in two of the arrays. Write a program to store the product of the

two arrays in the third array. Produce a display using the MessageBox class

that shows the contents of all three arrays using a single line for an element from

all three arrays. For an added challenge, design your solution so that the two

original arrays have a different number of elements. Use 1 as the multiplier when

you produce the third array.
5. Write a program that allows the user to enter any number of names, last name

first. Using one of the predefined methods of the Array class, order the names

in ascending order. Display the results.
6. Write a two class application that has as a data member an array that can store state

area codes. The class should have a member method that enables users to test an

area code to determine if the number is one of the area codes in the state exchange.

The member method should use one of the predefined methods of the Array

class and return true if the argument to the method is one of the state codes.

Override the ToString( ) method to return the full list of area codes with each

surrounded by parentheses. To test the class, store a list of state codes in a onedimensional

array. Send that array as an argument to the class. Your application

should work with both an ordered list of area codes or an unordered list.

7. Write an application that allows the user to input monthly rainfall amounts for

one year. Calculate and display the average rainfall for the year. Display the

month name along with the rainfall amount and its variance from the mean.


8. Write a program that accepts any number of homework scores ranging in value

from 0 through 10. Prompt the user for a new score if they enter a value outside

of the specified range. Prompt the user for a new value if they enter an

alphabetic character. Store the values in an array. Calculate the average excluding

the lowest and highest scores. Display the average as well as the highest and

lowest scores that were discarded.


9. Write a program that allows any number of values between 0 and 10 to be

entered. When the user stops entering values, display a frequency distribution

bar chart. Use asterisks to show the number of times each value was entered. If a

given number is not entered, no asterisks should appear on that line. Your

application should display error messages if a value outside the acceptable range

is entered or if a non-numeric character is entered.


10. Write a two class solution that includes data members for the name of the

course, current enrollment, and maximum enrollment. Include an instance

method that returns the number of students that can still enroll in the course.

The ToString( ) method should return the name of the course, current

enrollment, and the number of open slots. Design your solution using parallel

arrays. Declare an array of class objects in your implementation class. Test your

application with the following data:



Chapter8. Advanced Colletions

PROGRAMMING EXERCISES

1. Write an application that creates and returns a one-dimensional array containing

all the elements in the two-dimensional array. Store the values in a row major

format. For testing purposes, you may do a compile-time initialization of a 12 x 5

two-dimensional array. Display both the two-dimensional and the one-dimensional

array. Be sure the values in the array are number aligned.
2. Write an application that will let you keep a tally of how well three salesmen are

performing selling five different products. You should use a two-dimensional

array to solve the problem. Allow the user to input any number of sales amounts.

Do a compile-time initialization of the salesperson’s names and product list.

Produce a report by salesman, showing the total sales per product.
3. Revise your solution for problem 2 so that you display the total sales per salesman.

Place the first and last names for the salesmen in an array. Write your solution so

that any number of salesmen and any number of products can be displayed. When

you display your final output, print the salesman’s last name only, sales for each

product, and the final sales for the salesman. After you display the tables of sales,

display the largest sales figure indicating which salesman sold it and which product

was sold.
4. Write a two class application that creates a customer code to be placed on a

mailing label for a magazine. Allow the user to input their full name with the first

name entered first. Prompt them to separate their first and last name with a space.

Ask for their birthdate in the format of mm/dd/yyyy. Ask for the month

(number) they purchased a subscription and ask for their zip code. Your mailing

label should contain the last name, followed by their year of birth, the number of

characters in the full name, the first three characters of the month they purchased

the subscription, and the last two digits of their zip. The code for Bob Clocksom

born 01/22/1993, who purchased his subscription during the 10th month of the

year and lists 32226 as his zip code would be Clocksom9312Oct26.


5. Write a program that allows the user to enter any number of names. Your

prompt can inform the user to input their first name followed by a space and

last name. Order the names in ascending order and display the results with the last

name listed first, followed by a comma and then the first name. If a middle initial

is entered, it should follow the first name. Your solution should also take into

consideration that some users may only enter their last name (one name).


6. Write an application that creates a two-dimensional array. Allow the user to

input the size of the array (number of rows and number of columns). Fill the

array with random numbers between the 0 and 100. Search the array for the

largest value. Display the array values, numbers aligned, and the indexes where

the largest value is stored.
7. Write a program that creates a two-dimensional array with 10 rows and 2

columns. The first column should be filled with 10 random numbers between

0 and 100. The second column should contain the squared value of the element

found in column 1. Using the Show( ) method of the MessageBox class,

display a table.
8. reAay ouyay aay hizway ithway igPay atin?Lay? (Translated: ‘‘Are you a whiz

with Pig Latin?’’) Write a program that converts an English phrase into a pseudo-

Pig Latin phrase (that is Pig Latin that doesn’t follow all the Pig Latin syntax

rules). Use predefined methods of the Array and string classes to do the work.

For simplicity in your conversion, place the first letter as the last character in the

word and prefix the characters ‘‘ay’’ onto the end. For example, the word

‘‘example’’ would become ‘‘xampleeay’’, and ‘‘method’’ would become ‘‘ethodmay.’’

Allow the user to input the English phrase. After converting it, display the

new Pig Latin phrase.
9. Write an application that displays revenue generated for exercise classes at the Tappan

Gym. The gym offers two types of exercise classes, zumba and spinning, six days per

week, four times per day. Zumba is offered at 1, 3, 5, and 7 p.m.; spinning is offered

at 2, 4, 6, and 8 p.m. When attendees sign up, they agree to pay $4.00 per class for

zumba and $5.00 for spinning. Produce a table displaying the number of attendees

per time slot. Display a row and column of totals showing the total number of

attendees by day and also time period. Also include a column showing the revenue

generated each day and the overall revenue per type of exercise. Do a compile-time

initialization of your data structures using data from the following table.

10. Write an application that enables you to randomly record water depths for

5 different locations at 0700 (7 a.m.), 1200 (noon), 1700 (5 p.m.), and 2100

(9 p.m.). The locations are Surf City, Solomons, Hilton Head, Miami, and

Savannah. For ease of input, you may want to code the locations (i.e., Surf

City = 1, Solomons = 2, etc.) and code the time (i.e., 0700 = 1, 1200 = 2, etc.).

If the same location and time are entered more than one time, store the last

value entered into the array. After the data is entered, display the average depth

at each location and the average depth by time period.

Chapter 9. Introduction to Windows Programming

PROGRAMMING EXERCISES

1. Create a Windows application that can be used to input a user’s name. Include an

appropriate label indicator for the name and a textbox for the input entry.

A button labeled OK should retrieve and display the value entered on another

label positioned near the bottom of the form. The font color for all objects should

be yellow. Change the background color of the form to an appropriate one to use

with your yellow text. Change the Font property to a font of your choice.

The size of the font for all objects except the Button should be at least 14 points.

The Button font should be 16 points. Add a title caption of ‘‘Name Retrieval

App’’ to the form. Initially clear the text from the label that will display your final

answer. When the OK button is pressed, retrieve the name and concatenate that

value with a Congratulatory message. For example, you might display, ‘‘Congratulations,

Brenda Lewis, you retrieved the data!’’, if your name was Brenda

Lewis. Align the controls so they are aesthetically pleasing. Be sure to change the

default names of all controls involved in program statements.


2. Create a Windows application that can be used to change the form color. Your

form background color should initially be blue. Provide at least two buttons with

two different color choices. Change the font style and size on the buttons. Align

the buttons so that they are in the center of the form. The buttons should be the

same size. Add event handlers for the buttons so that when the user clicks the

button, the form changes color, and a message box is displayed alerting the user as

to what color the form is. Be sure to name any controls used in program

statements prior to registering your event. Change the default title bar text.

Hint: This exercise may require you to do some research. You may want to review

the code placed in the .Designer.cs file after you set the form’s initial color.


3. Create a Windows application that contains two textboxes (with labels) and one

button. The textboxes should be used to allow the user to input the x- and ycoordinates

to indicate where the form should be positioned. When the user

clicks the button, the window should be moved to that new point. Be sure to

label the textboxes appropriately. Change the form’s background color. Add a

title caption to the form. Include a heading above the textboxes and button.

Enlarge the size of the font. Only allow positive integers to be used for the

coordinates.


Hint: One easy way to do this is to set the location using an instance of the

Point class when the user clicks the button. To do this, you could allow the

user to input values for both x and y into two separate textbox objects. After

being retrieved, they would need to be parsed or converted to their integer

equivalent. Then use the numeric values for x and y to set the location by typing

Location = new Point(x,y);.

4. Create a Trip Calculator Windows application that can be used to determine

miles per gallon for a given trip. Set the Form object properties of Name,

ForeColor, BackColor, Size, Location, Text, and AcceptButton. The

form should contain labels and textboxes to allow the user to input trip destination,

miles traveled, and gallons of gas consumed. Two buttons should be placed

on the form. Name all objects used in program statements. When the user clicks

the button that performs the calculations, display in a label the miles per gallon

for that trip. The second button should be used to reset or clear textbox entries.


5. Create a Windows application that contains two textboxes and two buttons. The

textboxes should be used to allow the user to input two positive numeric values.

The buttons should be labeled Add and Multiply. Create event-handler methods

that retrieve the values, perform the calculations, and display the result of the

calculations on a label. The result label should initially be set to be invisible with a

font color of yellow. If invalid data is entered, change the font color to red on the

result label and display a message saying ‘‘Value must be numeric and > 0.’’
When the final answer is displayed, the font color should be yellow. Additional

labels will be needed for the textboxes captions. Do not allow non-numeric

characters to be entered. Invoke the TryParse( ) method to retrieve the

values. All controls involved in program statements should be named. Right

justify values in the textbox.
6. Create a Windows application that contains a textbox for a person’s name. Plan

that the user may enter only first and last name, or they may enter first, middle,

and last names. Include labels to store first, middle, and last names. A button

should be included. When the button is clicked, retrieve the full name, separate it

into first, middle (if present), and last names and then display the labeled name

values.
7. Create a Windows application that contains two textboxes and three buttons. One

of the textboxes and one of the buttons are initially invisible. The first textbox

should be used to input a password. The textbox should be masked to some

character of your choosing so that the characters entered by the user are not seen

on the screen. When the user clicks the first button, the second textbox and button

should be displayed with a prompt asking the user to reenter his or her password.

Set the focus to the second password textbox. Now, when the user clicks the

second button, have the application compare the values entered to make sure they

are the same. Display an appropriate message indicating whether they are the same.

Once the check is made, display a third button that resets the form.
8. Create a Windows application that can be used to determine distance traveled

given speed and time. Recall that distance = speed * time. Provide textboxes for

time and speed and a button to calculate to the distance. Be sure only numeric

data is able to be entered into the textboxes. Experiment with the controls’

properties. Spend time with your design so that your GUI is very user friendly

and looks nice.

9. Create a Windows application that functions like a banking account register.

Separate the business logic from the presentation layer. The graphical user

interface should allow the user to input the account name, number, and balance.

Provide textbox objects for withdrawals and deposits. A button should be

available for clicking to process withdrawal and deposit transactions showing

the new balance.


10. Create the higher/lower guessing game using a graphical user interface. Allow

users to keep guessing until they guess the number. Keep a count of the number

of guesses. Choose two colors for your game: one should be used to indicate

that the value the users guessed is higher than the target; the other is used to

indicate that the value the users guessed is lower than the target. With each new

guess, show the guess count and change the form color based on whether the

guess is higher than the target or lower. When they hit the target, display a

message on a label indicating the number of guesses it took. Several approaches

can be used to seed the target: one is to generate a random number by

constructing an object of the Random class. For example, the following

stores a random whole number between 0 and 100 in target:
Random r = new Random();

int target = r.Next(0,101);



Chapter10. Programming based on events

PROGRAMMING EXERCISES

1. Create a graphical user interface that allows the users to enter personal

information such as their names, e-mail addresses, and phone numbers.

Include a menu that provides a minimum of four features. The first displays

the information entered by the user in a message box. The second clears the

entries so that new values can be entered, the third menu option displays

information about the application such as who developed it and what version

it is. Another menu option closes the application. Be creative and be sure to

produce an aesthetically pleasing design using options from the Format menu

if you are using Visual Studio.
2. Create a Windows application that can be used as a sign-up sheet for ski

equipment for the Flyers Sports Club. The club has ski equipment that it

makes available to members at a minimal charge. In an attempt to determine

what type of equipment members might need for an upcoming trip, they

have asked you to design and implement an equipment-needs form. Include

CheckBox objects that allow users to select the type of gear they will need

to purchase for the trip. Include selections of snow gloves, skis, goggles,

earmuffs, and other items you feel are appropriate. Include at least one picture

image on your application. After all selections are made, display a message

indicating what items have been selected. You will probably want to include

menu options to display and clear the order for the next user. Also include an

option that enables the user to exit the application.


3. Create a graphical user interface that can be used by a community group to

enable youths to sign up for different sporting events. Include radio buttons

with five different sport names. Only one of these should be selectable.

Program your event-handler method so that a message is displayed with each

selection of a different sport. For example, if one of the sports is skiing, the

message might say, ‘‘Bring warm clothes!’’ Also include a PictureBox

object on the form to display pictures of the sporting event. When the

particular sport is selected, make the PictureBox visible. You can find free

graphics on the Internet to use in your application. Hint: One way to

associate a file to the PictureBox control is to Import an image from the

Image property.
4. Create a Message Displayer that has one ComboBox object with a list of at

least four of your favorite sayings. In your design, include the capability of

letting users enter their own sayings. When a selection is made or a new entry

is typed, display the selection on a Label object on your form. Add a

menu to the application that includes at least the menu options of Format and

Help. Under the Format selection, include options of Font and Color. Wire

the Font and Color options to the Windows predefined Font and Color

dialog boxes so that when their values are changed, the text in the Label

object displaying the saying is changed.
5. Create an order form that allows bags to be purchased. There are six

different types: full decorative, beaded, pirate design, fringed, leather, and

plain. Create a ListBox object for the different styles. Include a

ComboBox for quantity. Quantities up to 10 should be provided. After

the user makes a selection, display a message indicating which selection

was made. Include an option to clear selections. Provide appropriate

error messages when selections are not made.
6. Add to the application in Exercise 5 by including a control that allows the user

to determine the type of shipping they desire. Include a set of radio buttons that

contain shipping options of overnight, three day, and standard. Add the price

for each bag to the listbox selection as follows: full decorative—$50.00;

beaded—$45.00; pirate design—$40.00; fringed—$25.00; leather—$80.00;

and plain—$20.00. Display the items sorted. Using methods of the string class,

retrieve and use the price from the listbox. The shipping charges are based on

the total purchase. The following percentages are used: overnight—10%; three

day—7%; and standard—5%. Display in a message box the shipping charge

along with the selection, quantity, and total cost.

7. The computer club is selling T-shirts. Create an attractive user interface that

allows users to select sizes (S, M, L, and XL) and quantity. Which controls

would be most appropriate? Remember, the fewer keystrokes required of

the user the better. Display the selections made by the user with the Process

menu option. Include an option to exit the application.
8. Add to your solution in Exercise 7 by including two more sizes, XSmall and

XXLarge. Add statements that process the order by calculating the total cost.

Each shirt is $16 except the XSmall and XXLarge; their specialty prices are

$20.00 each. Allow users to purchase different sizes on the same order. Include

an ‘‘Add to Cart’’ option from the Process menu that enables the user to add

multiple selections to the order. Display the total cost for each selection and the

final cost for the order. Include a Help menu option that displays instructions.
9. Create aWindows application for purchasing floor covering. Allow the length

and width (feet and inches) of a room to be entered. Be sure to include program

statements that will keep your program from crashing if they enter nonnumeric

characters for the room dimensions. Have a control that displays

different types along with the prices of floor covering. Using the tab control,

provide selections such as Hardwood, Carpet, and Laminate. On each tab allow

the user to select a type and price. Include, for example, options like Oak,

Maple, Walnut, and Cherry Hardwood floors with prices such as $34.95 per

square yard for Oak and $41.95 per square yard for Cherry. After the users enter

their room dimensions and selects the floor covering and price, display the total

cost to cover the room. Include an option to clear selections. Place both the

type of floor covering and the price in a single control, such as a ComboBox

and use string manipulation techniques to strip the price out of the string.

10. Create an application for a Pizza Delivery Company. You might check out

the graphical user interface shown in Figure 10-21. Your solution does not

need to resemble this one; however, it might give you some ideas. You must

provide a place for the user to enter their contact information (i.e., address,

phone number, and e-mail) and some of the contact information should be

displayed when an order is placed.

Your application should have a picture logo and company name. Provide

selections such as Small,Medium, and Large for size. Allow users to select from

at least a dozen items to place on their pizza. You might consider offering

different types of sauce (i.e., tomato, pesto, or no sauce), different types of

crust, different specialty types of pizza (Supreme, Veggie, etc.). BE

CREATIVE! You can also sell wings, bread sticks, chicken strips, or

something else of your choosing. Consider offering beverages.

You must display the price for the order and allow the user to change their

mind while they are ordering and reset the order form. Experiment,

explore, change properties, and then review the .Designer.cs file.



Download 247.83 Kb.

Share with your friends:
1   2   3




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

    Main page