Write code to complete DoublePennies()'s base case. Sample output for below program:Number of pennies after 10 days: 1024#include // Returns number of pennies if pennies are doubled numDays timeslong long DoublePennies(long long numPennies, int numDays){long long totalPennies = 0;/* Your solution goes here */else {totalPennies = DoublePennies((numPennies * 2), numDays - 1);}return totalPennies;}// Program computes pennies if you have 1 penny today,// 2 pennies after one day, 4 after two days, and so onint main(void) {long long startingPennies = 0;int userDays = 0;startingPennies = 1;userDays = 10;printf("Number of pennies after %d days: %lld\n", userDays, DoublePennies(startingPennies, userDays));return 0;}

Answers

Answer 1

Answer:

The complete code along with output and comments for explanation are given below.

Explanation:

#include <stdio.h>

// function DoublePennies starts here

// The function DoublePennies returns number of pennies if pennies are doubled numDays times

// this is an example of recursive function which basically calls itself

long long DoublePennies(long long numPennies, int numDays){

long long totalPennies = 0;

\\ here we implemented the base case when number of days are zero then return the number of pennies

if(numDays == 0)  

return numPennies;

// if the base case is not executed then this else condition will be executed that doubles the number of pennies for each successive day.

else

{

totalPennies = DoublePennies((numPennies * 2), numDays - 1);

}

return totalPennies;

}

// driver code starts here

// Program computes pennies if you have 1 penny today,

// 2 pennies after one day, 4 after two days, and so on

int main(void)

{

// initialize starting pennies and number of days

long long startingPennies = 0;

int userDays = 0;

// input starting pennies and number of days

startingPennies = 1;

userDays = 10;

// print number of pennies and number of days

printf("Number of pennies after %d days: %lld\n", userDays, DoublePennies(startingPennies, userDays));

return 0;

}

Output:

Test 1:

Number of pennies after 10 days: 1024

Test 2:

Number of pennies after 2 days: 4

Test 3:

Number of pennies after 0 days: 1

Write Code To Complete DoublePennies()'s Base Case. Sample Output For Below Program:Number Of Pennies
Write Code To Complete DoublePennies()'s Base Case. Sample Output For Below Program:Number Of Pennies
Answer 2

To complete the base case of the DoublePennies() function, you add an 'if' condition to check if numDays is less than or equal to zero and return numPennies. Otherwise, the function calls itself recursively with doubled pennies and decremented days.

The student is asking how to complete the base case for the DoublePennies function, which is a recursive function designed to calculate the number of pennies if the number of pennies doubles every day for a certain number of days. The base case should stop the recursion by returning the current number of pennies when the number of days remaining reaches zero.

To complete the base case for the DoublePennies function, you would write the following code:

if (numDays <= 0) {
   totalPennies = numPennies;
} else {
   totalPennies = DoublePennies((numPennies * 2), numDays - 1);
}

This code checks if numDays is less than or equal to zero and, if so, assigns the current value of numPennies to totalPennies. If numDays is greater than zero, the function recursively calls itself with doubled pennies and one less day.


Related Questions

Which of the following statements about weathering is true?
a Physical and chemical are the two types of weathering,
b. Weathering occurs when rocks are subjected to the movement of wind or water
C, Humans are the only cause of weathering
d. Movement is required for weathering to take place,
Please select the best answer from the choices provided
us Activity

Answers

Answer:

Physical and chemical are two types of weathering

Explanation:

reAay ouyay aay hizway ithway igPay atin?Lay? (Translated: "Are you a whiz with Pig Latin?") Write a program that converts an English phrase into a pseudo-Pig Latin phrase (that is Pig Latin that doesn’t follow all the Pig Latin syntax rules). Use predefined methods of the Array and string classes to do the work. For simplicity in your conversion, place the first letter as the last character in the word and prefix the characters "ay" onto the end. For example, the word "example" would become "xam-pleeay," and "method" would become "ethodmay." Allow the user to input the English phrase. After converting it, display the new Pig Latin phrase.

Answers

Answer:

Check the explanation

Explanation:

package com.prt.test;

package com.prt.test;

  import java.util.Arrays;

  import java.util.Scanner;

  public class StringEncryption {

      public static void main(String[] args)

      {

  try{

          String concatedString1="";//testing();

          StringBuffer encryptedString=new StringBuffer();

Scanner scanner = new Scanner(System.in);

         

          System.out.println("enter the string ");

         

          String userInput = scanner.nextLine();// to read the string

         

          String[] words=userInput.split("\\s");//to split the words if user enter the string with period

         

          for(String word:words)

          {

              int numberOfSpacesadd=1;

              String subs=word.substring(0, 1);//to split the first letter

              String s1=word.substring(1);//to split the after the first letter

              String concatedString=s1+subs;

              concatedString1=concatedString+"ay";//to add the adding phrase

              String addSpace = String.format("%"+ numberOfSpacesadd +"s", " ");//for adding the space after the word

                 

              encryptedString.append(concatedString1+addSpace);

             

          }

         

System.out.println(encryptedString.toString().trim()+"?");

  }catch(Exception e)

  {

      System.out.println(" try another time");

  }  

      }

  }

 

Output :

enter the string

Are You a Whiz with Pig Latin?

reAay ouYay aay hizWay ithway igPay atin?Lay?

Assume that network MTU limitations necessitate that an IP datagram be split into two fragments of different sizes. In the resulting IP datagrams, indicate which of the following header fields is guaranteed to be the same and which could be different. You should be comparing the headers of the two fragments to each other, not to the header of the original. Briefly justify each answer.
Header fields:
IHL
Total length
Identification
D Flag
M flag
Fragment Offset
Header checksum

Answers

Answer:

Consider a packet of size 756 bytes. Enters a network having mtu=500. Now packet will be fragmented in two fragment.

Fragment 1 : 480 data +20 byte header.

Fragment 2 : 276 data + 20 byte header.

Let's compare header of the two fragments.

Internet header length (IHL) ⇒ Due to same size of both fragment header, IHL value will be same. If header length is 20 IHL, then will contain 0101.

Total length ⇒ Total length can be different. Looking at our case, fragment 1 contain 480 byte data while fragment 2 contains 276 byte so total length will be different.

Identification ⇒ Identification is same for all fragment belonging to same packet  

