2. Using the Book class developed in HW 4, write an application, BookLibrary, that creates a library (array) of up to 10 books and gives the user three options: to add a book, to delete a book from the library or to change a book’s information (i.e. number of pages and/or title) in the library. a. If the user selects the add option, issue an error message if the library is full. Otherwise, prompt the user for a book title. If the book with that title exists, issue an error message (no duplicated books titles are allowed). Otherwise, prompt the user for the number of pages and add the book. b. If the user selects the delete option, issue an error message if the library is empty. Otherwise, prompt the user for a book title. If the book with that title does not exist, issue an error message. Otherwise, "delete" (do not access the book for any future processing). c. If the user selects the change option, issue an error message if the library is empty. Otherwise, prompt the user for a book title. If the requested book title does not exist, issue an error message. Otherwise, prompt the user for a new title and/or number of pages and change the book information.

Answers

Answer 1

BookLibrary, that creates a library (array) of up to 10 books. If the user selects the add option, issue an error message if the library is full.If the book with that title exists, issue an error message

Explanation:

import java.util.Scanner;

import java.util.Arrays;

public class Derro_BooksLibrary {

public static void main(String[] args) {

 Derro_Books[] Library = new Derro_Books[10];

 Scanner scan = new Scanner(System.in);

 Derro_Books book1 = new Derro_Books("", 20);

 Derro_Books book2 = new Derro_Books("hi", 10);

 Library[0] = book1;

 Library[1] = book2;

 System.out.println("Enter 1 for add, 2 for delete, 3 for change, 4 to stop application: ");

 int answer = scan.nextInt();

 int counter = 0;

 int z = 0;

 while (true) {

  if (answer == 1) {

   for (Derro_Books book : Library) {

    counter = counter + 1;

   }

   if (counter == 10) {

    System.out.println("Library full");

   }

   System.out.println("Enter Title: ");

   String title = scan.nextLine();

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

    if (title == Library[i].getTitle()) {

     System.out.println("No Duplicated Books Titles Are Allowed");

     break;

    }

    else {

     z++;

    }

   }

   if (z < Library.length) {

   System.out.println("Enter number of pages: ");

   int pages = scan.nextInt();

   Library[z + 1] = new Derro_Books(title, pages);

  }

  if (answer == 2){

   if (Library.length == 0) {

    System.out.println("Library is empty");

   }

   System.out.println("Enter title of book: ");

   String title2 = scan.nextLine();

   for (int d = 0; d < Library.length; d++) {

    if (title2 == Library[d].getTitle())

     // Delete book

     System.out.println("Deleted book: " + title2);

    else

     System.out.println("Book does not exist");

   }

  }

  if (answer == 3) {

   if (Library.length == 0) {

    System.out.println("Library is empty.");

   } else {

    System.out.println("Enter book title: ");

    String title3 = scan.nextLine();

    for (int y = 0; y < Library.length; y++) {

     if (title3 != Library[y].getTitle())

      continue;

     else {

      System.out.println("Enter number of pages: ");

      int pages = scan.nextInt();

      Library[y] = new Derro_Books(title3, pages);

     }

    }

   }

  }

  String[] StringList = new String[10];

  for (int y = 0; y < Library.length; y++) {

   StringList[y] = Library[y].getTitle();

  }

  Arrays.sort(StringList);

  for (String bookt : StringList) {

   System.out.println(bookt + Library);

  }

 }

}

}

}


Related Questions

Task1: #Define a function called show_students which takes 2 parameters students and message #Print out a message, and then the list of students #Next, put the students in alphabetical order and print them #Next, Put students in reverse alphabetical order and print them Example Output: Our students are currently in alphabetical order. - Aaron - Bernice - Cody Our students are now in reverse alphabetical order. - Cody - Bernice - Aaron

Answers

Answer:

def show_students(message, sList):    print(message)    print(sList)    print("Our students are currently in alphabetical order")    sList.sort()    output = ""    for student in sList:        output += "-" + student    print(output)    print("Our students are currently in reverse alphabetical order")    sList.sort(reverse=True)    output = ""    for student in sList:        output += "-" + student    print(output)   show_students("Welcome to new semester!", ["Aaron","Bernice", "Cody"])

Explanation:

Firstly we declare a function that will take two inputs, message and student list (Line 1).

In the function, we first print the message and the original input student list (Line 2 - 3). Next, we use sort method to sort the input list and then output the sorted items from the list using a for loop (Line 5-10).

Next, we sort the list again by setting reverse = True and this will sort the list in descending order (Line 13). Again we use the similar way mentioned above to output the sorted items (in descending order) using a for loop (Line 14 -17)

We test the function using a sample student list (Line 18) and we shall get the output:

Welcome to new semester!

['Aaron', 'Bernice', 'Cody']

Our students are currently in alphabetical order

-Aaron-Bernice-Cody

Our students are currently in reverse alphabetical order

-Cody-Bernice-Aaron

On the Cities worksheet, select the range E14:H18 and apply Comma Style with zero decimal places. Select the range E13:H13 and apply Accounting Number format with zero decimal places.

Answers

Answer:

The complete work sheet is attached, also use these formulas below for more guidance:

E13 =IF(C13="No",$F$2,$F$4) copy down to E18

F13 =VLOOKUP(B13,$A$7:$B$10,2,0)*$B$5 copy down to F18

H13 =SUM(D13:G13) copy down to H18

I2 =AVERAGE(H13:H18)

I3 =MIN(H13:H18)

I4 =MAX(H13:H18)

Yet another variation: A better packet switched network employs the concept of acknowledgment. When the end user’s device receives a packet correctly it sends an acknowledgment to the sender. Here too, a packet is received correctly with probability p, but the sender keeps sending copies of a given packet until a copy is correctly received (signaled by acknowledgment). Let random variable N be the number of times the same message packet is sent. a) Find the PMF PN (n). b) To avoid excessive delays (too many repeated transmissions of same packet), it is required that the network maintain P[N < 4] > 0.95. Find the minimum value of p that will satisfy this requirement

Answers

Answer:

a. see explaination

b. 0.632

Explanation:

Packet switching is a method of grouping data that is transmitted over a digital network into packets. Packets are made of a header and a payload.

See attachment for the step by step solution of the given problem.

Write a program in python that reads an unspecified number of integers from the user, determines how many positive and negative values have been read, computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point with 2 digits after the decimal. Here is an example of sample run: Enter an integer, the input ends if it is 0: 1 Enter an integer, the input ends if it is 0: 2 Enter an integer, the input ends if it is 0: -1 Enter an integer, the input ends if it is 0: 3 Enter an integer, the input ends if it is 0: 0 The number of positivies is 3 The number of negatives is 1 The total is 5 The average is 1.25

Answers

The program which displays the number of positive and negative values inputted. The program written in python 3 goes thus :

pos_val = 0

#initialize a variable to hold the number of positive values

neg_val = 0

#initialize a variable to hold the number of negative values

sum = 0

#initialize a variable to hold the sum of all values

while True :

#A while loop is initiated

val = int(input("Enter integer values except 0 : "))

#prompts user for inputs

if val == 0 :

#checks if inputted value is 0

 break

#if True end the program

else :

#otherwise

 sum +=val

#add the value to the sum variable

 

 if val > 0 :

#checks if value is greater than 0

  pos_val += 1

#if true increase positive value counts by 1

 else :

  neg_val += 1

#if otherwise, increase negative value counts by 1

freq = float(pos_val + neg_val )

#calculates total number of values

print('The number of positive values is = ', pos_val)

#display number of positive values

print('The number of negative values is = ', neg_val)

#display number of negative values

print('The total sum of values is = ', sum)#display the total sum

