Write a program that searches for key by using Binary Search algorithm. Before applying this algorithm your array needs to be sorted ( USE ANY SORTING ALGORITHM you studied ) C++

Answers

Answer 1

Here's an example C++  program that performs a binary search on a sorted array:

#include <iostream>

using namespace std;

// Function to perform the binary search

int binarySearch(int array[], int lowest_number, int highest_number, int key) {

  while (lowest_number <= highest_number) {

      // Calculate the middle index of the current subarray

      int middle = lowest_number + (highest_number - lowest_number) / 2;

      // Check if the key is found at the middle index

      if (array[middle] == key)

          return middle;

      // If the key is greater, search in the right half of the subarray

      if (array[middle] < key)

          lowest_number = middle + 1;

      // If the key is smaller, search in the left half of the subarray

      else

          highest_number = middle - 1;

  }

  // Key not found

  return -1;

}

// Function to perform selection sort to sort the array in ascending order

void selectionSort(int array[], int size) {

  for (int i = 0; i < size - 1; i++) {

      // Assume the current index has the minimum value

      int minIndex = i;

      // Find the index of the minimum value in the unsorted part of the array

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

          if (array[j] < array[minIndex])

              minIndex = j;

      }

      // Swap the minimum value with the first element of the unsorted part

      swap(array[i], array[minIndex]);

  }

}

int main() {

  // Initialize the unsorted array

  int array[] = {9, 5, 1, 8, 2, 7, 3, 6, 4};

  // Calculate the size of the array

  int size = sizeof(array) / sizeof(array[0]);

  // Key to be searched

  int key = 7;

  // Sort the array in ascending order before performing binary search

  selectionSort(array, size);

  // Perform binary search on the sorted array

  int result = binarySearch(array, 0, size - 1, key);

  // Check if the key is found or not and print the result

  if (result == -1)

      cout << "Key not found." << endl;

  else

      cout << "Key found at index: " << result << endl;

  return 0;

}

You can learn more about C++  program at

https://brainly.com/question/13441075

#SPJ11


Related Questions

Multiple users share a 10Mbps link. Each user requires 10Mbps when transmitting, but each user transmits for only 10% of the time. Suppose packet switching is used. Assuming that there are two users, what is the probability that the link cannot support both users simultaneously?

Answers

Probability that link cannot support both users = 1 - Probability that both users can transmit = 1 - 0.01 = 0.99. The probability is 0.99.

Given that multiple users share a 10Mbps link. Each user requires 10Mbps when transmitting, but each user transmits for only 10% of the time. Suppose packet switching is used.

Assuming that there are two users, we need to determine the probability that the link cannot support both users simultaneously.

To solve this problem, we have to find the probability that at least one user is transmitting at any given moment, and both users require the link at the same time.

Therefore, the link can't support both users simultaneously.

Let's consider the first user. Since the user transmits for only 10% of the time, the probability of the user transmitting is given by:

Probability of user 1 transmitting = 0.1

Next, we will consider the second user.

As given, each user transmits for only 10% of the time.

Hence, the probability of the second user transmitting is given by:

Probability of user 2 transmitting = 0.1

We know that the probability of the link supporting both users is:

Probability of both users transmitting

= (Probability of user 1 transmitting) x (Probability of user 2 transmitting)

= 0.1 x 0.1

= 0.01

Therefore, the probability that the link cannot support both users simultaneously is:

Learn more about probability from the given link:

https://brainly.com/question/13604758

#SPJ11

a) Encrypt the following text using Caesar Cipher (3 Shifts) "This course is good". b) Use Columnar Transposition (four-column permutation) to encrypt the plaintext "TODAY IS LAST THURSDAY". c) Find the hard knapsack for the simple knapsack [1, 3, 5, 11], use w=7 and n=13. d) Encrypt the binary message 10010101 using the hard knapsack using previous question

Answers

a) Encrypt the following text using Caesar Cipher (3 Shifts) "This course is good".To encrypt the given text using the Caesar cipher with a shift of 3 letters, we replace each letter with the letter that comes three places after it. This means that A becomes D, B becomes E, C becomes F, and so on. We can use the following table to do this replacement: Original Text: T H I S   C O U R S E   I S   G O O DEncrypted Text: W K L V   F R X U V H   L V   J R R G (each letter shifted by 3 positions)Therefore, the encrypted text is WKLV FRXUVH LV JRRG using Caesar Cipher with 3 shifts.

b) Use Columnar Transposition (four-column permutation) to encrypt the plaintext "TODAY IS LAST THURSDAY".To encrypt the plaintext using a columnar transposition, we write the plaintext into a grid with a number of rows equal to the length of the key, and then read the columns of the grid from left to right, writing them into the ciphertext. The key for the permutation is "PERM".TODAYISLASTTHURAY (original text arranged in a grid)P E R M P E R M P E (key for columnar transposition)T O D A Y I S L A S T T H U R A Y (text arranged in columns)YTSITLRTOADSHAYLUSY (encrypted text)Therefore, the encrypted text is YTSITLRTOADSHAYLUSY using Columnar Transposition with a four-column permutation.

c) Find the hard knapsack for the simple knapsack [1, 3, 5, 11], use w=7 and n=13.To find the hard knapsack for the simple knapsack [1, 3, 5, 11], we must first find an inverse for the number 3 modulo 13. This is because we must multiply each number in the simple knapsack by this inverse to get the hard knapsack. The inverse of 3 modulo 13 is 9 since 3 * 9 is congruent to 1 modulo 13. Therefore, the hard knapsack is [9, 4, 11, 8], obtained by multiplying each number in the simple knapsack by 9 modulo 13.

d) Encrypt the binary message 10010101 using the hard knapsack using the previous question. To encrypt the binary message 10010101 using the hard knapsack [9, 4, 11, 8], we must first represent the binary message as a sum of numbers in the hard knapsack. This can be done by taking each bit in the binary message and multiplying it by the corresponding number in the hard knapsack. For example, the first bit is 1, so multiply it by 9. The second bit is 0, so we don't add anything. And so on...Binary message: 1 0 0 1 0 1 0 1Hard knapsack: 9 4 11 8Product: 9   0   0   8   0  11   0   8 (multiplication of each bit by corresponding hard knapsack element)The sum of these numbers is 36, which is equal to 5 modulo 13. Therefore, the encrypted message is 5.

For further information on Caesar Cipher visit:

https://brainly.com/question/14754515

#SPJ11

a) Encrypt the following text using Caesar Cipher (3 Shifts) "This course is good." The given plaintext is "This course is good." Caesar Cipher is a substitution cipher that works by shifting the letters to the right or left by a certain number of spaces, known as the shift or key. The given shift is 3. Therefore, each letter in the plaintext will be replaced by the letter 3 positions to the right of it.