D flag (don't fragment) ⇒ This is used to indicate weather packet is fragmented or not. D=1 not a fragment. D=0 fragment. So this D flag will be same.

M flag (more fragment) ⇒ This is used to indicate more fragment present or not. M=1 more fragment are present. M=0 last fragment.

Fragment offset ⇒This is used to indicate position of fragment among fragments. This value will be different for two fragment.

Header checksum : As many other fields of two fragment is different thus checksum of two fragment will also be different.

Explanation:

See all the explanation in the answer.

Create an array of 10 fortune cookie sayings that will be randomly displayed each time the user reloads the page. The fortune will be sayings like: "Procrastination is the thief of time." Let the visitor get a new fortune when a button is clicked. g

Answers

Answer:

let cookieNumber = Math.floor(Math.random() * 10)

switch (cookieNumber) {

  case 1:

   document.write('Fortune 1')

   break;

  case 2:

   document.write('Fortune 2')

   break;

   case 3:

   document.write('Fortune 3')

   break;

  case 4:

   document.write('Fortune 4')

   break;

  case 5:

   document.write('Fortune 5')

   break;

  case 6:

   document.write('Fortune 6')

   break;

  case 7:

   document.write('Fortune 7')

   break;

  case 8:

   document.write('Fortune 8')

   break;

  case 9:

   document.write('Fortune 9')

   break;

  case 10:

   document.write('Fortune 10')

Explanation:

The cookieNumber is generated using Math.random(), which is rounded to a whole number using Math.floor(). Then, a switch block is used to display a different fortune depending on the value of cookieNumber.

5. Write a 500- to 1,000-word description of one of the following items or of a piece of equipment used in your field. In a note preceding the description, specify your audience and indicate the type of description (general or particular) you are writing. Include appropriate graphics, and be sure to cite their sources correctly if you did not create them (see Appendix, Part B, for documentation systems). a. GPS device b. MP3 player c. waste electrical and electronic equipment d. automobile jack e. bluetooth technology

Answers

Final answer:

This response examines the role of smartphones, laptops, and GPS devices in daily life, considering how they affect communication, work, travel, and convenience.

Explanation:

Understanding how electronic devices shape our daily lives can provide insight into their pervasive influence and the reliance we've developed on technology. For this exercise, we'll examine three common devices: a smartphone, a laptop, and a GPS device.

Smartphones have become nearly indispensable in modern life. They serve as communication hubs, personal assistants, and portable entertainment systems. The smartphone keeps us connected through calls, texts, emails, and social media. It also helps manage our schedules, set alarms, and capture memories through its camera. Life without smartphones would mean a return to separate devices for each of these functions and a significant loss in convenience and efficiency.

Laptops offer portable computing power that enables us to work, learn, and play from virtually anywhere. They are essential for students and professionals alike, as they support software for creating documents, managing data, and facilitating online meetings. The absence of laptops would drastically change the landscape of mobile work and education, likely requiring a heavier reliance on desktop computers and physical media.

A GPS device provides accurate navigation and location tracking, which is especially useful for travel and logistics. The utility of GPS extends beyond simple navigation to include applications in science, military, and emergency services. Without GPS technology, we would need to rely on physical maps and alternative methods for location tracking, potentially complicating travel and critical operations.

Assume you have a variable, budget, that is associated with a positive integer. Assume you have another variable, shopping_list, that is a tuple of strings representing items to purchase in order of priority. (For example: ("codelab", "textbook", "ipod", "cd", "bike")) Furthermore, assume you have a variable, prices that is a dictionary that maps items (strings such as those in your shopping list) to positive integers that are the prices of the items. Write the necessary code to determine the number of items you can purchase, given the value associated with budget, and given that you will buy items in the order that they appear in the tuple associated with shopping_list. Associate the number of items that can be bought with the variable number of items.

Answers

Final answer:

To calculate the number of items purchasable within a budget, use a for loop to iterate through the shopping_list, subtracting item prices from the budget and incrementing a counter until the budget cannot afford an item.

Explanation:

To determine the number of items a student can purchase with their given budget, we need to iterate through the shopping_list tuple in order and subtract the item prices from the budget using the prices dictionary until the budget cannot cover any additional items. Here is a code snippet that accomplishes this task:

number_of_items = 0
for item in shopping_list:
   if budget >= prices[item]:
       budget -= prices[item]
       number_of_items += 1
   else:
       break

In this code, we use a loop to go through each item in the shopping_list. If the current budget can cover the cost of the item based on its price, we deduct the price from the budget and increment the number_of_items counter by one. If the budget is not sufficient to cover an item's cost, we exit the loop, and number_of_items will then hold the total number of items that can be purchased within the budget constraint.

General Description You have been chosen to create a version of connect 4. In this version, there can be forbidden positions, or places that neither x nor o can play. However, connecting four together is still the way to win, and this can be done vertically, horizontally, diagonally (or anti-diagonally if you distinguish between the backward diagonal). Required Features 1. You must implement two new game options, one for two players, and one for x player vs computer. a. The player is always x and the computer is always o in that case. b. Player one and two alternate turns. c. Players cannot overwrite each other's moves. d. Players cannot play on forbidden places, and forbidden places do not count for victory. 2. At the start of each game:________. a. Ask the player what game board they want to load. b. Then start with the x player, and alternate. c. Check for victory after each move, not after each pair of moves. d. Players may enter a move, two integers separated by a space, or the words "load game" or "save game" which will either load or save over the current game. 3. You must implement a load game feature. Ask for the file name and load that file. If a game is currently in progress, overwrite that game and immediately start on the loaded game. 4. You must implement a save game feature. Ask for the name that you wish to save to, and save the file to that name. 5. Detect when one or the other player has adjoined the spheres (connected four). a. Display a message with the winning player. b. End that game. c. Go back to the main menu. d. If the board is full, then that is a tie. Design Document There is no design document for this project. It has been replaced with a testing script. Any questions about design documents will be ignored. Required names and Interface Your project should be in proj2.py The design of project 2 is mostly up to you, but we will require that your project create a class: class Adjoin TheSpheres: This must have a method whose definition is: def main menu self):

Answers

To create a custom Connect 4 game in Python, implement two modes (two players and player vs. computer), along with save and load features.

The code for the following is:

from IPython.display import display, HTML, clear_output

import random

import time

# Game Constants

ROWS = 6

COLUMNS = 7

PIECE_NONE = ' '

PIECE_ONE = 'x'

PIECE_TWO = 'o'

PIECE_COLOR_MAP = {

PIECE_NONE : 'white',

PIECE_ONE : 'black',

PIECE_TWO : 'red',}

DIRECTIONS = ((-1, -1), (-1, 0), (-1, 1),( 0, -1), ( 0, 1),( 1, -1), ( 1, 0), ( 1, 1),)

# Board Functions

def create_board(rows=ROWS, columns=COLUMNS):

''' Creates empty Connect 4 board '''

board = []

for row in range(rows):

board_row = []

for column in range(columns):

board_row.append(PIECE_NONE)

board.append(board_row)

return board

# Copy board

def copy_board(board):

''' Return a copy of the board '''

rows = len(board)

columns = len(board[0])

copied = create_board(rows, columns)

for row in range(rows):

for column in range(columns):

copied[row][column] = board[row][column]

return copied

def print_board(board):

''' Prints Connect 4 board '''

for row in board:

print('|' + '|'.join(row) + '|')

def drop_piece(board, column, piece):

''' Attempts to drop specified piece into the board at the

specified column If this succeeds, return True, otherwise return False.'''

for row in reversed(board):

if row[column] == PIECE_NONE:

row[column] = piece

return True

return False

def find_winner(board, length=4):

''' Return whether or not the board has a winner '''

rows = len(board)

columns = len(board[0])

for row in range(rows):

for column in range(columns):

if board[row][column] == PIECE_NONE:

continue

if check_piece(board, row, column, length):

return board[row][column]

return None

def check_piece(board, row, column, length):

''' Return whether or not there is a winning sequence starting from

this piece '''

rows = len(board)

columns = len(board[0])

for dr, dc in DIRECTIONS:

found_winner = True

for i in range(1, length):

r = row + dr*i

c = column + dc*i

if r not in range(rows) or c not in range(columns):

found_winner = False

break

if board[r][c] != board[row][column]:

found_winner = False

break

if found_winner:

return True

return False

# HTML/SVG Functions

def display_html(s):

''' Display string as HTML '''

display(HTML(s))

def create_board_svg(board, radius):

''' Return SVG string containing graphical representation of board '''

rows = len(board)

columns = len(board[0])

diameter = 2*radius

svg = '<svg height="{}" width="{}">'.format(rows*diameter, columns*diameter)

svg += '<rect width="100%" height="100%" fill="blue"/>'

for row in range(rows):

for column in range(columns):

piece = board[row][column]

color = PIECE_COLOR_MAP[piece]

cx = column*diameter + radius

cy = row*diameter + radius

svg += '<circle cx="{}" cy="{}" r="{}" fill="{}"/>'.format(cx, cy, radius*.75, color)

svg += '</svg>'

return svg

A small monster collector has captured ten Bagel-type small monsters. Each Bagel-type small monster has a 35% chance of being a Sesame Seed-subtype and a 20% chance of being a Whole Wheat-subtype.What is the probability of exactly eight of the captured small monsters being Whole Wheat-subtypes?What is the probability of at least one of the captured small monsters being a Sesame Seed-subtype?What is the probability that there are no Sesame Seed- or Whole Wheat-subtype small monsters captured?What is the probability that are at least two Whole Wheat/Sesame Seed dual-subtype small monsters captured?

Answers

Answer:

Check the explanation

Explanation:

Each Bagel-type small monster has 0.35 probability of being a Sesame Seed-subtype and 0.2 probability of being a Whole Wheat-subtype.

The probability that exactly 8 of them are Whole Wheat-subtype is [tex]\binom{10}{8}(0.2)^8(0.8)^2[/tex] using multiplication principle, because first need to choose which 8 are Whole Wheat-subtype, and if exactly 8 of them are Whole Wheat-subtype, then other two are not Whole Wheat-subtype. The former has probability 0.2, while the latter has probability 1-0.2 = 0.8 .

Kindly check the attached images below for the complete answer to the question above

3) Write a program named Full_XmasTree using a nested for loop that will generate the exact output. This program MUST use (ONLY) for loops to display the output below. For example the 1st row prints 1 star 2nd row prints 2, the 3rd row print 3 stars and so forth... This program is controlled by the user to input for the amount of row. "Prompt the user to enter the dimensions of the tree" A good test condition is the value of ten rows. (hint***)This program should account for white spaces print("* "). Remember the purpose of print() and println()

Answers

Answer:

Following are the code to this question:

//import package

import java.util.*;  

public class Full_XmasTree   //defining class

{        

// defining main method

public static void main(String as[])  

   {  

       int X,a,b; //defining integer variable

       Scanner obx = new Scanner(System.in); // creating Scanner class object

       System.out.print("Please enter: "); //print message

       X = obx.nextInt(); // input value from user

       for (a = 0; a < X; a++) //defining loop to print pattern  

       {

           for (b = X - a; b > 1; b--)//use loop for print white space  

           {

           System.out.print(" ");//print space

           }

           for (b = 0; b <= a; b++) // use loop to print values  

           {

               System.out.print("* "); //print asterisk values

           }

           System.out.println(); //using print method for new line

       }

   }

}

Output:

please find the attachment.

Explanation:

In the given java code, a class "Full_XmasTree" is declared, in which the main method is declared, inside this method three integer variable "X, a, and b", in this variables "a and b" is used in a loop, and variable X is used for user input.

In the next line, the Scanner class object is created, which takes input in variable X, and for loop is used to print asterisk triangle. In the first for loop, use variable a to count from user input value, inside the loop, two for loop is used, in which first is used to print white space and second is used for the print pattern.

The Full_XmasTree program illustrates the use of loops

Loops are used for operations that must be repeated until a certain condition is met.

The Full_XmasTree program

The Full_XmasTree program written in Java where comments are used to explain each action is as follows:

import java.util.*;  

public class Full_XmasTree{        

public static void main(String as[])  {  

   //This creates a Scanner object

   Scanner input = new Scanner(System.in);

   //This prompts the user for the number of rows

   System.out.print("Rows: ");

   //This gets input the user for the number of rows

   int rows = input.nextInt();

   //The following iteration prints the full x-mas tree

   for (int i = 0; i < rows; i++){

       for (int j = rows - i; j > 1; j--){

           System.out.print(" ");

       }

       for (int j = 0; j <= i; j++){

           System.out.print("* ");

       }

       System.out.println();

      }

  }

}

Read more about loops at:

https://brainly.com/question/24833629

This program will keep track of win-tied-loss and points earned records for team. There are 6 teams and each week there are three games (one game per team per week). Enter the team numbers and game scores in an array within the program rather than user typing at command prompt.After reading in each week, the program should print out the win-tied-loss records and points earned for each team. A win is two points, tied game is one point and a loss is zero points. For example:How many weeks of data: 3For week 1, game 1, enter the two teams and the score: 0 1 1 4That is in week 1, game 1 is between team 0 team 1. Final scores are team 0 is 1 and team 1 is 4. Therefore, team 1 has 2 points, team 0 has 0 points. Similarly,For week 1, game 2, enter the two teams and the score: 2 3 1 2For week 1, game 3, enter the two teams and the score: 4 5 2 0For week 2, game 1, enter the two teams and the score: 0 2 3 0For week 2, game 2, enter the two teams and the score: 1 4 0 1For week 2, game 3, enter the two teams and the score: 3 5 4 4For week 3, game 1, enter the two teams and the score: 0 4 8 7For week 3, game 2, enter the two teams and the score: 1 5 0 0For week 3, game 3, enter the two teams and the score: 2 3 6 9

Answers

Answer:

Check the explanation

Explanation:

import java.util.*;

public class TeamRecords {

   public static void main(String[] args) {

       int teams = 6;

       System.out.print("How many weeks of data: ");

       Scanner sc = new Scanner(System.in);

       System.out.println();

       int weeks = sc.nextInt();

       int[] wins = new int[teams];

       int[] ties = new int[teams];

       int[] losses = new int[teams];

       

       //Each entry in points is an array with two elements

       //the first element is the team and the second element is the points

       //This will keep the team associated with the points when we sort the array

       int[][] points = new int[teams][2];

       for (int i = 0; i<teams; i++) {

           points[i][0] = i;

       }

       int[] pointsFor = new int[teams];

       int[] pointsAgainst = new int[teams];

       for (int week=1; week <= weeks; week++) {

           System.out.println();

           for (int game=1; game <= teams/2; game++) {

               System.out.print("For week "+week+", game "+game+", enter the two teams and the score: ");

               int team1 = sc.nextInt();

               int team2 = sc.nextInt();

               int score1 = sc.nextInt();

               int score2 = sc.nextInt();

               if (score1 > score2) {

                   wins[team1]++;

                   losses[team2]++;

                   points[team1][1] += 2;                    

               } else if (score1 < score2) {

                   wins[team2]++;

                   losses[team1]++;

                   points[team2][1] += 2;

               } else {

                   ties[team2]++;

                   ties[team1]++;

                   points[team1][1] ++;

                   points[team2][1] ++;

               }

               pointsFor[team1] += score1;

               pointsFor[team2] += score2;

               pointsAgainst[team1] += score2;

               pointsAgainst[team2] += score1;

               

           }

       }

       

       System.out.println();

       System.out.println("League Standing after 2 weeks:");

       System.out.println();

       System.out.println("W T L");

       for (int team=0; team < teams; team++) {

           System.out.println("Team "+team+" "+wins[team]+" "+ties[team]+" "+losses[team]);

       }

       System.out.println();

       System.out.println("Points Table:");

       

       // sort the points array in descending order

       // based on the number of points earned by each team

       // (which is the second element of each int array that makes up the points array)

       Arrays.sort(points,new Comparator<int[]>() {

           public int compare(int[] o1, int[] o2) {

               return (new Integer(o2[1])).compareTo(o1[1]);

           }

       });

       

       System.out.println();

       

       for (int i=0; i<points.length; i++) {

           System.out.println("Team "+points[i][0]+" "+points[i][1]);

       }

       

       System.out.println();

       System.out.println("Winning percentages: ");

       for (int i=0; i<teams; i++) {

           System.out.println("Team "+i+" "+(wins[i]*100/(new Float(weeks)))+"%");

       }

       System.out.println();

       System.out.println("Points scored for/against:");

       for (int i=0; i<teams; i++) {

           System.out.println("Team "+i+" "+pointsFor[i]+"/"+pointsAgainst[i]);

       }

   }

}

Asks the user for the full path of a file to be read - path should include the folder and filename.
Asks the user for the full path of a file to be written - path should include the folder and filename.
Declares an array of strings of 1024 words.
Opens the input and output files.
Reads the file word by word into the array.
Prints the content of the array in reverse order to both screen and output file at the same time.
Remember :
Check that input file opened successfully.
Input file can be quite smaller than 1024 words, exactly 1024 words or much larger than 1024 words.
Close the files before program ends.
Put a 'pause' in your program before it ends.

Answers

Answer:

See explaination

Explanation:

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

int size = 10;

string inputFileName, outputFileName;

cout << "Please enter input file name, including full path: ";

cin >> inputFileName;

cout << "Please enter output file name, including full path: ";

cin >> outputFileName;

ifstream inFile(inputFileName.c_str());

ofstream outFile(outputFileName.c_str());

// checking whether input and output files are good to open

if(!inFile.is_open())

{

cout << "Cannot open " << inputFileName << endl;

exit(EXIT_FAILURE);

}

if(!outFile.is_open())

{

cout << "Cannot open " << outputFileName << endl;

exit(EXIT_FAILURE);

}

// declare an array of string to store 1024 words

string words[size];

// read the file for exactly 1024 words

// assuming each line of input file contains only 1 word

int count = 0;

string word;

while(getline(inFile, word))

{

if(count == size)

break;

words[count++] = word;

}

inFile.close();

// now we need to print the words array in reverse order both to the console and to the output file, simultaneously

cout << "WORDS:\n------\n";

for(int i = size - 1; i >= 0; i--)

{

if(words[i] != "")

{

cout << words[i] << endl;

outFile << words[i] << endl;

}

}

outFile.close();

system("pause");

return 0;

}