print('The average is {:.2f}' .format((sum))

#display the average of the inputs

Learn more : https://brainly.com/question/19323897

The program reads integers from the user until 0 is entered, counts positive and negative values, calculates total and average (excluding zeros), and outputs the results.

Here's the Python program that meets the requirements:

positives = 0

negatives = 0

total = 0

count = 0

# Loop to read integers from user

while True:

   num = int(input("Enter an integer, the input ends if it is 0: "))    

   # Check if the input is 0 to end the loop

   if num == 0:

       break    

   # Increment counters based on positive/negative values

   if num > 0:

       positives += 1

   elif num < 0:

       negatives += 1    

   # Add non-zero input to total and increment count

   if num != 0:

       total += num

       count += 1

# Calculate average (excluding zeros)

if count != 0:

   average = total / count

else:

   average = 0

# Output results

print("The number of positives is", positives)

print("The number of negatives is", negatives)

print("The total is", total)

print("The average is {:.2f}".format(average))

The program initializes variables to count positive and negative integers, keep track of the total, and count the number of inputs.It uses a `while` loop to continuously read integers from the user until 0 is entered.Inside the loop, it updates the counters for positive and negative integers, adds non-zero integers to the total, and increments the count.After the loop, it calculates the average (excluding zeros) and outputs the results using formatted strings.

This program meets the requirements specified in the prompt and terminates when the user enters 0.

Translate the following C++ program to MIPS assembly program. *Please explain each instruction of your code by a comment and submit a .asm file*#include using namespace std; void myfunction(int arr[], int n) { int writes = 0; for(int start = 0; start <= n-2; start++){ int item = arr[start]; int pos = start; for(int i = start+1; i< n; i++) if (arr[i]

Answers

This response translates a C++ function to MIPS assembly language, detailing each MIPS instruction with comments and explanations. The step-by-step process converts high-level constructs like loops and conditions into MIPS equivalents. Detailed MIPS code is provided and explained for better understanding.

Translation of C++ Program to MIPS Assembly

The provided C++ function performs an operation on an array, and we will convert each instruction to its MIPS equivalent.

C++ Code:

#include  using namespace std;

void myfunction(int arr[], int n)

{ int writes = 0;

for(int start = 0; start <= n-2; start++)

{ int item = arr[start];

int pos = start;

for(int i = start+1; i < n; i++)

if (arr[i] < item) pos++;

// ... for swapping and updating ... }}

MIPS Assembly Code:

# Comment: function myfunction(int arr[], int n) defined start:

# Commentary on each variable:

# arr = $a0 (base address of the array)

# n = $a1 (number of elements in array)

# writes = $s0

# start = $s1

# item = $s2

# pos = $s3

# i = $s4

# Clear writes variable to 0 li $s0, 0

# Outer loop for start = 0 to n-2 outer_loop: move $s1, $zero

# initialize start move $s1, $t0

# copy start from $t0

# Check condition start <= n-2: sub $t2, $a1, 2 ble $s1, $t2, continue_outer_loop j end_of_program continue_outer_loop:

# int item = arr[start] sll $t1, $s1, 2

# start * 4 add $t3, $a0, $t1

# arr[start] lw $s2, 0($t3)

# item = arr[start]

# int pos = start move $s3, $s1

# pos = start

# Inner loop for(int i = start+1; i < n; i++) inner_loop: add $s4, $s1, 1

# i = start + 1 move $t4, $a1

# $t4 = n ble $s4, $t4, continue_inner_loop j update_outer_loop continue_inner_loop:

# if (arr[i] < item) lw $t5, 0($t3)

# arr[i] blt $t5, $s2, increment_pos j end_inner_loop increment_pos: add $s3, $s3, 1

# pos++ end_inner_loop: j inner_loop update_outer_loop:

# ... code for swapping and updating ... j outer_loop end_of_program:

Here are the detailed explanations for each MIPS instruction:

li $s0, 0: Initialize counter 'writes' to 0.

move $s1, $zero: Initialize 'start' to 0.

sll $t1, $s1, 2: Calculate memory offset for arr[start] (start*4).

add $t3, $a0, $t1: Get the address of arr[start].

lw $s2, 0($t3): Load value of arr[start] into 'item'.

move $s3, $s1: Initialize 'pos' with 'start'.

add $s4, $s1, 1: Set 'i' to start+1.

blt $t5, $s2,: Compare arr[i] with 'item'.

add $s3, $s3, 1: Increment 'pos' if arr[i] is less than 'item'.

he function below takes one parameter: a list of strings (string_list). Complete the function to return a new list containing only the strings from the original list that are less than 20 characters long.

Answers

Answer:

def select_short_strings(string_list):

   new_list = []

   

   for s in string_list:

       if len(s) < 20:

           new_list.append(s)

   return new_list

   

lst = ["apple", "I am learning Python and it is fun!", "I love programming, it is easy", "orange"]

print(select_short_strings(lst))

Explanation:

- Create a function called select_short_strings that takes one argument string_list

Inside the function:

- Initialize an empty list to hold the strings that are less than 20

- Inside the loop, check the strings inside string_list has a length that is smaller than 20. If found one, put it to the new_list.

- When the loop is done, return the new_list

- Create a list to check and call the function

Answer:

# the solution function is defined

# it takes a list as parameter

def solution(string_list):

# an empty new list is initialized

new_list = []

# a loop that loop through the splitted_list

# it checks if the length of each string is less than 20

# if it is less than 20

# it is attached to the new list

for each_string in string_list:

if(len(each_string) < 20):

new_list.append(each_string)

# the new list is printed

print(new_list)

# the function is called with a sample list

solution(["The", "player", "determined", "never", "compromised"])

Explanation:

The program is written in Python and it is well commented.

The function below takes a single input, containing list of strings. This function should return string containing an HTML unordered list with each of in_list strings as a list item. For example, if provided the list ['CS 105', 'CS 125', 'IS 206'], your function should return a string containing the following. The only whitespace that is important is those contained in the given strings (e.g., the space between CS and 105).

Answers

The following code will be used to calculate the given requirement.

Explanation:

This function will return string containing an HTML unordered list with each of in_list strings as a list item

def make_html_unordered_list(in_list):

   result = '<ul>\n'

   for item in in_list:

       result += '<li>' + item + '</li>\n'

   return result + '</ul>'

# Testing the function here. ignore/remove the code below if not required

print(make_html_unordered_list(['CS 105', 'CS 125', 'IS 206']))

Note: The only whitespace that is important is those contained in the given strings.

The program is an illustration of loops.

Loops are used to perform repetitive and iterative operations.

The function in Python where comments are used to explain each line s as follows:

#This defines the function

def make_html_unordered_list(in_list):

   #This creates the opening tag of an HTML unordered list

   result = '<ul>\n'

   #This iterates through the list

   for item in in_list:

       #This creates the unordered list, without the last closing tag

       result += '<li>' + item + '</li>\n'

   #This returns the unordered list, with the last closing tag

  return result + '</ul>'

Read more about similar programs at:

https://brainly.com/question/14282285

Guidelines:
 Loops are completely banned (for loop and while loop)
 You must use recursion in each function
 You are not allowed to import anything.
 You are not allowed to use the built-in function max(). Everything else is okay
 You are allowed to use sets, dictionaries, and any of their respective operations.
 You are allowed to use any string method except for string.join()
 You can do string slicing, but you cannot use the string[::-1] shortcut.
 You can use any list operation, except for list.sort() and list.reverse()
 Do not hard code to the examples
------------------------------------------------------------------------------------------------------------
Functions (You must use recursion in each function WITHOUT altering the original function signature):
def merge(listA, listB):
Description:
Combine two lists into one list, maintaining the order of the elements. You should assume that both lists given to this function contain elements in ascending order (smallest first).
Parameters:
listA, listB, two lists of elements (could be anything – assume homogenous data)
Return value:
a list, the combination of elements from listA and listB in ascending order.
Examples:
merge([1,2,3], [4,5,6]) → [1,2,3,4,5,6]
merge([1,2,3], [2,3,4]) → [1,2,2,3,3,4]
merge([2,4,6], [1,3,5]) → [1,2,3,4,5,6]
---------------------------------------------------
def largest_sum(xs, x, y):

Description:
Zig-zag through a two-dimensional list of integers from some starting point until you reach one of the list's boundaries, computing the largest sum that you find along the way. X and Y represent the row and column position in xs of the first number to use in the sum. The zig-zag pattern is made by limiting yourself to only looking at the number immediately on the right of (x,y) and the number immediately below (x,y) when figuring out which of those numbers yields the largest sum.

Parameters: xs, a 2D list of integers, x,y are the row and col position in xs
Return value: an integer, the largest sum you can find from position (x,y)
Examples:
largest_sum([[1,2],[3,0]],0,0) → 4
largest_sum([[5,6,1],[2,3,3]],0,0) → 17
largest_sum([[0,7,5],[6,-1,4],[-5,5,2]],0,0) → 18
largest_sum([[0,7,5],[6,-1,4],[-5,5,2]],1,1) → 6

Answers

Answer:

See Explaination

Explanation:

def merge(listA, listB):

if not listA:

return listB

if not listB:

return listA

# create a empty resulting list(merged list)

result = []

# check the first elements of list listA, listB)

if(listA[0]<listB[0]):

# append the first element of listA to result

result.append(listA[0])

# use recursion to get remaning elements

# listA is now reduced to listA[1:]

result.extend(merge(listA[1:],listB))

else:

# append the first element of listB to result

result.append(listB[0])

# use recursion to get remaning elements

# listB is now reduced to listB[1:]

result.extend(merge(listA,listB[1:]))

# return the resultant list

return result

def largest_sum(xs, x, y):

# get number of rows and columns

m = len(xs[0])

n = len(xs)

# if move is invalid

if(x>=n or y>=m):

return 0

# check if we have reached boundary then return xs[x][y]

if(x==(n-1) and y==(m-1)):

return xs[x][y]

else:

# return max of two possible moves(leftmove, down move)

# move left (in this increment x)

left = xs[x][y] + largest_sum(xs,x+1,y)

# move down (in this increment y)

down = xs[x][y] + largest_sum(xs,x,y+1)

# return the maximum of two possible moves

if(left>down):

return left

else:

return down

# test code

print("Output for sample test cases given in problem:")

print(merge([1,2,3], [4,5,6]))

print(largest_sum([[1,2],[3,0]],0,0))

print(largest_sum([[5,6,1],[2,3,3]],0,0))

print(largest_sum([[0,7,5],[6,-1,4],[-5,5,2]],0,0))

print(largest_sum([[0,7,5],[6,-1,4],[-5,5,2]],1,1))

12. In cell I9, create a formula without using a function that first adds the selected boxed set’s net weight (cell I8) to the packing weight (cell F5), and then divides the value by 16 to show the shipping weight in pounds.

Answers

Answer:

=(I8+F5)/16

Explanation:

In cell I9, we type the following

=(I8+F5)/16

I8 is the boxed set net weight

F5 is the packing weight

The question asked us to add and divide by 16

We use the addition operator '+' instead of built-in "SUM" function as required by the question.

So, we add I8 and F5 and then divide by 16 in cell I9.

Alice and Bob decide to communicate using NTRUEncrypt with parameters (N, p, q) = (7, 3, 29). Alice’s public key is h(x) = 3 + 14X − 4X2 + 13X3 − 6X4 + 2X5 + 7X6 . Bob sends Alice the plaintext message m(x)= 1+ X − X2 − X3 − X6 using the random element r(x) = −1 + X2 − X5 + X6.

(a) What ciphertext does Bob send to Alice?

(b) Alice’s private key is f(x) = −1 + X − X2 + X4 + X6 and F 3(x)=1+ X + X2 + X4 + X5 − X6. Check your answer in (a) by using f and F 3 to decrypt the message.

Answers

Final answer:

To encrypt the plaintext message, Bob uses Alice's public key and a random element. The ciphertext is obtained by multiplying the plaintext message with the public key. To decrypt the ciphertext, Alice uses her private key by multiplying the ciphertext with the private key polynomial and reducing modulo p.

Explanation:

To encrypt the plaintext message, Bob needs to use Alice's public key along with a random element. The ciphertext is obtained by multiplying the plaintext message with the public key. In this case, the plaintext message m(x)= 1+ X − X2 − X3 − X6 and the random element r(x) = −1 + X2 − X5 + X6. By multiplying these polynomials, Bob obtains the ciphertext c(x)= -1 - X - X^2 + 4X^3 + 8X^4 - 5X^5 - 30X^6 + 5X^7 - 6X^9 - 3X^10 + 8X^11 + 13X^12 + 2X^13 - 6X^14 + 26X^15 - 16X^16.

To decrypt the ciphertext, Alice uses her private key. She multiplies the ciphertext with her private key polynomial and reduces modulo p, resulting in the decrypted message. The private key polynomial for Alice is f(x) = −1 + X − X2 + X4 + X6. By multiplying the ciphertext c(x) with the private key polynomial f(x) modulo 3, the decrypted message is obtained: d(x)= 1+ X − X2 − X3 − X6.

In the sport of diving, seven judges award a score between 0 and 10, where each score may be a floating-point value. The highest and lowest scores are thrown out and the remaining scores are added together. The sum is then multiplied by the degree of difficulty for that dive. The degree of difficulty ranges from 1.2 to 3.8 points. The total is then multiplied by 0.6 to determine the diver’s score. Write a computer program that will ultimately determine the diver’s score. This program must include the following methods:

Answers

A diver's score in diving is calculated by taking the middle five scores from judges, summing them up, multiplying by the dive's degree of difficulty, and then multiplying by 0.6. A computer program designed to calculate these scores would need to incorporate methods for each step of this process.

The sport of diving involves judges awarding scores to divers based on their performance. To calculate a diver's score, a computer program must follow these steps:

Receive a score between 0 and 10 from each of the seven judges.Discard the highest and lowest scores.Add the remaining five scores together.Multiply this sum by the degree of difficulty for the dive, which ranges from 1.2 to 3.8.Finally, multiply by 0.6 to determine the diver's final score.

This scoring system ensures that outliers do not disproportionately affect the diver's score and that the degree of difficulty is appropriately factored into the final score, producing a fair assessment of the performance. The computer program must include methods to perform each of these tasks, ensuring accurate point tallies and final calculations for each dive.

C++ Project

1) Prompt the user to enter a string of their choosing (Hint: you will need to call the getline() function to read a string consisting of white spaces.) Store the text in a string. Output the string. (1 pt)

Ex:

Enter a sample text:

We'll continue our quest in space. There will be more shuttle flights and more shuttle crews and, yes, more volunteers, more civilians, more teachers in space. Nothing ends here; our hopes and our journeys continue! You entered: We'll continue our quest in space. There will be more shuttle flights and more shuttle crews and, yes, more volunteers, more civilians, more teachers in space. Nothing ends here; our hopes and our journeys continue!




(2) Implement a PrintMenu() function, which has a string as a parameter, outputs a menu of user options for analyzing/editing the string, and returns the user's entered menu option. Each option is represented by a single character. If an invalid character is entered, continue to prompt for a valid choice. Hint: Implement Quit before implementing other options.

Call PrintMenu() in the main() function. Continue to call PrintMenu() until the user enters q to Quit.

More specifically, the PrintMenu() function will consist of the following steps:

-print the menu

-receive an end user's choice of action (until it's valid)

-call the corresponding function based on the above choice


Ex:

MENU

c - Number of non-whitespace characters

w - Number of words

f - Find text

r - Replace all !'s

s - Shorten spaces

q - Quit

Choose an option:




(3) Implement the GetNumOfNonWSCharacters() function. GetNumOfNonWSCharacters() has a constant string as a parameter and returns the number of characters in the string, excluding all whitespace. Call GetNumOfNonWSCharacters() in the PrintMenu() function.

Ex:

Number of non-whitespace characters: 181

(4) Implement the GetNumOfWords() function. GetNumOfWords() has a constant string as a parameter and returns the number of words in the string. Hint: Words end when a space is reached except for the last word in a sentence. Call GetNumOfWords() in the PrintMenu() function.

Ex:

Number of words:35

(5) Implement the FindText() function, which has two strings as parameters. The first parameter is the text to be found in the user provided sample text, and the second parameter is the user provided sample text. The function returns the number of instances a word or phrase is found in the string. In the PrintMenu() function, prompt the user for a word or phrase to be found and then call FindText() in the PrintMenu() function. Before the prompt, call cin.ignore() to allow the user to input a new string.

Ex:

Enter a word or phrase to be found:
more
"more" instances: 5

(6) Implement the ReplaceExclamation() function. ReplaceExclamation() has a string parameter and updates the string by replacing each '!' character in the string with a '.' character. ReplaceExclamation() DOES NOT output the string. Call ReplaceExclamation() in the PrintMenu() function, and then output the edited string.

Ex.

Edited text: We'll continue our quest in space. There will be more shuttle flights and more shuttle crews and, yes, more volunteers, more civilians, more teachers in space. Nothing ends here; our hopes and our journeys continue.

(7) Implement the ShortenSpace() function. ShortenSpace() has a string parameter and updates the string by replacing all sequences of 2 or more spaces with a single space. ShortenSpace() DOES NOT output the string.

Answers

Answer:

see explaination

Explanation:

#include <iostream>

#include <string>

using namespace std;

//function declarations

char PrintMenu(string& userString);

int GetNumOfNonWSCharacters(const string userString);

int GetNumOfWords(const string userString);

int FindText(const string& userString, const string& findString);

void ReplaceExclamation(string& periodString);

void ShortenSpace(string& shortenedString);

char menuChoice;

int main()

{

string userString;

cout << "Enter a sample text: ";

getline(cin, userString);

cout << endl << endl << "You entered: " << userString << endl;

PrintMenu(userString);

while (menuChoice != 'q')

{

PrintMenu(userString);

}

// system("pause");

return 0;

}

char PrintMenu(string& userString)

{

cout << "MENU" << endl;

cout << "c - Number of non-whitespace characters" << endl;

cout << "w - Number of words" << endl;

cout << "f - Find text" << endl;

cout << "r - Replace all !'s" << endl;

cout << "s - Shorten spaces" << endl;

cout << "q - Quit" << endl << endl;

cout << "Choose an option: " << endl;

cin >> menuChoice;

while ((menuChoice != 'c') && (menuChoice != 'w') && (menuChoice != 'f') && (menuChoice != 'r') && (menuChoice != 's') && (menuChoice != 'q'))

{

cout << "MENU" << endl;

cout << "c - Number of non-whitespace characters" << endl;

cout << "w - Number of words" << endl;

cout << "f - Find text" << endl;

cout << "r - Replace all !'s" << endl;

cout << "s - Shorten spaces" << endl;

cout << "q - Quit" << endl << endl;

cout << "Choose an option: " << endl;

cin >> menuChoice;

}

if (menuChoice == 'c')

{

cout << "Number of non-whitespace characters: " << GetNumOfNonWSCharacters(userString) << endl << endl;

}

else if (menuChoice == 'w')

{

cout << "Number of words: " << GetNumOfWords(userString) << endl << endl;

}

else if (menuChoice == 'f')

{

string stringFind;

cin.clear();

cin.ignore(20, '\n');

cout << "Enter a word or phrase to be found: " << endl;

getline(cin, stringFind);

cout << "\"" << stringFind << "\"" << " instances: " << FindText(userString, stringFind) << endl;

}

else if (menuChoice == 'r')

{

cout << "Edited text: ";

ReplaceExclamation(userString);

cout << userString << endl << endl;

}

else if (menuChoice == 's')

{

ShortenSpace(userString);

cout << "Edited text: " << userString << endl;

}

return menuChoice;

}

int GetNumOfNonWSCharacters(const string userString)

{

int numCharNotWhiteSpace = 0;

for (size_t i = 0; i < userString.size(); i++)

{

if (!isspace(userString.at(i)))

{

numCharNotWhiteSpace += 1;

}

}

return numCharNotWhiteSpace;

}

int GetNumOfWords(const string userString)

{

int numWords = 1;

for (size_t i = 0; i < userString.size(); i++)

{

if (isspace(userString.at(i)) && !isspace(userString.at(i + 1)))

{

numWords += 1;

}

}

return numWords;

}

int FindText(const string& userString, const string& findString)

{

int numInstance = 0;

int indx = 0;

string editedString;

editedString = userString;

while (editedString.find(findString) != string::npos)

{

numInstance++;

indx = editedString.find(findString);

editedString = editedString.substr(indx + findString.length(), (editedString.length() - 1));

}

return numInstance;

}

void ReplaceExclamation(string& periodString)

{

for (size_t i = 0; i < periodString.size(); i++)

{

if (periodString.at(i) == '!')

{

periodString.at(i) = '.';

}

}

}

void ShortenSpace(string& shortenedString)

{

for (size_t i = 0; i < shortenedString.size(); i++)

{

if (isspace(shortenedString.at(i)) && !isalpha(shortenedString.at(i + 1)))

{

shortenedString.erase(i, 1);

}

}

}

Multiple arrays. Jump to level 1 For any element in keysList with a value greater than 40, print the corresponding value in itemsList, followed by a space. Ex: If keysList = {32, 105, 101, 35} and itemsList = {10, 20, 30, 40}, print: 20 30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 #include #include using namespace std; int main() { const int SIZE_LIST = 4; int keysList[SIZE_LIST]; int itemsList[SIZE_LIST]; int i; cin >> keysList[0]; cin >> keysList[1]; cin >> keysList[2]; cin >> keysList[3]; cin >> itemsList[0]; cin >> itemsList[1]; cin >> itemsList[2]; cin >> itemsList[3]; /* Your code goes here */ cout << endl; return 0; } 1 2 Check Next

Answers

Answer:

Replace/* Your code goes here */ with

for(int count = 0; count<4; count++)

{

if(keysList[count] > 40)

{

cout<<itemsList[count]<<" ";

}

}

Explanation;

The solution provides used an iteration to loop from the first toll the last.

The index of an array starts at 0

The index of the last element is calculated as total element - 1

Since the count of the array is 4, the last index is 4 - 1 = 3.

In the solution provides, a count integer variable is declared to iterate through the keysList array

Each element of keysList array is tested to know if it's greater than 40.

If yes the corresponding element in itemsList is printed followed by a space

Else

Nothing is done

The codes segment goes thus

for(int count = 0; count<4; count++)

{

if(keysList[count] > 40)

{

cout<<itemsList[count]<<" ";

}

}

The programming projects of Chapter 4 discussed a Card class that represents a standard playing card. Create a class called DeckOfCards that stores 52 objects of the Card class. Include methods to shuffle the deck, deal a card, and report the number of cards left in the deck. The shuffle method should assume a full deck. Create a driver class with a main method that deals each card from a shuffled deck, printing each card as it is dealt.

Answers

The DeckOfCards class manages a deck of 52 Card objects. It provides methods to shuffle, deal a card, report the number of cards left, and display the deck.

To implement the DeckOfCards class, we can utilize the Card class you created in Assignment 4 and add methods to manage a deck of cards. The UML Class diagram for DeckOfCards might look like:

+-----------------------------------+

|          DeckOfCards          |

+-----------------------------------+

| - cards: List<Card>           |

+-----------------------------------+

| + DeckOfCards()              |

| + shuffle()                         |

| + dealCard(): Card           |

| + cardsLeft(): int               |

| + toString(): String            |

+-----------------------------------+

The DeckOfCards class contains a List of Card objects, representing the deck. The constructor initializes the deck, and the shuffle method randomizes the order of cards. The dealCard method returns the top card and reduces the count of remaining cards. The cardsLeft method returns the count of remaining cards, and toString provides a string representation of the deck.

Here's a simplified implementation in Java:

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class DeckOfCards {

   private List<Card> cards;

   public DeckOfCards() {

       cards = new ArrayList<>();

       for (int suit = 1; suit <= 4; suit++) {

           for (int faceValue = 1; faceValue <= 13; faceValue++) {

               cards.add(new Card(suit, faceValue));

           }

       }

   }

   public void shuffle() {

       Collections.shuffle(cards);

   }

   public Card dealCard() {

       if (cards.isEmpty()) {

           return null; // Deck is empty

       }

       return cards.remove(0);

   }

   public int cardsLeft() {

       return cards.size();

   }

   public String toString() {

       StringBuilder deckString = new StringBuilder();

       for (Card card : cards) {

           deckString.append(card.toString()).append("\n");

       }

       return deckString.toString();

   }

}

For the driver class, you can create an instance of DeckOfCards, print the initial deck, shuffle it, and then deal and print each card from the shuffled deck.

The question probable maybe:

In Assignment 4, you created a Card class that represents a standard playing card. Use this to design and implement a class called DeckOfCards that stores 52 objects of the Card class. Include methods to shuffle the deck, deal a card, and report the number of cards left in the deck, and a toString to show the contents of the deck. The shuffle methods should assume a full deck. Document your design with a UML Class diagram. Create a separate driver class that first outputs the populated deck to prove it is complete, shuffles the deck, and then deals each card from a shuffled deck, displaying each card as it is dealt.

Hint: The constructor for DeckOfCards should have nested for loops for the face values (1 to 13) within the suit values (1 to 4). The shuffle method does not have to simulate how a deck is physically shuffled; you can achieve the same effect by repeatedly swapping pairs of cards chosen at random.

Create an ERD based on the Crow's Foot notation using the following requirements: An INVOICE is written by a SALESREP. Each sales representative can write many invoices, but each invoice is written by a single sales representative. The INVOICE is written for a single CUSTOMER. However, each customer can have many invoices. An INVOICE can include many detail lines (LINE), each of which describes one product bought by the customer. The product information is stored in a PRODUCT entity. The product's vendor information is found in a VENDOR entity.

Answers

Answer:

Check the explanation

Explanation:

An Entity Relationship Diagram (ERD) can be described as a data structures snapshot. An Entity Relationship Diagram reveals entities (tables) in a database and the relationships among tables that are within that database. For a perfect database design it is important to have an Entity Relationship Diagram.

The below diagram is the solution to the question above.

How do i enter this as a formula into excel IF function?




In cell C15, enter a formula using an IF function to determine if you need a loan. Your available cash is located on the Data sheet in cell A3 ($9000). If the price of the car is less than or equal to your available cash, display "no". If the price of the car is more than your available, cash, display "yes". Use absolute references where appropriate—you will be copying this formula across the row. The available cash is 9000




What would I enter into the Logical_test section?

Answers

Answer:

Call microsoft

Explanation:

Exel Is My Worst Nightmare Just Call Microsoft "I'd Hope They'd Have A Answer For That"

The IF function allows the user to make logical comparison among values.

The formula to enter in cell 15 is: [tex]\mathbf{=IF(\$A\$4 > \$A\$3, "yes", "no")}[/tex]

The syntax of an Excel IF function is:

[tex]\mathbf{=IF (logical\_test, [value\_if\_true], [value\_if\_false])}[/tex]

Where:

IF [tex]\to[/tex] represents the IF function itselflogical_test [tex]\to[/tex] represents values to be compared[value_if_true] [tex]\to[/tex] represents the return value if the condition is true [value_if_false] [tex]\to[/tex] represents the return value if the condition is false

From the question, the cells to compare are:

Cell A3The cell that contains the car price (assume the cell is A4)

So, the IF function that compares both cells is:

[tex]\mathbf{=IF(A4 > A3, "yes", "no")}[/tex]

The above formula checks if A4 is greater than A3.

If the condition is true, the result is "yes"Otherwise, it is "no"

The question requires that the cells are referenced using absolute cell referencing.

This means that, we make use of the dollar sign ($), when writing the cells.

So, the correct formula is:

[tex]\mathbf{=IF(\$A\$4 > \$A\$3, "yes", "no")}[/tex]

Read more about Excel formulas at:

https://brainly.com/question/1285762

A digital certificate system Group of answer choices uses third-party CAs to validate a user's identity. uses digital signatures to validate a user's identity. uses tokens to validate a user's identity. is used primarily by individuals for personal correspondence.

Answers

Answer: A. Uses third-party CA's to validate a users identity.

Explanation:

A digital certificate is a binding electronic document used in the exchange of messages between a sender and receiver across the internet. It is useful in validating the identities of all users so that none can deny either sending or receiving a message. It also offers some protection to the data sent and received.

Certification Authorities are recognized bodies who have the responsibility of ensuring the true identities of users. After achieving this they then issue a certificate that can serve as a guarantee. A public key is present in the certificate which only the true users can access.

These Certification Authorities would then confirm that the key and digital signature matches the identities of the users.

Answer:

uses third-party CAs to validate a user's identity.

Explanation:

Digital certificate is an electronic file which can be used to verify the identity of a party on the Internet. A digital certificate can be likened to an electronic passport of the internet.

It is issued by an organization called a certificate authority (CA).

A digital certificate system uses a trusted third party (certification authority), to validate a user's identity.

python Write a class named Taxicab that has three **private** data members: one that holds the current x-coordinate, one that holds the current y-coordinate, and one that holds the odometer reading (the actual odometer distance driven by the Taxicab, not the Euclidean distance from its starting point). The class should have an init method that takes two parameters and uses them to initialize the coordinates, and also initializes the odometer to zero. The class should have get methods for each data member: get_x_coord, get_y_coord, and get_odometer. The class does not need any set methods. It should have a method called move_x that takes a parameter that tells how far the Taxicab should shift left or right. It should have a method called move_y that takes a parameter that tells how far the Taxicab should shift up or down. For example, the Taxicab class might be used as follows:

Answers

Answer:

see explaination

Explanation:

class Taxicab():

def __init__(self, x, y):

self.x_coordinate = x

self.y_coordinate = y

self.odometer = 0

def get_x_coord(self):

return self.x_coordinate

def get_y_coord(self):

return self.y_coordinate

def get_odometer(self):

return self.odometer

def move_x(self, distance):

self.x_coordinate += distance

# add the absolute distance to odometer

self.odometer += abs(distance)

def move_y(self, distance):

self.y_coordinate += distance

# add the absolute distance to odometer

self.odometer += abs(distance)

cab = Taxicab(5,-8)

cab.move_x(3)

cab.move_y(-4)

cab.move_x(-1)

print(cab.odometer) # will print 8 3+4+1 = 8

Final answer:

The Taxicab class in Python should have private data members for x-coordinate, y-coordinate, and the odometer. It includes an initializer, get methods for each data member, and methods to move the taxicab horizontally and vertically, updating the odometer with each movement.

Explanation:

The student's question pertains to writing a Python class named Taxicab which models a taxicab's movements and odometer readings. To implement this, you would define the class with private data members for the x-coordinate, y-coordinate, and odometer reading. The odometer should track the total distance driven rather than the Euclidean distance from the start point. The class should have an init method to initialize these values, where the x and y coordinates are set by provided parameters and the odometer starts at zero. Additionally, there should be get methods for each of these private data members to allow access to their values. Movement methods move_x and move_y should be implemented to handle horizontal and vertical movements, respectively, and the odometer should be updated accordingly based on the magnitude of the movement.

Given the following System with a maximum of 18 devices: Job No. Devices Allocated Maximum Required Remaining Needs Job 1 6 8 X Job 2 2 9 X Job 3 5 8 X Job 4 3 5 X Using the Banker’s Algorithm, answer these questions: a. Calculate the number of available devices. b. Determine the remaining needs for each job in each system. c. Determine whether the system is safe or unsafe.

Answers

Complete Data:

Job No.          Devices Allocated       Maximum Required       Remaining Need

Job 1                          6                                        8                                    X

Job 2                          2                                        9                                    X

Job 3                          5                                        8                                    X

Job 4                          3                                         5                                   X    

Answer:

a) Number of available devices = 2