To encrypt "This course is good" using Caesar Cipher with a shift of 3, we will shift each letter to the right by 3 positions, as shown below: T   H   I   S   C   O   U   R   S   E       I   S       G   O   O   D    -----------------W   K   L   V   F   R   X   U   V   H       L   V       J   R   R   Gb) Use Columnar Transposition (four-column permutation) to encrypt the plaintext "TODAY IS LAST THURSDAY. "The plaintext "TODAY IS LAST THURSDAY" will be written in 4 columns as shown below: T   O   D   A   Y      I   S      L   A   S   T       T   H   U   R   S   D   A   Y    ------------------------A   O   T   H   R   S   Y   I   S   L       D   A   A   U   Y   T   Y c) Find the hard knapsack for the simple knapsack [1, 3, 5, 11], use w=7 and n=13.The hard knapsack is obtained using the given equation: si = (r * n) + (w * si-1) mod m where s0 = 1, m = n + 1, w = 7, and r = (n + 1) / 2.The value of r is calculated as r = (n + 1) / 2 = (13 + 1) / 2 = 7Substituting the values in the equation, we get:s0 = 1s1 = (r * n) + (w * s0) mod m= (7 * 1) + (7 * 1) mod 14= 14s2 = (r * n) + (w * s1) mod m= (7 * 1) + (7 * 14) mod 14= 11s3 = (r * n) + (w * s2) mod m= (7 * 1) + (7 * 11) mod 14= 10s4 = (r * n) + (w * s3) mod m= (7 * 1) + (7 * 10) mod 14= 6s5 = (r * n) + (w * s4) mod m= (7 * 1) + (7 * 6) mod 14= 4s6 = (r * n) + (w * s5) mod m= (7 * 1) + (7 * 4) mod 14= 5The hard knapsack is therefore [7, 14, 11, 10, 6, 4, 5]. d) Encrypt the binary message 10010101 using the hard knapsack using the previous question. The hard knapsack we obtained in the previous question is [7, 14, 11, 10, 6, 4, 5]. The binary message is 10010101.The ciphertext is calculated as: c = (s1 + s3 + s4 + s5) mod m*where m = n + 1 = 13 + 1 = 14. Substituting the values, we get: c = (14 + 10 + 6 + 4) mod 14= 34 mod 14= 6. Therefore, the ciphertext for the binary message 10010101 is 6.

Learn more about Knapsack here: https://brainly.com/question/33325120.

#SPJ11

all of the following are examples of commonly used tools in relief printing, except which?

Answers

The commonly used tools in relief printing include brayers, linoleum cutters, and woodcut tools. The exception is etching needles.

Relief printing is a printmaking technique where the raised surface of the printing block is inked, and the recessed areas are kept ink-free. When the inked block is pressed onto paper, it transfers the image in reverse. Several tools are utilized in relief printing to create intricate and expressive artworks. Here are the commonly used ones:

Brayers: Brayers are rubber rollers that artists use to apply ink evenly on the surface of the relief block. They come in various sizes and are essential for achieving smooth and consistent ink coverage.

Linoleum cutters: Linoleum cutters are tools used to carve designs into linoleum blocks. They have different cutting blades or tips that allow artists to create various lines and textures in the linoleum surface.

Woodcut tools: Woodcut tools consist of chisels and gouges that artists use to carve images into wooden blocks. These tools come in different shapes and sizes, enabling artists to create both bold and delicate lines in their prints.

Learn more about Printing

brainly.com/question/31087536

#SPJ11

object-oreineted programming// java
1. Declare and initialize an array of any 5 non-negative integers. Call it data. 2. Write a method printEven that print all even value in the array. 3. Then call the method in main

Answers

//java

public class ArrayExample {

   public static void main(String[] args) {

       int[] data = {2, 5, 10, 7, 4};

       printEven(data);

   }

   

   public static void printEven(int[] arr) {

       for (int num : arr) {

           if (num % 2 == 0) {

               System.out.println(num);

           }

       }

   }

}

In the given solution, we create a class called `ArrayExample` with a `main` method. Inside the `main` method, we declare and initialize an array of 5 non-negative integers called `data` with the values {2, 5, 10, 7, 4}.

We then call the `printEven` method, passing the `data` array as an argument. The `printEven` method is responsible for printing all the even values in the array.

Within the `printEven` method, we use a for-each loop to iterate over each element in the array. For each element, we check if it is divisible by 2 (i.e., even) by using the modulus operator (%). If the element is indeed even, we print it using `System.out.println(num)`.

The result of running this program will be the output of the even values in the `data` array, which in this case is:

Output:

2

10

4

Learn more about Java oop code

brainly.com/question/33329770

#SPJ11

Purpose A review of pointers, dynamic memory allocation/deallocation, struct data type, array, sorting, memory leak, dangling pointers Project description This project utilizes A1, handling employee information from the given file. The requirements are as follows. 1. Display the total number of employees as the first output 2. As your program reads the information of an employee from the file, it must dynamically allocate a memory to store the information of an employee 3. Add sorting functionality to your program that sorts employees based on SSN. To implement sorting algorithms, use the bubble sort, and selection sort, respectively. 4. Deallocate all dynamically allocated memory that used the heap. 5. When you implement the above, define each of the following functions. a. void print(Employee*[], int); display all the employees, the second parameter variables is the actual size of the array b. void print(Employee*); display the information of a single employee, which is called by print () in the above. Function overloading is applied here c. void print_header(); display the table header which indicates the interpretation of each column d. int sort_menu(); display two choices to and prompt the user c. void bubble_sort(Employee*[], int); the second parameter variables is the actual size of the array f. void selection_sort(Employee*[], int); the second parameter variables is the actual size of the array To incorporate the above functions, think about the flow of your program and which function should be located where. This will produce a flow chart of your program.

Answers

Develop a program in C that reads employee information from a file, dynamically allocates memory, sorts employees based on SSN using bubble sort and selection sort, and deallocates memory.

Develop a program in C that reads employee information from a file, dynamically allocates memory, sorts employees based on SSN using bubble sort and selection sort, deallocates memory, and includes functions for displaying employee information.

This project involves handling employee information from a given file using pointers, dynamic memory allocation/deallocation, and struct data type in C.

The program needs to display the total number of employees, dynamically allocate memory for each employee's information, sort the employees based on their SSN using bubble sort and selection sort algorithms, deallocate the dynamically allocated memory, and define several functions for displaying employee information and performing sorting operations.

The flow of the program should be carefully considered and a flow chart can be created to visualize the program structure.

Learn more about Develop a program

brainly.com/question/14547052

#SPJ11

Write a simple test plan for either of these:
1) Email sending service
Include detailed explanations of:
1) What all scenarios will you cover? 2) How will you test attachments and images in the email? 3) How will you test templating?
4) How can this process be automated? Code is not required for this question, however, include brief explanations of the steps, packages/libraries you might use and why.

Answers

Test Plan: Email Sending Service - Covering various scenarios, testing attachments/images, templating, and automating the process using frameworks like Selenium/Cypress and libraries like Nodemailer/Mailgun API for efficient and consistent testing.

Test Plan: Email Sending Service

1) Scenarios to Cover:

Sending a basic text email. Sending an email with attachments. Sending an email with embedded images. Testing various email clients and devices for compatibility. Testing different email providers and protocols (SMTP, POP3, IMAP). Testing error handling and edge cases (invalid email addresses, server errors, etc.). Performance testing for handling a large volume of emails.

2) Testing Attachments and Images:

Create test cases to verify that attachments are correctly attached to the email and can be opened. Verify that images are properly embedded within the email and displayed correctly. Test different types of attachments (documents, images, videos) and ensure they are delivered successfully.

3) Testing Templating:

Create test cases to validate that email templates are rendered correctly. Test dynamic content insertion into the template (e.g., user names, dates, personalized information). Verify that the correct template is used based on the email's purpose or recipient.

4) Automation Process:

Use a test automation framework like Selenium or Cypress to automate the email-sending process. Write test scripts that simulate user actions, such as filling out the email form and submitting it. Use libraries like Nodemailer or Mailgun API for sending emails programmatically in the test scripts. Implement assertions to verify the successful delivery of emails, correct attachment rendering, and template accuracy. Integrate the automated tests into a continuous integration system for regular execution.

By automating the testing process, we can achieve:

Faster and more efficient test execution. Consistent and repeatable test results. Early detection of issues and regressions. Improved overall test coverage.

Integration with the development workflow for continuous testing and deployment.