Final answer:

The question is about creating a program for file reading and writing, including array manipulation and outputting content in reverse. The program must handle input/output operations, file size variations, and ensure resource management by closing files properly.

Explanation:

The student's question pertains to writing a program that can read and write files, and specifically handle reading words into an array and then outputting them in reverse order to a file and the screen. The steps to achieve this involve prompting the user for file paths, checking the success of opening files, handling files of various sizes, and managing resources correctly by closing files. A 'pause' before the program ends is also required, likely to allow the user to see the output before the program closes.

To begin, here's a simplified pseudo-code outline:

Ask the user for the input file path (including the directory and file name).Ask the user for the output file path (including the directory and file name).Declare an array of strings, sized to 1024 elements.Open the input file and check if it opens successfully. If not, display an error message.Open the output file for writing.Read the words from the input file into the array until the file ends or the array is full.Output the array contents in reverse order to the screen and write them to the output file.Close both files.Implement a pause at the end of the program.

Note: When implementing the read operation, the program should consider the file size which may be larger than the array and handle it appropriately, perhaps by reading in chunks if necessary.

Write the getNumGoodReviews method, which returns the number of good reviews for a given product name. A review is considered good if it contains the string "best" (all lowercase). If there are no reviews with a matching product name, the method returns 0. Note that a review that contains "BEST" or "Best" is not considered a good review (since not all the letters of "best" are lowercase), but a review that contains "asbestos" is considered a good review (since all the letters of "best" are lowercase). Complete method getNumGoodReviews. /** Returns the number of good reviews for a given product name, as described in part (b). */ public int getNumGoodReviews(String prodName)