b) Remaining need for job 1 = 2

Remaining need for job 2 = 7

Remaining need for job 3 = 3

Remaining need for job 4 = 2

c) The system is safe

Explanation:

a) Calculate the number of available devices

Number of available devices = (Maximum number of devices) - (Total number of devices allocated)

Maximum number of devices  = 18

Total number of allocated devices = (6 + 2 + 5 + 3)

Total number of allocated devices = 16

Number of available devices = 18 - 16

Number of available devices = 2

b) Determine the remaining needs for each job in each system

Remaining needs = (Maximum Required - Number of devices allocated)

For Job 1

Remaining need = 8 - 6 = 2

For Job 2

Remaining need = 9 - 2 = 7

For Job 3

Remaining need = 8 - 5 = 3

For Job 4

Remaining need = 5 - 3 = 2

c) Determine whether the system is safe or unsafe

For the system to be safe, Need ≤ Available

Where New Available = Available + Allocation

For Job 1

Need = 2

Available devices = 2

2 ≤ 2   (Job 1 is safe)

New available = 2 + 6 = 8

For Job 2

Need = 7

Available devices = 8

7 ≤ 8   (Job 2 is safe)

New available = 2 + 8 = 10

For Job 3

Need = 3

Available devices = 10

3 ≤ 10   (Job 3 is safe)