Learn more about Email Sending Service: https://brainly.com/question/2978895

#SPJ11

Compute the time required to read file consisting of 5000 sectors from a drive with 8 ms average seek time, rotating at 15000 rpm, 512 bytes per sector and 1000 sectors per track for the following storage. (i) File is Stored sequentially (ii) File is Stored randomly Explain with appropriate formula elaborations, calculations, and pictorial illustrations b. Explain with illustration what is a Journaling Flash File System? How is Wear Leveling and Garbage Collection managed by Flash devices hosting this file system?

Answers

The time required to read the file sequentially can be calculated using the formula:

Total Time = Seek Time + Rotational Latency + Transfer Time

To compute the time required to read the file sequentially, we consider three factors: seek time, rotational latency, and transfer time. Seek time is the time taken for the drive's read/write head to position itself over the desired track. Rotational latency is the time taken for the desired sector to rotate under the read/write head. Transfer time is the time taken to actually transfer the data from the drive to the system.

First, let's calculate the seek time. Since the file is stored sequentially, the drive needs to seek only once to reach the desired track. The average seek time is given as 8 ms.

Next, we calculate the rotational latency. The drive is rotating at 15000 rpm, which means it completes one revolution in 1/15000 minutes (1/15000 * 60 seconds). Since there are 1000 sectors per track, each sector takes (1/15000 * 60 seconds) / 1000 to rotate under the read/write head.

Finally, we calculate the transfer time. Each sector has 512 bytes, so the total transfer time is (5000 sectors * 512 bytes) / transfer rate, where the transfer rate depends on the drive's specifications.

By adding the seek time, rotational latency, and transfer time, we can determine the total time required to read the file sequentially.

Learn more about revolution

brainly.com/question/29158976

#SPJ11

Learning debugging is important if you like to be a programmer. To verify a program is doing what it should, a programmer should know the expected (correct) values of certain variables at specific places of the program. Therefore make sure you know how to perform the instructions by hand to obtain these values. Remember, you should master the technique(s) of debugging. Create a new project Assignment02 in NetBeans and copy the following program into a new Java class. The author of the program intends to find the sum of the numbers 4,7 and 10 . (i) Run the program. What is the output? (ii) What is the expected value of sum just before the for loop is executed? (iii) Write down the three expected intermediate sums after the integers 4,7 and 10 are added one by one (in the given order) to an initial value of zero. (iv) Since we have only a few executable statements here, the debugging is not difficult. Insert a System. out. println() statement just after the statement indicated by the comment " // (2)" to print out sum. What are the values of sum printed (press Ctrl-C to stop the program if necessary)? (v) What modification(s) is/are needed to make the program correct? NetBeans allows you to view values of variables at specific points (called break points). This saves you the efforts of inserting/removing println() statements. Again, you must know the expected (correct) values of those variables at the break points. If you like, you can try to explore the use break points yourself

Answers

Debugging involves identifying and fixing program errors by understanding expected values, using print statements or breakpoints, and making necessary modifications.

What is the output of the given program? What is the expected value of the sum before the for loop? What are the expected intermediate sums after adding 4, 7, and 10? What values of sum are printed after inserting a println() statement? What modifications are needed to correct the program?

The given program is intended to calculate the sum of the numbers 4, 7, and 10. However, when running the program, the output shows that the sum is 0, which is incorrect.

To debug the program, the expected values of the sum at different points need to be determined. Before the for loop is executed, the expected value of the sum should be 0.

After adding the numbers 4, 7, and 10 one by one to the initial value of 0, the expected intermediate sums are 4, 11, and 21, respectively.

To verify these values, a System.out.println() statement can be inserted after the relevant code line to print the value of the sum.

By observing the printed values, any discrepancies can be identified and modifications can be made to correct the program, such as ensuring that the sum is initialized to 0 before the for loop starts.

Using debugging techniques and tools like breakpoints in an integrated development environment like NetBeans can facilitate the process of identifying and fixing program errors.

Learn more about Debugging involves

brainly.com/question/9433559

#SPJ11

Complete the code below for the function definition of func_1: def func_1 ( IDENTIFY WHAT GOES HERE ): sum =a+b print("summation of your inputs is", sum) a b a,b a+b

Answers

To complete the code for the function definition of func_1, you need to include a and b as the parameters. So, the complete function definition would be:

def func_1(a, b):A function definition in Python has the following format:def function_name(parameters):    ''' docstring '''    statement(s)The function_name, enclosed in parentheses, is followed by a list of parameters that may be empty or have one or more items. In the given code, a and b are the parameters that will receive the values that the user inputs.Next, the function body contains the actual code that the function executes.

In the given code, we have to sum the values of a and b and print the result using the print() function. The sum is assigned to a variable sum and printed along with a message as "summation of your inputs is". Finally, the complete code for the function definition of func_1 is:def func_1(a, b):    sum = a + b    print("summation of your inputs is", sum),

To know more about code visit:

https://brainly.com/question/30782010

#SPJ11

Describe the algorithm used by your favorite ATM machine in dispensing cash. Give your description in a pseudocode

Answers

An algorithm is a set of instructions or rules for performing a specific task. An ATM machine is an electronic device used for dispensing cash to bank account holders.

Here's a pseudocode for the algorithm used by an ATM machine to dispense cash.

1. Begin

2. Verify if card is inserted.

3. If card is not inserted, display "Insert your ATM card". If card is inserted, move to step 4.

4. Verify if the card is valid or invalid.

5. If the card is invalid, display "Invalid card".

6. If the card is valid, verify the PIN number entered.

7. If the PIN number is correct, proceed to the next step. If not, display "Invalid PIN".

8. If the PIN is correct, ask the user how much cash they want to withdraw.

9. If the requested amount is less than the available balance, proceed to step

10. If not, display "Insufficient funds".10. Count and dispense cash.

11. Display "Transaction Successful".

12. End.Hope that helps.

Learn more about pseudocode at https://brainly.com/question/17102236

#SPJ11

// Specification A1 - Date class Put all the date code in class Date class. 2. / / Specification A2 - External date initialization Set the data for your Date class externally, either through a setter method or a constructor. 3. / Specification A3 - Component Test Method in Date Create a method in the date class which performs self diagnostics. That is, it instantiates a date object with known data and then compares the results with expected, correct, answers. Use this to demonstrate your input routines are working. Prove month, day, and year are indeed set correctly by A 2
and the resulting output is formatted as expected.

Answers

Specification A1 - Date class: All the date code should be put in the class Date class.Specification A2 - External date initialization: The data for your Date class should be set externally, either through a setter method or a constructor.

Specification A3 - Component Test Method in Date: A method should be created in the date class which performs self diagnostics. That is, it instantiates a date object with known data and then compares the results with expected, correct, answers.The  Specification A1 - Date class: All the date code should be put in the class Date class.Explanation:The Date class is where all date code should be placed, according to Specification A1.

It is responsible for handling all date-specific operations.2. Specification A2 - External date initialization: The data for your Date class should be set externally, either through a setter method or a constructor.To fulfill Specification A2, the data for the Date class must be set from outside the class. This can be accomplished through either a setter method or a constructor.3.

To know more about data visit:

https://brainly.com/question/28421434

#SPJ11

Define a function max (const std::vector & ) which returns the largest member of the input vector.

Answers

Here's a two-line implementation of the max function:

```cpp

#include <vector>

#include <algorithm>

int max(const std::vector<int>& nums) {

 return *std::max_element(nums.begin(), nums.end());

}

```

The provided code defines a function called "max" that takes a constant reference to a vector of integers as input. This function is responsible for finding and returning the largest element from the input vector.