Answers

Final answer:

The getNumGoodReviews method returns the number of good reviews for a given product name. It checks if a review contains the string "best" in lowercase and increments the count of good reviews if it does. Finally, the method returns the count of good reviews.

Explanation:

The getNumGoodReviews method can be implemented by iterating over the reviews and checking if each review contains the string "best" in lowercase. If a review matches this condition, the count of good reviews is incremented. Finally, the method returns the count of good reviews.

Here is an example implementation in Java:

public int getNumGoodReviews(String prodName) {
   int count = 0;
   for (String review : reviews) {
       if (review.toLowerCase().contains("best")) {
           count++;
       }
   }
   return count;
}

Problem 1 (10%): You are asked to design a database for an auto-shop that satisfies the following requirements: a. Each customer has a unique customer identification number, a name, address, day time telephone number, evening telephone number. The customer name includes first name, middle initial and last name. The address includes street address, city, state, and zip code. The telephone numbers include area code and the number. b. Each car type has a unique type name, the make, model, and year of make. c. The car has a unique license number, a car type, color, type of transmission, and the customer who brings the car to the auto-shop. d. The database keeps records of repairs. The repair record includes the date of the repair, the car that the repair was done, the name of the engineer who did the repair, and the cost of the repair.

Answers

Answer:

see explaination

Explanation:

I am considering some relationship for this ER Diagram as follows :

(i) One Car can have only one type.

(ii) One Car needs more than one repairings.

(iii) A customer can have more than one car and a car must belong to only one customer.

Write a complete program that: 1. Prompt the user to enter 10 numbers. 2. save those numbers in a 32-bit integer array. 3. Print the array with the same order it was entered. 3. Calculate the sum of the numbers and display it. 4. Calculate the mean of the array and display it. 5. Rotate the members in the array forward one position for 9 times. so the last rotation will display the array in reverse order. 6. Print the array after each rotation. check the sample run.

Answers

Answer:

see explaination

Explanation:

oid changeCase (char char_array[], int array_size ) {

__asm{

// BEGIN YOUR CODE HERE

mov eax, char_array; //eax is base image

mov edi, 0;

readArray:

cmp edi, array_size;

jge exit;

mov ebx, edi; //using ebx as offset

shl ebx, 2;

mov cl, [eax + ebx]; //using ecx to be the storage register

check:

//working on it

cmp cl, 0x41; //check if cl is <= than ASCII value 65 (A)

jl next_indx;

cmp cl, 0x7A; //check if cl is >= than ASCII value 122 (z)

jg next_indx;

cmp cl, 'a';

jl convert_down;

jge convert_up;

convert_down:

or cl, 0x20; //make it lowercase

jmp write;

convert_up:

and cl, 0x20; //make it uppercase

jmp write;

write:

mov byte ptr [eax + ebx], cl //slight funky town issue here,

next_indx:

inc edi;

exit:

cmp edi, array_size;

jl readArray;

mov char_array, eax;

// END YOUR CODE HERE

}

}

Flight Simulation software, which imitates the experience of flying, is often used to train airline pilots. Which of the following is LEAST likely to be an advantage of using flight simulation software
for this purpose?

A) Flight simulation software allows pilots to practice landing in a variety of different terrains and
weather conditions without having to physically travel

B) Flight simulation software could save money due to the cost of maintenance and fuel for actual
training flights

C) Flight Simulation software provides a more realistic experience for pilots than actual training flights.

D) Flight simulation software allows for the testing of emergency air situations without serious
consequences.​

Answers

Answer:

C) Flight Simulation software provides a more realistic experience for pilots than actual training flights.

Explanation:

Flight simulation softwares are used to teach prospective pilots in aviation schools. These softwares paint the conditions they are likely to face during real flights and how to cope with them.

Flight simulation software allows pilots to practice landing in a variety of different terrains and weather conditions without having to physically travel.

