Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Programming Fundamentals: Important Questions and Answers, Exams of Programming Languages

A variety of programming fundamentals topics, including input validation, array manipulation, function implementation, and problem-solving exercises. It presents several programming challenges and their solutions, covering areas such as chips and salsa sales tracking, positive vs. Negative number counting, temperature variation analysis, magic square creation, price calculation, exam grading, lottery simulation, vector modification, baseball team data analysis, name searching, gas price tracking, markup calculation, sales division comparison, falling distance calculation, coin tossing, present value computation, population modeling, heating energy and time estimation, prime number listing, multiplication table generation, distance traveled, population growth prediction, queue waiting time estimation, random number guessing games, student line-up management, array element addressing, test score processing, function parameter manipulation, and more.

Typology: Exams

2020/2021

Uploaded on 10/16/2022

tree8976
tree8976 🇮🇳

3 documents

1 / 37

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Largest and Second Largest Even Numbers
Write a program to input 15 integers into an array. The program should then
display
the largest and second largest even numbers in the array.
Rainfall Statistics
Write a program that lets the user enter the total rainfall for each of 12 months into
an array of doubles. The program should calculate and display the total rainfall for
the year, the average monthly rainfall, and the months with the highest and lowest
amounts.
Input Validation: Do not accept negative numbers for monthly rainfall figures.
Programming foundamentals important questions answers
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25

Partial preview of the text

Download Programming Fundamentals: Important Questions and Answers and more Exams Programming Languages in PDF only on Docsity!

Largest and Second Largest Even Numbers

Write a program to input 15 integers into an array. The program should then

display

the largest and second largest even numbers in the array.

Rainfall Statistics

Write a program that lets the user enter the total rainfall for each of 12 months into

an array of doubles. The program should calculate and display the total rainfall for

the year, the average monthly rainfall, and the months with the highest and lowest

amounts.

Input Validation: Do not accept negative numbers for monthly rainfall figures.

Chips and Salsa Write a program that lets a maker of chips and salsa keep track of sales for five differ- ent types of salsa: mild, medium, sweet, hot, and zesty. The program should use two parallel 5-element arrays: an array of strings that holds the five salsa names, and an array of integers that holds the number of jars sold during the past month for each salsa type. The salsa names should be stored using an initialization list at the time the name array is created. The program should prompt the user to enter the number of jars sold for each type. Once this sales data has been entered, the program should produce a report that displays sales for each salsa type, total sales, and the names of the highest selling and lowest selling products. Input Validation: Do not accept negative values for number of jars sold.

Temperature Variation The weather service center of a certain city records the highest temperature, lowest temperature, and humidity of each day. Write a program that maintains three arrays and initializes the highest temperature, lowest temperature, and humidity in the three arrays, for each day of the first 10 days of a month. The program should then create a weather report that includes the following information:

  • Highest temperature and lowest temperature.
  • Diurnal variation in each day.
  • Humidity of each day and whether it is greater or less than the average humidity. Finally, in an end note, it should display the maximum temperature, minimum tem- perature, and overall variation in temperature in the duration. Union of Two Sets A set is a collection of similar elements. A union of two sets A and B is a set of elements in which each element belongs to set A, set B, or both. It is represented as A < B. For example, if A 5 {1, 3, 5, 7} and B 5 {3, 6, 7, 9, 11}, then A < B 5 {1, 3, 5, 6, 7, 9, 11}. Write a program that represents set A, set B, and set A < B as three arrays. The maxi- mum size of the arrays representing sets A and B should be 10. The program should ask the user to input the sizes of sets A and B and then the elements of sets A and B. It should then display A < B. Input Validation: Do not accept values less than 1 or more than 10 as sizes of sets A and B.

Lo Shu Magic Square The Lo Shu Magic Square is a grid with 3 rows and 3 columns shown in Figure 7-19. The Lo Shu Magic Square has the following properties:

  • The grid contains the numbers 1 through 9 exactly.
  • The sum of each row, each column, and each diagonal all add up to the same number. This is shown in Figure 7-20. In a program, you can simulate a magic square using a two-dimensional array. Write a function that accepts a two-dimensional array as an argument, and determines whether the array is a Lo Shu Magic Square. Test the function in a program. Price Calculation Write a program that uses the following arrays:

plu: an array of price lookup codes (PLU) for products at a grocery store

  • price: an array of gross prices of products
  • vat: an array of the Value Added Tax (VAT) rate for each product The program should relate the data in each array through the subscripts. The nth