To achieve this, the code utilizes the `<algorithm>` library in C++. Specifically, it calls the `std::max_element` function, which returns an iterator pointing to the largest element in a given range. By passing `nums.begin()` and `nums.end()` as arguments to `std::max_element`, the function is able to determine the maximum element in the entire vector.

The asterisk (*) in front of `std::max_element(nums.begin(), nums.end())` dereferences the iterator, effectively obtaining the value of the largest element itself. This value is then returned as the result of the function.

In summary, the `max` function finds the maximum value within a vector of integers by utilizing the `std::max_element` function from the `<algorithm>` library. It is a concise and efficient implementation that allows for easy retrieval of the largest element in the input vector.

The `std::max_element` function is part of the C++ Standard Library's `<algorithm>` header. It is a versatile and powerful tool for finding the maximum (or minimum) element within a given range, such as an array or a container like a vector.

By passing the beginning and end iterators of the vector to `std::max_element`, it performs a linear scan and returns an iterator pointing to the largest element. The asterisk (*) is then used to dereference this iterator, allowing us to obtain the actual value.

This approach is efficient, as it only requires a single pass through the elements of the vector. It avoids the need for manual comparisons or loops, simplifying the code and making it less error-prone.

Using `std::max_element` provides a concise and readable solution for finding the maximum element in a vector. It is a recommended approach in C++ programming, offering both simplicity and efficiency.

Learn more about max function

brainly.com/question/31479341

#SPJ11

Why Linked List is implemented on Heap memory rather than Stack memory?

Answers

The heap memory is preferred for implementing linked lists due to its ability to provide dynamic memory allocation and longer lifespan for the data structure

Linked list is implemented on heap memory rather than stack memory due to the following reasons:Heap memory can provide a large memory block to the linked listHeap memory has the capacity to store dynamic memory.

Linked lists contain nodes that can be of varying sizes, thus heap memory is perfect for that purpose.Linked lists usually have a structure that can grow or shrink depending on the input, heap memory allows dynamic allocation and deallocation of memory without any restrictions.

This means that we can adjust the memory allocated to the linked list at runtime.Heap memory is also helpful in avoiding memory fragmentation. Memory fragmentation occurs when memory is allocated and deallocated without much planning and foresight.

Learn more about dynamic memory at

https://brainly.com/question/15179474

#SPJ11

Please provide the executable code with environment IDE for ADA:
Assume that there are two arbitrary size of integer arrays (Max. size 30), the main program reads in integer numbers into two integer arrays, and echo print your input, call a subroutine Insertion Sort for the first array to be sorted, and then print out the first sorted array in the main. Call a subroutine efficient Bubble Sort for the second array to be sorted, and then print out the second sorted array in the main. Call a subroutine MERGE that will merge together the contents of the two sorted (ascending order) first array and second array, storing the result in the third (Brand new array) integer array – the duplicated date should be stored only once into the third array – i.e. merge with comparison of each element in the array A and B. Print out the contents of third array in main. Finally, call a function Binary Search with a target in the merged array (third) and return the array index of the target to the main, and print out the array index.
Please provide the running code and read the problem carefully and also provide the output

Answers

Here is the executable code for sorting and merging arrays in Ada.

What is the code for sorting and merging arrays in Ada?

The main program reads in integer numbers into two integer arrays, performs insertion sort on the first array, efficient bubble sort on the second array, merges the two sorted arrays into a third array, and finally performs a binary search on the merged array.

with Ada.Text_IO;

use Ada.Text_IO;

procedure Sorting is

  type Integer_Array is array(1..30) of Integer;

  procedure Insertion_Sort(Arr: in out Integer_Array; Size: in Integer) is

     i, j, temp: Integer;

  begin

     for i in 2..Size loop

        temp := Arr(i);

        j := i - 1;

        while j > 0 and then Arr(j) > temp loop

           Arr(j + 1) := Arr(j);

           j := j - 1;

        end loop;

        Arr(j + 1) := temp;

     end loop;

  end Insertion_Sort;

  procedure Efficient_Bubble_Sort(Arr: in out Integer_Array; Size: in Integer) is

     i, j, temp: Integer;

     swapped: Boolean := True;

  begin

     for i in reverse 2..Size loop

        swapped := False;

        for j in 1..i-1 loop

           if Arr(j) > Arr(j + 1) then

              temp := Arr(j);

              Arr(j) := Arr(j + 1);

              Arr(j + 1) := temp;

              swapped := True;

           end if;

        end loop;

        exit when not swapped;

     end loop;

  end Efficient_Bubble_Sort;

  procedure Merge(Arr1, Arr2: in Integer_Array; Size1, Size2: in Integer; Result: out Integer_Array; Result_Size: out Integer) is

     i, j, k: Integer := 1;

  begin

     while i <= Size1 and j <= Size2 loop

        if Arr1(i) < Arr2(j) then

           Result(k) := Arr1(i);

           i := i + 1;

        elsif Arr1(i) > Arr2(j) then

           Result(k) := Arr2(j);

           j := j + 1;

        else

           Result(k) := Arr1(i);

           i := i + 1;

           j := j + 1;

        end if;

        k := k + 1;

     end loop;

     while i <= Size1 loop

        Result(k) := Arr1(i);

        i := i + 1;

        k := k + 1;

     end loop;

     while j <= Size2 loop

        Result(k) := Arr2(j);

        j := j + 1;

        k := k + 1;

     end loop;

     Result_Size := k - 1;

  end Merge;

  function Binary_Search(Arr: in Integer_Array; Size: in Integer; Target: in Integer) return Integer is

     low, high, mid: Integer := 1;

  begin

     high := Size;

     while low <= high loop

        mid := (low + high) / 2;

        if Arr(mid) = Target then

           return mid;

        elsif Arr(mid) < Target then

           low := mid + 1;

        else

           high := mid - 1;

        end if;

     end loop;

     return -1; -- Target not found

  end Binary_Search;

  A, B, C: Integer_Array;

  A_Size, B_Size, C_Size: Integer;