It helps in saving money due to the cost of maintenance and fuel for actual

training flights.

It however doesn’t create realistic experience for pilots than actual training flights.

Answer:

I think aswell that its C.

Explanation:

Things like Xplane-11 can give you that more realistic expirence, because you can simulate weather conditions and you can train to land or just generally fly in the Simulator. Also it can simulate the failures which will train the pilot how to react to a situation say like an engine failure. If you have an engine failure or a fire, extinguish it and shut down the engine. After that you notify ATC and squwak 7700. After that you either return to the airport that you took off from, or you land at a nearby airport.

There are number of issues to consider when composing security policies. One such issue concerns the use of security devices. One such device is a ____________, which is a network security device with characteristics of a decoy that serves as a target that might tempt a hacker.

Answers

Answer:

honeypot.

Explanation:

Okay, let us first fill in the gap in the question above. Please, note that the capitalized word is the missing word.

"There are number of issues to consider when composing security policies. One such issue concerns the use of security devices. One such device is a HONEYPOT , which is a network security device with characteristics of a decoy that serves as a target that might tempt a hacker''.

In order to make the world a safer place to live, there is a need for good and efficient Security policies. These policies are set by the authority or the government (legislative arm and executive arm of the Government) and with this the Judicial arm of the Government interprete and make sure that the policies are enforced.

In order to enforce the security policies and with the advancement of science, engineering and technology, devices are being made or produced to help in enforcing security policies and one of them is the use of HONEYPOT.

The main use or advantage of honeypot is to track hackers or anything related to hacking.

Linda is starting a new cosmetic and clothing business and would like to make a net profit of approximately 10% after paying all the expenses, which include merchandise cost, store rent, employees’ salary, and electricity cost for the store. She would like to know how much the merchandise should be marked up so that after paying all the expenses at the end of the year she gets approximately 10% net profit on the mer- chandise cost. Note that after marking up the price of an item she would like to put the item on 15% sale. Write a program that prompts Linda to enter the total cost of the merchandise, the salary of the employees (including her own salary), the yearly rent, and the estimated electric- ity cost. The program then outputs how much the merchandise should be marked up so that Linda gets the desired profit.

Answers

Answer:

Program Plan:  

• Declare the variables.  

• Prompt the user to enter the cost of the merchandise.  

• Prompt the user to enter the salary of the employees.

• Prompt the user to enter the yearly rent.

• Prompt the user to enter the electricity cost.

• Compute the total expenses.

• Compute the markup price.

• Compute the markup percentage.

• Display the percentage on the screen.

Explanation:

See attached images for the program and sample output

This answer includes a Python program to help Linda calculate the required markup for her business. It ensures she achieves her desired 10% net profit after all expenses and a 15% sale discount.

To calculate the markup percentage Linda needs in her cosmetic and clothing business, we have to account for all her expenses (merchandise cost, store rent, employees' salary, electricity cost) and her desired profit margin. Here is a Python program to help Linda determine the required markup-

def calculate_markup(total_merchandise_cost, salary, yearly_rent, electricity_cost):

  total_expenses = total_merchandise_cost + salary + yearly_rent + electricity_cost

  desired_profit = 0.10 × total_merchandise_cost  # 10% of merchandise cost

  sales_needed = total_expenses + desired_profit

  # When the item has to be sold at a 15% discount

  selling_price_after_discount = sales_needed / (1 - 0.15)  # reverse engineering the discount

  # Markup percentage calculation

  markup = (selling_price_after_discount - total_merchandise_cost) / total_merchandise_cost * 100

  return markup

# Example usage

merchandise_cost = float(input('Enter the total cost of the merchandise: '))

salary = float(input("Enter the salary of the employees (including her own salary): "))

yearly_rent = float(input("Enter the yearly rent: "))

electricity_cost = float(input("Enter the estimated electricity cost: "))

markup_percentage = calculate_markup(merchandise_cost, salary, yearly_rent, electricity_cost)

print(f'The merchandise should be marked up by approximately {markup_percentage:.2f}% to achieve the desired profit.')

This program calculates the total expenses, adds the desired profit, adjusts for the 15% discount and then calculates the necessary markup.

Write a multi-threaded program that outputs prime numbers. The program should work as follows: the user will run the program and enter a number on the command line. The program creates a thread that outputs all the prime numbers less than or equal to the number entered by the user. Also, create a separate thread that outputs this subset of the above primes that have the following property: the number that is derived by reversing the digits is also prime (e.g., 79 and 97).

Answers

Final answer:

A multi-threaded program can be written in a programming language like Java to output prime numbers. The program will take a number as input from the user and create two separate threads. The first thread will output all the prime numbers less than or equal to the number entered, while the second thread will output the subset of these primes that have the property of being prime when their digits are reversed.

Explanation:

A multi-threaded program can be written in a programming language like Java to output prime numbers. The program will take a number as input from the user and create two separate threads. The first thread will output all the prime numbers less than or equal to the number entered by the user, while the second thread will output the subset of these primes that have the property of being prime when their digits are reversed.

The program can be implemented using a function to check if a number is prime and another function to reverse the digits of a number. The first thread can iterate from 2 to the input number, checking if each number is prime, and output the prime numbers. The second thread can then take the output of the first thread, reverse each number, and check if the reversed number is also prime.

This multi-threaded program allows for parallel processing, where the first thread can find prime numbers and output them, while the second thread can simultaneously check the property of reversed primes. This can help in improving the efficiency of the program and make it faster.

Create a view named Top10PaidInvoices that returns three columns for each vendor: VendorName, LastInvoice (the most recent invoice date), and SumOfInvoices (the sum of the InvoiceTotal column). Return only the 10 vendors with the largest SumOfInvoices and include only paid invoices.

Answers

Answer:

See Explaination

Explanation:

SELECT TOP 10 VendorName AS Name, MAX(InvoiceDate) AS LastInvoice, SUM(InvoiceTotal) AS SumOfInvoices

FROM dbo.Vendors V JOIN dbo.Invoices I

ON V.VendorID = I.VendorID

WHERE PaymentDate IS NOT NULL

GROUP BY VendorName

ORDER BY SumOFInvoices desc;

Final answer:

The question involves creating a SQL view named Top10PaidInvoices, which entails using aggregation functions, a GROUP BY clause, and a LIMIT clause to display the top 10 vendors with the highest sum of paid invoices along with their latest invoice date.

Explanation:

The student's question pertains to the creation of a SQL view named Top10PaidInvoices which requires a combination of SQL commands to generate a list of the ten vendors with the highest sum of paid invoices. To achieve this, a SQL statement including aggregation functions such as SUM and MAX would be used alongside GROUP BY and ORDER BY clauses to calculate the SumOfInvoices and LastInvoice respectively for each vendor. This view should also use a subquery or a common table expression (CTE) with a ROW_NUMBER() window function to ensure that only the top 10 vendors are returned, based on the sum of their paid invoices.

The resulting SQL command might look something like this:

CREATE VIEW Top10PaidInvoices AS
SELECT VendorName,
      MAX(InvoiceDate) AS LastInvoice,
      SUM(InvoiceTotal) AS SumOfInvoices
FROM Invoices
WHERE IsPaid = 1
GROUP BY VendorName
ORDER BY SUM(InvoiceTotal) DESC
LIMIT 10;

Note that the exact SQL syntax could vary depending on the database management system (RDBMS) being used. The LIMIT 10 clause specifies that only the top 10 records should be considered, however, in some RDBMS, the TOP or FETCH FIRST clause might be appropriate

What is true regarding the cellular phone concept? a. a single radio broadcast tower system enables greater frequency reuse compared to a multiple cell phone system b. increasing base station transmit power is required to decrease the size of a cell c. by increasing the number and density of cells within a service area, you increase the overall complexity of the entire system d. decreasing the size of a cell expends greater power from the mobile device, and therefore reduces the device’s operating time

Answers

Answer:

The answer is "Option c".

Explanation:

A mobile phone is a telecom device, which uses radio signals around an internet-connected area but is served at the same fixed location with a cell tower or transmitter, enabling calls to be transmitted electronically across a wide range, to a fixed over the Internet. By increasing the amount and size of layers within the same market area, the total size of the overall system is improved, and the wrong choices can be described as follows:

In option a, It is wrong because it can't reuse radio wave frequency. In option b, It decreases the size of the cell, that's why it is incorrect. In option d, It reduces the size of the cells, which increases the capacity of the smartphone and it also decreases the total time of the device, that's why it is wrong.

A small grocery store has one checkout.You have been asked to write a program to simulate the grocery store as it checks out customers.YOU ARE REQURED TO USE A QUEUE TO SOLVE THE PROBLEM.The queue program (qu.py) is located on the Instructor drive.Here are some guidelines:
1. A customer gets to the checkout every 1 – 5 minutes
2. The checker can process one customer every 5 – 15 minutes (depends on how many groceries customer has 10 items or less will take 5 minutes, 11- 20 items will take 6 10 minutes, more than 20 items will take 11-15 minutes- you will need two random numbers)
3. The program should find the average wait time for customers and the number of customers left
4. Use the random number generator to get values for when customers get to the checkout and 5 You are not required to use classes, but it might make things easier than 20 items will take 11 - 15 minutes-you will need two random numbers) in the queue how long the checker will take.