New available = 5 + 10 = 15

For Job 4

Need = 2

Available devices = 15

2 ≤ 15   (Job 2 is safe)

New available = 3 + 15 = 18

Since all the jobs are safe, the system is safe

1. Perform risk analysis for your home network. 2. Prepare a disaster recovery plan for your home net- work. 3. Research antivirus and antispyware so ware that you can purchase for your home network

Answers

Answer:

See the attached file for the answers

Explanation:

Find attached for the explanation

Amnswer:

Exposure of kids to unwanted pages, poor power system and refusal to backup works are some of the risk analysts

Explanation:

RISK ANALYSIS

1. Kids access to unwanted pages and sites if online are a big risk to private information and exposure to threat from hackers and information scammers

2. Poor power system results in an abrupt shutdown of system which is not encouraged. This is commonly responsible for system breakdown and other malfunctioning of the system

3. Lack of backup structure when not put in place are a very good avenue to home network risk which could have a very harmful effect to the home network activities.

DISASTER RECOVERY PLANS

1. Establish a system recovery and restore plans that could help you roll back actions when there is a system error that prevents the network from booting or starting up.

2. Establish a system restriction plan on your home network when kids and children are involved in it usage else vital information and configurations could be hampered. Focus in this context should also be geared towards website control system and constant system monitoring structure.