begin

  -- Read input for array A

  Put_Line("Enter the size of array A (maximum 30

Learn more about merging arrays

brainly.com/question/13107940

#SPJ11

Output: Loop through the order and inside the loop check to see if the item reside in the menu. If it is in the menu, then print it out. Retrieve the index of the menu item. Use that index to determine the menu item price from the price list. Print the price for the item. If there is an item that is not on the menu, print a message stating that this item is not on the menu. When the order is ready, print that the order is ready and the price for the complete order. Format the money for currency. Compare your results with the screenshot provided. I have included the detail for my test case if you want a second list to further test your processing results. Optional Specific (comments you can include in your code if desired) / Pseudocode (Order): # define a list of menu items # define a list of prices that correspond to menu items # define list containing customer order \# initialize the total_price to 0.0 # print report header - Order Detail # use for in loop to traverse customer order # inside the loop check to see if ordered item is in the menu # print menu item name # assign menu item index to variable \# use index variable to show price from price list # increment total_price # else print 'Sorry, we don't have # print order is ready # prepare the order total # print the total price.

Answers

Java code that implements the desired functionality based on the provided instructions and pseudocode is given in the explanation section.

In the below given code, we define the menu list containing menu items, the prices list containing corresponding prices, and the order list containing the customer's order.

We then loop through the customer's order using a for-each loop. Inside the loop, we check if each ordered item is present in the menu using the contains() method. If it is, we print the menu item name, retrieve its index using indexOf(), get the corresponding price from the prices list using get(), and add it to the total_price variable. We also print the price for the item using the currencyFormatter.

If an item is not found in the menu, we print a message stating that the item is not on the menu.

Finally, we print that the order is ready and display the total price for the complete order using the currencyFormatter to format the price as currency. The program is given below:

*******************************************************************

import java.text.NumberFormat;

import java.util.ArrayList;

import java.util.List;

public class OrderProcessor {

   public static void main(String[] args) {

       // Define a list of menu items

       List<String> menu = new ArrayList<>();

       menu.add("Hamburger");

       menu.add("Cheeseburger");

       menu.add("Hotdog");

       menu.add("French Fries");

       menu.add("Onion Rings");

       // Define a list of prices that correspond to menu items

       List<Double> prices = new ArrayList<>();

       prices.add(2.99);

       prices.add(3.49);

       prices.add(1.99);

       prices.add(1.49);

       prices.add(1.99);

       // Define the customer order

       List<String> order = new ArrayList<>();

       order.add("Hotdog");

       order.add("Cheeseburger");

       order.add("Chicken Sandwich");

       order.add("French Fries");

       double total_price = 0.0; // Initialize the total_price to 0.0

       NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(); // Formatter for currency

       System.out.println("Order Detail:");

       

       // Loop through the customer order

       for (String item : order) {

           // Check if the ordered item is in the menu

           if (menu.contains(item)) {

               System.out.println(item); // Print menu item name

               int index = menu.indexOf(item); // Assign menu item index to variable

               

               double price = prices.get(index); // Retrieve the price from the price list

               total_price += price; // Increment the total_price

               

               System.out.println(currencyFormatter.format(price)); // Print the price for the item

           } else {

               System.out.println("Sorry, we don't have " + item + " on the menu."); // Print message for items not on the menu

           }

       }

       

       System.out.println("Order is ready.");

       System.out.println("Total Price: " + currencyFormatter.format(total_price)); // Print the total price for the complete order

   }

}

*******************************************************************

the program and its output is also attached.

You can learn more about loop in java at

https://brainly.com/question/33183765

#SPJ11

This question requires 4 different codes. We are using Python to create Numpy arrays. Please assist with the codes below.
Thank you, will rate. Note: it is important you do all the instructions in the order listed. We test your code by setting a fixed np. random. seed, so in order for your code to match the reference output, all the functions must be run in the correct order. We'll start off by obtaining some random integers. The first integer we get will be randomly chosen from the range [0,5). The remaining integers will be part of a 3×5 NumPy array, each randomly chosen from the range [3,10). Set equal to with as the only argument. Thenset equal to np.random. randint with 3 as the first argument, 10 as the high keyword argument, and (3, 5) as the keyword argument. # CODE HERE The next two arrays will be drawn randomly from distributions. The first will contain 5 numbers drawn uniformly from the range [-2.5, 1.5]. Se equal to with the and high keyword arguments set to 1.5, respectively. The and keyword argument should be set to 5 . * CODE HERE The second array will contain 50 numbers drawn from a normal distribution with mean 2.0 and standard deviation 3.5. Set equal to with the keyword and argument should be set to (10,5). The second array will contain 50 numbers drawn from a normal distribution with mean 2.0 and standard deviation 3.5. argument should be set to (10,5). ]: # CODE HERE To choose a value, we'll use a probability distribution of [0.5,0.1,0.2,0.2], i.e. will have a probability of 0.1, etc. Set equal to a list of the specified values, in the order given. Set equal to with

Answers

The codes for generating the requested NumPy arrays are as follows:

What are the four different Python codes for generating NumPy arrays with specified ranges and distributions?

The first code snippet uses the `np.random.randint` function to generate a random integer within the specified range [0, 5). This is stored in the variable `first_integer`.

The second code snippet creates a NumPy array named `array1` using `np.random.randint`. The arguments provided are the range [3, 10) for the random integers and the size of the array, which is (3, 5) for a 3x5 array.

The third code snippet generates an array called `array2` using `np.random.uniform`. The arguments passed are the range [-2.5, 1.5] for the uniform distribution and the size of the array, which is 5.

The fourth code snippet creates an array named `array3` using `np.random.normal`. The arguments specified are the mean (2.0), standard deviation (3.5), and the size of the array (10 rows and 5 columns).

Learn more about NumPy arrays

brainly.com/question/30764048

#SPJ11

Your task is to evaluate and write a report on an existing application, eBook, or online story. You should align your report with UX principles and concepts, demonstrating your understanding of these concepts in relation to your chosen application or website.
You should be concise in your report as you will be required to write no more than 800 words. In your report, you should pay particular attention to UX and UI best practices. You should explain how your chosen application or website resembles or demonstrates the use of design patterns.
You may consider design aspects like layout, navigation, conventions, graphics, text, and colour in your report.

Answers

To evaluate and write a report on an existing application, eBook, or online story, you should align your report with UX principles and concepts. You should demonstrate your understanding of these concepts in relation to your chosen application or website.

While writing the report, you should pay particular attention to UX and UI best practices and explain how your chosen application or website resembles or demonstrates the use of design patterns. You may consider design aspects like layout, navigation, conventions, graphics, text, and color in your report.The evaluation and report writing process on an existing application, eBook, or online story requires the incorporation of UX principles and concepts.

The UX principles and concepts help to enhance the application’s usability, user experience, and user satisfaction.The primary focus of the evaluation and report writing process is to evaluate the application or website’s design, layout, content, and features. As such, the report should provide an accurate representation of the application or website’s user interface, user experience, and its overall effectiveness.

To know more about application visit:

https://brainly.com/question/31354585

#SPJ11

the given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incremented. the program fails and throws an exception if the second input on a line is a string rather than an integer. at fixme in the code, add try and except blocks to catch the valueerror exception and output 0 for the age. ex: if the input is: lee 18 lua 21 mary beth 19 stu 33 -1 then the output is: lee 19 lua 22 mary 0 stu 34

Answers

To fix the program and handle the ValueError exception, add a try-except block around the age increment code, converting the age to an integer. If a ValueError occurs, set the age to 0.

To fix the program and catch the ValueError exception, we need to add a try-except block around the line of code where the age is incremented. This way, if the second input on a line is a string instead of an integer, the program will catch the exception and output 0 for the age.

Here's how we can modify the code to achieve this:

1. Start by initializing an empty dictionary to store the names and ages:
```
names_and_ages = {}
```

2. Read the input until the user enters -1:
```
while True:
   name = input("Enter a name: ")
   if name == "-1":
       break
   age = input("Enter the age: ")
```

3. Inside the loop, add a try-except block to catch the ValueError exception:
```
   try:
       age = int(age)  # Convert the age to an integer
       age += 1  # Increment the age by 1
   except ValueError:
       age = 0  # Set the age to 0 if a ValueError occurs
```

4. Add the name and age to the dictionary:
```
   names_and_ages[name] = age
```

5. After the loop ends, iterate over the dictionary and output the names and ages:
```
for name, age in names_and_ages.items():
   print(name, age)
```

By adding the try-except block around the code that increments the age, we can catch the ValueError exception if the age input is not an integer. In this case, we set the age to 0. This ensures that the program doesn't fail and continues to execute correctly.

Let's apply this modified code to the example input you provided:

Input:
```
lee 18
lua 21
mary beth 19
stu 33
-1
```

Output:
```
lee 19
lua 22
mary 0
stu 34
```

Now the program successfully catches the ValueError exception and outputs 0 for the age when necessary.

Learn more about program : brainly.com/question/23275071

#SPJ11

Trace this method public void sortList() \{ int minlndex, tmp; int n= this.size(); for (int i=1;i<=n−1;i++){ minlndex =i; for (int i=i+1;i<=n;i++){ if (( Integer) this.getNode(i).getData() < (Integer) this.getNode(minlndex).getData()) \{ minindex =i; if (minlndex ! =i){ this.swapNodes(i, minlndex); \} \}

Answers

To trace the method public void sort List() is explained below :Code snippet :public void sort List  int min lndex,

The above code is used to sort a singly linked list in ascending order. Here, we need to find the minimum element in the list. The minimum element is found by comparing each element of the list with the first element of the list. If any element is smaller than the first element, it is stored as the minimum element.

After the minimum element is found, it is swapped with the first element of the list. Then, we repeat the same process for the remaining elements of the list. Finally, we get a sorted linked list in ascending order.

To know more about public void visit:

https://brainly.com/question/33636055

#SPJ11

true or false: in the worst case, adding an element to a binary search tree is faster than adding it to a linked list that has both head and tail pointers/references.

Answers

The given statement "In the worst case, adding an element to a binary search tree (BST) is faster than adding it to a linked list that has both head and tail pointers/references" is false.

Binary search trees and linked lists have different characteristics when it comes to adding elements. Let's break down the process step by step:

1. Binary search tree (BST): A binary search tree is a data structure in which each node has at most two children. The left child is smaller than the parent, and the right child is larger.

When adding an element to a BST, we compare the element to the current node's value and recursively traverse either the left or right subtree until we find an appropriate place to insert the new element. In the worst case, this process can take O(n) time, where n is the number of elements in the tree. This happens when the tree is unbalanced and resembles a linked list.

2. Linked list: A linked list is a linear data structure in which each element (node) contains a value and a reference to the next node. In a linked list with both head and tail pointers/references, adding an element to the end (tail) is a constant-time operation, usually O(1). This is because we have direct access to the tail, making the insertion process efficient.

Therefore, in the worst-case scenario where the binary search tree is unbalanced and resembles a linked list, adding an element to the BST will take O(n) time while adding it to the linked list with head and tail pointers/references will still be O(1) since we have direct access to the tail.

In summary, adding an element to a binary search tree is not faster than adding it to a linked list with both head and tail pointers/references in the worst case.

Hence, The given statement "In the worst case, adding an element to a binary search tree is faster than adding it to a linked list that has both head and tail pointers/references" is false.

Read more about BST at https://brainly.com/question/20712586

#SPJ11

Will a new router improve Wi-Fi range?.

Answers

Yes, a new router can improve Wi-Fi range.

Upgrading to a new router can indeed enhance the Wi-Fi range and overall coverage in your home or office. Older routers may have limited range or outdated technology, which can result in weak signals and dead spots where Wi-Fi connectivity is compromised.

Newer routers are equipped with advanced technologies such as multiple antennas, beamforming, and improved signal amplification. These features help to extend the range of the Wi-Fi signal, allowing it to reach farther and penetrate through walls and obstacles more effectively.

Additionally, newer routers often support faster wireless standards, such as 802.11ac or 802.11ax (Wi-Fi 5 or Wi-Fi 6). These standards offer higher data transfer speeds and improved performance, which can contribute to a better Wi-Fi experience and stronger signals across a larger area.

When considering a new router to improve Wi-Fi range, it is essential to assess factors such as the router's maximum coverage range, the number of antennas, and the supported wireless standards. Choosing a router that aligns with your specific needs and offers improved range capabilities can make a noticeable difference in extending your Wi-Fi coverage and reducing signal issues.

Learn more about router

brainly.com/question/31845903

#SPJ11

Write a C program which calculate and print average of several students grades - Student Grades read from Keyboard. - Use while loop. - To stop iteration from keep looping use sentinel 9999.

Answers

Here is the C program to calculate and print the average of several students' grades that are read from the keyboard using a while loop with sentinel 9999:

```
#include

int main() {
  int grade, sum = 0, count = 0;

  printf("Enter grades of students: \n");

  printf("Enter grade or 9999 to quit: ");
  scanf("%d", &grade);

  while(grade != 9999) {
     sum += grade;
     count++;
     printf("Enter grade or 9999 to quit: ");
     scanf("%d", &grade);
  }

  if(count == 0) {
     printf("No grades were entered.");
  } else {
     double average = (double) sum / count;
     printf("Average of the grades is %.2lf", average);
  }

  return 0;
}
```

In this program, we first initialize the variables grade, sum, and count to 0. Then, we prompt the user to enter the grades of the students and start a while loop to read the grades from the keyboard. The loop runs until the user enters the sentinel value 9999.

Inside the loop, we add the grade to the sum and increment the count of grades entered. We then prompt the user to enter the next grade or to quit. After the loop ends, we check if any grades were entered and print the average of the grades if grades were entered. If no grades were entered, we print a message saying so.

Learn more about here:

https://brainly.com/question/33334224

#SPJ11

PROGRAMMING IN C !!! NO OTHER LANGUAGE ALLOWED
Note: You are not allowed to add any other libraries or library includes other than (if you believe you need it).
Description: The function sorts the array "numbers" of size "n" elements. The sorting is in descending order if the parameter "descendFlag" is set to (1) and is in ascending order if it is anything else.
Arguments:
int *numbers -- array of integers
unsigned int n -- length of array "numbers"
int descendFlag -- order of the sort (1) descending and ascending if anything else.
Example:
int arr[] = {14, 4, 16, 12}
sortArray(arr, 4, 0); // [4, 12, 14, 16]
sortArray(arr, 4, 1); // [16, 14, 12, 4]
Starting Code:
#include
void sortArray(int *numbers, unsigned int n, int descendFlag) {
// TODO
}

Answers

The function "sortArray" is designed to sort the array "numbers" in the descending order if the parameter "descendFlag" is set to (1) and the array "numbers" in ascending order if the parameter "descendFlag" is anything else. Therefore, if the user inputs (1) in the function, then the array "numbers" will be sorted in descending order.

On the other hand, if the user inputs any other number in the function, then the array "numbers" will be sorted in ascending order. The following is the main answer to this question.The solution is given below: #include void sortArray).The sortArray function has two nested for loops, the inner loop iterates through the array elements and sorts them based on the condition set by the user (ascending or descending order). The outer loop sorts the array in ascending or descending order based on the inner loop iterations.

if the "descendFlag" parameter is set to 1, it sorts the array in descending order. You can run this code on any C compiler. The function signature, arguments, and example are also given in the question.

To know more about "sortArray" visit:

https://brainly.com/question/31414928

#SPJ11

What is a typical marking used to indicate controlled unclassified information?.

Answers

The one that is a typical marking used to indicate controlled unclassified information is sensitive but unclassified (SBU). The correct option is B.

"Sensitive But Unclassified" (SBU) is a common designation for Controlled Unclassified Information (CUI).

This marking is used to designate material that is not classified but nevertheless has to be protected because it is sensitive.

CUI includes a wide range of sensitive data, including personally identifiable information (PII), private company data, law enforcement data, and more.

The SBU designation acts as a warning to handle such material with caution and to limit its distribution to authorised persons or institutions.

Organisations and government agencies may efficiently manage and secure sensitive but unclassified information by adopting the SBU designation, preserving its secrecy and integrity.

Thus, the correct option is B.

For more details regarding SBU, visit:

https://brainly.com/question/28524461

#SPJ4

Your question seems incomplete, the probable complete question is:

What is a typical marking used to indicate Controlled Unclassified Information (CUI)?

A) CONFIDENTIAL

B) SENSITIVE BUT UNCLASSIFIED (SBU)

C) TOP SECRET

D) UNCLASSIFIED