Answers

Answer:

Check the explanation

Explanation:

PYTHON CODE :

#import random function

from random import randint

#class Queue declaration

class Queue:

#declare methods in the Queue

def __init__(self):

self. items = []

def isEmpty(self):

return self. items == []

def enqueue(self, item):

self.items. insert(0, item)

def dequeue(self):

return self. items. pop()

def size(self):

return len(self. items)

def getInnerList(self):

return self.items

#This is customer Queue

class Customer:

#declare methods

def __init__(self,n):

self.numberOfItems=n

def __str__(self):

return str(self. numberOfItems)

def getNumberOfItems(self):

return self. numberOfItems

#This is expresscheker customer queue

class Expresschecker:

def __init__(self,n):

self.numberOfItems=n

def __str__(self):

return str(self. numberOfItems)

def getNumberOfItems(self):

return self. numberOfItems

#Returns random checkout time, based on number of items

def checkOut(Expresschecker):

items = Expresschecker. getNumberOfItems()

if items <= 10:

return randint(2, 5)

if items <= 20:

return randint(6, 9)

return randint(10, 14)

#Initiate queue for the Expresschecker

Expresschecker = Queue()

#declare total customers

totalcheckoutCustomers = 10

#express Customers shopping..

for i in range(totalcheckoutCustomers):

#Each putting Between 1 to 25 items

randomItemsQty = randint(1, 25)

customer = Customer(randomItemsQty)

#Getting into queue for checkout

Expresschecker. enqueue(customer)

#====Now all express Customers having

#random qty of items are in Queue======

#intial time

totalTime=0

#define the size of the queue

totalcheckoutCustomers = Expresschecker. size()

#using for-loop until queue is empty check out

#the items in the express cheker queue

while not(Expresschecker. isEmpty()):

totalTime+=randint(1,5)

#Picking a customer

expresscustomer = Expresschecker. dequeue()

#Processing the customer

timeTaken = checkOut(expresscustomer)

#add the time for each custimer

totalTime+=timeTaken

#compute average waiting time

averageWaitingTime = totalTime/totalcheckoutCustomers

#display the average waiting time

print("Average waiting time for the express customer queue is "

+str(averageWaitingTime)+" minutes ")

print("Remaining Custimers in the express customer Queue is: ",

Expresschecker. size())

#Returns random checkout time, based on number of items

def checkOut(customer):

items = customer. getNumberOfItems()

if items <= 10:

return randint(1, 5)

if items <= 20:

return randint(6, 10)

return randint(11, 15)

#in

customersQueue = Queue()

totalCustomers = 20 #Change number of customers here

#Customers shopping..

for i in range(totalCustomers):

#Each putting Between 1 to 25 items

randomItemsQty = randint(1, 25)

customer = Customer(randomItemsQty)

#Getting into queue for checkout

customersQueue. enqueue(customer)

#====Now all Customers having random qty

#of items are in Queue======

totalTime=0

totalCustomers = customersQueue. size()

while not(customersQueue. isEmpty()):

totalTime+=randint(1,5)

#Picking a customer

customer = customersQueue. dequeue()

#Processing the customer

timeTaken = checkOut(customer)

totalTime+=timeTaken

#Result=============================

averageWaitTime = totalTime/totalCustomers