Your program should store the correct answers shown above in an array. It should ask the user to enter the student’s answers for each of the 20 questions, and the answers should be stored in another array. After the student’s answers have been entered, the program should display a message indicating whether the student passed or failed the exam. (A student must correctly answer 15 of the 20 questions to pass the exam.) It should then display the total number of correctly answered questions, the total number of incorrectly answered questions, and a list showing the question numbers of the incorrectly answered questions. Input Validation: Only accept the letters A, B, C, or D as answers. file is also in the Chapter 07 source code folder.) The program should determine the number of questions that the student missed, then display the following:

  • A list of the questions missed by the student, showing the correct answer and the incorrect answer provided by the student for each missed question
  • The total number of questions missed
  • The percentage of questions answered correctly. This can be calculated as Correctly Answered Questions ÷ Total Number of Questions
  • If the percentage of correctly answered questions is 70 percent or greater, the pro- gram should indicate that the student passed the exam. Otherwise, it should indicate that the student failed the exam.

A Graded Social Network The goal of a social network is to connect people. In an early attempt, people were asked to grade each other on a scale of 1 to 10. An algorithm would decide who was friend with whom. The idea was that anyone whom someone graded a 5 or more would be that person’s friend. In a certain experiment with three people, this was the input:

Person Friend score of

person 1

Friend score of

person 2

Friend score of

person 3

John 10 4 7 Mike 3 2 4 Mary 10 10 10 It was expected that people would be each other’s friends, but it turned out that this was not the case. In this case, for example, Mike indicated that he had no friends at all. Because of this and various other obvious reasons, this social network failed. However, it may still be interesting to write a program to repeat the experiment. The program should use a string array of length 5 to hold the names of the people in the network, and five int arrays to hold their friend scores. The program should let the user enter five names and five scores per person. It should then display the number of friends per person and their names.

the following shows the lottery array and the user array with sample numbers stored in each. There are two matching digits (elements 2 and 4). Lottery array: 7 4 9 1 3 User array: 4 2 9 7 3 The program should display the random numbers stored in the lottery array and the number of matching digits. If all of the digits match, display a message proclaiming the user as a grand prize winner. vector Modification Modify the National Commerce Bank case study presented in Program 7-23 so pin1, pin2, and pin3 are vectors instead of arrays. You must also modify the testPIN func- tion to accept a vector instead of an array.

World Series Champions If you have downloaded this book’s source code, you will find the following files in this chapter’s folder:

  • Teams.txt—This file contains a list of several Major League baseball teams in alpha- betical order. Each team listed in the file has won the World Series at least once.
  • WorldSeriesWinners.txt—This file contains a chronological list of the World Series’ winning teams from 1903 to 2012. (The first line in the file is the name of the team that won in 1903, and the last line is the name of the team that won in 2012. Note the World Series was not played in 1904 or 1994.) Write a program that displays the contents of the Teams.txt file on the screen and prompts the user to enter the name of one of the teams. The program should then dis- play the number of times that team has won the World Series in the time period from 1903 to 2012.

TIP: Read the contents of the WorldSeriesWinners.txt file into an array or vector.

When the user enters the name of a team, the program should step through the array or vector counting the number of times the selected team appears.

loop that does the following:

  • Displays the contents of the board array.
  • Allows player 1 to select a location on the board for an X. The program should ask the user to enter the row and column numbers.
  • Allows player 2 to select a location on the board for an O. The program should ask the user to enter the row and column numbers.
  • Determines whether a player has won, or a tie has occurred. If a player has won, the program should declare that player the winner and end. If a tie has occurred, the program should display an appropriate message and end. Player 1 wins when there are three Xs in a row on the game board. The Xs can appear in a row, in a column, or diagonally across the board. Player 2 wins when there are three Os in a row on the game board. The Os can appear in a row, in a column, or diagonally across the board. A tie occurs when all of the locations on the board are full, but there is no winner. Hot or Cold Hints Write a program in which the user must guess a random number in the range from 1 to 100. The user must keep on guessing until the number is correctly guessed, but encouragements are printed to make sure that the user keeps on playing. In the student sample programs for this book, you will find a text file named 19_hints.txt. The file contains eight responses, such as “That is very cold. Try again.”, “You are getting closer.”, “I can feel the heat.”, and so forth. The program should read the responses from the file into an array or vector. It should prompt the user to enter a value. If the value is correct, the program should end, but if the guess is not correct, it should be compared to the previous attempt. If this attempt is worse than the previous guess, one of the first four responses should be displayed. Otherwise, display one of the last four responses. For the first guess, the first four responses should be used when the difference between the guess and the correct answer is larger than 20. Contents of 19_hints.txt: Incorrect and very cold. You are not getting closer. Oh my! You are far away and getting cold. It's chilly in here. No number in the neighborhood. It seems like winter is settling in. The secret is well hidden. Not good yet, but you are getting closer and warmer. Almost there, I can already feel the heat. You are reaching the goal. It already feels comfy and warm. Better than ever. The temperature is increasing.