which statement about methods is true? group of answer choices a method must return a value all methods require multiple arguments some methods carry out an action; others return a value the return value of a method must be stored in a variable

Answers

One true statement about methods is that some methods carry out an action, while others return a value. Option c is correct.

Methods in programming are used to perform specific tasks or actions. Some methods, known as void methods, do not return a value and are used to execute a particular action or set of actions. For example, a void method could be used to display a message on the screen or modify a variable's value without returning any specific result.

On the other hand, some methods are designed to return a value. These methods are used when we need to perform a calculation or retrieve information from a specific operation. The return value of such methods can be stored in a variable or used directly in another part of the program.

In summary, while some methods perform actions, others return values that can be utilized in the program.

Therefore, c is correct.

Learn more about methods https://brainly.com/question/14802425

#SPJ11

Need help determining what normalization rules can be applied to my database. Attached is a copy of my database that I made in MySQL. Need to apply the Normalization rules to my database design. And describe how 1NF, 2NF, and 3NF apply to your design/database schema.
orders table: ordered(primary), orderstatus, orderdate, deliverytime, totalprice, customerid(foreign)
customer table: customerid (primary),name, address, city, state, zipcode, phonenumber, email
pizza table: pizzaid(primary), pizzaprice, pizzaquantity, pizzaname(meat lovers, cheese lovers, veggie), pizzatoppings (olives, peppers, mushrooms, pepperoni), orderid(foreign)
beverage table: bevid(primary), bevname (sprite, water, Pepsi), bevprice, bevquantity, orderid(foreign)