print("Average wait time for the customer queue is

"+str(averageWaitTime)+" minutes ")

print("Remaining Customers in the customer Queue is:

",customersQueue. size())

Hannah weighs 210 pounds using the English System of measurement. If we convert her weight to the Metric System, she would weigh 95.34 kilograms. If Jessica weighs 145 pounds using the English System, what is her weight using the Metric System. To convert pounds from the English System to kilograms using the Metric System you multiply the number of pounds by .454 to get the number of kilograms. Write a program that will prompt the user for a weight, measured in pounds, and convert the weight to kilograms.

Answers

Answer:

Check the explanation

Explanation:

C++ PROGRAM

#include <iostream>

using namespace std;

int main()

{

float pounds;

float kilograms;

cout<<"Please enter the weight in pounds :";

cin>>pounds;

kilograms=pounds*0.454;

cout<<"The weight in Kilogram is:"<<kilograms<<"kilograms";

return 0;

}

Kindly check the attached image below for the code output.

You are creating a classification model from a DataFrame that contains data about traffic on highways in a US state, which contains multiple feature columns and a label column that indicates whether or not each highway is over-congested. You want to train a model, and then test it to compare predicted labels with known labels in the DataFrame. What should you do? Train the model with the entire DataFrame, and then test it with the entire DataFrame. Train the model with the entire DataFrame, and then create a new DataFrame containing random values with which to test it. Split the DataFrame into two randomly sampled DataFrames, and then train the model with one DataFrame and test it with the other. Train the model with the first row of the DataFrame, and then test it with the remaining rows.

Answers

Answer:

Split the data into two randomly sampled DataFrame,and then train the model with one DataFrame and test it with the other .As we have know labels in the data frame ,so this approch will give us a better picture on how accuractly our model is trained

Explanation:

Split the data into two randomly sampled DataFrame,and then train the model with one DataFrame and test it with the other .As we have know labels in the data frame ,so this approch will give us a better picture on how accuractly our model is trained

Final Instructions Your company ABC Consulting Company is asked to provide a proposal for the upcoming company expansion. You will need to research and provide quotes for new computers, cabling, network security and type of network topology. A Network proposal has to be developed for a manufacturing company that plans to move to a larger facility. They are currently in a 1500 square foot building. Below is the current office setup.
• Reception - 1 computer and printer
• CEO Office - 1 computer and printer
• Accounting Office - 5 computers and 5 printers
• Business Office – 3 computers and 3 printers
• Human Resources – 2 printers and 2 printers
• Sales Office – 10 computers and 10 printers
They are moving to a 3500 square foot building with 3 floors and each floor will have switches and routers to accommodate that floor. Below are the proposed additions:
• CEO Secretary – 1 computer and printer (CEO’s office area)
• Chief Financial Officer – 1 computer and printer (Accounting Department)
• Secretary - Chief Financial Officer – 1 computer and printer (Accounting Department)
• Information Technology – 2 computers and 2 printers
• Breakroom – 2 computers
• Human Resources – 6 computers and 2 network printers
• Sales – 6 computers and 2 network printers
• Wireless network for employees and guests
• Each department will have at least 2 empty offices for additional employees.
Your proposal will need to include the following information:
• Determine the number of drops for the new facility (2 drops per office)
• Determine the type of network cables (CAT5e, CAT6, etc.)
• Determine the type of security for the network
• Determine type of hardware and software
Deliverables
• Written proposal to the CEO include a timeline for completion
• Cost analysis to include computers, servers and cabling (make, model quantities and cost)
• Detailed diagram showing location of network devices and type of topology

Answers

Answer:

See attached images for the topology and total costing

A company uses the account code 669 for maintenance expense. However, one of the company's clerks often codes maintenance expense as 996. The highest account code in the system is 750. What would be the best internal control check to build into the company's computer program to detect this error?

Answers

Answer:

The correct answer to the following question will be "Valid-code test".

Explanation:

Even though no significance labels (including a standardized test score parameter) exist, valid data input codes or protocols could still be defined by having to type the correct codes as well as ranges.

To diagnose the given mistake, a valid code review will be the strongest internal control audit to incorporate into the organization's computer program.To insert valid code the syntax is: <Code or Range>. Throughout this scenario, each code is decided to enter on another step.

Write an interactive Python calculator program. The program should allow the user to type a mathematical expression, and then print the value of the expression. Include a loop so that the user can perform many calculations (say, up to 100). Note: To quit early, the user can make the program crash by typing a bad expression or simply closing the window that the calculator program is running in. You'll learn better ways of terminating interactive programs in later chapters.55

Answers

Answer:

please check this images that are below

Explanation:

Given the code that reads a list of integers, complete the number_guess() function, which should choose a random number between 1 and 100 by calling random.randint() and then output if the guessed number is too low, too high, or correct.
Import the random module to use the random.seed() and random.randint() functions.

random.seed(seed_value) seeds the random number generator using the given seed_value.
random.randint(a, b) returns a random number between a and b (inclusive).

For testing purposes, use the seed value 900, which will cause the computer to choose the same random number every time the program runs.
Ex: If the input is:
32 45 48 80
the output is:
32 is too low. Random number was 80.
45 is too high. Random number was 30.
48 is correct! 80 is too low.
Random number was 97.

# TODO: Import the random module
import random
def number_guess(num):
# TODO: Get a random number between 1-100
# TODO: Read numbers and compare to random number

if__name__ == "_main_":
# Use the seed 900 to get the same pseudo random numbers every time
random. seed(900)

# Convert the string tokens into integers
user_input = input()
tokens = user_input.split()
for token in tokens:
num = int(token)
number_guess(num)

Answers

Answer:

Following are the code to this question:

import random #import package

def number_guess(num): #define method number_guess

   n = random.randint(1, 100) #define variable n that hold random number

   if num < n: #define if block to check gess number is less then Random number  

       print(num, "is too low. Random number was " + str(n) + ".") #print message

   elif num > n: #check number greater then Random number

       print(num, "is too high. Random number was " + str(n) + ".") #print message

   else: #else block  

       print(num, "is correct!") #print message

if __name__ == '__main__': #define main method

   random.seed(900) #use speed method

   user_input = input() #define variable for user_input

   tokens = user_input.split()  #define variable that holds split value

   for token in tokens: #define loop to convert value into string token  

       num = int(token) # convert token value in to integer and store in num  

       number_guess(num)  # call number_guess method

Output:

33

33 is too low. Random number was 80.

Explanation:

In the above-given python code, first, we import the random package, in the next line, a method number_guess is defined, that accepts num parameter,  in this method, we store the random number in n variable and check the value from the conditional statement.

In this, we check value is less than from random number, it will print message too low, and its Random number. otherwise, it will go in the elif section. In this section it will check the value is greater than from a random number, it will print the message to high, and its Random number. otherwise, it will go to else section. In this, it will prints number and it is correct. In the main method, we input value, and use a token variable to convert the value into string token, and then convert its value into an integer, and then call the method number_guess.

Provide the code to insert a subtitle track named "Spanish Version" using the track text in the spanish.vtt file and the Spanish source language. Make this the active track in the video clip.

Answers

Answer:

See explaination

Explanation:

<video id="video" controls preload="metadata"> <source src="video/sintel-short.mp4" type="video/mp4"> <source src="video/sintel-short.webm" type="video/webm"> <track label="English" kind="subtitles" srclang="en" src="captions/vtt/sintel-en.vtt" default> <track label="Deutsch" kind="subtitles" srclang="de" src="captions/vtt/sintel-de.vtt"> <track label="Español" kind="subtitles" srclang="es" src="captions/vtt/sintel-es.vtt"> </video>

The operation times for the major functional units are 200ps for memory access, 200ps for ALU operation, and 100ps for register file read or write. For example, in single-cycle design, the time required for every instruction is 800ps due to lw instruction (instruction fetch, register read, ALU operation, data access, and register write). Here, we only consider lw instruction for speedup comparison. [2 pts]


a. If the time for an ALU operation can be shortened by 25%, will it affect the speedup obtained from pipelining? If yes, why? Otherwise, why?

b. What if the ALU operation now takes 25% more time? Will it affect the speedup obtained from pipelining? If yes, why? Otherwise, why? Then what is clock cycle time?

Answers

Answer:

a.

No, it will not affect the speedup obtained from pipe lining.

b.

Yes,it will affect.

Speedup time can be calculated as; 850 / 250 = 3.4

It means that pipeline speed up will reduce to 3.4, so the clock cycle time is 850 ps

Explanation:

See all solution attached

Design a class called NumDays. The class’s purpose is to store a value that represents a number of work hours and convert it to a number of days. For example, 8 hours would be converted to 1 day, 12 hours would be converted to 1.5 days, and 18 hours would be converted to 2.25 days. The class should have a constructor that accepts a number of hours, as well as member functions for storing and retrieving the hours and days. The class should also have the following overloaded operators: • (+) Addition operator. When two NumDays objects are added together, the overloaded + operator should return the sum of the two objects’ hours members. • (-) Subtraction operator. When one NumDays object is subtracted from another, the overloaded − operator should return the difference of the two objects’ hours members. Part 2: Design a class named TimeOff. The purpose of the class is to track an employee’s sick leave, vacation, and unpaid time off. It should have, as members,

Answers

Answer:

Check the explanation

Explanation:

#include <iostream>

#include <string>

using namespace std;

//class declaration

class NumDays{

private:

   double hours;

   double days;

public:

   //constructor

   NumDays(double h = 0){

       hours = h;

       days = h/(8.00);

   }

   //getter functions

   double getHours(){

       return hours;

   }

   double getDays(){

       return days;

   }

   //setter functions

   void setHours(double h){

       hours = h;

       days = h/(8.00);

   }

   void setDays(double d){

       days = d;

       hours = d*(8.00);

   }

   //overload + operator

   double operator+ (const NumDays &right){

       return hours+right.hours;

   }

   //overload - operator

   double operator- (const NumDays &right){

       //check if subtraction will give negative value

       if(hours < right.hours){

           cout << "ERROR! Cannot subtract! Now terminating!\n";

           exit(0);

       }

       return hours-right.hours;

   }

   //overload prefix ++ operator

   NumDays operator++(){

       //pre-increment hours member

       ++hours;

       //update days member

       days = hours/(8.00);

       //return modified calling object

       return *this;

   }

   //overload postfix ++ operator

   NumDays operator++(int){

       //post-increment hours member

       hours++;

       //update days member

       days = hours/(8.00);

       //return modified calling object

       return *this;

   }

   //overload prefix -- operator

   NumDays operator--(){

       //pre-decrement hours member

       --hours;

       //update days member

       days = hours/(8.00);

       //return modified calling object

       return *this;

   }

   //overload postfix -- operator

   NumDays operator--(int){

       //post-decrement hours member

       hours--;

       //update days member

       days = hours/(8.00);

       //return modified calling object

       return *this;

   }

};

int main()

{

   //create first object

   cout << "Creating object with 12 hours...\n";

   NumDays obj1(12);

   cout << obj1.getHours() << " hours = " <<obj1.getDays() << " days.\n";

   //create second object

   cout << "\nCreating object with 18 hours...\n";

   NumDays obj2(18);

   cout << obj2.getHours() << " hours = " <<obj2.getDays() << " days.\n";

   //test overloaded + operator

   cout << endl << "Adding hours... " << obj1 + obj2 << " hours.\n";

   //test overloaded - operator

   cout << endl << "Subtracting hours... " << obj2 - obj1 << " hours.\n\n";

   //test overloaded ++ operators

   cout << "Pre- and post-incrementing first object...\n";

   ++obj1;

   cout << obj1.getHours() << " hours = " <<obj1.getDays() << " days.\n";

   obj1++;

   cout << obj1.getHours() << " hours = " <<obj1.getDays() << " days.\n";

   //test overloaded -- operators

   cout << "\nPre- and post-decrementing second object...\n";

   --obj2;

   cout << obj2.getHours() << " hours = " <<obj2.getDays() << " days.\n";

   obj2--;

   cout << obj2.getHours() << " hours = " <<obj2.getDays() << " days.\n";

   return 0;

}

Answer:

Sew explaination foe code

Explanation:

Code below:

#include <iostream>

using namespace std;

class NumDays{

int hours;

float day;

public:

NumDays()

{

hours=0;

day=0.0;

};

NumDays(int h)

{

hours=h;

day=float(h/8.0);

};

int getHour()

{

return hours;

}

float getDay()

{

return day;

}

NumDays operator +(NumDays obj)

{

int h=getHour()+obj.getHour();

NumDays temp(h);

return temp;

}

NumDays operator -(NumDays obj)

{

int h=getHour()-obj.getHour();

NumDays temp(h);

return temp;

}

const NumDays& operator++() //prefix

{

++hours;

day=float(hours/8.0);

return *this;

}

const NumDays& operator--() //prefix

{

--hours;

day=float(hours/8.0);

return *this;

}

const NumDays operator++(int) //postfix

{

NumDays temp(*this);

++hours;

day=float(hours/8.0);

return temp;

}

const NumDays operator--(int) //postfix

{

NumDays temp(*this);

--hours;

day=float(hours/8.0);

return temp;

}

};

int main()

{

NumDays obj(2),obj2(10),obj3,obj4;

obj3=obj2-obj;

cout<<"'obj3=obj2-obj'=> Day:"<<obj3.getDay()<<"##Hour:"<<obj3.getHour()<<"\n";

obj3=obj+obj2;

cout<<"'obj3=obj+obj2'=> Day:"<<obj3.getDay()<<"##Hour:"<<obj3.getHour()<<"\n";

obj4=obj3++;

cout<<"'obj4=obj3++' => Day:"<<obj4.getDay()<<"##Hour:"<<obj4.getHour()<<"\n";

obj4=++obj3;

cout<<"'obj4=++obj3' => Day:"<<obj4.getDay()<<"##Hour:"<<obj4.getHour()<<"\n";

obj4=obj3--;

cout<<"'obj4=obj3--' => Day:"<<obj4.getDay()<<"##Hour:"<<obj4.getHour()<<"\n";

obj4=--obj3;

cout<<"'obj4=--obj3' => Day:"<<obj4.getDay()<<"##Hour:"<<obj4.getHour()<<"\n";

};

Other Questions
What could happen if people do not fulfill a civic duty or responsibility? "Give a specific example" If the determinant of this matrix is 24, what is the value of b?[tex]\left[\begin{array}{ccc}-5&4&1\\5&-7&-4\\-6&b&6\end{array}\right][/tex] When a certain ball is dropped, the function f(x)=4.5(0.65)^x models its height in feet after each bounce, where x is The bounce number. To the nearest hundredth, what is the height after the third bounce? what did kenny kane ask iggy to get him once he heard the police came? Your bill at a register is $153.60. Which would be better for you: A 15% off coupon or a $20 off coupon? a) 7.7 ftb) 13.4 ftc) 10.3 ftd) 12.3 ft How did new inventions change life for farmers? Find 6% of $5.65 and round the product to the nearest cent. Please Help!!! Braniest!!!!What is the converse of a theorem?A.A statement that is givenB.A statement that cannot be provenC.A statement that is proved by two different theoremsD.A statement formed by transposing what is to be proved by a theorem and what is given An independent gas station sits beside a busy highway. Half of its customers are travelers passing through the area. On a sign in front of the gas station two pricetiers are advertised for the same grades of gasoline. Gasoline purchased with cash is 20 cents per gallon less than gasoline purchase with a credit card.Why would the gas station charge more for purchases made with a credit card? To offset processing fees charged by credit card companiesTo protect credit card users from ID theftTo bring in more customersTo discourage the use of credit cards 4. What did the communists in Hungary do? if a pack of 24 pencils cost $2.35 how much does a single pencil cost A population of sagebrush lives in a grassland ecosystem. Over several years, erosion causes the soil of the grassland to have an increasing amount of sand in it. The data below was collected by scientists studying the ecosystem.YearPercentage ofSand in SoilAverage Height ofSagebrush (meters)Number ofSagebrush Plants1381.151202421.161293451.141374511.15145If the soil is 53% sand next year, which of the following statements is the most likely prediction? A. The average height of the sagebrush will decrease. B. The average height of the sagebrush will increase. C. The size of the sagebrush population will increase. If Miranda flips a coin twice, what is the probability that both coins will land heads up?The probability that the first coin will land heads up isThe probability that the second coin will land heads up isThe probability that both coins will land heads up is Need help!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Why is it difficult for all of the countries of the world to agree on how to solveenvironmental problems?there is a split about the levels of responsibility and equality between rich andpoor nationssome nations are more supportive of the precautionary principle than othersthere are often not consequences for nations that do not follow through withinternational agreementsall of these Kamden is a mind-reading alien. He had each friend draw and look at a card, then he guessed whether the card had a star on it. When might a country specialize in producing a particular good?OA. When it has high opportunity costs for producing that goodOB. When it has an absolute advantage in production of that goodOC. When its costs of transportation are particularly lowCD. When it has a well-developed productive infrastructure) Mike has 9 lollipops, 6 peanut butter cups and 3 pieces of chocolate. If he divides the candy equally into 3 bags, how many pieces of candy will be in each bag? Evidence supporting E.coli DNA polymerase III having the major role in nucleotide incorporation during replication includes:a) A point mutation can inactivate DNA pol III and inhibit replication.b) DNA polymerase III has a high Vmax.c) Replication is blocked at high temperatures in temperature sensitive mutants with a thermolabile form of DNA polymerase III.d) There are ten or fewer molecules of enzyme per cell.e) All of the above. Steam Workshop Downloader