3. Power backup plans must include setting up a steady power source which should serve as alternatives to inconsistent power outage, irregular power supply and possible related issues. Such power structure should be able to mitigate for any network activities that requires a long time to backup

4. Other home network activities that requires consistent and constant backup should be done through external storage devices and through on line drives in order to ensure that document are not lost when emergency breakdown occurs.

SYSTEM ANTIVIRUS AND ANTI SPYWARES

From research some of the most used antivirus with spyware's features that has been largely used both online band offline include;

1. The Norton 360

2. Norton security

3. Avast

4. Avira ad lots more.

Which of the following exhibit spatial locality: 1. Repetition control flow 2. Binary search on an array of integers 3. Accessing the elements of a row in a 2D array that is heap allocated as an array of arrays

Answers

Answer:

1. Repetition control flow

3. Accessing the elements of a row in a 2D array that is heap allocated as an array of arrays

Explanation:

1. Elements in 1D memory are stored in contiguous memory location thus it follows spatial locality. ( RIGHT OPTION)

2. Binary search in an array does not follow spatial locality because the elements in an array with the binary search are not accessed in a contiguous manner but in a non-contiguous manner. HENCE IT IS NOT RIGHT OPTION

3. Sequencing control also follows spatial locality ( RIGHT OPTION)

Write a program in C which will open a text file (Scores.txt) containing section number and total scores of students of CSCI1320. You need to create the file Scores.txt using any text editor like Notepad etc and make sure the file is in the same directory of your c program. Your program needs to open the file and based on section number, compute the average score for each section. Finally, you need to print section number along with average score and find the section with the highest average score. Consider there are only 3 sections for the course CSCI1320. [Note: use have to use pointers and user-defined functions wherever necessary. You need to demonstrate both pass-by value and pass-by-reference in this program]