Answers

Normalization is a method that improves database design by minimizing redundancy and ensuring data consistency.

There are three normalization rules: 1NF (First Normal Form), 2NF (Second Normal Form), and 3NF (Third Normal Form).Here is a description of how the three normalization rules apply to the database design:First Normal Form (1NF): The first normal form requirement is that the values in the column must be atomic. Each column should have a unique value. If a column contains multiple values, it should be divided into several columns with unique values.

In the given database, there are three tables that follow 1NF: customer, orders, and pizza.Second Normal Form (2NF): The second normal form requirement is that the database must be in first normal form. The second normal form requires that each non-key attribute in a table must be functionally dependent on the entire primary key. In the given database, the pizza table violates the 2NF. The pizza table should be split into two separate tables: Pizza Toppings and Pizza Item.

To know more about database visit:

https://brainly.com/question/30163202

#SPJ11

Most of Word's table styles are based on which style? Table Normal style Table Heading style Table style Normal style In a nested table, which of the following terms refers to the table within the main table? split table divided table child table parent table Which of the following performs simple or more complex mathematical calculations in a table? syntax formulas operators values

Answers

Most of Word's table styles are based on the Table Normal style. In a nested table, the term that refers to the table within the main table is the child table. Mathematical calculations in a table are performed using formulas.

Word's table styles provide a consistent and professional look to tables. The Table Normal style serves as the base for most table styles in Word. It sets the default formatting for tables, such as font, cell borders, and background colors. By applying different table styles based on the Table Normal style, users can easily change the appearance of tables in their documents without manually adjusting each formatting element.

In a nested table, which is a table embedded within another table, the term used to refer to the table within the main table is the child table. It is a subordinate table that exists within the context of the primary or parent table. Nested tables are often used to organize and structure complex data or create more advanced layouts within a table structure.

To perform mathematical calculations in a table, Word provides the functionality of formulas. Formulas allow users to apply simple or more complex mathematical operations to the data within the table cells. Users can input formulas using a specific syntax and utilize operators and values to perform calculations. This feature is particularly useful when working with numerical data in tables, enabling users to perform calculations such as addition, subtraction, multiplication, and division.

Learn more about nested table

brainly.com/question/31088808

#SPJ11

Modify the above program to complete the same task by replacing the array with ArrayList so that the user does not need to specify the input length at first. The recursion method's first argument should also be changed to ArrayList. The user input ends up with −1 and −1 is not counted as the elements of ArrayList. REQUIREMENTS - The user input is always correct (input verification is not required). - Your code must use recursion and ArrayList. - The recursion method int addition (ArrayList al, int startindex) is a recursion one whose arguments are an integer ArrayList and an integer, the return value is an integer. - The main method prompts the user to enter the elements of the ArrayList myArrayList, calculates the addition of all elements of the array by calling the method addition (myArrayList, 0 ), displays the result as the following examples. - Your code must work exactly like the following example (the text in bold indicates the user input). Example of the program output: Example 1: The elements of your array are: 123456−1 The addition of 1,2,3,4,5,6 is 21 . Example 2: The elements of your array are: 2581267−1 The addition of 2,5,8,12,67 is 94.

Answers

The modified program that tend to use ArrayList as well as recursion to calculate the sum of elements entered by the user is given in the code below.

What is the program?

java

import java.util.ArrayList;

import java.util.Scanner;

public class ArrayListRecursion {

   public static void main(String[] args) {

       Scanner scanner = new Scanner(System.in);

       ArrayList<Integer> myArrayList = new ArrayList<>();

       

       System.out.println("Enter the elements of the ArrayList (-1 to stop):");

       int num = scanner.nextInt();

       while (num != -1) {

           myArrayList.add(num);

           num = scanner.nextInt();

       }

       

       System.out.print("The elements of your ArrayList are: ");

       for (int i = 0; i < myArrayList.size(); i++) {

           System.out.print(myArrayList.get(i));

           if (i < myArrayList.size() - 1) {

               System.out.print(",");

           }

       }

       System.out.println();

       

       int sum = addition(myArrayList, 0);

       System.out.println("The addition of " + formatArrayList(myArrayList) + " is " + sum + ".");

   }

   

   public static int addition(ArrayList<Integer> al, int startIndex) {

       if (startIndex == al.size() - 1) {

           return al.get(startIndex);

       } else {

           return al.get(startIndex) + addition(al, startIndex + 1);

       }

   }

   

   public static String formatArrayList(ArrayList<Integer> al) {

       StringBuilder sb = new StringBuilder();

       for (int i = 0; i < al.size(); i++) {

           sb.append(al.get(i));

           if (i < al.size() - 1) {

               sb.append(",");

           }

       }

       return sb.toString();

   }

}

Therefore, the program keeps asking the user for a number until they enter -1. After that, it shows the items in the ArrayList and adds them all together using the plus method.

Read more about ArrayList here:

https://brainly.com/question/29754193

#SPJ4

set gatherTokens(string text)
//TODO: Write function in C++. This should be written before the main function. Example of an output below

Answers

Given below is the code snippet of a function named `gatherTokens(string text)` in C++ that can be used to gather the tokens from the input text provided. The function `gatherTokens()` takes in a string argument `text` and returns the output as a vector of strings that contains all the individual tokens in the input text.```cpp
#include
using namespace std;

vector gatherTokens(string text) {
   vector tokens;
   stringstream check1(text);
   string intermediate;
   while (getline(check1, intermediate, ' ')) {
       tokens.push_back(intermediate);
   }
   return tokens;
}

int main() {
   string text = "This is a sample text.";
   vector tokens = gatherTokens(text);
   for (auto i : tokens) {
       cout << i << endl;
   }
   return 0;
}
```
Output:```
This
is
a
sample
text.
```Here, the `gatherTokens()` function takes a string argument `text` as input and returns a vector of string tokens as output. This function uses the `stringstream` class to split the input `text` into individual strings separated by a space character and adds each of these individual strings to the `tokens` vector. Finally, the function returns the `tokens` vector containing all the individual tokens from the input `text`.

For similar coding problems on C++ visit:

https://brainly.com/question/32202409

#SPJ11

