Answer:
See explaination
Explanation:
format RAT
Number=input('Enter the no. of resistors:');
R=ParallelR(Number)
function Req=ParallelR(N)
R=0;
for i=1:N
r=input('Enter Resistor Value:');
R=R+1/r;
end
Req=(1/R);
end
Open IDLE. Create a new script file (File-->New File, Ctrl n on Windows, Cmd n on macOS). On the first line, place your name in a comment. Create a program that does the following: Requests an integer number from the user This number will determine the number of rows that will be displayed Print out a header row Displays the current row number, that number multiplied by ten, then multiplied by 100, then multiplied by 1000, in tabular format Repeat this until the required number of rows have been displayed This program must account for the user having stated zero (0) rows should be displayed Your output should resemble the following: Python Output 5
Answer:
program:
#your name
print("{:10} {:10} {:10}".format("Number","Square","Cube"))
print("{:<10} {:<10} {:<10}".format(0,0,0))
print("{:<10} {:<10} {:<10}".format(1,1,1))
print("{:<10} {:<10} {:<10}".format(2,2**2,2**3))
print("{:<10} {:<10} {:<10}".format(3,3**2,3**3))
print("{:<10} {:<10} {:<10}".format(4,4**2,4**3))
print("{:<10} {:<10} {:<10}".format(5,5**2,5**3))
print("{:<10} {:<10} {:<10}".format(6,6**2,6**3))
print("{:<10} {:<10} {:<10}".format(7,7**2,7**3))
print("{:<10} {:<10} {:<10}".format(8,8**2,8**3))
print("{:<10} {:<10} {:<10}".format(9,9**2,9**3))
print("{:<10} {:<10} {:<10}".format(10,10**2,10**3))
output:
Number Square Cube
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
Consider a set of mobile computing clients in a certain town who each
need to be connected to one of several possible base stations. We’ll
suppose there are n clients, with the position of each client specified
by its (x, y) coordinates in the plane. There are also k base stations; the
position of each of these is specified by (x, y) coordinates as well.
For each client, we wish to connect it to exactly one of the base
stations. Our choice of connections is constrained in the following ways.
There is a range parameter r—a client can only be connected to a base
station that is within distance r. There is also a load parameter L—no
more than L clients can be connected to any single base station.
Your goal is to design a polynomial-time algorithm for the following
problem. Given the positions of a set of clients and a set of base stations,
as well as the range and load parameters, decide whether every client can
be connected simultaneously to a base station, subject to the range and
load conditions in the previous paragraph
Answer: answer given in the explanation
Explanation:
We have n clients and k-base stations, say each client has to be connected to a base station that is located at a distance say 'r'. now the base stations doesn't have allocation for more than L clients.
To begin, let us produce a network which consists of edges and vertex
Network (N) = (V,E)
where V = [S, cl-l, - - - - cl-n, bs-l - - - - - - bs-k, t]
given that cl-l, - - - - - cl-n represents nodes for the clients
also we have that bs-l, - - - - - bs-k represents the nodes for base station
Also
E = [ (s, cl-i), (cl-i,bs-j), (bs-j,t)]
(s, cl-i) = have capacity for all cl-i (clients)
(cl-i,bs-j) = have capacity for all cl-i clients & bs-j (stations)
⇒ using Fond Fulkorson algorithm we find the max flow in N
⇒ connecting cl-i clients to bs-j stations
like (cl-i, bs-j) = 1
if f(cl-i, bs-j) = 0
⇒ say any connection were to produce a valid flow, then
if cl-i (clients) connected f(s,cl-i) = 1 (o otherwise)
if cl-i (clients) connected to bs-j(stations) f(cl-i,bs-j) = 1 (o otherwise)
f(bs-j,t) = no of clients (cl-i) connected to bs-j
⇒ on each node, the max flow value (f) is longer than the no of clients that can be connected.
⇒ create the connection between the client and base station i.e. cl-l to base bs-j iff f(cl-i, bs-j) = 1
⇒ when considering the capacity, we see that any client cannot directly connect to the base stations, and also the base stations cannot handle more than L clients, that is because the load allocated to the base statsion is L.
from this, we say f is the max no of clients (cl-i) that can be connected if we find the max flow, we can thus connect the client to the base stations easily.
cheers i hope this helps
Write a function that takes an integer, val, as an argument. The function asks the user to enter a number. If the number is greater than val, the function displays Too high. and returns 1; if the number is less than val, the function displays Too low. and returns –1; if the number equals val, the function displays Got it! and returns 0. Call the function repeatedly until the user enters the right number.
Answer:
import java.util.*;
public class num2 {
public static void main(String[] args) {
//Set the Value of the argument
int val = 5;
//Call the method
int returnedNum = testInteger(val);
//Use a While to continously call the method as long as the returned value is not 0
while(returnedNum != 0){
int rt = testInteger(val);
//Break out of loop when the user enters correct value and the return is 0
if(rt == 0){
break;
}
}
}
//The Method definition
public static int testInteger(int val){
//Prompt and receive user input
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int userNum = in.nextInt();
//Check different values using if and else statements
if(userNum > val){
System.out.println("Too High");
return 1;
}
else if(userNum < val){
System.out.println("Too Low");
return -1;
}
else{
System.out.println("Got it");
return 0;
}
}
}
Explanation:
This is solved with Java Programing Language
Pay close attention to the comments provided in the code
The logic is using a while loop to countinually prompt the user to enter a new number as long as the number entered by the user is not equal to the value of the argument already set to 5.
Answer:
def high_low(val):
number = int(input("Enter a number: "))
if number > val:
print("Too high")
return 1
elif number < val:
print("Too low")
return -1
elif number == val:
print("Got it!")
return 0
val = 7
while True:
if high_low(val) == 0:
break
Explanation:
The code is in Python.
Create a function called high_low that takes one parameter, var
Ask the user for a number. Check the number. If the number is greater than 1, smaller than 1 or equal to 1. Depending on the number, print the required output and return the value.
Set the value to a number. Create a while loop iterates until the user enters the correct number, when the return value of the function is equal to 0, that means the user entered the correct number. Otherwise, it keeps asking the number and prints the appropriate message.
Write a function DrivingCost with parameters drivenMiles, milesPerGallon, and dollarsPerGallon, that returns the dollar cost to drive those miles. All items are of type float. Ex: If the function is called with 50 20.0 3.1599, the function returns 7.89975. Define that function in a program whose inputs are the car's miles/gallon and the gas dollars/gallon (both floats). Output the gas cost for 10 miles, 50 miles, and 400 miles, by calling your DrivingCost function three times. Ex: If the input is 20.0 3.1599, the output is: 1.57995 7.89975 63.198 Note: Small expression differences can yield small floating-point output differences due to computer rounding. Ex: (a b)/3.0 is the same as a/3.0 b/3.0 but output may differ slightly. Because our system tests programs by comparing output, please obey the following when writing your expression for this problem. In the DrivingCost function, use the variables in the following order to calculate the cost: drivenMiles, milesPerGallon, dollarsPerGallon.
Answer:
See explaination
Explanation:
Function DrivingCost(float drivenMiles, float milesPerGallon, float dollarsPerGallon) returns float cost
float dollarsPerMile
//calculating dollars per mile
dollarsPerMile=dollarsPerGallon/milesPerGallon
//calculating cost
cost=dollarsPerMile*drivenMiles
Function Main() returns nothing
//declaring variables
float miles_per_gallon
float dollars_per_gallon
//reading input values
miles_per_gallon = Get next input
dollars_per_gallon = Get next input
//displaying cost for 10 miles
Put DrivingCost(10,miles_per_gallon,dollars_per_gallon) to output
//printing a blank space
Put " " to output
//displaying cost for 50 miles
Put DrivingCost(50,miles_per_gallon,dollars_per_gallon) to output
Put " " to output
//displaying cost for 400 miles
Put DrivingCost(400,miles_per_gallon,dollars_per_gallon) to output
List 3 specific uses for an Excel spreadsheet in the field you are going into. Give specific examples of how you could or have used Excel in the field. Choose examples that you are familiar with, remembering that personal stories always makes a post more interesting
Answer:
The answer to this question can be defined as below:
Explanation:
The three uses of the spreadsheet can be described as follows:
In Business:
All organizations use Excel, which uses daily by Microsoft Excel, as a key feature of the Microsoft Office company Desktop Suite. Spreadsheets preparation manuals contain worksheets for documents and tablets.In Auditing:
It is a function, that be can provide you with several methods for inspecting by constructing 'short cuts' obstacles. Multiple functions have been helpful, and that you have reduced returns with the time it takes for something to be hung up.In nursing:
All related to figures should be available in a list. Health staff may very well use them to calculate their patients, profits and costs. You should keep a list of clients and medication. They may have to keep hospital-based, clients are at the healing facility on weekends, subtle features of hours employed by medical staff and various items.Write a program that asks the user to enter two dates (in YYYY-MM-DD format), and then prints which date is earlier. Your program should print an error message if the user enters an invalid date (like 2019-15-99).
Answer:
import java.util.*;
public class Dates {
public static void main(String[] args) {
String January,February, March, April, May, June, July,
August, September,October, November, December, month;
January = February = March = April = May = June = July =
August = September = October = November = December = month = null;
Scanner myScanner = new Scanner(System.in);
System.out.print("Enter date in the format mm/dd/yyyy: ");
String input = myScanner.next();
String months = input.substring(0,1);
int monthInt = Integer.parseInt(months);
if (monthInt == 01){
month = January;
}
else if (monthInt == 02){
month = February;
}
else if (monthInt == 03){
month = March;
}
else if (monthInt == 04){
month = April;
}
else if (monthInt == 05){
month = May;
}
else if (monthInt == 06){
month = June;
Checkpoint 7.61 Write the prototype for a function named showSeatingChart that will accept the following two-dimensional array as an argument. const int ROWS = 20; const int COLS = 40; string seatingChart[ROWS][COLS]; Note: The two-dimensional array argument must be a const string array. You must include a second integer argument (scalar, not an array).
Answer:
void showSeatingChart(const string [][COLS], int);
Explanation:
void showSeatingChart(const string [][COLS], int);
The above function showSeatingChart() will display the 2D array of seating chart.
The return type of this function is void because it does not need to retun anything.
The parameter of the function is a 2D array which is seatingChart[ROWS][COLS].
The type of this 2D array is string that means it is a 2D array of string. It will contain string elements.
To declare a prototype of a function, there should be a semi-colon (;) at the end of declaration.
The definition of the function should be given outside main() function and declaration of the function should be above the main() function or at the beginning of the program with declaration of constant variables.
Let us assume that processor testing is done by filling the PC,registers, and data and instruction memories with some values(you can choose which values), letting a single instruction execute, then reading the PC, memories, and registers. These values are then examined to determine if a particular fault is present. Can you design a test (values for PC, memories, and registers) that would determine if there is a stuck-at-0 fault on this signal?
Answer:
See explaination for the details.
Explanation:
PC can be any valid value that is divisible by 4. In that case, lets pick 20000.
We can pick any instruction dat writes to a register. Lets pick addi.
The destination register number must be odd so that it has good value of 1. The opposite of the stock-add-value we want to test for. Lets go ahead and pick register 9.
Make register 9 have a value of 20 and register 9 jas a value of 25 prior to the add instruction.
addi. $9, zero, 22
When the value read from register 8 after the add instruction is 22, we know that we have found the fault.
Final answer:
A test to determine a stuck-at-0 fault in a CPU involves preloading specific values into the PC, registers, and instruction memory, executing an instruction, and checking if the expected values are reflected post-execution. A failure to update a signal from 0 suggests a stuck-at-0 fault. This test is part of the broader endeavor of programming and diagnostics within computer engineering.
Explanation:
To design a test that determines if there is a stuck-at-0 fault on a signal within a Central Processing Unit (CPU), one could start by setting the Program Counter (PC), registers, and memory to specific non-zero values, execute an instruction that would change the state of the signal in question, and then verify if the expected changes occur.
For instance, if testing a register expected to be set to a value of 1 by an instruction, you might initialize the instruction memory with an instruction like 'SET REGISTER' to the non-zero value, and the register itself with 0. Once the instruction executes, if the register does not reflect the value that was written to it, this suggests a possible stuck-at-0 fault. This kind of fault means that no matter what value is intended for that signal, it always reads as 0, which indicates a malfunctioning component inside the CPU.
Write a program to simulate the design process of the course. First, create a struct for the course which consists of following members: course number (int type, e.g. 1200), course start date (int type, e.g. 20200107), course hours (int type, how many hours per week) and lecturer ID (int type). Second, create a struct for lecturer, which has following members: lecturer ID (int type), lecturer office hours (int type, how many office hours per week) and course teaching(array[int] type). Third, create a struct for student, which as following members: student ID (int type), course taken (array[int type). Then answer following questions 1, 2 and 3 based on these structures: 1. The department decide to offer three courses in a semester: 1000, 1100 and 1200. Please create these courses with structs you defined above. Their information is given below: Course number Course start date Course hours Lecturer ID 1000 20200107 2 100 1100 20200113 4 200 1200 20200203 4 100 2. Department also assigned two lecturers to teach these courses. Please create documents for lecturers and print out the information for both lectures on the screen. Note: Each lecturer will be assigned 2 hours office hours for each course he/she teaches. 3. A student, whose ID is 2000, are considering taking 2 courses among above courses. Please print out how many course hours he/she needs to take each week. Note, simply add up the course hours from table in question 1 will not be considered as correct answer. Your program should first ask this student to input the course number he/she registered, then print the total course hours. 4. Conduct an experiment with Arduino using an Angle Rotary Sensor and a Servo (connect sensors to Arduino appropriately). The Angle Rotary Sensor must control the movement of the Servo. In other words, when you change the angle of the Rotary Angle Sensor (0 to 300 degrees), the Servo will rotate the short white blade accordingly after mapping the Angle Rotary Sensor value (0 to 300 to a Servo position (0 to 180). Also, display the angle degree of the Angle Rotary Sensor and the position of the Servo on the Serial Monitor window. Use Serial.print function to print on the Serial Monitor window, which can be open by clicking on the icon- on the upper right area of the Arduino window. Also, you need to use the following statement in the setup function: Serial.begin(9600);
Answer:
#include <iostream>
using namespace std;
struct Course
{
int courseNumber;
int courseStartDate;
int courseHours;
int lecturerId;
};
struct Lecturer
{
int lecturerId;
int officeHours;
Course courseTeaching[2];
};
struct Student
{
int studentId;
Course coursesTaken[2];
};
int main()
{
Course courseObj1, courseObj2, courseObj3;
courseObj1.courseNumber = 1000;
courseObj1.courseStartDate = 20200107;
courseObj1.courseHours = 2;
courseObj1.lecturerId = 100;
courseObj2.courseNumber = 1100;
courseObj2.courseStartDate = 20200113;
courseObj2.courseHours = 4;
courseObj2.lecturerId = 200;
courseObj3.courseNumber = 1200;
courseObj3.courseStartDate = 20200203;
courseObj3.courseHours = 4;
courseObj3.lecturerId = 100;
Lecturer lecturerObj1, lecturerObj2;
lecturerObj1.lecturerId = 100;
lecturerObj1.officeHours = 2;
lecturerObj1.courseTeaching[0] = courseObj1;
lecturerObj1.courseTeaching[1] = courseObj3;
lecturerObj2.lecturerId = 200;
lecturerObj2.officeHours = 2;
lecturerObj2.courseTeaching[0] = courseObj2;
Student student;
student.studentId = 2000;
student.coursesTaken[0] = courseObj1;
student.coursesTaken[1] = courseObj3;
cout << "1. Lecturer ID: " << lecturerObj1.lecturerId << "\tOffice Hours: " << lecturerObj1.officeHours << endl;
for(int i = 0; i < 2; i++)
cout << "COURSE " << (i + 1) << ":\n---------\n" << "Course Number: " << lecturerObj1.courseTeaching[i].courseNumber << endl << "Course start date: " << lecturerObj1.courseTeaching[i].courseStartDate << endl << "Course hours: " << lecturerObj1.courseTeaching[i].courseHours << endl << "Lecturer ID: " << lecturerObj1.courseTeaching[i].lecturerId << endl;
cout << "\n2. Lecturer ID: " << lecturerObj2.lecturerId << "\tOffice Hours: " << lecturerObj2.officeHours << endl;
for(int i = 0; i < 1; i++)
cout << "COURSE " << (i + 1) << ":\n---------\n" << "Course Number: " << lecturerObj2.courseTeaching[i].courseNumber << endl << "Course start date: " << lecturerObj2.courseTeaching[i].courseStartDate << endl << "Course hours: " << lecturerObj2.courseTeaching[i].courseHours << endl << "Lecturer ID: " << lecturerObj2.courseTeaching[i].lecturerId << endl;
int courseNumber;
cout << "\n Enter the course number: ";
cin >> courseNumber;
int index = -1;
int len = sizeof(student.coursesTaken) / sizeof(student.coursesTaken[0]);
int totalHours = 0;
for(int i = 0; i < len; i++)
{
if(student.coursesTaken[i].courseNumber == courseNumber)
{
totalHours += student.coursesTaken[i].courseHours;
}
}
if(totalHours == 0)
cout << "\n Student is not registered to this course!\n";
else
cout << "\nStudent " << student.studentId << " needs " << totalHours << " hours per week of this course.\n";
return 0;
}
Explanation:
Create the 3 objects of Course class and set their properties respectively.Create the 2 objects of Lecturer class and set their properties respectively.Create an object of Student class and set their properties respectively.Run a for loop and check whether the current courseNumber is already added and then increment the total number of hours for that course.Finally check if totalHours is equal to 0 or not and then display the suitable message accordingly.• Reads an integer n (you can assume n won’t be negative and don’t worry about exception handling) • Using a recursive method, compute and write to the screen all integers with n digits in which the digit values are strictly increasing. For example, if n =3, the result is 012 013 014 015 016 017 018 019 023 024 025 026 027 028 029 034 035 036 037 038 039 045 046 047 048 049 056 057 058 059 067 068 069 078 079 089 123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189 234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267 268 269 278 279 289 345 346 347 348 349 356 357 358 359 367 368 369 378 379 389 456 457 458 459 467 468 469 478 479 489 567 568 569 578 579 589 678 679 689 789
Answer:
The Codes and Screenshot to answer the question above are both given below:(the Screenshot is attached to offer you an additional readability of code)
note: File Name must be the same as our class name ( which is Increasing.java in our case.)
Explanation:
Code is given below:
/* File Name Should be Increasing.java
* Java program to print all n-digit numbers whose digits
* are strictly increasing from left to right
*/
import java.util.Scanner;
class Increasing
{
// Function to print all n-digit numbers whose digits
// are strictly increasing from left to right.
// out --> Stores current output number as string
// start --> Current starting digit to be considered
public static void findStrictlyIncreasingNum(int start, String out, int n)
{
// If number becomes N-digit, print it
if (n == 0)
{
System.out.print(out + " ");
return;
}
// Recall function 9 time with (n-1) digits
for (int i = start; i <= 9; i++)
{
// append current digit to number
String str = out + Integer.toString(i);
// recurse for next digit
findStrictlyIncreasingNum(i + 1, str, n - 1);
}
}
// Driver code for above function
public static void main(String args[])
{ //User Input
Scanner sc = new Scanner( System.in);
System.out.println("Enter a number:");
int n = sc.nextInt();
//Function to calcuclate and print strictly Increasing series
findStrictlyIncreasingNum(0, " ", n);
}
}
//End of Code
Using the world_x database you installed in Module 1, list the countries and the capitals of each country. Modify your query to limit the list to those countries where less than 30% of the population speaks English. Be sure to identify the literary sources you used to look up any SQL syntax you used to formulate your query. Submit your query and query results Word file.
Answer:
SELECT country.Name, city.Name
FROM country
JOIN countrylanguage ON country.Code = countrylanguage.CountryCode
JOIN city ON country.Capital = city.ID
WHERE countrylanguage.Language = 'English'
AND countrylanguage.Percentage < 30;
Explanation:
SELECT is used to query the database and get back the specified fields.
City.Name is an attribute of city table.
country.Name is an attribute of country table.
FROM is used to query the database and get back the preferred information by specifying the table name.
country , countrylanguage and city are the table names.
country and countrylanguage are joined based ON country.Code = countrylanguage.CountryCode
countrylanguage and city are joined based ON country.Capital = city.ID
WHERE is used to specify a condition based on which the data is to be retrieved. The conditions are as follows:
countrylanguage.Language = 'English'
countrylanguage.Percentage < 30;
What are the final TTL and the destination IP enclosed in the set of IP datagrams when they arrive at the webserver www.? Does this webserver send a UDP segment or an ICMP message back to the host? What are the type and code enclosed in such UDP segment or ICMP message? What’s the source IP in the IP datagram carrying this UDP/ICMP packet? Whose IP is used as the destination IP for this UDP/ICMP packet? (hint: websever’s, my computer’s, router 147.153.69.30’s, or …?)
Answer:particular layer N, a PDU is a complete message that implements the protocol at that layer. However, when this “layer N PDU” is passed down to layer N-1, it becomes the data that the layer N-1 protocol is supposed to service. Thus, the layer N protocol data unit (PDU) is called the layer N-1 service data unit (SDU). The job of layer N-1 is to transport this SDU, which it does in turn by placing the layer N SDU into its own PDU format, preceding the SDU with its own headers and appending footers as necessary. This process is called data encapsulation, because the entire contents of the higher-layer message are encapsulated as the data payload of the message at the lower layer.
What does layer N-1 do with its PDU? It of course passes it down to the next lower layer, where it is treated as a layer N-2 SDU. Layer N-2 creates a layer N-2 PDU containing the layer N-1 SDU and layer N-2’s headers and footers. And the so the process continues, all the way down to the physical layer. In the theoretical model, what you end up with is a message at layer 1 that consists of application-layer data that is encapsulated with headers and/or footers from each of layers 7 through
Explanation:
A marker automaton (MA) is a deterministic 1-tape 1-head machine with input alphabet {0, 1}. The head can move left or right but is constrained to the input portion of the tape. The machine has the ability to write only one new character to a cell, namely #. (a) Give an example of language D that is accepted by an MA but is not context-free. Justify your answer. (b) Show that Kma = { hM, wi : M is an MA accepting w } is recursive.
Answer:
See explaination
Explanation:
In our grammar for arithmetic expression, the start symbol is <expression>, so our initial string is:
<expression >
Using rule 5 we can choose to replace the nonterminal, producing the string:
<expression >*<expression >
We now have two nonterminals, to replace, we can apply rule three to the first nonterminal, producing the string:
<expression >+<expression>*<expression>
We can apply rule two to the remaining nonterminal, we get:
(number)+number*number
This is a valid arithmetic expression as generated by grammar.
Given a grammar G with start symbol S, if there is some sequence of production that when applied to the initial string S, result in the string s, then s is in L (G). the language of the grammar.
6.4 Predicting Prices of Used Cars. The file ToyotaCorolla.csv contains data on used cars (Toyota Corolla) on sale during late summer of 2004 in the Netherlands. It has 1436 records containing details on 38 attributes, including Price, Age, Kilometers, HP, and other specifications. The goal is to predict the price of a used Toyota Corolla based on its specifications. (The example in Section 6.3 is a subset of this dataset.) Split the data into training (50%), validation (30%), and test (20%) datasets. Run a multiple linear regression with the outcome variable Price and predictor variables Age_08_04, KM, Fuel_Type, HP, Automatic, Doors, Quarterly_ Tax, Mfr_Guarantee, Guarantee_Period, Airco, Automatic_airco, CD_Player, Powered_Windows, Sport_Model, and Tow_Bar. a. What appear to be the three or four most important car specifications for predicting the car’s price?
Answer:
Compare the predictions in terms of the predictors that were used, the magnitude of the difference between the two predictions, and the advantages and disadvantages of the two methods.
Our predictions for the two models were very simmilar. A difference of $32.78 (less than 1% of the total price of the car) is statistically insignificant in this case. Our binned model returned a whole number while the full model returned a more “accurate” price, but ultimately it is a wash. Both models had comparable accuracy, but the full regression seemed to be better trained. If we wanted to use the binned model I would suggest creating smaller bin ranges to prevent underfitting the model. However, when considering the the overall accuracy range and the car sale market both models would be
Explanation:
a.Create the logic for a program that calculates and displays the amount of money you would have if you invested $5000 at 2 percent simple interest for one year. Create a separate method to do the calculation and return the result to be displayed.
b. Modify the program in Excercise 3a so that the main program prompts the user for the amount of money and passes it to the interest calculating method.
c. Modify the program in Excercise 3b so that the main program also prompts the user for the interest rate and passses both the amount of money and the interest rate to the interest calculating method.
// Pseudocode PLD Chapter 9 #3 pg. 421
// Start
// Declarations
// num amount
// num newAmount
// num interestRate
// output "Please enter the dollar amount. "
// input amount
// output "Please enter the interest rate(e.g., nine percet should be entered as 9.0). "
// input interestRate
// newAmount = FutureValue(amount,interestRate)
// output "The new dollar amount is ", newAmount
// Stop
//
//
//
// num FutureValue(num initialAmount, num interestRate)
// Declarations
// num finalAmount
// finalAmount = (1 + interestRate/100) * initialAmount
// return finalAmount
Answer:
see explaination
Explanation:
a)
amount = 5000
rate = 2
year = 1
interest = calculateInterest(amount, rate, year);
finalAmount = amount + interest
###### function ######
calculateInterest(amount, rate, year):
interest = (amount*rate*year)/100;
return interest
b)
amount <- enter amount
rate = 2
year = 1
interest = calculateInterest(amount, rate, year);
finalAmount = amount + interest
###### function ######
calculateInterest(amount, rate, year):
interest = (amount*rate*year)/100;
return interest
c)
#include <iostream>
using namespace std;
// function defination
double calculateInterest(double amount, double rate, int year);
int main(){
double amount, rate;
int year = 1;
cout<<"Enter amount: ";
cin>>amount;
cout<<"Enter rate: ";
cin>>rate;
// calling method
double interest = calculateInterest(amount, rate, year);
cout<<"Amount after 1 year: "<<(amount+interest)<<endl;
return 0;
}
// function calculation
double calculateInterest(double amount, double rate, int year){
return (amount*rate*year)/100.0;
}
In this exercise we have to use the knowledge in computational language in python to write the following code:
We have the code can be found in the attached image.
So in an easier way we have that the code is
a)amount = 5000
rate = 2
year = 1
interest = calculateInterest(amount, rate, year);
finalAmount = amount + interest
calculateInterest(amount, rate, year):
interest = (amount*rate*year)/100;
return interest
b)amount <- enter amount
rate = 2
year = 1
interest = calculateInterest(amount, rate, year);
finalAmount = amount + interest
calculateInterest(amount, rate, year):
interest = (amount*rate*year)/100;
return interest
c)#include <iostream>
using namespace std;
double calculateInterest(double amount, double rate, int year);
int main(){
double amount, rate;
int year = 1;
cout<<"Enter amount: ";
cin>>amount;
cout<<"Enter rate: ";
cin>>rate;
double interest = calculateInterest(amount, rate, year);
cout<<"Amount after 1 year: "<<(amount+interest)<<endl;
return 0;
}
double calculateInterest(double amount, double rate, int year){
return (amount*rate*year)/100.0;
}
See more about python at brainly.com/question/18502436
Answer the following questions based on your readings from Module 1. Describe a time when you or someone you observed showed a poor work ethic. Discuss how their work ethic can be improved. Apart from good work ethic and communication skills, what are two more skills that are good for IT professionals? Your answer should be between 150 to 200 words. (10 points)
Answer:
An example of poor work ethic which I encountered recently was the observation of poor hygiene by an employee of a fast-food outlet of a renowned company.
Explanation:
Some patties suddenly slipped out of his hands and fell on the ground. He did not discard them and simply put them into burg adversely. ers. The fall must have soiled and contaminated them, which would affect the health of consumers. Such incidents can be avoided by the company by training the staff in such possibilities and suggesting corrective actions. Monitoring and taking action against offenders will also help. IT professionals should have good analytical and interpersonal skills besides cross-cultural sensitivity to do good in their roles.
You should apologize for his mistake for reaching the wrong place. The message should be through an electronic message ( sms ) or another instant messaging service, followed by a telephone call. The content of the message should comprise of an apology for not being able to reach in time, the reason for the misunderstanding, your current location and the approximate time it will take to reach the venue. It will be better if you share your location with the client through a GPS enabled application, so that it will be convenient to coordinate.
The tow more skills that are good for IT professionals the the skill off After sale services, and to establish a good relationship with clients.
Using the C language, write a function that accepts two parameters: a string of characters and a single character. The function shall return a new string where the instances of that character receive their inverse capitalization. Thus, when provided with the character ’e’ and the string "Eevee", the function shall return a new string "EEvEE". Using the function with the string "Eevee" and the character ’E’ shall produce "eevee".
Answer:
#include <stdio.h>
void interchangeCase(char phrase[],char c){
for(int i=0;phrase[i]!='\0';i++){
if(phrase[i]==c){
if(phrase[i]>='A' && phrase[i]<='Z')
phrase[i]+=32;
else
phrase[i]-=32;
}
}
}
int main(){
char c1[]="Eevee";
interchangeCase(c1,'e');
printf("%s\n",c1);
char c2[]="Eevee";
interchangeCase(c2,'E');
printf("%s\n",c2);
}
Explanation:
Create a function called interchangeCase that takes the phrase and c as parameters.Run a for loop that runs until the end of phrase and check whether the selected character is found or not using an if statement.If the character is upper-case alphabet, change it to lower-case alphabet and otherwise do the vice versa.Inside the main function, test the program and display the results.Suppose you are an art thief (not a good start) who has broken into an art gallery. All you have to haul out your stolen art is your briefcase which holds only W pounds of art and for every piece of art, you know its weight. Write a program that contains a dynamic programming function to determine your maximum profit. Include a main program that tests your function against each of the following two data sets (each happens to have n=5 items; but your function should work for other values of n as well; we are likely to test your code against another random dataset with an unknown number of items):
Data set 1:
Items 1, 2, 3, 4, and 5 have weights 2, 3, 4, 5 , 9 and value 3, 4, 8, 8, and 10, respectively. Let W = 20.
Data set 2:
Items 1, 2, 3, 4, and 5 have weights 1, 2, 5, 6, 7 and value 1, 6, 18, 22, and 28, respectively. Let W = 11.
Answer:
Check the explanation
Explanation:
weights = [2,3,4,5,9] #assign the weights here
value = [3,4,8,8,10] #assign the values here
#recursive function to get the maximum weight for a given knapsack
def getMaxWeight(weights,value,W,n):
#check if any elements are there or check if the knapsack can hold any more weights
if(n==0 or W==0):
return 0
elif(weights[n]>W):
#if the current value of the weight is greater than what a knapsack can hold then discard that
return getMaxWeight(weights,value,W,n-1)
else:
#either choose the current weight or do not choose based on the maximum values
return max(value[n]+getMaxWeight(weights,value,W-weights[n],n-1),getMaxWeight(weights,value,W,n-1))
if __name__ == '__main__':
W=20
n=len(weights)-1
print("Weights are:",weights)
print("Values are:",value)
print("Maximum value for given knapsack is:",getMaxWeight(weights,value,W,n))
Kindly check the attached output images below.
Write a method manyStrings that takes an ArrayList of Strings and an integer n as parameters and that replaces every String in the original list with n of that String. For example, suppose that an ArrayList called "list" contains the following values:("squid", "octopus")And you make the following call:manyStrings(list, 2);Then list should store the following values after the call:("squid", "squid", "octopus", "octopus")As another example, suppose that list contains the following:("a", "a", "b", "c")and you make the following call:manyStrings(list, 3);Then list should store the following values after the call:("a", "a", "a", "a", "a", "a", "b", "b", "b", "c", "c", "c")You may assume that the ArrayList you are passed contains only Strings and that the integer n is greater than 0.
Answer:
public static ArrayList manyStrings(ArrayList<String> list, int n){
ArrayList<String> newList = new ArrayList<String>();
for (int i=0; i<list.size(); i++) {
for (int j=0; j<n; j++) {
newList.add(list.get(i));
}
}
return newList;
}
Explanation:
Create a method called manyStrings that takes two parameters, list and n
Create a new ArrayList that will hold new values
Create a nested for loop. The outer loop iterates through the list. The inner loop adds the elements, n of this element, to the newList.
When the loops are done, return the newList
Write a program that takes as input an arithmetic expression followed by a semicolon ";". The program outputs whether the expression contains matching grouping symbols. For example, the arithmetic expressions {25 + (3 – 6) * 8} and 7 + 8 * 2 contains matching grouping symbols. However, the expression 5 + {(13 + 7) / 8 - 2 * 9 does not contain matching grouping symbols. If the expression contains matching grouping symbols, the program output should contain the following text: Expression has matching grouping symbol If the expression does not contain matching grouping symbols, the program output should contain the following text:
Answer:
See explaination for the details of the answer.
Explanation:
#include <iostream>
#include <stack>
using namespace std;
int main(){
string str;
cout<<"Enter a String: ";
std::getline (std::cin,str);
bool flag=true;
stack<char> st;
for(int i=0;i<str.size();i++){
if( (str.at(i)>='0' && str.at(i)<='9') || str.at(i)=='+' || str.at(i)=='-' || str.at(i)=='/'|| str.at(i)=='*' || str.at(i)==' ' ){
// cout<<str.at(i) <<"came"<<endl;
continue;
}
if( str.at(i)=='{' || str.at(i)=='(' ){
st.push(str.at(i));
}
else if(!st.empty() &&((st.top() == '{' && str.at(i) == '}') || (st.top() == '(' && str.at(i) == ')')))
st.pop();
else{
flag=false;
break;
}
}
if(!st.empty()){
cout<<"Does not match"<<"\n";
}else{
if(flag)
cout<<"Match"<<"\n";
else
cout<<"Does not match"<<"\n";
}
return 0;
}
See attachment for the output.
1. Discuss the personal and professional implications of so much individual data being gathered, stored, and sold. Should businesses be allowed to gather as much as they want? Should individuals have more control over their data that are gathered?
Answer:
Professional implications refers to when a number of folders in a laptop/machine goes higher,how to manage information becomes a problem, resulting into informational retrieval and storage issues.
Personal Implications refers to sharing of information on different websites, which might result in information theft or fraud once it gets into the hands of wrong people.
Business should be allowed to have access as much they want because, by having a standard procedures such as terms and conditions, this will enable them to protect their information, before allowing individuals to sign up on their sites, in terms of agreement of what the user wants to do with the contents.
Individuals should be allowed to have share more content on the internet, so that at any given time, if they can cancel the read access mode of any content they are accessing on the internet.
Explanation:
Just as the population increases, the need to store more information by the population as goes higher.
When an any information is to be stored, it needs disk allocation or storage. Now, we may be required to store address, Names of individuals, profile photos or phone numbers and so on. there are various path or method of achieving this.
The implications of storing this information are stated below
Professional Implications: As the number of files and folders in an office laptop/machines increases, this can lead to two vital issues which van either be information retrieval or storage issues.
Information retrieval: Putting together of information either from knowledge of mining or data can become more tedious as the data volume is increased. This can be done by using tools associated with knowledge mining.Storage issues: The number of disks that save data needs to be included on a regular basis for the purpose of accommodating the increasing customer's data.Personal implications: This refers to sharing many personal data to different sites on the web in a way of an electronic format this may result in threat referred to as'Data stealing or Theft.
In a more understanding way, the information that is shared by us to a particular site on the web is given out to another third party website for some benefit that are monetary.with this out information is at risk and can be used for negative purposes such as internet fraud or theft.
Business should be permitted to retrieve the data that they need unless there is standard defined Terms and Conditions before permitting a user to have access to their site on the web, so long as the information they collect are used for better and meaning purposes.
Users should be given full control to the contents that they like to share on various website/apps. At any given time, they can cancel the read access mode from any of their contents present in internet.
Given the following SQL Query, which columns would you recommend to be indexed? SELECT InvoiceNumber, InvoiceDate, Invoice_Total, Invoice_Paid, Invoice_Total - Invoice_Paid as Balance FROM Invoice WHERE Invoice_Date >= "2015-07-20" and Salesman_Id = "JR" ORDER BY DESC Invoice_Total Drag the correct answers to one of the three pockets.
Answer:
Invoice_Date and Salesman Id
Explanation:
As the WHERE clause looking at the Invoice_Date and Salesman Id columns so they should be indexed for the following reasons.
Uniquely identifiable records are guaranteed by the unique indexes in the database.Data can be quickly retrieved.The usage of indexes results in much better performance.It can help with quick presorted list of records.A digital pen is an example of this type of device used in the information processing cycle.
Answer:
input device, data capture device
Explanation:
A digital pen is an input device that can be used for data capture.
In this task, you will perform normalization on a crude table so that it could be stored as a relational database.
The staff at 'Franklin Consulting' have to routinely visit their clients in other cities. Franklin have a fleet of cars available for staff travels. During their trips, the staff sometimes need to fill up the car fuel. Upon returning from the trip, the staff claim that expenses back by providing the fueling receipt and some other essential information. The accountant records all of that information in a spreadsheet. Below are the spreadsheet column headers and a sample of data from each column.
Column Name
Example Data
Trip ID
4129
Staff name
Sarah James
Car details
Toyota Land Cruiser 2015
License Plate
1CR3KT
Odometer reading
25,067
Service station
Coles Express
Station address
27 Queen St, Campbelltown, NSW 2560
Fill up time
30 Jan 2020, 2:45 pm
Fuel type
Unleaded 95
Quantity litres
55
Cost per litre
$1.753
Total paid
$96.42
Given the information in above table,
1. Draw a dependency diagram to show the functional dependencies existing between columns. State any assumptions you make about the data and the attributes shown in the table. (3 marks)
2. Show the step by step process of decomposing the above table into a set of 3NF relations. (5 marks)
3. Review the design of your 3NF relations and make necessary amendments to define proper PKs, FKs and atomic attributes. Any additional relations may also be defined at this stage. Make sure all of your attributes conform to the naming conventions. (3 marks)
4. Draw the Crow’s Foot ERD to illustrate your final design. (4 marks)
Answer:
Check the explanation
Explanation:
(1.) The functional dependencies based on assumptions are as follows:-
Trip determines which staff was there in the trip, the car used for the trip, the quantity of fuel used in the trip, the fill up time and the total paid of the trip.
Service station refers to its address
Car details consist of the details of license plate, odometer reading and the fuel type used in the car
fuel type and the fill up time will help to determine the cost of the fuel at that time
cost of the fuel and the quantity of fuel used will determine the total paid
From the above assumptions the functional dependencies are as follows:-
Trip ID -> Staff Name, Car Details, Service Station, Quantity, Fill Up Time, Total Paid
Service Station -> Station Address,
Car Details -> License Plate, Odometer reading, Fuel Type
Fuel Type, Fill up Time -> Cost per litre
Cost per Litre, Quantity -> Total Paid
(2.) Initially the relation is as follows:-
R (Trip ID, Staff Name, Car Details, License Plate, Odometer Reading, Service Station, Station Address, Fill up Time, Fuel type, Quantity, Cost per Litre, Total Paid)
For 1 NF there should not be composite attributes,in the above relation Staff Name and Station Address are composite attributes therefore it will be decomposed as follows:-
R (Trip ID, Staff First Name,Staff Last Name, Car Details, License Plate, Odometer Reading, Service Station, Street, City, State, Zip Code, Fill up Time, Fuel type, Quantity, Cost per Litre, Total Paid)
For 2 NF there should not be partial dependency that is non prime attribute should not dependent upon any 1 prime attribute of candidate key, since in the given relation there is only 1 candidate key which is only Trip ID, therefore the relation is already in 2 NF.
For 3 NF there should not be transitive dependency that is non prime attribute should not dependent upon the other non prime attribute, if it is present then the relation will be decomposed into sub relations, the given relation is not in 3 NF therefore it will be decomposed as follows:-
R1 (Trip ID, Staff First Name, Staff Last Name, Car Details, Service Station, Quantity, Fill up time, Total paid)
R2 (Service Station, Street, City, State, Zip Code)
R3 (Car Details, License Plate, Odometer reading, Fuel Type)
R4 (Fuel Type, Fill up Time, Cost per litre)
R5 (Cost per Litre, Quantity, Total Paid)
(3.) After the 3 NF we add the primary and foreign key constraints as follows:-
R1 (Trip ID, Staff First Name, Staff Last Name, Car Details, Service Station, Quantity, Fill up time, Total paid)
R2 (Service Station, Street, City, State, Zip Code)
R3 (Car Details, License Plate, Odometer reading, Fuel Type)
R4 (Fuel Type, Fill up Time, Cost per litre)
R5 (Cost per Litre, Quantity, Total Paid)
In the above relational schema the primary keys are represented with bold and foreign keys by italic
(4.) The ER diagram of the above relational schema using crow's foot notation are as shown in the attached image below:-
Please refer to the MIPS solution in the question above. How many total instructions are executed during the running of this code? How many memory data references will be made during execution?
Answer:
MIPS designs are used in SGI's computer product line; in many embedded systems; on Windows CE devices; Cisco routers; and video consoles such as the Nintendo 64 or the Sony PlayStation, PlayStation 2 and PlayStation Portable. Most recently, NASA used one of them on the New Horizons probe1.
Explanation:
The earliest MIPS architectures were 32-bit fsfs (generally 32-bit wide data paths and registers), although later versions were implemented in 64-bit. There are five backward compatible revisions of the MIPS instruction set, called MIPS I, MIPS II, MIPS III, MIPS IV, and MIPS 32/64. In the last of these, MIPS 32/64 Release 2, a record control set is defined to major. Also several "extensions" are available, such as the MIPS-3D, consisting of a simple set of floating point SIMD instructions dedicated to common 3D tasks, the MDMX (MaDMaX) made up of a more extensive set of integer SIMD instructions that use 64-bit floating-point registers, MIPS16 which adds compression to the instruction flow to make programs take up less space (presumably in response to the Thumb compression technology of the ARM architecture) or the recent MIPS MT that adds multithreading functionalities similar to the HyperThreading technology of Intel Pentium 4 processors
Answer:
PLEASE SEE EXPLAINATION
Explanation:
for the code given in C Language :-
for(i=0; i<=100; i++)
{
a[i]=b[i]+C;
}
Given address of a =$a0
Gievn address of b = $a1
$t0 holds i
s0 holds constant C
Assembly Language
addi $t0, $zero, 0
loop: slti $t1, $t0, 101
beq $t1, $zero, exist
sll $t2, $t0, 2
add $t3, $t2, $a1
lw $t3, O($t3)
add $t3, $t3, $s0
add $t4, $t2, $a0
sw $t3, O($t4)
i loop
instructions of 1+101*8=809
101 itereations*2 per itereation sw)=202 data references
Answer the following Python Interview questions • How is Python an interpreted language? • What is the difference between Python Arrays, lists, tuples, and records? Explain it with examples • What does [::-1] do? Explain it with an example • How can you randomize the items of a list in place in Python? • What is the difference between range & xrange?Explain it with an example • What advantages do NumPy arrays offer over (nested) Python lists? • How to add values to a python array? Explain it with an example • What is split used for? Explain it with an example
Answer:
1. Python is called as interpreted language. However as a programming language it is not fully compiled nor interpreted language. Python program runs from direct source code which makes it byte code interpreted.
An Interpreter is the one which takes the code and performs the actions specified in the code. It turns the code into intermediate language which is again translated to machine language understood by the processor. Interpreted or compiled are the property of the implementation and not of the language.
2. Array : It is a collection of same data type elements stored at contagious memory location. It is handled in python with module array. All the elements of array must be of same data type. In order to manipulate same data types arrays are used.
Ex: array1 = a.array ('i', [10, 20, 30]) this is a array of integer type.
Lists : Python lists are ordered data structure and are like non homogeneous dynamic sized arrays. It may contain integers, strings, boolean, or objects.
Ex: List1 = [70, 89, 98] , List2 = ["Rose", "Lilly", "Jasmine"]
List3 = [1, 10, 100, 'Test', 'Test1']
Tuple : It is a collection of objects separated by commas and they are immutable. It is static which makes them faster.
Ex: tupule1 = ('element1', 'element2')
List and Tuple in Python are the class of data structure. The list is dynamic, whereas tuple has static characteristics.
Lists are mutable but tuples are not.
tuples are mainly used to access the elements where as lists are used in operations like insertion and deletion.
Iterations are time consuming in list where as it is faster in tuples.
tuples don't have inbuilt methods but list has many builtin methods.
tuples takes slightly less memory that lists in Python
Records: Records data structure will have fixed number of fields and each field may have a name and different type. Immutable records are implemented using named tuple.
3. Syntax of slice in python is list[<start>:<stop>:<step>] and it can be used on tuples and lists.
so X [::-1] means that it will start from the end towards the first element by taking each of the elements.
for ex: X = '9876'
X [::-1] will result in '6789'.
Means it will reverse all the elements in the array.
4. Items of list can be shuffled with the random.shuffle() function of a random module.
Syntax is : random.shuffle(x, random)
x- It is a sequence to shuffle and can be list or tuple.
random- it is a optional argument which returns random float number between 0.1 to 1.0.
5. range() – Range function returns a range object which is a type of iterable object.
xrange() – xrange function returns the generator object that can be used to display numbers only by looping. Only particular range is displayed on demand and hence called “lazy evaluation“.
• Return type of range () is range object whereas that of xrange() is xrange object.
• Variable to store the range using range () takes more memory but xrange takes comparative less memory.
• Range returns the list but xrange returns the xrange object. Hence operations on list can be applied for range but not on xrange.
• Xrange is faster to implement than range as xrange evaluates only generator objects.
• Xrange is depreciated in Python 3 and above.
For ex :
x = range (10, 100)
y= xrange (10, 100)
#To know the return type we can print it
print ( return type of range () is : “)
print (type (x))
print ( return type of xrange () is : “)
print (type (y))
Output will be list and xrange respectively.
6. NumPy's arrays are more compact than Python lists
reading and writing items is also faster with NumPy.
Memory taken by python lists are way higher than NumPy arrays.
Python lists don’t support vectorized operation.
Since lists can contain objects of different types its type information must be stored and executed every time operation is performed on it.
Memory taken by python lists are a lot higher than that of NumPy Arrays.
Reading and writing of elements in NumPy arrays are faster than lists.
NumPy arrays are compact and accumulate lesser storage.
Numpy is convenient and efficient.
For ex :
Metrics operations are easy in NumPy.
Checkerboard pattern can be done using NumPy.
7. Attached as Image
8. split() method returns a list of strings after breaking the given string by the specified separator. It is splitting of string into list with each word is a list item.
Syntax : str.split ( separator, maxsplit)
Separator : its is delimiter used and by default whitespace is used as separator.
Maxsplit : Maximum number of times to split the string. By default it has no limit.
For ex:
text = 'apples and oranges are different '
print(text.split())
output will be : ['apples', 'and', 'oranges', 'are', 'different' ]
Explanation:
Answer:
It Is C to shorten it The answer is C
Explanation:
(a) Implement (in Java) the RadixSort algorithm to sort in increasing order an array of integer keys.
public void radixSort(int arr[])
In your implementation you must consider that each key contains only even digits (0, 2, 4, 6, and 8). Your program must detect the case of odd digits in the keys, and, in this case, abort.
Note: To storage and process the bucket lists, use an ArrayList structure.
(b) What is the running time complexity of your radixSort method? Justify.
.
Final answer:
The provided response includes a Java implementation of the radixSort algorithm that sorts an array of integers with only even digits and aborts if odd digits are found. The running time complexity is O(nk) but is effectively O(n) due to the fixed set of digits.
Explanation:
The student has asked to implement the radixSort algorithm in Java, which sorts an array of integers containing only even digits (0, 2, 4, 6, and 8). Moreover, the program should abort if odd digits are present in the keys. Here's an example implementation:
import java.util.ArrayList;
class RadixSortExample {
public void radixSort(int[] arr) {
final int RADIX = 10;
// Find the maximum number to know the number of digits
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
// Abort if odd digits found
for (int num : arr) {
if (containsOddDigit(num)) {
throw new IllegalArgumentException("Array contains odd digits, which is not allowed.");
}
}
// Perform sorting
for (int exp = 1; max / exp > 0; exp *= RADIX) {
countSort(arr, exp);
}
}
private void countSort(int[] arr, int exp) {
ArrayList<ArrayList<Integer>> bucketList = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
bucketList.add(new ArrayList<>());
}
// Distribute the numbers based on the digit at the given exponent
for (int num : arr) {
int bucketIndex = (num / exp) % 10;
bucketList.get(bucketIndex).add(num);
}
// Merge the buckets
int index = 0;
for (int i = 0; i < 10; i++) {
for (int num : bucketList.get(i)) {
arr[index++] = num;
}
}
}
private boolean containsOddDigit(int num) {
while (num > 0) {
if ((num % 10) % 2 != 0) return true;
num /= 10;
}
return false;
}
}
As for the running time complexity of the radixSort method, it is O(nk), where n is the number of keys and k is the number of digits in the maximum key. The algorithm runs digit by digit, but since we're dealing with a fixed set of digits (even digits only), the k value is bounded and the complexity can also be seen as O(n) for practical considerations, especially when the range of the input is restricted.
Design and implement a GUI application that uses text fields to obtain two integer values (one text field for each value) along with a button named "display" to display the sum and product of the values. Assume that the user always enters valid integer values as inputs.
Answer:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sum, product, num1, num2 As Integer
num1 = Val(TextBox1.Text)
num2 = Val(TextBox2.Text)
sum = num1 + num2
product = num1 * num2
TextBox3.Text = sum
TextBox4.Text = product
End Sub
End Class
Explanation:The solution is implemented in Visual Basic Programming LanguageTwo textboxes are created to receive the user's input and two textboxes for displaying sum and product respectivelyEach of these controls are appropriately labeled (See the attached GUI interface)The Sum is calculated by adding the values from textbox1 and 2The product is calculated by multiplying both12. In cell I9, create a formula without using a function that first adds the selected boxed set’s net weight (cell I8) to the packing weight (cell F5), and then divides the value by 16 to show the shipping weight in pounds.
Answer:
=(I8+F5)/16
Explanation:
In cell I9, we type the following
=(I8+F5)/16
I8 is the boxed set net weight
F5 is the packing weight
The question asked us to add and divide by 16
We use the addition operator '+' instead of built-in "SUM" function as required by the question.
So, we add I8 and F5 and then divide by 16 in cell I9.
Write the constructor for the Theater class. The constructor takes three int parameters, representing the number of seats per row, the number of tier 1 rows, and the number of tier 2 rows, respectively. The constructor initializes the theaterSeats instance variable so that it has the given number of seats per row and the given number of tier 1 and tier 2 rows and all seats are available and have the appropriate tier designation. Row 0 of the theaterSeats array represents the row closest to the stage. All tier 1 seats are closer to the stage than tier 2 seats. Complete the Theater constructor. /** Constructs a Theater object, as described in part (a). * Precondition: seatsPerRow > 0; tier1Rows > 0; tier 2 Rows >= 0 */ public Theater(int seatsPerRow, int tier1Rows, int tier 2 Rows)
Answer:
See explaination
Explanation:
class Seat {
private boolean available;
private int tier;
public Seat(boolean isAvail, int tierNum)
{ available = isAvail;
tier = tierNum; }
public boolean isAvailable() { return available; }
public int getTier() { return tier; }
public void setAvailability(boolean isAvail) { available = isAvail; } }
//The Theater class represents a theater of seats. The number of seats per row and the number of tier 1 and tier 2 rows are
//determined by the parameters of the Theater constructor.
//Row 0 of the theaterSeats array represents the row closest to the stage.
public class Theater {
private Seat[][] theaterSeats; /** Constructs a Theater object, as described in part (a). * Precondition: seatsPerRow > 0; tier1Rows > 0; tier2Rows >= 0 */
public Theater(int seatsPerRow, int tier1Rows, int tier2Rows) {
theaterSeats= new Seat[tier1Rows+tier2Rows][seatsPerRow];
}
public boolean reassignSeat(int fromRow, int fromCol, int toRow, int toCol) {
if(theaterSeats[toRow][toCol].isAvailable()) {
int tierDestination =theaterSeats[toRow][toCol].getTier();
int tierSource =theaterSeats[fromRow][fromCol].getTier();
if(tierDestination<=tierSource) {
if(tierDestination==tierSource) {
if(fromRow<toRow) {
return false;
}else {
theaterSeats[toRow][toCol].setAvailability(false);
theaterSeats[fromRow][fromCol].setAvailability(true);
return true;
}
}
theaterSeats[toRow][toCol].setAvailability(false);
theaterSeats[fromRow][fromCol].setAvailability(true);
return true;
}else {
return false;
}
}else {
return false;
}
}
public static void main(String[] args) {
//Lets understand it with simple example
Theater t1 = new Theater(3,1,2);
//Our threater has 3 seat in each row and we have one tier 1 row and 1 tier 2 row
//total no of seat will be 9.
//Lets create our seat
t1.theaterSeats[0][0] = new Seat(true,1);
t1.theaterSeats[0][1] = new Seat(false,1);
t1.theaterSeats[0][2] = new Seat(true,1);
t1.theaterSeats[1][0] = new Seat(true,2);
t1.theaterSeats[1][1] = new Seat(true,2);
t1.theaterSeats[1][2] = new Seat(true,2);
t1.theaterSeats[2][0] = new Seat(false,2);
t1.theaterSeats[2][1] = new Seat(false,2);
t1.theaterSeats[2][2] = new Seat(true,2);
//Lets print out theater and see which seat is available or which is not
System.out.println("Theater===>");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
System.out.print("["+i+"]"+"["+j+"] : "+t1.theaterSeats[i][j].isAvailable()+" ");
}
System.out.println();
}
System.out.println("(2,1) want to change seat to (0,0)");
System.out.println("["+2+"]"+"["+1+"]"+"===>"+"["+0+"]"+"["+0+"]");
t1.reassignSeat(2, 1, 0, 0);
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
System.out.print("["+i+"]"+"["+j+"] : "+t1.theaterSeats[i][j].isAvailable()+" ");
}
System.out.println();
}
}
}