Answers

Answer:

See explaination

Explanation:

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

int main()

{

FILE *fp;

char section[10][2], score[10][10],buf[10][4], buf1[4];

int i=0, j = 0, k = 0, l = 0, c1 = 0, c2 = 0, c3 = 0, sec;

float avg1 = 0 ,avg2 = 0, avg3 = 0 ,avg[3] ,max;

fp = fopen("scores.dat","r");

/* read data from scores.dat file and store into buf */

while(fscanf(fp, "%s", buf[i++])!=EOF);

/* separate scores and sections */

for(j=1; j<i; j++){

if(j%2!=0){

strcpy(section[k++], buf[j-1]);

}

else{

strcpy(score[l++], buf[j-1]);

}

}

/* calculate avgerage */

for(i=0;i<7;i++){

if(strcmp(section[i], "1")){

avg1 = avg1 + atof(score[i]);

c1++;

}

if(strcmp(section[i], "2")){

avg2 = avg2 + atof(score[i]);

c2++;

}

if(strcmp(section[i], "1")){

avg3 = avg3 + atof(score[i]);

c3++;

}

}

avg[0] = avg1/c1;

avg[1] = avg2/c2;

avg[2] = avg3/c3;

max = avg[0];

for(i=0;i<3; i++)

if(avg[i] > max){

max = avg[i];

sec = i;

}

printf("Sectrion 1 Avg: %f\nSection 2 Avg: %f\nSection 3 Avg: %f\nHighest Avg by:Section %s\n",avg[0],avg[1],avg[2],section[sec]);

}

Objective:This assignment is designed to give you experience with thinking about algorithm analysis and performanceevaluation.Project DescriptionYou will analyze three algorithms to solve the maximum contiguous subsequence sum problem, and then evaluate the performance of instructor-supplied implementations of those three algorithms. You will compare your theoretical results to your actual results in a written report.What is the maximum contiguous subsequence sum problem?Given a sequence of integers A1, A2 ... An (where the integers may be positive or negative), find a subsequence Aj, ..., Ak that has the maximum value of all possible subsequences.The maximum contiguous subsequence sum is defined to be zero if all of the integers in the sequence are negative.

Answers

