Assignment Chef icon Assignment Chef

Browse assignments

Assignment catalog

33,401 assignments available

[SOLVED] Ics 141 – 02 assignment 2: classes and objects

Part 1. Declare ‘Employee’ In this Assignment, you will implement a Java class, called ‘Employee’, which can be used to represent employee objects in an application to be used, for example, in an HR application. You will then test your class by implementing another class, called ‘EmployeeDriver’. To start, Open Eclipse and create a new project and name it ‘HRApplication’ then follow the following steps: Create a class called ‘Employee’ inside the ‘HRApplication ‘ project. 1. Declare the following instance variables in ‘Employee’. Remember that instance variables must be declared as private. a. name (of type String). b. hourlyRate (of type double). c. hours (of type int). 2. Declare the following variable to be a Constant. a. TAX (of type double). Tax rate (between 0 and 1.0) Part 2. Constructor and Getters/Setters 1. Declare a constructor for the ‘Employee’ class that takes three input parameters and use the input parameters to initialize the instance variables. 2. Create getters and setters for each instance variable. 3. Implement a ‘toString’ method to print the employees’ information if one doesn’t exist. Part 3. Declare an ‘EmployeeDriver’ 1. Go to the driver class, inside the main method, declare a variable of type ‘Employee’ and call it ‘myEmployee’. 2. Using a sentinel loop, prompt the user for a name, a rate and hour(s) worked. Use the inputs to instantiate an employee object and to initialize the instance variables. Choose any values. (Note: you have to use new keyword to instantiate variables in the employee class. 3. Inside the while loop check if the inputs, rate and hours are invalid; less than 0. Display an error message to the user if the values are invalid. Then prompt the user if they would like to continue or not. 4. Call the ‘toString’ method from ‘EmployeeDriver’ to print the employees’ information. 5. Test different inputs values to verify the code works as expected and that it executes error free Part 4. Methods – Do not start until after Feb. 1st lecture 1. Create a method with a return type double to calculate and display the amount each employee will be paid before taxes. 2. Create a method with a return type double to calculate and display the amount each employee will be taxed 3. Create a method with a return type double to calculate and display the amount each employee will be paid after taxes have been withheld 4. Create a method with a return type double to calculate and display the total amount of taxes the company will withhold 5. Call/Invoke each method from the Driver class on the employee object and display the results. Grading Your grade in this assignment depends on the following: • Your submission meets all the requirements as described above. • The program is robust with no runtime errors or problems. • You follow the good programming practices as discussed in class (check Lecture 1’s slides) • You follow the below submission instructions. Submission Instructions • Follow the following steps to upload your code to D2L: o Create a java project and call it Assignment1 (e.g., mine will be called DillonAssignment1) o Create one.java files to solve the problem described above. o Archive your .java file into a zip file using Eclipse using the following steps:  In Eclipse Project Explorer, right click on the src folder of the project and click on Export.  Choose General then Archive File and click Next.  Use the Browse key to choose a folder to store the archive file on your hard drive and give the file the same name as your project (e.g., Dillon1.zip), then click Save, then click Finish.  Upload the .zip file you created to the D2L folder called Assignment 1.  It is important that you upload only one zip file. Your assignment will not be graded if you upload individual .java files to the drop box.

$25.00 View

[SOLVED] Csci 4260/6260 assignment 1: adversarial attack

Problem 1. Classify the following acts as a violation of confidentiality, of integrity, of availability, or of some combination of three. You should clearly state any assumptions you make. (i) John and his friends take CS department’s nike server offline by sending massive amount of network packets. (ii) Alice breaks into UGA’s eLC web server and changes her grade for HW1. (iii) Bob obtains his classmate’s myid and password. (iv) A ransomware encrypts the victim’s hard drive with a secret key, and a criminal asks for money in exchange for decryption. Note: The answers to the above questions are not unique and hence you need to clearly explain why you think the act violates a certain principle as best as you can. 1 Fast Gradient Sign Method Recall the fast gradient sign method (FGSM) we learned in class. Let x orig ∈ R 3×H×W denote an image of width W, height H, and with 3 color channels R, G, and B and y orig ∈ {1, 2, . . . , K} be its true label. Suppose we have a pre-trained neural network fθ : R 3×H×W → {1, 2, . . . , K} that takes an image as input and returns a label. FGSM formulates the problem of generating an adversarial example x adv from the given image x orig as an optimization problem: x adv = arg max x L(fθ(x), yorig) subject to ∥x − x orig∥∞ ≤ ϵ , (1) where L is a loss function, ϵ > 0 is a small constant, and ∥·∥∞ denotes L∞ norm. Problem 2. Answer the following questions. You should elaborate the rationale behind your answer using mathematical symbols and equations whenever possible. (a) Notice that the problem (1) enforces the constraint that the magnitude of perturbation (or noise) x − x orig is small using the L∞ norm. Read this Wikipedia article and give the mathematical definition of L∞ norm. Explain in detail what the role of this L∞ norm constraint is in the adversarial attack. (b) Suppose that you mistakenly change the L∞ norm constraint in (1) into L2 norm constraint. What do you think how this changed formulation affects x adv in terms of perturbation (or noise)? Your answer should be based on the observed difference between L∞ and L2 norms. (c) Write the equation for updating the adversarial example x adv using the FGSM. Your answer should be written using the symbols and notations used in our lecture slides. (d) Is it possible to generate an adversarial image that incurs 0 loss. That is, does there exist an adversarial example x adv such that L(fθ(x adv), yorig) = 0? (e) Notice that the above is a formulation for untargeted attack. Suggest a way to modify the optimization problem in (1) to perform the targeted attack. In other words, provide an equation of optimization problem for a targeted attack. You can denote the target class by y target . Problem 3. Suppose that your (hypothetical) TA decided to construct an adversarial attack without using a reference image, i.e., without access to x orig and came up with the following formulation. x adv = arg min x 1 2 ∥fθ(x) − y target∥ 2 2 , where y target is the class to which the TA wants to misguide fθ. Do you think the resulting image, the solution of the above optimization problem, look like a natural image? You should justify your answer in detail. DeepFool Recall that the DeepFool method uses an orthogonal projection for generating adversarial example. Specifically, given an image to attack x orig, it projects x orig onto the decision boundary of a classifier. Problem 4. (graduate only) Figure 1 shows a linear line f corresponding to a linear classifier and an image x orig in 2D space. Derive an equation corresponding to the L2 distance between x orig and x proj. You need to show your derivation step by step. 2 x1 x2 f(x1, x2) = w1x1 + w2x2 + b = w⊺x + b = 0 w x orig x proj Figure 1: A linear classifier f(x) = 0 Programming Questions Generating Adversarial Examples Consider a neural network fθ : R 784 → R 10 consisting of three linear layers. For this assignment, we will use the MNIST dataset, an image dataset of handwritten digits (for more detailed description of this dataset, please refer to this page). Figure 2 shows the visualization of the first 10 images in the training dataset. Figure 2: Visualization of the first 10 examples in MNIST dataset Each image x is a matrix of size 28 × 28 but converted into a vector (by concatenating its row vectors) x ∈ R 784 to be used as input to a linear layer. The neural network generates the output 3 as follows: input: x ∈ R 784 z (1) = W(1)x + b (1) , W(1) ∈ R 512×784 , b (1) ∈ R 512 (2) a (1) = sigmoid(z (1)) applied element-wise (3) z (2) = W(2)a (1) + b (2) , W(2) ∈ R 512×512 , b (2) ∈ R 512 (4) a (2) = sigmoid(z (2)) applied element-wise (5) z (3) = W(3)a (2) + b (3) , W(3) ∈ R 10×512 , b (3) ∈ R 10 (6) a (3) = softmax(z (3)), (7) where, for a vector z = (z1, . . . , zn) ⊺ , sigmoid(z) =  1 1 + e−z1 , 1 1 + e−z2 , . . . , 1 1 + e−zn ⊺ and softmax(z) = e z1 Pn j=1 e zj , e z2 Pn j=1 e zj , . . . , e zn Pn j=1 e zj !⊺ . The (model) parameters are θ = {W(1) , b (1) ,W(2) , b (2) ,W(3) , b (3)}. Notice that, given an image x ∈ R 784, the network fθ(x) computes its (intermediate) outputs according to (2) – (7) and returns a vector a (3) ∈ R 10, the i th entry of which corresponds to the class probability P[Y = i | X = x] for class i. Since a (3) is the class probabilities estimated by our neural network model, let’s denote it by yb = a (3). To measure how close this estimated probability is to the ground truth (i.e., labels), we use the following loss function, known as cross-entropy. L(θ; x, y) := − X 10 i=1 yi log ˆyi , where ˆyi denotes the i th entry of yb. The network was trained on the MNIST dataset for 100 epochs using the stochastic gradient descent algorithm with mini-batch size=256 and step size=0.1. Figure 3 shows the performance of trained network against epoch numbers. Figure 3: The train/test performance of network over epochs You can download the trained (model) parameters from here. It is also included in the base code zip archive. For your convenience, the trained neural network object was serialized using Python’s pickle library. To learn how to use the pickle class, see the examples in this page. The essential functionality of pickle class is to serialize object into or de-serialize from the file. For example, to load the trained model from the file “trained model.pkl”, use the following code fragment. 4 1 with open(‘trained_model.pkl’, ‘rb’) as fid: 2 model = pickle.load(fid) 3 4 # now you can use the model class Similarly, for your convenience, the serialized MNIST dataset is provided here. 1 with open(‘mnist.pkl’, ‘rb’) as fid: 2 dataset = pickle.load(fid) 3 4 # dataset is a dictionary containing the training and test sets. The keys and values of dataset object is described in Table 1. Key Value ’training images’ numpy array of size (60, 000 × 784) ’training labels’ numpy array of size (60, 000,) ’test images’ numpy array of size (10, 000 × 784) ’test labels’ numpy array of size (10, 000,) Table 1: Dataset directionary Here are some important functions of MLP class in the provided base code. • model.forward(x) : This function takes a batch of images and performs the forward operation and returns the output, the estimated class probabilities for images in x. Here x is a 2D numpy array, each row corresponding to an image. Mathematically, it returns yb = fθ(x). • model.backward(y) : This function implements the famous Backpropagation algorithm. It computes the gradients recursively and returns three lists. – grad_w : gradient w.r.t. W, i.e., it contains h ∂L ∂W(1) , ∂L ∂W(2) , ∂L ∂W(3) i . – grad_b : gradient w.r.t. b, i.e., it contains h ∂L ∂b(1) , ∂L ∂b(2) , ∂L ∂b(3) i . – delta : gradient w.r.t z, i.e., it contains h ∂L ∂z (1) , ∂L ∂z (2) , ∂L ∂z (3) i . You won’t need to call this function directly because this function returns ∇θL (the gradient of loss function w.r.t. model parameter θ) which is used for updating the model parameter θ. • grad_wrt_input(x, y) : This is the function you’ll be mainly using to generate your adversarial examples. It computes the gradient(s) w.r.t. the given input pair(s) (x, y). In other words, it returns ∇xL(θ; x, y) = ∂L ∂x . To visualize your adversarial example, you can use visualize_example() function which has the following input arguments. • x_img : a numpy array corresponding to your adversarial image 5 • y_probs : class probabilities for x_img (estimated by fθ) • b_unnormalize : if set True, the function unnoromalizes the given image by applying the inverse of standardization. Fix this to True. • label : an integer value corresponding to the label of x_img • filename : a string with which the visualization is stored if provided. If filename=None, the function displays the plot without storing it into a file. Problem 5. In this problem, our goal is to generate a random image x adv that our neural network fθ believes it belongs to class y target ∈ [0, 9]. • Generate a random image x0 ∈ R 784 each of whose entry is randomly drawn from the uniform distribution Uniform(−α, α). Set α = 0.1. • Given x0, our goal is to gradually modify xt until the neural network fθ recognizes it as an instance of class y target using the gradient descent algorithm. • The fact that xt is recognized as an instance of class y target means that the loss L(θ; xt , y) takes the minimum value when y = y target. For your understanding, think about why this is the case. Since x0 is randomly initialized, at the first iteration x0 will not be classified into class y target, which means L(θ; xt , ytarget) is high. Hence, our goal is to gradually change xt such that L(θ; xt , ytarget) decreases. In other words, we will solve the following optimization problem using the gradient descent algorithm. x adv = arg min x L(θ; xt , ytarget) • Repeat the gradient decent update until xt is classified into y target • Implement the following function. 1 def generate_image_for_class(model, target_class): 2 “”” 3 This function Generates a random image that will be classified 4 as class target_class by the neural network. 5 6 Parameters: 7 ———————————— 8 model: neural network model object 9 target_class: integer, target_class to which the network classifies the image 10 alpha: each pixel in the image is initialized by sampling from 11 uniform distribution over (-alpha, alpha) 12 “”” 13 # —————————————-# 14 # Your code goes here # 15 # —————————————-# 16 17 18 def main(): 19 model = None 20 with open(‘trained_model.pkl’, ‘rb’) as fid: 21 model = pickle.load(fid) 22 23 for c in range(10): 6 24 generate_image_for_class(model, c) 25 26 27 if __name__ == “__main__”: 28 main() 29 – Your function should store the generated image as ‘‘targeted random img class [y target].png’’. – Generate the images for y target = 0, 1, 2, . . . , 9. – If necessary, you can change the prototypes of above functions. – Your generated image will not look like any digit (recall that you started with a random image in which each pixel value is drawn from a uniform distribution), yet your neural network will classify it as a digit belonging to class y target . Problem 6. In this problem, we will perform an untargeted attack using the Fast Gradient Sign Method (FGSM). This means that we don’t have any specific target class y target in mind. The attack is regarded as successful as long as the network misclassifies the given image. • The first example, denoted by x test in your test set is an instance of class 7 (i.e., y test = 7). • Use the first example in the test set as a starting point. That is, your x0 = x test . • Using the FGSM algorithm, perturb xt until it is not classified as class y test . • In other words, solve the following optimization problem. x adv = argmax x L(θ; x test, ytest) subject to ∥x − x orig∥∞ ≤ ϵ , where ϵ = 0.05. Store the generated input as “FGSM untargeted.png” using visualize_example() function. 1 def fgsm(x_test, y_test, model, eps=0.05): 2 # ——————————–# 3 # Your code goes here # 4 # ——————————–# 5 6 return x 7 8 9 def main(): 10 # load datasets 11 mnist = None 12 with open(‘mnist.pkl’, ‘rb’) as fid: 13 mnist = pickle.load(fid) 14 15 # load model 16 model = None 17 with open(‘trained_model.pkl’, ‘rb’) as fid: 18 model = pickle.load(fid) 19 20 # ——————————–# 7 21 # Your code goes here # 22 # ——————————–# 23 24 x_adv = fgsm(x_test, y_test, model) 25 # visualize x adv 26 27 if __name__ == “__main__”: 28 main() 8

$25.00 View

[SOLVED] Ics 141 – 02 assignment 1: problem solving using variables and i/o

Objective You are asked to write a program to help a small company calculate the amount of money to pay their employees. In this simplistic world, the company has exactly three employees. However, the number of hours per employee may vary. The company will apply the same tax rate to every employee. To receive full credits, create a video recording less than 10 minutes with your face on camera describing your code step by step. Upload the java package as well. Problem Description Inputs (entered by user of the program) • Name of first employee • Hourly rate • Number of hours worked • Name of second employee • Hourly rate • Number of hours worked • Name of third employee • Hourly rate • Number of hours worked • Tax rate (between 0 and 1.0) Processing and Output • Calculate and display the amount each employee will be paid before taxes • Calculate and display the amount each employee will be taxed • Calculate and display the amount each employee will be paid after taxes have been withheld • Calculate and display the total amount of taxes the company will withhold • Display your name You may separate the processing/calculation step from the output step or you may combine those steps. It is your choice. Important Note: You may face a problem with nextLine() method does not stop to allow you to enter a text from the keyboard. This problem may appear when you call nextLine() after calling nextInt() or nextDouble(). The reason for this problem is that the nextLine() reads the new line (i.e., enter) that you type after writing your integer or double from the keyboard. To solve this problem, add a redundant nextLine() method after each nextInt() or nextDouble(). For example, instead of using the following code to read an integer: int x = scan.nextInt() use the following instead: int x = scan.nextInt() scan.nextLine() //redundant Requirements Prompt the user for the inputs and store the values in variables • You must include all the inputs and outputs listed above and perform the calculations correctly • Make the output look attractive • The program should display your name • Comment your code. At the top of the program include your name, a brief description of the program and what it does and the due date. • The program must be written in Java and submitted via D2L. Grading Your grade in this assignment depends on the following: • Your submission meets all the requirements as described above. • The program is robust with no runtime errors or problems. • You follow the good programming practices as discussed in class (check Lecture 1’s slides) • You follow the below submission instructions. Submission Instructions • Follow the following steps to upload your code to D2L: o Create a java project and call it Assignment1 (e.g., mine will be called DillonAssignment1) o Create one.java files to solve the problem described above. o Archive your .java file into a zip file using Eclipse using the following steps:  In Eclipse Project Explorer, right click on the src folder of the project and click on Export.  Choose General then Archive File and click Next.  Use the Browse key to choose a folder to store the archive file on your hard drive and give the file the same name as your project (e.g., Dillon1.zip), then click Save, then click Finish.  Upload the .zip file you created to the D2L folder called Assignment 1.  It is important that you upload only one zip file. Your assignment will not be graded if you upload individual .java files to the drop box.

$25.00 View

[SOLVED] Csci 4260/6260 assignment 3: anonymization and differential privacy

1 Sensitivity Calculation Problem 1. (30 pts) Consider a dataset D = {x1, x2, . . . , xn} consisting of n elements, each of which is drawn from the universe U = {1, 2, . . . , 100}. Compute the sensitivity of the following query functions and provide an example neighboring dataset pair that yields the highest sensitivity, i.e., give an example of (D, D′ ). 1 (1) q(D) = |{x : x > p , x ∈ D}|, i.e., the number of elements greater than p. Compute the sensitivity of q under two different definitions of neighboring datasets we learned in class (i.e., one under the proper subset definition and the other under the replacement definition). You need to describe your logic or reasoning in detail. (2) q(D) = Pn i=1 xi Compute the sensitivity of q under two different definitions of neighboring datasets. (3) q(D) = median({x1, x2, . . . , xn}) For this problem, use the replacement definition and assume n is an odd number. 2 Variance of Noisy Answer Problem 2. (10 pts) Let’s quickly check your understanding on the Laplace random variable. Let q : X n → R be a query function whose sensitivity is 1 (for example, the count query). We know that the Laplace mechanism M generates its private answer as shown below satisfies ϵ-differential privacy. M(D) = q(D) + Y noise , where Y ∼ Lap 0, λ = 1 ϵ  . (1) Show that M(D) is an unbiased estimate of q(D). (2) Suppose that we split the total privacy budget ϵ into two chunks, [ ϵ 2 , ϵ 2 ], and obtain R1 = M(D) = q(D) + Lap  0, λ = 2 ϵ  R2 = M(D) = q(D) + Lap  0, λ = 2 ϵ  What is the variance of R1 + R2, i.e., Var(R1 + R2)? (3) Now consider splitting the privacy budget as [ ϵ 3 , 2ϵ 3 ] and computing R1 = M(D) = q(D) + Lap  0, λ = 3 ϵ  R2 = M(D) = q(D) + Lap  0, λ = 3 2ϵ  Compute the variance of R1 and R2 and state which answer is more useful (i.e., better utility). 3 Private Synthetic data generation via Histograms Consider the following dataset consisting of 1,000 observations randomly generated using the scikit-learn package. See the attached CSV file containing the dataset. It contains two attributes x1 and x2 and a label y. As you can see from Figure 1, (x1, x2)-coordinate values are restricted to the range [0, 1) 1 The label yi , for i = 1, . . . , 1000, is an integer, i.e., yi ∈ {0, 1}. 0 and 1 correspond to the blue and red dots in the figure, respectively. We will generate a synthetic dataset that resembles the one in Figure 1 under differential privacy. Here are steps we will be taking to generate the synthetic dataset. 1The notation [a, b) means the interval defined by a ≤ x < b. The left square bracket means that the lower bound a is inclusive while the right parenthesis means that the upper bound is not inclusive. 2 0.0 0.2 0.4 0.6 0.8 1.0 x1 0.0 0.2 0.4 0.6 0.8 1.0 x 2 Figure 1: A dataset randomly generated using the scikit-learn package 1 Building a 2D histogram (1) Construct bins by splitting each dimension into k intervals. (2) Count the number of observations that fall into each bin. Definition 1 (Histogram) A histogram H = (b1, . . . , bm) constructed from a dataset D is a collection of bins bi, each of which is a tuple bi = (r i 1×r i 2 , counti) = [s i 1 , fi 1 ) × [s i 2 , fi 2 ), counti  , where • rect = (r i 1 × r i 2 ) denotes the rectangular region associated with bi, and • counti is the number of observations in rect, i.e.,{(x1, x2) ∈ D | s i 1 ≤ x1 < fi 1 , si 2 ≤ x2 < fi 2}. 2 For example, if we split each dimension into two intervals, [0, 0.5) and [0.5, 1.0), we obtain 2 × 2 = 4 bins in total. Each bin is composed of 2D range and count. The range is a Cartesian product of two intervals, one from dimension x1 and the other from x2. The count is an integer that represents the number of observations falling into the rectangle formed by the associated range. An example of 2D histogram is shown in Table 1 3 . Alternatively, this Bin bi .range bi .count b1 [0, 0.5) × [0, 0.5) 123 b2 [0, 0.5) × [0.5, 1.0) 377 b3 [0.5, 1.0) × [0, 0.5) 346 b4 [0.5, 1.0) × [0.5, 1.0) 154 Table 1: An example 2D histogram obtained by splitting each dimension into 2 equi-width intervals. can be viewed as laying a regularly spaced grid over a rectangle [0, 1) × [0, 1) and counting number of observations contained in each cell. 2For a set X, |X| denotes the number of elemnts in X. 3Note that the count values in Table 1 are not calculated from the dataset you will be using in this homework. In other words, even if you get different count values, it doesn’t mean that your implementation is incorrect. 3 Problem 3. Implement the function that construct a histogram. 1 def construct_histogram(X, n_split): 2 “”” 3 Parameters: 4 ————————– 5 X: 2D array of size (n, 2), containing observations 6 n_split: integer, the number of intervals to have on each dimension 7 8 Return: 9 ————————- 10 h: 1D array containing bin counts; the bins are enumerated from left to 11 right and top to bottom. For our example in Table 1, it should return 12 (377, 154, 123, 346) = (b2, b4, b1, b3). 13 “”” 14 pass 15 Consider releasing the histogram you constructed. Problem 4. Using the histogram you constructed, propose a way to generate a dataset that can satisfy k-anonymity. You need to elaborate your idea. For which value of k, does your dataset satisfy the k-anonymity? Draw a table showing how the dataset to be released look like. 2 Releasing the histogram using the Laplace mechanism Given a query function q : X n → R, the Laplace mechanism M first computes the true answer q(D) and draw a random noise Y from a Laplace distribution Lap (0, λ) with mean 0 and scale factor λ. We saw in class that setting λ = ∆q ϵ allows to achieve ϵ-differential privacy: Mq(D) = q(D) + Y , Y ∼ Lap (0, λ) . We also learned in class how to release histograms (a sequence of count values) under differential privacy. As a warm-up, let’s compute the sensitivity of releasing histograms. Problem 5. Recall that we talked about two different ways of defining neighboring datasets: proper subset definition VS replacement definition. Let H = (h1, h2, . . . , hn), where hi is an integer corresponding to the number of observations in the i th bin of H, i.e., bi .count. For each definition, derive the sensitivity of function releasing a histogram of length n. Your answer must clearly show each step taken to compute the sensitivity. Now we are ready to write a function that release histogram under ϵ-differential privacy. Problem 6. Write a function that releases a histogram using the Laplace mechanism. You can use numpy.random.laplace to generate the Laplace noise. 1 def dp_histogram(histo, epsilon): 2 “”” 3 Parameters: 4 ———————— 5 histo: 1D array containing count values of a histogram 6 epsilon: privacy budget, a real number greater than 0. 4 7 8 Returns: 9 ———————— 10 noisy_histo: 1D array containing count values, each entry is perturbed 11 with Laplace noise 12 “”” 13 pass 3 Post-processing the released histogram. A drawback of using the Laplace mechanism for releasing histograms is that the release count values can be negative and are real numbers (rather than integers). What we learned in class is that the privacy guarantee of differential privacy is invariant under post-processing. This means that we can freely transform the differentially privately released output and the result is still ϵ-differentially private as long as the algorithm you used to transform the output doesn’t make use of the noise injected by the Laplace mechanism. After post-processing the histogram, we will normalize the histogram to convert the count values into probabilities. This is simply done by dividing each post-processed count values by their total sum. Problem 7. Write a simple function that turns negative count values into zeros. 1 def postprocess(noisy_histo): 2 “”” 3 Parameters: 4 —————————- 5 noisy_histo: 1D array containing noisy count values 6 7 Returns: 8 —————————- 9 probs: 1D array that contains the probabilities for each bin. 10 “”” 11 pass 4 Generating a synthetic dataset. Let’s recall the information available to us. We have a noisy histogram He = (b1, b2, . . . , bn) = {bi = ([s i 1 , fi 1 ) × [s i 2 , fi 2 ), counti , probi )} n i=1 containing count and prob for each rectangle formed by two intervals. This tells us that we can create a dataset by generating counti observations within the range [s i 1 , fi 1 )×[s i 2 , fi 2 ). For simplicity, we assume observations are uniformly distributed over [s i 1 , fi 1 ) × [s i 2 , fi 2 ). You can use numpy.random.uniform to randomly generate uniformly distributed values. Problem 8. Write a function that generate a synthetic dataset of size 1,000. 1 def synthesize_dataset(noisy_histo): 2 “”” 3 Parameters: 4 ————————- 5 noisy_histo: tuple containing bin ranges and bin counts 5 6 7 Returns: 8 ————————- 9 syn_dataset: 2D array containing 10 “”” 5 Experimenting with the synthetic datasets Problem 9. Generate synthetic datasets for three different values of ϵ = 0.1, 1.0, 10.0 and for three different values of n split=2, 4, 8. Visualize the datasets you generated using the following code. You should provide 3 × 3 = 9 visualizations. 1 import matplotlib.pyplot as plt 2 3 def visualize_2d(X, filename, y=None): 4 “”” 5 Visualize the dataset given in X 6 7 Parameters: 8 ————— 9 X: 2D array of shape (n, 2) 10 filename: a string, the name of file to store the figure 11 “”” 12 fig, ax = plt.subplots() 13 14 ax.scatter(X[:, 0], X[:, 1], cmap=plt.get_cmap(‘jet’)) 15 ax.set_xlabel(r’$x_1$’, fontsize=15) 16 ax.set_ylabel(r’$x_2$’, fontsize=15) 17 plt.tight_layout(pad=0.1) 18 plt.savefig(filename) 19 Problem 10. Discuss the trade-offs played by the following hyper-parameters. • privacy budget ϵ • number of splits n split

$25.00 View

[SOLVED] Csci 1730 project 2 understanding the heap, dynamic memory management, and pointers

Problem / Exercise The purpose of this assignment is to write a C program that maps out its dynamic memory usage as the program executes to solve a simple problem of computing the average grade of a list of grades and determining which grades are >= or = or < the average as shown in the examples. Also, the program should correctly print out the total heap usage, the total heap usage much match our examples, it must be consist with the output from valgrind. Study the examples in the examples section to understand the problem before you start to code. This section only gives general parts of the algorithm you’ll need to implement. You’ll need to reverse engineer the examples shown in the examples section to get your program’s I/O to be consistent with our examples. 1 Project Requirements Your program must adhere to all requirements stated below. 1. Your program must be written in C, its source code should be in a file named proj2.c, and all files for this assignment should be in a directory named proj2. 2. Your program may only contain the following include statements: (a) #include (b) #include (c) #include The use of any other include statements than those mentioned above will result in a grade of zero on this assignment. 3. Your program may only use the following functions that are part of the C language: (a) printf (b) scanf (c) malloc (d) free All other functions you must design and implement yourself. The use of any other built-in functions than those mentioned above will result in a grade of zero on this assignment. The four functions above are necessary for this assignment. 4. Your program must store all grades (all inputs >= 0) on the heap using arrays of the fixed sizes as shown in the examples (sizes of 40, 80, 120, …). 5. Do not ask (or prompt) the user for how many grades they would like to input. The input format must match our examples, and this is designed to simulate real world data where the length of the input may not be known at the start of the program. 6. Your source code cannot contain a [ or a ], which is common syntax to use for arrays. This is a requirement because we want students in this course to get more experience with pointer syntax and pointer arithmetic. If a single [ or a single ] is found in your source code, then you will receive a zero on this assignment. Use pointer notation and pointer arithmetic instead of the square bracket notation for this assignment. 7. Your program’s I/O must match the examples except the memory addresses will be different each time the program is run, and this is okay. However, the relative memory addresses should be consistent (consecutive grades should be in addresses that are 8 bytes apart). 8. Your program’s total heap usage output must be consistent with valgrind’s output for total heap usage when your program is run in valgrind. You must run your program with valgrind for many examples to ensure this is consistent and that no memory leaks are present in your program when it executes. Substantial points will be lost if your program has a memory leak or its total heap usage is not consistent with valgrind. 9. Your program must compile with all targets, dependencies, and commands given in the Makefile, which is on eLC for this project, and your program cannot contain any compiler errors or warnings when compiled using the provided Makefile. 10. After you finish the program and submit it, consider the following questions. What are the limitations of using fixed length arrays for problems dealing with variable length input? What are the advantages of using fixed sized arrays for problems with variable length inputs? What other data structures are useful for problems dealing with variable length inputs? 2 C Program Coding Style Requirements 1. All functions must be commented. Comments must include a brief description of what the function does, its input(s), its output, and any assumptions associated with calling it. If your function has a prototype and an implementation separated into different parts of your source code, then you only need to put the comments for that function above its prototype (there is no need to comment both the prototype and implementation; commenting the prototype is sufficient). 2. All structs, unions, and enums must be commented. 3. All global variables and static variables must be commented. 4. All identifiers must be named well to denote their functionality. Badly named identifiers are not allowed. For example, identifiers like a, aaa, b, bbb, bbbb are bad names for identifiers. 5. Every line of source code must be indented properly and consistently. README.txt File Requirements Make sure to include a README.txt file (use a .txt file extension) that includes the following information presented in a reasonably formatted way: ˆ Your First and Last Name (as they appear on eLC) and your 810/811# ˆ Instructions on how to compile and run your program. Since we are using a Makefile for this assignment, then these instructions should pretty simple based on the provided Makefile. Submission Submit your files before the due date and due time stated on eLC. Submit your files on eLC under the Assignment named Project 2. Submit only the following files. 1. All source files required for this assignment: proj2.c 2. A README.txt file filled out correctly Do not submit any compiled code. Also, do not submit any zipped files or directories. Do not submit a Makefile. We will use our own, unmodified copy of the provided Makefile to compile your program. We only need the files mentioned above with the file extensions aforementioned. Grading: 30 points If your program does not compile on odin using the provided Makefile and using the required compiler for this course (gcc version 11.2.0), then you’ll receive a grade of zero for this assignment. Otherwise, your program will be graded using the criteria below. Program runs correctly with various test cases on odin 30 points README.txt file missing or incorrect in some way -3 points Not submitting to the correct Assignment on eLC -3 points Late penalty for submitting 0 hours to 24 hours late -6 points One or more compiler warnings -6 points Not adhering to one or more coding style requirements -6 points Valgrind identifies a memory leak (definitely, indirectly, or possibly lost) -6 points Program does not use the heap to store grades -30 points Source code contains an unauthorized include statement -30 points Source code contains an unauthorized built-in function call -30 points Source code contains a single [ or a single ] -30 points Not submitting this assignment before its late period expires -30 points Penalty for not following instructions (invalid I/O, etc.) Penalty decided by grader 3 You must test, test, and retest your code to make sure it compiles and runs correctly on odin with any given set of valid inputs. This means that you need to create many examples on your own (that are different than the examples in this assignment) to ensure you have a correctly working program. Your program’s I/O must match the examples given in the Examples section. We will only test your program with valid sets of inputs. Examples Each example is a separate run of a correctly working program. Your program’s I/O should match these examples except the memory addresses will typically be different for each run. However, the relative memory addresses should be consistent as aforementioned. input1.txt, output1.txt, input2.txt, and output2.txt are on eLC, and those files contain the full input and outputs for the large examples. Students must test, test, and retest their code with many examples and run each example in valgrind to ensure their programs are correct, contain no memory leaks, and that total heap summary outputted by their program is consistent with valgrind (please note that valgrind uses commas to separate thousands places, and we do not have to print commas to separate thousands places in our total heap usage, and this is shown in some of the examples). ./proj2.out Enter a list of grades below where each grade is separated by a newline character. After the last grade is entered, enter a negative value to end the list. -2.5 The average of 0 grades is 0.000000. total heap usage: 0 allocs, 0 frees, 0 bytes allocated ./proj2.out Enter a list of grades below where each grade is separated by a newline character. After the last grade is entered, enter a negative value to end the list. 97.5 Allocated 40 bytes to the heap at 0x8d8010. Stored 97.500000 in the heap at 0x8d8010. -12.5 The average of 1 grades is 97.500000. 1. The grade of 97.500000 is >= the average. Freed 40 bytes from the heap at 0x8d8010. total heap usage: 1 allocs, 1 frees, 40 bytes allocated ./proj2.out Enter a list of grades below where each grade is separated by a newline character. After the last grade is entered, enter a negative value to end the list. 85.4 Allocated 40 bytes to the heap at 0xb94010. Stored 85.400000 in the heap at 0xb94010. 28.5 Stored 28.500000 in the heap at 0xb94018. 98.75 Stored 98.750000 in the heap at 0xb94020. 100.0 Stored 100.000000 in the heap at 0xb94028. 0 Stored 0.000000 in the heap at 0xb94030. Stored 5 grades (40 bytes) to the heap at 0xb94010. Heap at 0xb94010 is full. Allocated 80 bytes to the heap at 0xb94040. Copied 5 grades from 0xb94010 to 0xb94040. Freed 40 bytes from the heap at 0xb94010. -2 The average of 5 grades is 62.530000. 1. The grade of 85.400000 is >= the average. 2. The grade of 28.500000 is < the average. 4 3. The grade of 98.750000 is >= the average. 4. The grade of 100.000000 is >= the average. 5. The grade of 0.000000 is < the average. Freed 80 bytes from the heap at 0xb94040. total heap usage: 2 allocs, 2 frees, 120 bytes allocated ./proj2.out Enter a list of grades below where each grade is separated by a newline character. After the last grade is entered, enter a negative value to end the list. 78 Allocated 40 bytes to the heap at 0x1c82010. Stored 78.000000 in the heap at 0x1c82010. 99 Stored 99.000000 in the heap at 0x1c82018. 100 Stored 100.000000 in the heap at 0x1c82020. -1 The average of 3 grades is 92.333333. 1. The grade of 78.000000 is < the average. 2. The grade of 99.000000 is >= the average. 3. The grade of 100.000000 is >= the average. Freed 40 bytes from the heap at 0x1c82010. total heap usage: 1 allocs, 1 frees, 40 bytes allocated ./proj2.out Enter a list of grades below where each grade is separated by a newline character. After the last grade is entered, enter a negative value to end the list. 92.3 Allocated 40 bytes to the heap at 0x104c010. Stored 92.300000 in the heap at 0x104c010. 88.7 Stored 88.700000 in the heap at 0x104c018. 56 Stored 56.000000 in the heap at 0x104c020. 78 Stored 78.000000 in the heap at 0x104c028. 45.7 Stored 45.700000 in the heap at 0x104c030. Stored 5 grades (40 bytes) to the heap at 0x104c010. Heap at 0x104c010 is full. Allocated 80 bytes to the heap at 0x104c040. Copied 5 grades from 0x104c010 to 0x104c040. Freed 40 bytes from the heap at 0x104c010. 100.00 Stored 100.000000 in the heap at 0x104c068. -5.6 The average of 6 grades is 76.783333. 1. The grade of 92.300000 is >= the average. 2. The grade of 88.700000 is >= the average. 3. The grade of 56.000000 is < the average. 4. The grade of 78.000000 is >= the average. 5. The grade of 45.700000 is < the average. 6. The grade of 100.000000 is >= the average. Freed 80 bytes from the heap at 0x104c040. total heap usage: 2 allocs, 2 frees, 120 bytes allocated ./proj2.out Enter a list of grades below where each grade is separated by a newline character. 5 After the last grade is entered, enter a negative value to end the list. 99.2 Allocated 40 bytes to the heap at 0x85a010. Stored 99.200000 in the heap at 0x85a010. 88.3 Stored 88.300000 in the heap at 0x85a018. 45.3 Stored 45.300000 in the heap at 0x85a020. 0 Stored 0.000000 in the heap at 0x85a028. 0 Stored 0.000000 in the heap at 0x85a030. Stored 5 grades (40 bytes) to the heap at 0x85a010. Heap at 0x85a010 is full. Allocated 80 bytes to the heap at 0x85a040. Copied 5 grades from 0x85a010 to 0x85a040. Freed 40 bytes from the heap at 0x85a010. 72.5 Stored 72.500000 in the heap at 0x85a068. 98.3 Stored 98.300000 in the heap at 0x85a070. 44.5 Stored 44.500000 in the heap at 0x85a078. 0 Stored 0.000000 in the heap at 0x85a080. 0 Stored 0.000000 in the heap at 0x85a088. Stored 10 grades (80 bytes) to the heap at 0x85a040. Heap at 0x85a040 is full. Allocated 120 bytes to the heap at 0x85a0a0. Copied 10 grades from 0x85a040 to 0x85a0a0. Freed 80 bytes from the heap at 0x85a040. 43.7 Stored 43.700000 in the heap at 0x85a0f0. 56.3 Stored 56.300000 in the heap at 0x85a0f8. 0 Stored 0.000000 in the heap at 0x85a100. -2 The average of 13 grades is 42.161538. 1. The grade of 99.200000 is >= the average. 2. The grade of 88.300000 is >= the average. 3. The grade of 45.300000 is >= the average. 4. The grade of 0.000000 is < the average. 5. The grade of 0.000000 is < the average. 6. The grade of 72.500000 is >= the average. 7. The grade of 98.300000 is >= the average. 8. The grade of 44.500000 is >= the average. 9. The grade of 0.000000 is < the average. 10. The grade of 0.000000 is < the average. 11. The grade of 43.700000 is >= the average. 12. The grade of 56.300000 is >= the average. 13. The grade of 0.000000 is < the average. Freed 120 bytes from the heap at 0x85a0a0. total heap usage: 3 allocs, 3 frees, 240 bytes allocated ./proj2.out < input1.txt > output1.txt; tail output1.txt; 6 98. The grade of 90.758400 is >= the average. 99. The grade of 34.443700 is < the average. 100. The grade of 73.924500 is >= the average. 101. The grade of 79.194500 is >= the average. 102. The grade of 3.167200 is < the average. 103. The grade of 56.274300 is >= the average. 104. The grade of 65.125000 is >= the average. 105. The grade of 40.944500 is < the average. Freed 880 bytes from the heap at 0x1172360. total heap usage: 22 allocs, 22 frees, 10120 bytes allocated valgrind ./proj2.out < input1.txt |& grep ’total’ total heap usage: 22 allocs, 22 frees, 10120 bytes allocated ==21413== total heap usage: 22 allocs, 22 frees, 10,120 bytes allocated ./proj2.out < input2.txt > output2.txt; tail output2.txt; 28102. The grade of 2.828200 is < the average. 28103. The grade of 56.698800 is >= the average. 28104. The grade of 38.142200 is < the average. 28105. The grade of 6.610100 is < the average. 28106. The grade of 24.604700 is < the average. 28107. The grade of 89.410300 is >= the average. 28108. The grade of 90.594200 is >= the average. 28109. The grade of 83.110400 is >= the average. Freed 224880 bytes from the heap at 0x11c3010. total heap usage: 5622 allocs, 5622 frees, 632250120 bytes allocated valgrind ./proj2.out < input2.txt |& grep ’total’ total heap usage: 5622 allocs, 5622 frees, 632250120 bytes allocated ==23105== total heap usage: 5,622 allocs, 5,622 frees, 632,250,120 bytes allocated

$25.00 View

[SOLVED] Csci 1730 project 3 differences in files using system calls learning

The goal of this project is to give you system programming experience with four file I/O system calls (open, close, read, and write), UNIX file permissions, and dynamic memory allocation and deallocation in C. In this project, you will implement a C program that reads in the contents of two input files. The program will then compare the two files, byte-by-byte, write differences into two output files, and output timings for the program’s two main steps as stated in the project’s requirements. Project Requirements Your program must adhere to all requirements stated in this document. 1. Write a C program that compares two input text files and writes every byte in file one that is different from file two into a third file named differencesFoundInFile1.txt and every byte that is different in file two from file one into a fourth file named differencesFoundInFile2.txt. If differencesFoundInFile1.txt or differencesFoundInFile2.txt exists in the present working directory, then your program should overwrite the file(s) with new output (do not append to these files). If these output files do not exist in the present working directory, then your program should create these files and assign both of them read and write permissions to the owner. The C source code must be implemented in a single file called proj3.c and it must compile with our provided Makefile to create an executable called proj3.out. You cannot alter the Makefile provided. Place all files for this project in the same directory. Your program must use the system calls open, close, read, and write. Your program may use stat and printf, but it CANNOT use any other file I/O functions than those aforementioned. 2. Your program must complete the project requirement 1 in two different steps as indicated below. Step 1: Compare input files one and two. This should be done by accessing 1 byte at a time from each of the files (use buffers of size 2: one byte to read and the other byte for a null character), comparing them, and writing any byte from file one that is not equal to the corresponding byte in file two into the file called differencesFoundInFile1.txt. This entire step should be implemented as a function called step1, and step1 should be called by your program’s main function. Step 2: Compare input files one and two. You will read both of the files into two dynamically allocated arrays. The input arrays should be allocated to be the exact size needed since we don’t want to waste RAM. You will then compare the two arrays and write any byte from file two that is not equal to the corresponding byte in file one into a third array (also dynamically allocated), and then copy that third array into a file called differencesFoundInFile2.txt. This entire step should be implemented as a function called step2, and step2 should be called by your program’s main function. 1 3. For each of the two steps in requirement 2, you will time how long the entire step takes to complete inside your program, and then output the two times to the command line when your program is finished (use gettimeofday()). In your README.txt file include the typical information as you did in previous projects and explain why the two times are different (if they are different). If they are not different, then explain why the two different steps results in the same times. Note: you will have to run larger input files to see a significant increase in the time the steps will take. 4. All arrays must be dynamically allocated and freed (with malloc/calloc and free). Programs that fail to do this will be penalized. Run valgrind to check for memory leaks. Your program should not contain any memory leaks. Your program must make at least one call to either malloc or calloc and at least one call to free. 5. Your program should be robust and include appropriate error checks. If there is an error reading a file, then your program should print (to standard output) “There was an error reading a file.” If there is an error writing to a file, then your program should print (to standard output) “There was an error writing to a file.” If there aren’t enough command line arguments (or too many), then print the “Usage” message shown in the Examples section. After an error message is printed, then your program should terminate gracefully as discussed in lecture class. 6. You may ONLY use the following #include statements in your proj3.c. The use of any additional #include statements or source code copied/pasted (or included in your source code in any other way) from other libraries than those mentioned below will result in a failing grade on this project. (a) #include (b) #include (c) #include (d) #include (e) #include (f) #include (g) #include 7. You may implement additional C functions and call upon these C functions that you implemented as needed to complete this project. 8. Do not use any global variables. Do not use any global pointers. Violating any one of these rules will result in a grade of zero on this assignment. 9. Do not use any static variables. Do not use any static pointers. Violating any one of these rules will result in a grade of zero on this assignment. 10. If you encounter any runtime or logic errors while implementing your project, then use GDB to debug your program. 11. Your final program’s executable, proj3.out, must have I/O that matches the examples exactly except for the timing output, which will vary each time your program is executed. Also, your program must correctly create (or overwrite) the two files (with read and write permissions for the owner) as aforementioned. Failure to follow the I/O provided in the Examples section may result in a failing grade for this project. Coding Style Requirements 1. All functions must be commented. Comments must include a brief description of what the function does, its input(s), its output, and any assumptions associated with calling it. If your function has a prototype and an implementation separated into different parts of your source code, then you only need to put the comments for that function above its prototype (there is no need to comment both the prototype and implementation; commenting the prototype is sufficient). 2. All structs, unions, and enums must be commented. 3. All identifiers must be named well to denote their functionality. Badly named identifiers are not allowed. For example, identifiers like a, aaa, b, bbb, bbbb are bad names for identifiers. 4. Every line of source code must be indented properly and consistently. 2 README.txt File Requirements Make sure to include a README.txt file (use a .txt file extension) that includes the following information presented in a reasonably formatted way: ˆ Your First and Last Name (as they appear on eLC) and your 810/811# ˆ Instructions on how to compile and run your program. Since we are using a Makefile for this assignment, then these instructions should pretty simple based on the provided Makefile. ˆ Explain why or why not the times for step 1 and step 2 are different as aforementioned. Examples The I/O of your final program must match the examples except for the timings, which will vary each time your program is executed. The input files can be found on eLC in examples.tar.gz. The entire file, examples.tar.gz, should be uploaded to your odin account, and its contents should be extracted using the tar command below on odin. tar -xvf examples.tar.gz The first line of each example contains one or more commands (separated by a ; for multiple commands), and your program should produce the correct output along with the two output files mentioned in the project’s requirements. You must check that all characters and character counts matches these examples exactly (otherwise, you may fail this project). ./proj3.out Usage: proj3.out ./proj3.out input1.txt Usage: proj3.out ./proj3.out a b There was an error reading a file. ./proj3.out input1.txt input2.txt; cat differencesFoundInFile1.txt differencesFoundInFile2.txt; Step 1 took 0.038000 milliseconds Step 2 took 0.018000 milliseconds cat!dog. ./proj3.out input1.txt input2.txt; cat differencesFoundInFile1.txt differencesFoundInFile2.txt | wc -c; Step 1 took 0.066000 milliseconds Step 2 took 0.040000 milliseconds 8 ./proj3.out input3.txt input4.txt; cat differencesFoundInFile1.txt differencesFoundInFile2.txt; Step 1 took 0.034000 milliseconds Step 2 took 0.016000 milliseconds aaaaa b ./proj3.out input3.txt input4.txt; cat differencesFoundInFile1.txt differencesFoundInFile2.txt | wc -c; Step 1 took 0.056000 milliseconds Step 2 took 0.017000 milliseconds 8 ./proj3.out input5.txt input6.txt; cat differencesFoundInFile1.txt differencesFoundInFile2.txt; Step 1 took 0.027000 milliseconds Step 2 took 0.039000 milliseconds a bbbbbb 3 ./proj3.out input5.txt input6.txt; cat differencesFoundInFile1.txt differencesFoundInFile2.txt | wc -c; Step 1 took 0.026000 milliseconds Step 2 took 0.016000 milliseconds 9 ./proj3.out alice1.txt alice2.txt; cat differencesFoundInFile1.txt differencesFoundInFile2.txt; Step 1 took 113.053000 milliseconds Step 2 took 0.724000 milliseconds showingAliceBender*Zoey! ./proj3.out alice1.txt alice2.txt; cat differencesFoundInFile1.txt differencesFoundInFile2.txt | wc -c; Step 1 took 113.401000 milliseconds Step 2 took 0.784000 milliseconds 24 ./proj3.out alice1.txt alice1.txt; cat differencesFoundInFile1.txt differencesFoundInFile2.txt | wc -c; Step 1 took 114.963000 milliseconds Step 2 took 0.646000 milliseconds 0 Submission Submit your files before the due date and due time stated on eLC. Submit your files on eLC under the Assignment named Project 3. Submit only the following files. 1. All source files required for this assignment: proj3.c 2. A README.txt file filled out correctly Do not submit any compiled code. Also, do not submit any zipped files or directories. Do not submit a Makefile. We will use our own, unmodified copy of the provided Makefile to compile your program. We only need the files mentioned above with the file extensions aforementioned. 1 Grading (30 points) If your program does not compile on odin using the provided Makefile and using the required compiler for this course (gcc version 11.2.0), then you’ll receive a grade of zero for this assignment. Otherwise, your program will be graded using the criteria below. Program runs correctly with various test cases on odin 30 points README.txt file missing or incorrect in some way -3 points Not submitting to the correct Assignment on eLC -3 points Late penalty for submitting 0 hours to 24 hours late -6 points One or more compiler warnings -6 points Not adhering to one or more coding style requirements -6 points Valgrind identifies a memory leak (definitely, indirectly, or possibly lost) -6 points Source code contains an unauthorized include statement -30 points Source code contains an unauthorized file I/O function call -30 points Source code contains a global variable or global pointer -30 points Source code contains a static variable or static pointer -30 points Penalty for not following instructions (invalid I/O, etc.) Penalty decided by grader You must test, test, and retest your code to make sure it compiles and runs correctly on odin with any given set of inputs. This means that you need to create many examples on your own (that are different than the aforementioned examples) to ensure you have a correctly working program. Your program’s I/O must match the examples given in the Examples section except for the timings, which will vary each time your program is executed. You may NOT assume inputs will be valid.

$25.00 View

[SOLVED] Computer science 1081 – assignment #12

Program #1 (worth 300 points) Follow the following steps to produce a program that writes out to multiple files, including in binary. 1. Create a structure definition with the tag “studentInfo” for a struct that will store the following g data: a. Name: char array, 100 characters (one of which is the null terminator) b. Age: integer c. GPA: double d. Grade: char 2. Create an array of 4 students and initialize the array with data 3. Write the data from the structure array to a text file called “studentsOutput.txt” a. You should write out the data in the following format: age+““ +gpa+““+grade+““+name+“ ” 4. Create a different text file called “studentsIn.txt” with 8 students, create data in a similar format to your studentsOutput.txt file (the data should be different, but use the same format) 5. Read the “studentsIn.txt” file into a second array. Display the contents of the array to the screen (please choose a method of displaying the student data that is formatted nicely for the user) 6. Write the data from your second array to a file called “studentsOutput.bin”, in binary mode. You should write out the array one element at a time. You should not write out the structure one field at a time (like you did for the text file), but instead the entire structure all at once. 7. Read the data from your “studentsOutput.bin” file into a third array (to verify that you wrote it out in a way that is readable). Programmatically compare the contents of the two arrays (loop for each element, checking that all of the fields are the same), and report whether the results were the same to the screen (for example: “Save file was successfully validated”) NOTE: do not use a string datatype in your struct definition, make sure you use a char array NOTE: use 3 digits of precision for the GPA in the text file

$25.00 View

[SOLVED] Computer science 1081 – assignment #11

Program #1 Write a program that uses a structure to pass around Movie Data information. Your program will have a function that prints all of the information about the structure, which will be called from your main function. Your main function will create two Movie Data variables, initializing them before calling the display function (one call per variable). One of your variables will be initialized using an initialization list, while the other will be initialized member by member. Please name the fields of your structure: title, director, year, and runtime. Please name your structure movieData, and the name of your display function displayMovie. Pass your structure to your function by constant reference parameter. You may use 2 movies of your choice to fill the data for the variables. Sample Outputs: Title Director Released Running Time: 88 minutes : War of the Worlds : Byron Haskin : 1953 Title Director Released Running Time: 118 minutes Press any key to continue . . . : War of the Worlds : Stephen Spielberg : 2005 Program #2 Write a program that stores information about 12 players in an array of structures. The structure (player) will contain 3 member fields: name, number, and points. When your program runs, it should call a function that will prompt the user to enter data for each of the fields for each of the 12 players. The function should take a reference parameter. Your program will then display a table of all of the players, and total points for the team. The number and name of the player who earned the most points should also be displayed. Sample Outputs: PLAYER ——— Player’s name: Ella Player’s number: 23 Points scored: 53 PLAYER ——— Player’s name: John Player’s number: 13 Points scored: 32 PLAYER ——— Player’s name: James Player’s number: 42 Points scored: 13 PLAYER ——— Player’s name: Frankie Player’s number: 82 Points scored: 14 PLAYER ——— Player’s name: Lindsey Player’s number: 84 Points scored: 24 PLAYER ——— Player’s name: Gabriel Player’s number: 46 Points scored: 24 PLAYER ——— Player’s name: Ruth Player’s number: 62 Points scored: 34 PLAYER ——— Player’s name: Fred Player’s number: 73 Points scored: 9 PLAYER ——— Player’s name: Molly Player’s number: 47 Points scored: 32 PLAYER ——— Player’s name: Nick Player’s number: 99 Points scored: 11 PLAYER ———Player’s name: Karen Player’s number: 96 Points scored: 23 PLAYER ——— Player’s name: Terry Player’s number: 44 Points scored: 6 NAME Ella John James Frankie Lindsey Gabriel Ruth Fred Molly Nick Karen Terry NUMBER PTS SCRD 23 53 13 32 42 13 82 14 84 24 46 24 62 34 73 9 47 32 99 11 96 23 44 6 TOTAL POINTS: 275 The player who scored the most points is: Ella #23 Press any key to continue . . .Program #3 Write a program that calculates pay for either an hourly paid worker, or a salaried worker. Hourly workers will have a pay rate and hours worked, while salaried worker will have a salary and bonus. The program should create a structure that works for both of these types of workers. The program should ask the user what type of worker they have information for, followed by questions related to the specific type of worker. You will create a function that will handle getting the input for the specific type of worker, using a reference parameter (getHourly & getSalaried). You will then call a print function that will use the information in the structure to print a report for that worker (call the function printWorker and use a const reference parameter). The structure definition name should contain the word “worker”. It will contain an enum, a double (for the gross pay), and a union of two sub-structures. The sub-structures will each have 2 fields, relating to the hourly and salaried data points. One sub-structure will be the hourly data; the other will be the salaried data. I highly recommend the idea of nesting the structs and unions in a single definition. You can think of the outer struct as containing information that is common to all variations of the full structure, while also having a union for the features that are unique to each variation (those features possibly needing to be groups themselves into structures if the variation has more than one unique feature). The question you then have for yourself is how you tell which part of the union to use when interacting with the structure variable – the answer to that lies with the enum datatype, where you can define a structure member (in the outer structure) that is a datatype of an enum with values for each of the variations. You then set which variation your variable represents in the enum member, and utilize that variation’s fields in the union. All while being able to reference these different variations with a single structure name. Sample Outputs: (H)ourly or (S)alaried? S Enter the salary amount: 23058 Enter the bonus amount: 3802 Salaried Worker Salary: $23058.00 Bonus: $3802.00 ———- Gross Pay: $26860.00 Press any key to continue . . . ==================================== (H)ourly or (S)alaried? H Enter the number of hours worked: 39 Enter the hourly pay rate: 14.83 Hourly Worker Hours: 39 Rate: $14.83 ———- Gross Pay: $578.37

$25.00 View

[SOLVED] Computer science 1081 – assignment #10

Program #1 Rewrite the following function to use pointers instead of reference variables. Write a main function that asks the user for 2 integer values, and then prints the result of the function call, as well as the ending values for the user’s inputs. int doSomething(int &x, int &y) { int temp = x; x = y * 10; y = temp * 10; return x + y; } Sample Outputs: Please enter a value for x: 7 Please enter a value for y: 8 The result of the function was: 150 x’s current value is 80 y’s current value is 70 Press any key to continue . .. Program #2 Write a function that accepts an integer array and size as arguments. The function should create a copy of the array, except that the elements should be reversed in the copy. The function should return a pointer to the new array (i.e. return the array itself). In the main function, you should ask the user how big the array will be, create the first array, and then fill the array with values from the user Sample Outputs: Enter the size of the array: 4 Enter Value 1: 1 Enter Value 2: 2 Enter Value 3: 3 Enter Value 4: 4 The reversed array is: [4, 3, 2, 1] The original array is: [1, 2, 3, 4] Press any key to continue . ..Program #3 Write a function that accepts an integer array and size as arguments. The function should create a new array that is twice the size of the first array. The function should copy the contents of the first array to the new array and initialize the unused elements of the second array with zeros. The function should return a pointer to the new array (i.e. the array itself) In the main function, you should ask the user how big the array will be, create the first array, and then fill the array with values from the user Sample Outputs: Enter the size of the array: 6 Enter Value 1: 1 Enter Value 2: 2 Enter Value 3: 3 Enter Value 4: 4 Enter Value 5: 5 Enter Value 6: 6 The expanded array is: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0] The original array is: [1, 2, 3, 4, 5, 6] Press any key to continue . ..

$25.00 View

[SOLVED] Computer science 1081 – assignment #09

Program #1 (worth 200 points) Write a program that prompts the user for values to fill a 4×5 array (matrix). Create a menu driven program within a loop that prompts the user if they want to: display the total of all of the cells in the matrix ; get the average of all of the cells in the matrix ; get the total of a specific row (prompt for which row) ; get the total of any column (prompt for the column) ; get the highest value in a row (prompt for which row). Include an “Exit” option in the menu. Continue to prompt the user for menu actions until they select the “Exit” option. Perform needed error checking. The program should have the following functions: int getTotal – takes a two-dimensional array, and returns the total of all the values double getAverage – takes a two-dimensional array, and returns the average of all of the values int getRowTotal – takes a two-dimensional array and integer, returns the total of the row in the array corresponding to the integer value int getColumnTotal – takes a two-dimensional array and integer, returns the total of the column in the array corresponding to the integer value int getHighestInRow – takes a two-dimensional array and integer, returns the highest value in the row of the array, corresponding to the integer value int getLowestInRow – takes a two-dimensional array and integer, returns the lowest value in the row of the array, corresponding to the integer value.Program #2 Write a program utilizes three integer variables, and three functions. The first function (getValues) should get a value from the user, and store it in the parameter, for each parameter. The second function (doubleValues) should double the value stored in each parameter. The third function (displayValues) should display each parameter. For all of the parameter, you will either use pass by value, or a pointer. You will not use reference parameters in this program. Note that not all three functions in this program will require pointers, only use the pointers where you need them in order to complete the task. Sample Outputs: Enter an integer: 5 Enter an integer: 4 Enter an integer: 3 The values doubled are: 10, 8, 6 Press any key to continue . . .

$25.00 View

[SOLVED] Computer science 1081 – assignment #07

Program #1: Write a program that uses a function displayMenu to display the following menu: Math Program: 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers 5. Quit When the user selects one of the options, the program will prompt them to input two numbers. It will then pass these numbers to a function, which will do the calculation and return the desired result. • There should be one function for each of the four non-quit menu options. The program will then output the correct answer. • The function names should be named in a way that corresponds to their action (add, subtract, multiply, and divide). • All of these functions should accept two floating point numbers, and return a floating point number. • Display all results to 2 significant digits. • All input and output with the user should be done in the main function. 1. The user is expected to input both numbers at the same time • The program should loop until the user selects option 5 (Quit), and should be notified if they do not pick an option between 1 and 5. Sample Output: Math Program: 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers 5. Quit Choice: 0 You must choose between 1 and 5! Math Program: 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers 5. Quit Choice: 2 Please enter two numbers: 4.5815 5.8481 The numbers subtracted are -1.27 Math Program: 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers 5. Quit Choice: 3 Please enter two numbers: 8 2 The numbers multiplied are 16.00 Math Program: 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers 5. Quit Choice: 5 Thanks for using the program! Press any key to continue . . .Program #2 Create a function repchar(char ch, int n) that has two default arguments. • You can define the default arguments in either the function prototype or the function definition (if you do not use a prototype for your function) • The function will display the character in ch, n number of times. Use ‘*’ as the default argument for ch and 45 as the default argument for n. • Call repchar three times in the main function as follows: 1. With no arguments 2. ‘=’ as the single argument 3. ‘+’ and 30 as the arguments • Do not print anything else from your function. Sample Output: ********************************************* ============================================= ++++++++++++++++++++++++++++++ Press any key to continue . . .Program #3 Create three defintions for an overloaded function repchar(). • Call each of the repchar definitions as follows: 1. repchar(); 2. repchar(‘=’); 3. repchar(‘+’, 30); • This program will be different from Program 2, as you will not use any default arguments, and will instead overload the function repchar three times. Sample Output: ********************************************* ============================================= ++++++++++++++++++++++++++++++ Press any key to continue . . .Program #4 Write a program that calculates the average of a group of test scores, where the lowest score in the group is dropped. It should use the following functions: – Void getScore() should ask the user for a test score, store it in a reference parameter variable, and validate it. This function should be called by main once for each of the five scores to be entered. – Void calcAverage() should calculate and display the average of the four highest scores. This function should be called just once by main and should be passed the five scores. – Int findLowest() should find and return the lowest of the five scores passed to it. It should be called by calcAverage, which uses the function to determine which of the five scores to drop. • The main function should define five variables, call getScore for each variable, call calcAverage passing all five variables, and exit • calcAverage should call findLowest • findLowest should return the value of the score to be dropped o You can then use this information to adjust the total score before averaging • Do not accept scores lower than 0 or higher than 100 o Loop until the user complies • Display the average to 3 significant digits Sample Outputs: Enter a test score: 81 Enter a test score: 95 Enter a test score: 73 Enter a test score: 88 Enter a test score: 94 After dropping the lowest score, the test average is 89 Press any key to continue . . . Enter a test score: -151 Enter a test score between 0 and 100: 51 Enter a test score: 151 Enter a test score between 0 and 100: 54 Enter a test score: 65 Enter a test score: 35 Enter a test score: 75 After dropping the lowest score, the test average is 61 Press any key to continue . . .

$25.00 View

[SOLVED] Computer science 1081 – assignment #08

Program #1 Write a program that lets the user enter 10 values into an array. The program should then display the largest and smallest values stored in the array. • Values should be stored in an array • Do not find the highest and lowest as the user enters data, instead find the highest and lowest values after all 10 values are entered by the user. • Consider using a function to get the input from the user (to make your main function easier to read) Sample Output: This program will ask you to enter ten values, then it will determine the largest and smallest of the values you entered. Enter an integer value: 1 Enter an integer value: 2 Enter an integer value: 3 Enter an integer value: 4 Enter an integer value: 5 Enter an integer value: 6 Enter an integer value: 7 Enter an integer value: 8 Enter an integer value: 9 Enter an integer value: 10 The largest value entered is 10 The smallest value entered is 1 Press any key to continue . . .Program #2 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. Do not accept negative numbers for monthly rainfall figures. • Use an array of doubles • Display values to 2 decimal places • Input validation not required (but make sure you accept doubles) • Do not do calculations for the ending analysis until all of the data has been entered. • Use functions to perform the various analysis on the array o Pass the array, and its size as parameters o Return the calculated result o This will help make your program modular, and easier to read. o Use the following names: getTotal, getAverage, getLargest, getSmallest Sample Output: Enter the rainfall (in inches) for month #1: 1 Enter the rainfall (in inches) for month #2: 2 Enter the rainfall (in inches) for month #3: 3 Enter the rainfall (in inches) for month #4: 1 Enter the rainfall (in inches) for month #5: 2 Enter the rainfall (in inches) for month #6: 3 Enter the rainfall (in inches) for month #7: 1 Enter the rainfall (in inches) for month #8: 2 Enter the rainfall (in inches) for month #9: 3 Enter the rainfall (in inches) for month #10: 1 Enter the rainfall (in inches) for month #11: 2 Enter the rainfall (in inches) for month #12: 3 The total rainfall for the year is 24.00 inches. The average rainfall for the year is 2.00 inches. The largest amount of rainfall was 3.00 inches. The smallest amount of rainfall was 1.00 inches. Press any key to continue . . .Program #3 Write a program that asks the user for the hours worked and pay rate for a predefined set of employee id numbers. After collecting this information, the program will calculate the wages for each employee and display the results in a table format. Your program will utilize 4 parallel arrays in order to achieve its goals: • empId: an array of long integers to hold the employee’s id number. Will be initialized with { 5658845, 4520125, 7895122, 8451277, 1302850, 7580489 } • hours: an array of integers to hold the number of hours worked by each employee • payRate: an array of real numbers to hold the pay rate for each employee • wages: an array of real numbers to hold the calculated wages for each employeeSample Outputs: Enter the requested information for each employee Employee #5658845 Hours worked: 24 Pay Rate: $12.54 Employee #4520125 Hours worked: 40 Pay Rate: $13.7 Employee #7895122 Hours worked: 37 Pay Rate: $16.84 Employee #8451277 Hours worked: 40 Pay Rate: $17.50 Employee #1302850 Hours worked: 35 Pay Rate: $22.45 Employee #7580489 Hours worked: 37 Pay Rate: $17.32 ——————————— Employee Wages ——————————— Employee #5658845 $ 300.96 Employee #4520125 $ 548.00 Employee #7895122 $ 623.08 Employee #8451277 $ 700.00 Employee #1302850 $ 785.75 Employee #7580489 $ 640.84 Press any key to continue . . .

$25.00 View

[SOLVED] Computer science 1081 – assignment #06

Program #1 Download the “Random.txt” file (file name may differ). This file contains a long list of random numbers. Copy the file to your hard drive, place it in the same folder as the CPP file you are coding (inside the solution folder) and then write a program that opens the file, reads all the numbers from the file, and calculates the following: A) The number of numbers in the file B) The sum of all the numbers in the file (a running total) C) The average of all the numbers in the file. The program should display the number of numbers found in the file, the sum of the numbers, and the average of the numbers. • You will need a text file called “Random.txt” to complete this program. You can download it from D2L. Save it in the same directory as your source file. • Make sure you test for a successful file open operation, if it fails to open, display an error message – if you have trouble getting your program to open the file, please email me • Use a constant to refer to the file location. Sample Output (values may differ from actual results for this particular random file): Number of numbers: 201 Sum of the numbers: 106042 Average of the numbers: 527.572 Press any key to continue . . . Program #2 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 item’s wholesale cost is 5.00 and its markup percentage is 100%, then the item’s retail price is 10.00. If the item’s wholesale cost is 5.00 and its markup percentage is 50% , then the item’s retail price is 7.50. The program should have a function named calculateRetail that receives the wholesale cost and markup percentage as arguments and returns the retail price of the item. Do not accept negative values for either the wholesale cost of the item or the markup percentage. • The calculateRetail function should not print anything to cout, instead it returns the value and the main-function does the printing Sample Output: Enter the item’s wholesale cost: 14.25 Enter the item’s markup percentage: 95 The item’s retail price is $27.79 Press any key to continue . . .Program #3 When an object is falling because of gravity, the following formula can be used to determine the distance the object falls in a specific time period: d = (1/2)gt^2. The variables in the formula are as follows: d is the distance in meters, g is 9.8, and t is the amount of time, in seconds, that the object has been falling. Write a function named fallingDistance that accepts an object’s falling time (in seconds) as an argument. The function should return the distance, in meters, that the object has fallen during that time interval. Write a program that demonstrates the function by calling it in a loop that passes the values 1 through 10 as arguments and displays the return value. • Display two significant digits for the distance fallen (i.e. 17.00, not 17) • Do not print data from the fallingDistance function, only return a value. Sample Output: Seconds Distance =============================== 1 2 3 4 5 6 7 8 9 4.90 meters 19.60 meters 44.10 meters 78.40 meters 122.50 meters 176.40 meters 240.10 meters 313.60 meters 396.90 meters 490.00 meters 10 Press any key to continue . . .Program #4 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 and then simulates the tossing of the coin that number of times. • The coinToss function is a non-returning function, thus you should print the result of the coin toss from the function itself • Use the C++ Random Number Generator o Generates a random number between 0 and 32767. o You have to seed the generator before using it. A good seed value is the current time. Use the following code to seed your generator. unsigned seed = time(0); srand(seed); o To generate a random number, between 1 and 2, use the expression number = 1 + rand() % 2; o You will need to include the following header files: #include #include Sample Output: How many tosses should I make? 7 1: tails 2: heads 3: heads 4: heads 5: tails 6: heads 7: heads Press any key to continue . . .

$25.00 View

[SOLVED] Computer science 1081 – assignment #05

Program #1 & #2 (NOTE: TWO DIFFERENT PROGRAMS) The distance a vehicle travels can be calculated as follows: distance = speed * time. For example, if a train travels 40 miles per hour for 3 hours, the distance traveled is 120 miles. Write a program that asks the user for the speed of a vehicle (in miles per hours) and how many hours it has traveled. The program should then use a loop to display the distance the vehicle has traveled for each hour of that time period. Do not accept a negative number for speed and do not accept any value less than 1 for time traveled. • Program #1: Write only using while loops • Program #2: Write only using do-while loops • Program should loop until the user enters correct data [INPUT VALIDATION] Sample Output: What is the speed of the vehicle in mph? 50 How many hours has it traveled? -4 How many hours has it traveled? 4 Hour Distance Traveled ——————————- 1 50 2 100 3 150 4 200 Press any key to continue . . . Program #3 Write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day and two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display the table showing how much the salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies. Do not accept a number less than 1 for the number of days worked. • Use a do-while loop for input validation • Use a for loop to calculate the pay increase and display the table Sample Output: For how many days will the pay double? 6 Day Total Pay ——————— 1 $ 0.01 2 $ 0.02 3 $ 0.04 4 $ 0.08 5 $ 0.16 6 $ 0.32 ——————— Total $ 0.63 Press any key to continue . . . Program #4 Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should first ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period. Do not accept a number less than 1 for the number of years. Do not accept negative number for the monthly rainfall. • Input validation not required • Only use for loops and nested loops for computation • Use a const for the number of months in the year. (for ease of testing interactively, consider a calendar with only 4 months in a year, your program should be able to work by just changing this constant) Sample Output: This program will calculate average rainfall over a period of years. How many years do you wish to average? 2 Year 1 Number of inches of rain for month 1? 4 Number of inches of rain for month 2? 5 Number of inches of rain for month 3? 6 Number of inches of rain for month 4? 7 Number of inches of rain for month 5? 8 Number of inches of rain for month 6? 9 Number of inches of rain for month 7? 1 Number of inches of rain for month 8? 2 Number of inches of rain for month 9? 3 Number of inches of rain for month 10? 4 Number of inches of rain for month 11? 5 Number of inches of rain for month 12? 6 Year 2 Number of inches of rain for month 1? 7 Number of inches of rain for month 2? 8 Number of inches of rain for month 3? 9 Number of inches of rain for month 4? 4 Number of inches of rain for month 5? 5 Number of inches of rain for month 6? 6 Number of inches of rain for month 7? 7 Number of inches of rain for month 8? 8 Number of inches of rain for month 9? 9 Number of inches of rain for month 10? 1 Number of inches of rain for month 11? 2 Number of inches of rain for month 12? 3 Over a period of 24 months, 129 inches of rain fell. Average monthly rainfall for the period is 5.375 inches. Press any key to continue . . .

$25.00 View

[SOLVED] Computer science 1081 – assignment #04

Program #1 Write a program that asks the user to enter a number within the range of 1 through 10. Use a switch statement to display the Roman numeral version of that number. Do not accept a number less than 1 or greater than 10. • Use a switch statement • Make sure that you tell the user if their input is not accepted Sample Outputs: Enter a number (1-10): 5 The Roman numeral version of 5 is V Press any key to continue . . . ======================================== Enter a number (1-10): 15 Enter a number in the range 1 through 10 Press any key to continue . . . Program #2 A software company sells a package that retails for $99. Quantity discounts are given according to the following table: Quantity Discount 10-19 20% 20-49 30% 50-99 40% 100 or more 50% Write a program that asks for the number of units sold and computes the total cost of the purchase. Make sure the number of units is greater than 0. • Use only the if statement, don’t use a switch or else block • Note: the auto-checker on this program does take some time (a few seconds on the college’s computers) to process the code checks Sample Outputs: How many units were sold? 48 The total cost of the purchase is $3326.40 Press any key to continue . . . ======================================== How many units were sold? -1 Error: Units sold must be positive integer Press any key to continue . . . Test the boundaries: does the result match expectations when you are 1 unit below, and 1 unit above the threshold (e.g. Quantity 9 and 10, getting the correct discount values) Program #3 A bank charges $10 per month plus the following check fees for a commercial checking account: $0.10 each for fewer than 20 checks $0.08 each for 20-39 checks $0.06 each for 40-59 checks $0.04 each for 60 or more checks The bank also charges an extra $15 if the balance of the account falls below $400 (before any check fees are applied). Write a program that asks for the beginning balance and the number of checks written. Compute and display the bank’s service fees for the month. Do not accept a negative value for the number of checks written. If a negative value is given for the beginning balance, display and urgent message indicating the account is overdrawn. • Use only the if statement • No message needs to be displayed if the account balance falls below the $400 threshold, just add the appropriate fee into the total. • For the overdrawn balance portion of the problem, determine if the fee will overdraw the account. However, display the message about overdrawing the account before displaying what the fees are. For example, if the account has $9.99 and the fees will total to $10, the account will be overdrawn. Sample Outputs: Enter the following information about your checking account Beginning balance: $1562 Number of checks written: 20 The bank fee this month is $11.60 Press any key to continue . . . ======================================== Enter the following information about your checking account Beginning balance: $10 Number of checks written: 2 Your account is overdrawn! The bank fee this month is $25.20 Press any key to continue . . . Program #4 Write a program that displays the following menu (see below). – If the user enters 1, the program should ask for the radius of the circle and then display its area. Use the formula area = pi*r^2. Use 3.14159 for pi and the radius of the circle for r. – If the user enters 2, the program should ask for the length and width of the rectangle and then display he rectangle’s area. Use the formula area = length * width. – If the user enters 3, the program should ask for the length of the triangle’s base and its height, and then display is area. Use the formula area = base * height * (1/2). – If the user enters 4, the program should end – Display an error message if the user enters a number outside the range of 1 through 4 when selecting an item from the menu. Do not accept negative values for the circle’s radius, the rectangle’s length or width, or the triangle’s base or height. • Use a switch statement to evaluate the user menu choice • Do input validation for the correct menu choice • Define Pi as a constant to 5 decimal places (3.14159) Sample Outputs: Geometry Calculator 1. Calculate the Area of a Circle 2. Calculate the Area of a Rectangle 3. Calculate the Area of a Triangle 4. Quit Enter your choice (1-4): 1 Enter the Radius: 5 The area is: 78.5397 Press any key to continue . . . Geometry Calculator 1. Calculate the Area of a Circle 2. Calculate the Area of a Rectangle 3. Calculate the Area of a Triangle 4. Quit Enter your choice (1-4): 2 Enter the length: 5 Enter the width: 4 The area is: 20 Press any key to continue . . . ======================================== Geometry Calculator 1. Calculate the Area of a Circle 2. Calculate the Area of a Rectangle 3. Calculate the Area of a Triangle 4. Quit Enter your choice (1-4): 3 Enter the base: 6 Enter the height: 4 The area is: 12 Press any key to continue . . . ======================================== Geometry Calculator 1. Calculate the Area of a Circle 2. Calculate the Area of a Rectangle 3. Calculate the Area of a Triangle 4. Quit Enter your choice (1-4): 4 Exiting Press any key to continue . . . ======================================== Geometry Calculator 1. Calculate the Area of a Circle 2. Calculate the Area of a Rectangle 3. Calculate the Area of a Triangle 4. Quit Enter your choice (1-4): 5 You must choose from the a listed option Press any key to continue . . .

$25.00 View

[SOLVED] Computer science 1081 – assignment #03

Program #1 A movie theater only keeps a percentage of the revenue earned from ticket sales. The remainder goes to the movie distributor. Write a program that calculates a theater’s gross and net box office profit for a night. The program should ask for the name of the movie, and how many adult and child tickets were sold. (The price of an adult ticket is $10.00 and a child’s ticket is $6.00). • Use constants for values that aren’t supplied by the user (such as the prices and profit margin) Sample Execution: Please enter the movie name: St. Patrick’s Revenge Please enter the number of adult tickets sold: 5621 Please enter the number of child tickets sold: 125 Movie Name: Adult Tickets Sold: Child Tickets Sold: Gross Box Office Profit: Net Box Office Profit: Amount Paid to Distributor: Press any key to continue . . . Things to Test/verify: “St. Patrick’s Revenge” 5621 125 $ 56960.00 $ 11392.00 $ 45568.00 – What happens if the movie name is more than a single word? – Are your outputs formatted for their units? – Did you use constants as specified?Program #2 A retail company must file a monthly sales tax report listing the sales for the month and the amount of sales tax collected. Write a program that asks for the month, the year, and the total amount collected at the cash register (that is, sales plus sales tax). Assume the state sales tax is 4 percent and the county sales tax is 2 percent. If the total amount collected is known and the total sales tax is 6 percent, the amount of product sales may be calculated as: S = (T/1.06). S is the product sales and T is the total income. • Display the year next to the month as shown in the example below • Use const for the tax rates Sample Execution: Please enter the Month: January Please enter the year: 2017 Please enter the total amount collected: $482 Month: January 2017 ——————– Total Collected: $ Sales: $ County Sales Tax: State Sales Tax: Total Sales Tax: Press any key to continue . . . Things to Test/verify: – What happens if the month name is more than a single word? – What happens if the year is not entered as an integer? – Are your outputs formatted for their units? – Did you use constants as specified? $ $ $ 482.00 454.72 9.09 18.19 27.28Program #3 Assuming there are no deposits other than the original investment, the balance in a savings account after one year may be calculated as: Amount = Principal * (1 + (Rate/T))^T. Principal is the balance in the savings account, Rate is the interest rate, and T is the number of times the interest is compounded during a year (T is 4 if the interest is compounded quarterly). Write a program that asks for the principal, the interest rate, and the number of times the interest is compounded. Sample Execution: Please enter the Principal Balance: $30284 Please enter the interest rate (as a decimal): 0.03 Please enter the number of times interest is compounded: 120 Interest Rate: Times Compounded: Principal: Interest: Amount in Savings: Press any key to continue . . . 3% 120 $ 30284.00 $ 922.17 $ 31206.17 Things to Test/verify: – Are your outputs formatted for their units? – What happens if the interest rate is a fractional (real) number?

$25.00 View

[SOLVED] Computer science 1081 – assignment #02

Program #1 Write a program that computes the tax and tip on a restaurant bill for a meal charge. The tax should be 6.75 percent of the meal cost. The tip should be 20 percent of the total after adding the tax. Display the meal cost, tax amount, tip amount, and total bill on the screen. • Use a const (constant) for the tax and tip rates (0.0675 and 0.2 respectively) • Ask the user for the cost of the meal Sample Output: Meal: $85.45 Tax: $5.76788 Tip: $18.2436 Total: $109.461 Press any key to continue . . . Test Cases to try and think about: • How does your program respond when the values entered are negative? • How does your program respond when the values entered are smaller than a penny?Program #2 You have been given a job as a programmer on a Cyborg supercomputer. In order to accomplish some calculations, you need to know how many bytes the following data types use: char, int, float, and double. You do not have any manuals, so you can’t look this information up. Write a C++ program that will determine the amount of memory used by these types and display the information on the screen. • Do not use any numeric literals; use the sizeof function to produce the correct sizes. Sample Output: char 1 int 4 float 4 double 8 Press any key to continue . . .Program #3 Kathryn bought 750 shares of stock at a price of $35.00 per share. She must pay her stockbroker a 2 percent commission for the transaction. Write a program that calculates and displays the following: The amount paid for the stock alone (without the commission); The amount of the commission; and the total amount paid (for the stock plus the commission). Generalize the program so that Kathryn can use it for other situations as well. • Have your program ask the user for the number of shares and the price per share • Use a const for the commission (0.02) Sample Output: Enter the number of shares: 25152 Enter the price per share: 12.5 Stock: $314400 Commission: $6288 Total: $320688 Press any key to continue . . . Test Cases to try and think about: • How does your program respond when the values entered are negative? • How does your program respond when the values entered are smaller than a penny? • Can you enter a fractional number of shares?

$25.00 View

[SOLVED] Computer science 1081 – assignment #01

Program #1 (Id: 165324) Enter Program 1-1 on page 9 of the textbook (also shown below). Do not change any of the string literals. Test the code with your own input samples to see if you can find any quirks in how the program interacts with the user.Program #2 (Id: 165435) Write a program that will ask the user to enter their maximum credit and credit already used. The program should then calculate their total remaining credit. Use the source code shown below, adding code as necessary without modifying the existing code. The following messages should be used with interfacing with the user: “What is your maximum credit?” “How much credit have you already used?” “Your remaining credit is $”Program #3 (Id: 165546) Write a program that will calculate the total for a retail sale. The program should ask the user for the retail price of the item being purchased and the sales tax rate. Once these items have been entered, the program should calculate and display the sales tax for the purchase and the total of the sale. The following messages should be used with interfacing with the user: “Please enter the retail price:” “Please enter the tax rate:” “The sales tax is: $” “The total price is: $” Hint: Copy and modify the previous programs! A good variable definition statement would be: double price, taxRate, salesTax, total; Hint: the tax rate will be entered as if it was [value]%, this means you need to modify the value in order to use it in a numeric calculation.

$25.00 View