1994 Gas Prices In the student sample programs for this book, you will find a text file named 1994_ Weekly_Gas_Averages.txt. The file contains the average gas price for each week in the year 1994 (There are 52 lines in the file. Line 1 contains the average price for week 1, line 2 contains the average price for week 2, and so forth.) Write a program that reads the gas prices from the file into an array or a vector. The program should do the following:

  • Display the lowest average price of the year, along with the week number for that price, and the name of the month in which it occurred.  Display the highest average price of the year, along with the week number for that price, and the name of the month in which it occurred.  Display the average gas price for each month. (To get the average price for a given month, calculate the average of the average weekly prices for that month.) 2D Array Operations Write a program that creates a two-dimensional array initialized with test data. Use any data type you wish. The program should have the following functions:
  • getTotal—This function should accept a two-dimensional array as its argument and return the total of all the values in the array.
  • getAverage—This function should accept a two-dimensional array as its argument and return the average of all the values in the array.
  • getRowTotal—This function should accept a two-dimensional array as its first argument and an integer as its second argument. The second argument should be

Markup Write a program that asks the user to enter an item’s wholesale cost and its markup percentage. It should then display the item’s retail price. For example:  If an items wholesale cost is 5.00 and and its markup percentage is 100 percent, then items retail price is 10.0.  If an items wholesale cost is 5.00 and and its markup percentage is 50 percent, then items retail price is 7.50. The program should have a function named calculateRetail that receives the wholesale cost and the markup percentage as arguments and returns the retail price of the item. Input Validation: Do not accept negative values for either the wholesale cost of the item or the markup percentage. Rectangle Area—Complete the Program If you have downloaded this book’s source code, you will find a partially written pro- gram named AreaRectangle.cpp in the Chapter 06 folder. Your job is to complete the program. When it is complete, the program will ask the user to enter the width and length of a rectangle, then display the rectangle’s area. The program calls the following functions, which have not been written:

  • getLength—This function should ask the user to enter the rectangle’s length then return that value as a double.
  • getWidth—This function should ask the user to enter the rectangle’s width then return that value as a double.
  • getArea—This function should accept the rectangle’s length and width as argu- ments and return the rectangle’s area. The area is calculated by multiplying the length by the width.
  • displayData—This function should accept the rectangle’s length, width, and area as arguments and display them in an appropriate message on the screen.

Winning Division Write a program that determines which of a company’s four divisions (Northeast, Southeast, Northwest, and Southwest) had the greatest sales for a quarter. It should include the following two functions, which are called by main:

  • double getSales() is passed the name of a division. It asks the user for a division’s quarterly sales figure, validates the input, then returns it. It should be called once for each division.
  • void findHighest() is passed the four sales totals. It determines which is the larg- est and prints the name of the high-grossing division, along with its sales figure. Input Validation: Do not accept dollar amounts less than $0.00.

Coin Toss Write a function named coinToss that simulates the tossing of a coin. When you call the function, it should generate a random number in the range of 1 through 2. If the random number is 1, the function should display “heads.” If the random number is 2, the function should display “tails.” Demonstrate the function in a program that asks the user how many times the coin should be tossed, then simulates the tossing of the coin that number of times. Present Value Suppose you want to deposit a certain amount of money into a savings account and then leave it alone to draw interest for the next 10 years. At the end of 10 years, you would like to have $10,000 in the account. How much do you need to deposit today to make that happen? You can use the following formula, which is known as the present value formula, to find out: P=

F

( 1 + r ) 2

The terms in the formula are as follows:

  • P is the present value, or the amount that you need to deposit today.
  • F is the future value that you want in the account. (In this case, F is $10,000.)
  • r is the annual interest rate.
  • n is the number of years that you plan to let the money sit in the account.

Write a program that has a function named presentValue that performs this calcula- tion. The function should accept the future value, annual interest rate, and number of years as arguments. It should return the present value, which is the amount that you need to deposit today. Demonstrate the function in a program that lets the user experi- ment with different values for the formula’s terms. Future Value Suppose you have a certain amount of money in a savings account that earns compound monthly interest, and you want to calculate the amount that you will have after a spe- cific number of months. The formula, which is known as the future value formula, is F= P X (1+i)^2 The terms in the formula are as follows:

  • F is the future value of the account after the specified time period.
  • P is the present value of the account.
  • i is the monthly interest rate.
  • t is the number of months. Write a program that prompts the user to enter the account’s present value, monthly interest rate, and the number of months that the money will be left in the account. The program should pass these values to a function named futureValue that returns the future value of the account, after the specified number of months. The program should display the account’s future value. Calorie Calculator Write a function that calculates the number of “bad” calories in a recipe. In this assign- ment, calories are considered bad when coming from fat or sugar. It should use the following functions:
  • void getWeight() should ask the user for a weight in pounds, store it in a refer- ence parameter variable, and validate it. The function should be called for both the sugar and fat weights.
  • double calculateCaloriesFat(double weight) accepts a weight as argument and returns the corresponding amount of calories by multiplying the weight with 4100.
  • double calculateCaloriesSugar(double weight) accepts a weight as argument and returns the corresponding amount of calories by multiplying the weight with 936.
  • double calculateBadCalories() must use the aforementioned functions to let the user input weights for fat and sugar and return the total of bad calories.