Answer:

Check the explanation

Explanation:

#include<stdio.h>

/*Function to return max sum such that no two elements

are adjacent */

int FindMaxSum(int arr[], int n)

{

 int incl = arr[0];

 int excl = 0;

 int excl_new;

 int i;

 for (i = 1; i < n; i++)

 {

    /* current max excluding i */

    excl_new = (incl > excl)? incl: excl;

    /* current max including i */

    incl = excl + arr[i];

    excl = excl_new;

 }

  /* return max of incl and excl */

  return ((incl > excl)? incl : excl);

}

/* Driver program to test above function */

int main()

{

 int arr[] = {5, 5, 10, 100, 10, 5};

 printf("%d \n", FindMaxSum(arr, 6));

 getchar();

 return 0;

}

Consider the following assembly language code:

I0: lw $s2, 0($s0)
I1: addi $s3, $s2, 4
I2: slt $t0, $s0, $s1
I3: add $t1, $t0, $s0
I4: sub $t4, $t1, $s2
I5: lw $t4, 100($s0)
I6: and $s0, $t0, $s3
I7: w $t5, 0($t1)

For each instruction, identify whether or not a hazard should be detected. If so, identify the type of hazard as structure, data, or control. Assume the instructions are being processed on a MIPS pipelined datapath without forwarding.

Answers

Answer:

See explaination

Explanation:

Given that:

Consider the MIPS assembly language code segment given below.

I1: addi $s3, $s2, 5

I2: sub $s1, $s3, $s4

I3: add $s3, $s3, $s1

I4: Iw $s2, 0($s3)

I5: sub $s2, $s2, $s4

I6: sw $s2, 200($s3)

I7: add $s2, $s2, $s4

(a) Identify the data dependency in the following code:

RAW - Read after write: This dependency occurs when instruction I2 tries to read register before instruction I1 writes it.

WAW - Write after write: This dependency occurs when instruction I2 tries to write register before instruction I1 writes it

• Read after write (RAW)

I1: addi $s3, $s2, 5

I2: sub $s1, $s3, $s4

• Read after write (RAW)

I2: sub $s1, $s3, $s4

I3: add $s3, $s3, $s1

• Write after write (WAW)

I4: lw $s2, 0($s3)

I5: sub $s2, $s2, $s4

• Read after write (RAW)

I5: sub $s2, $s2, $s4

I6: sw $s2, 200($s3)

(b) Data hazards which can be solved by forwarding:

(1) Read after write (RAW)

I1: addi $s3, $s2, 5

I2: sub $s1, $s3, $s4

addi $s3, $s2,5 IF ID EXE MEM WB

sub $51, $s3, $s4 IF ID EXE MEM WB

(2) Read after write (RAW)

I2: sub $s1, $s3, $s4

I3: add $s3, $s3, $s1

sub $51, $s3. $54 IF | ID EXE |MEM WB

add $s3, $s3, $s1 IF | ID EXE | MEM | WB

(3) Read after write (RAW)

I5: sub $s2, $s2, $s4

I6: sw $s2, 200($s3)

sub $52, $s2, $54 IF ID |EXE MEM | WB

sw $52, 200($s3) IF ID EXE MEM WB

(c) Data hazards which can lead to pipeline stall:

• Write after write (WAW)

I4: lw $s2, 0($s3)

I5: sub $s2, $s2, $s4

lw $s2, 0($s3) IF ID EXE MEM WB

sub $s2, $s2, $s4 IF ID Stall EXE | MEM | WB

Define a struct named PatientData that contains two integer data members named heightInches and weightPounds. Sample output for the given program with inputs 63 115: c language

Answers

Answer:

Following are program to this question:

#include <stdio.h> //defining hader file  

struct PatientData //defining structure PatientData

{

  int heightInches, weightPounds; //defining integer variable

};

int main() //defining main method

{

struct PatientData pd= {63,115}; //creating structure object and assign value

printf("%d %d", pd.heightInches, pd.weightPounds); //print value

return 0;

}

Output:

63 115

Explanation:

The program to this question can be described as follows:

In this program, a structure "PatientData" is declared, in which two integer variables, that is "heightInches and weightPounds". Then the main method is declared, inside the main method, structure object "pd" is created, that assigns a value, that is "63 and 115", and uses the print method, that prints its value.

Project 4: Strictly Identical arrays

Problem Description:

Two arrays are strictly identical if their corresponding elements are equal. Write a program with class name StrictlyIdentical that prompts the user to enter two lists of integers of size 5 and displays whether the two are strictly identical.

Here are two sample runs:

Sample 1:

Enter 5 elements of list1: 23 55 31 2 10

Enter 5 elements of list2: 23 55 31 2 10

Two lists are strictly identical.

Sample 2:

Enter 5 elements of list1: 23 55 31 2 10

Enter 5 elements of list2: 23 55 3 2 10

Two lists are not strictly identical.

You need to define and utilize a user-defined function using the following method header:

public static boolean equals(int[] array1, int[] array2)

This method will return true if array1 and array2 are strictly identical otherwise it will return false. Note that it is incorrect to check the equality of two arrays using array1 == array2 because they are reference type variables. You need to use a for loop to check each element of array1 and array2. If any of the corresponding elements differ, these two lists are not strictly identical. If all of the corresponding elements are the same, these two lists are strictly identical.

You can use the following steps in your code:

Declare and create two arrays list1 and list2 of integer type and size 5.

Prompt the user to enter 5 elements of list1 and list2. Use for loop to read these entries and assign them to the elements of list1 and list2 respectively (for example, list1[i] = input.nextInt().)

Invoke the boolean method equals (that you defined) to pass the two arrays. If the return type is true then display that the lists are strictly identical. Otherwise, display that the two lists are not strictly identical.

What to deliver?

Your .java file including:

1. (Code: 5 points, Comments: 3 points)
Your code with other appropriate comments.

2. (2 points) Two sample run test the following lists:

(1) 1 2 3 4 5 and 1 2 3 4 5

(2) 1 2 3 4 5 and 5 4 3 2 1

Answers

Answer:

import java.util.Scanner;

public class StrictlyIdentical

{

public static void main(String[] args) {

 Scanner input = new Scanner(System.in);

 int[] list1 = new int[5];

 int[] list2 = new int[5];

 System.out.println("Enter the numbers for list1: ");

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

        list1[i] = input.nextInt();

    }

    System.out.println("Enter the numbers for list2: ");

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

        list2[i] = input.nextInt();

    }

 

 if (equals(list1, list2))

     System.out.println("the lists are strictly identical.");

 else

     System.out.println("the two lists are not strictly identical.");

}

public static boolean equals(int[] array1, int[] array2) {

    boolean isIdentical = true;

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

        if (array1[i] != array2[i])

            isIdentical = false;

    }

    return isIdentical;

}

}

Explanation:

Create a function called equals that takes two parameters, array1, and array2

Initialize the isIdentical as true, this will be our control variable to change its value if two arrays are not identical

Create a for loop that iterates through the arrays. If corresponding elements of the arrays are not equal, set isIdentical as false.

When the loop is done, return the isIdentical

Inside the main:

Declare two arrays

Ask the user to enter numbers for the arrays using for loop

Check if two arrays are identical using the equal function. Print the appropriate message

Create a procedure that generates a random string of length L , containing all capital letters. The procedure, CreateRandomString, receives the length of the string (L) in EAX, and returns the pointer to a byte array in ESI held the random string. Part 2 Write a driver program uses the CreateRandomString procedure to generate 20 random strings. Each random string with a random length between 1~100. Output all strings in the console window.

Answers

Final answer:

A student seeks help with assembly programming to create a procedure generating random strings of capital letters. The procedure must handle varying lengths and return a pointer to the generated string. The driver program calls this procedure multiple times to output different strings.