Create a Ticket class. The design is up to you. Write the necessary methods. Part II Create a MovieTicket class that inherits from Ticket class. The design is up to you. Write the necessary methods. Part III Create a Theater class. The design is up to you. Write the necessary methods, Part IV Implement a method that returns the total price of the MovieTickets in the Theater. Part V Implement a method that removes all MovieTickets that the date is expired. You can use int or String objects to represent the date.

Answers

In the Ticket class, a variable is created to store the price of the ticket. A constructor is created to set the price of the ticket. A method is created to return the price of the ticket.

The Movie Ticket class is created as a subclass of the Ticket class using the extends keyword. A variable is created to store the date of the ticket. A constructor is created to set both the price and date of the ticket. A method is created to return the date of the ticket .Part III: Theater Class creation Here is the main answer to create a Theater class: import java.

The Theater class is created to keep track of a list of movie tickets. An Array List is created to store the movie tickets. A method is created to add a movie ticket to the list. A method is created to get the total price of all the movie tickets in the list. A method is created to remove all the expired movie tickets from the list using a String object to represent the date

To know more about ticket visit:

https://brainly.com/question/33631996

#SPJ11

Other Questions
An intern has started working in the support group. One duty is to set local policy for passwords on the workstations. What tool would be best to use?grpol.mscpassword policysecpol.mscsystem administrationaccount policy A work-study job in the llbrary pays $9.49hr and a job in the tutoring center pays $16.09hr. How long would it take for a tutor to make over $520 more than a student working in the library? Round to the nearest hour. It would take or hours. pragmatic intelligence governs during childhood. adolescence. adulthood. throughout the life span. what does mafatu do before he lanches his canoe in a stage i company, if the entrepreneur falters, the company usually flounders. this is labeled by greiner as a crisis of Suppose we have a data set with five predictors, X 1=GPA,X 2= IQ, X 3= Level ( 1 for College and 0 for High School), X 4= Interaction between GPA and IQ, and X 5= Interaction between GPA and Level. The response is starting salary after graduation (in thousands of dollars). Suppose we use least squares to fit the model, and get ^0=50, ^1=20, ^2=0.07, ^3=35, ^4=0.01, ^5=10. (a) Which answer is correct, and why? i. For a fixed value of IQ and GPA, high school graduates earn more, on average, than college graduates. 3. Linear Regression ii. For a fixed value of IQ and GPA, college graduates earn more, on average, than high school graduates. iii. For a fixed value of IQ and GPA, high school graduates earn more, on average, than college graduates provided that the GPA is high enough. iv. For a fixed value of IQ and GPA, college graduates earn more, on average, than high school graduates provided that the GPA is high enough. (b) Predict the salary of a college graduate with IQ of 110 and a GPA of 4.0. (c) True or false: Since the coefficient for the GPA/IQ interaction term is very small, there is very little evidence of an interaction effect. Justify your answer. how and why where africanized honey bees originally imported to brazil Identify the correct implementation of using the "first principle" to determine the derivative of the function: f(x)=-48-8x^2 + 3x Suppose the demand for a product is given by P=602Q. Also, the supply is given by P=10+3Q. If a $10 per-unit excise tax is levied on the buyers of a good, after the tax, the total quantity of the good sold is 4 (8) 6 None of these 2 trabecular bone represents the spongy, less dense, and relatively weaker bone most prevalent in the vertebrae and ball of the femur. a)TRUE b)FALSE Documentation procedures do not include which of the following? all controls written down and kept updated pre-numbered documents alarms set at the close of the business day source documents sent promptly to the accounting department A processor with a clock rate of 2.5 GHz requires 0.28 seconds to execute the 175 million instructions contained in a program.a) What is the average CPI (cycles per instruction) for this program?b) Suppose that the clock rate is increased, but the higher clock rate results in an average CPI of 5 for the program. To what new value must the clock rate be increased to achieve a speedup of 1.6 for program?c) Suppose that instead, the programmer optimizes the program to reduce the number of instructions executed from 175 million down to 159090910. If before and after the optimization the clock rate is 2.5 GHz and the average CPI is 4, what speedup is provided by the optimization? Express your answer to two decimal places. The market price of a semi-annual pay bond is $986.70. It has 29.00 years to maturity and a yield to maturity of 7.23%. What is the coupon rate?Derek borrows $316,196.00 to buy a house. He has a 30-year mortgage with a rate of 5.57%. After making 85.00 payments, how much does he owe on the mortgage? Heat capacity of liquid water 4.18J/(gk) Energy transferred? Let Z(x),D(x),F(x) and C(x) be the following predicates: Z(x) : " x attended every COMP2711 tutorial classes". D(x) : " x gets F in COMP2711". F(x) : " x cheated in the exams". C(x) : " x has not done any tutorial question". K(x) : " x asked some questions in the telegram group". Express the following statements using quantifiers, logical connectives, and the predicates above, where the domain consists of all students in COMP2711. (a) A student gets F in COMP2711 if and only if he/she hasn't done any tutorial question and cheated in the exams. (b) Some students did some tutorial questions but he/she either absent from some of the tutorial classes or cheated in the exams. (c) If a student attended every tutorial classes but gets F, then he/she must have cheated in the exams. (d) Any student who asked some questions in the telegram group and didn't cheat in the exams won't get F. a pair of blue jeans is best associated with which cultural subsystem? Regular Expressions is a Python library for:A. Text pattern matchingB. Draw graphsC. Image ProcessingD. Numerical ComputationExplain your answer (This is important) g efforts to beat out competitors in existing markets and instead invent a new industry or new market segment that renders existing competitors largely irrelevant and allows a company to create and capture altogether new d What is the value of each of the following expressions? 8+10 2= 8/2 3= 2 2 (1+4) 2= 6+10/2.012= Laylow Limited is a property investment company in Durban. It specialises in commercial letting of property including corporate buildings, flats and retail shopping outlets. During the recent civil unrest, one of the commercial properties owned by Laylow Limited was destroyed. ArtFood Limited, rented this property directly from Laylow Limited for the last 40 years thus Laylow Limited has had an excellent relationship with them. The building Laylow Limited is currently occupying, is owned by Laylow Limited) and used by them as admin offices. The building has a large first floor and ample parking which will be ideally suited to ArtFood Limited.Laylow Limited has another vacant property which is ideally suited to Laylow Limited to use as their admin building and have been wanting to move the offices for the last few months. Laylow Limited has seen this as an ideal opportunity to move their admin offices from the building andthen rent the building out to ArtFood Limited. ArtFood Limited was extremely grateful for this offer and has taken the offer up from the 1st of July 2020.The following details relate to the building that Laylow Limited was occupying and will now be let to ArtFood Limited.- Purchased for R1 500 000 on the 1 January 2019 (useful life 50 years)- Fair Value of the building R1 550 000 30 June 2020- Fair Value R1 490 000 31 December 2020During the year, Laylow Limited spent the following amounts on another investment property they own which consists of a block of flats:- R25 000 to replace on the globes in the building which blew during a power surge after loadshedding 31 August 2020- R350 000 to build an extra floor on the rooftop to rent out as a penthouse under an operating lease 30 September 2020- Damages to the lift system from the loadshedding the lift system was quite outdated and therefore cannot be repaired. The lift system had to be replaced at a cost of R85 000. The FV of the damaged lift was R7 000. 30 September 2020Laylow Limited uses cost model to measure Property, Plant & Equipment and the Fair Value model to measure Investment Property. Laylow Limited has a 31st December year end.Required:1. What is difference between an Investment Property & an Owner-Occupied Property (Tip provide the definition of each type to determine the difference) (5)2. When will transfers in and out of Investment property occur (list the criteria for a transfer to take place)? (3)3. Prepare the journal entries in the books of Laylow Limited for the year ended 31st December 2020 for all the transactions as noted above.Please include