Explanation:

The student's question relates to the field of assembly programming and specifically deals with creating a procedure that generates a random string. The procedure CreateRandomString receives the length of the string in the EAX register and returns a pointer to the string in the ESI register. The driver program calls this procedure 20 times to generate random strings with lengths varying between 1 and 100 characters, using uppercase ASCII character codes (65-90).To implement this in assembly, pseudocode for the CreateRandomString procedure would set up the loop to iterate L times, each time generating a random number within the range of uppercase letter ASCII codes and storing it in the resulting array. After the string is crafted, the pointer to this array is placed in the ESI register for the calling program to use. The calling or driver program uses a loop to generate 20 such strings, each time generating a new length at random from 1 to 100, then calling CreateRandomString and outputting the result to the console.

(Multiply the digits in an integer) Write a program that reads an integer between 0 and 1000 and multiplies all the digits in the integer. For example, if an integer is 932 , the multiplication of all its digits is 54 . Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit. For instance, 932 % 10

Answers

Answer:

number = int(input("Enter a number: "))

product = 1

while number > 0:

   digit = number % 10

   number -= digit

   number /= 10

   product *= digit

print(int(product))

Explanation:

*The code is in Python

Ask the user for an integer

Initialize the product variable that will hold the multiplication of the digits

Initialize a while loop that iterates until number is greater than 0

To find the digit of a number, use number modulo 10. Then subtract the result from the number and divide the new number by 10.

Multiply each digit and hold the value in the product

When the loop is done, print the product

python3 Write a program with a function that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized. For instance, if the argument is "hello. my name is Joe. what is your name?" the function should return the string "Hello. My name is Joe. What is your name?". The program should let the user enter a string and then pass it to the function. The modified string should be displayed.

Answers

Answer:

MyString= input('Enter string: ')

string_capitalize(MyString)

print(MyString)

def string_capitalize(str):

        str= str.capitalize()

        return str

Explanation:

This python code is learnt to access string value from users and capitalize all characters in the beginning of each sentence.

List the physical storage media available on the computers you use routinely. Give the speed with which data can be accessed on each medium. (Your answer will be based on the computers and storage media that you use)

Answers

Answer:

In daily routine I use different physical storage media such as Hard disk drive, USB (Flash Memory). Data can be accesses through these devices at the speed of up to 100 Mbps and 1 Mbps respectively.

Explanation:

There are different storage media that we can use to transfer data between different computer devices or store data permanently such as hard disk drive, floppy disk, optical storage devices (CD and DVD), USB (Flash Memory) and SD Cards. These storage medias have different purpose and different applications of use. All these devices works on different accessing speed of data.

In my daily routine, I usually use Hard disk drive for permanent storage of my important data and USB device for transferring data between different device or to keep data temporarily. Hard disk drives are available in terabyte size now a days while USB drives are available in the range 32 to 64 GB. Hard disk drive has data accessing speed of up to 100 Mbps and USB drive has almost speed of up to 1 Mbps to access data.

Other Questions
Which sample fairly represents the population? Select two options.measuring the height of every fiftieth person on the school roster to determine the average height of the boys in the schoolcalling every third person on the soccer team's roster to determine how many of the team members have completed theirfundraising assignmentobserving every person walking down Main Street at 5 p.m. one evening to determine the percentage of people who wearglassessending a confidential e-mail survey to every one-hundredth parent in the school district to determine the overall satisfaction athe residents of the towntaking a poll in the lunch room (where all students currently have to eat lunch) to determine the number of students who wantto be able to leave campus during lunch Use the following list to answer the question. -Publication of the "Pentagon Papers" -News reports of the My Lai Massacre -Increased bombing of North Vietnam -Shootings at Kent State, OhioWhat was the impact of these events?Your answer:decline of the antiwar movementresignation of President Richard Nixongreater public opposition to the Vietnam Wardivision among Nixon's Republican supporters Suppose taxi fares from Logan Airport to downtown Boston is known to be normally distributed and a sample of seven taxi fares produ confidence intervalwe are 95% confident that a randomly selected taxi fare will be between S2051 and S2421 95% of all taxi fares are between S2051 and S2421 We are 95% confident that the average tau fare between Logan Airport and downtown Boston will fall between S2051 and S2421. The mean amount of a taxi fare is S22.31, 95% of the time during the last few months, maria has seen deer in her backyard on 13 days and no deer on 52 days. What is the approximate probability that she will see deer in her yard tomorrow?A) 0.25B)1/5C) 33.3 %D) 2/3 Implement a class to represent a playing card. Your class should have the following methods: __ init _ (self, rank, suit) rank is an int in the range 1-13 indicating the ranks ace-king' and suit is a single character "d ' " "c' " "h ' " or "s" indicating the suit (diamonds, clubs, hearts, or spades). Create the corresponding card. getRank(self) Returns the rank of the card. get Suit (self) Returns the suit of the card. value(self) Returns the Blackjack value of a card. Ace counts as 1, face cards count as 10. __ str __ (self) Returns a string that names the card. For example, "Ace of Spades". Test your card class with a program that prints out n randomly generated cards and the associated Blackjack value where n is a number supplied by the user. Snowfall is rare at the South Pole because the air over the South Pole is usually Which statement best defines an editorial? Darren invests $4,500 into an account that earns 5% annual interests. How much will be in the account after 10 years if the interest rate is compounded annually, quarterly, monthly, or daily? Which compounded interest rate should Darren choose? 1) Austin reached into his backpack to make sure that it was there. He wasnt sure he needed his inhaler, but he was checking just in case. His chest was tight as he once again attempted a deep breath. He completely filled his lungs and exhaled smoothly. He repeated this rhythm several times, surprised at the ease at which it came. But hed keep the inhaler in his pocket. It had been a long time since hed had a real asthma attack, since Little League, in fact. But it was never too far from his mind, especially when he played baseball.2) Austin loved baseball, like fish love water, but he felt his asthma had probably kept him from reaching his full athletic potential. He knew todays practice would be tough, for tomorrow was a big game. He was right. It was rough, and Austin and several others werent at the top of their game today. Coach Tanner firmly patted Austins shoulder as they headed for the dugout. Youve got to stop using it as a crutch, and let it go son. Coach said in a firm, low voice.Coach Tanner appears to be the kind of person who What does the Earth's atmosphere do? Create meteorsRegulate temperaturesControl populationProvide light Numa turma, 5% dos homens e 2% das mulheres tem mais de 1,60m de altura. Por outro lado, 60% dos estudantes so homens. Se um estudante selecionado aleatoriamente e tem mais de 1,60m de altura, qual a probabilidade de que o estudantes seja mulher? Name 2 characteristics of Japanese art and architecture You can determine the index of refraction of a substance by measuring its critical angle for total internal reflection. True or False Was the Boston massacre truly massacre Which of the following is not considered to be a medial thigh muscle?A. Adductor longus B. Adductor brevis C. GracilisD. Vastus lateralis E. Adductor magnus Jay won 14 out of the last 20 video games he played. Find the probability of Jay winning the next video game he plays. For each of the following characteristics, say whether it describes a perfectly competitive firm, a monopolistically competitive firm, both, or neither. a. sells a product differentiated from that of its competitors b. has marginal revenue less than price c. earns economic profit in the long run d. produces at the minimum of average total cost in the long run e. equates marginal revenue and marginal cost f. charges a price above marginal cost How do I find the quadratic equation from its graph? Which measure of central tendency would be best to describe the following set of data? 2 5 4 1 3 52,251 6 a. median b. mode c. mean d. all of the above Many Asian Americans fought for the United States in World War I. The United States recognized their efforts byawarding them naturalization.funding their college tuitions.paying for their return to Asia.giving them free houses and cars.