A perfect binary tree is a complete binary tree with all levels fully filled. Add a method in the BST class to return true if the tree is a perfect binary tree.

Answers

Answer 1

Answer:

class BST {

static class Node

{

int val;

Node left, right;

}

static boolean checkPerfectBT(Node node, int h, int d)

{

if (node == null)

return true;

 

if (node.left == null && node.right == null)

{

if(h==d+1)

return true;

else

return false;

}

 

if (node.left == null || node.right== null)

return false;

 

return checkPerfectBT(node.left, h, d+1) && checkPerfectBT(node.right, h, d+1);

}

static int height(Node node)

{

int dep = 0;

while (node != null)

{

node = node.right;

dep=dep+1;

}

return dep;

}

static boolean isPerfectBT(Node node)

{

int h = height(node);

return checkPerfectBT(node, h, 0);

}

 

static Node addNode(int x)

{

Node node = new Node();

node.val= x;

node.right = null;

node.left = null;

return node;

}

public static void main(String args[])

{

int i,j,k;

Node node= null;

node = addNode(34);

node.left = addNode(2);

node.right = addNode(322);

 

node.left.left = addNode(21);

node.left.right = addNode(23);

node.right.left = addNode(37);

node.right.right = addNode(54);

 

if (isPerfectBT(node) == true)

System.out.println("This is a Perfect Binary tree");

else

System.out.println("This is Not a perfect Binary Tree");

}

}

Explanation:

Calculate the depth of BST by using a while loop until it reaches a null value.In the addNode method, make an object of Node class.In the main method, pass the values to addNode method.Finally display the relevant message to show if it's Perfect or not.

Related Questions

Create a class named College Course that includes data fields that hold the department (for example, ENG), the course number (for example, 101), the credits (for example, 3), and the fee for the course (for example, $360). All of the fields are required as arguments to the constructor, except for the fee, which is calculated at $120 per credit hour. Include a display () method that displays the course data. Create a subclass named Lab Course that adds $50 to the course fee. Override the parent class display () method to indicate that the course is a lab course and to display all the data. Write an application named UseCourse that prompts the user for course information. If the user enters a class in any of the following departments, create a LabCourse: BIO, CHM, CIS, or PHY. If the user enters any other department, create a CollegeCourse that does not include the lab fee. Then display the course data. Save the files as CollegeCourse.java, LabCourse.java, and UseCourse.java.

Answers

Answer:

File: clgCourse.java

public class clgCourse

{

  private final double CREDIT_HOUR_FEE = 120.00;

  private String dpt;

  private int courseNo;

  private int credits;

  private double courseFee;

  public clgCourse(String newdpt, int newcourseNo, int newCredits)

  {

      dpt = newdpt.toUpperCase();

      courseNo = newcourseNo;

      credits = newCredits;

      courseFee = CREDIT_HOUR_FEE * credits;

  }

  public String getdpt()

  {

      return dpt;

  }

  public int getcourseNo()

  {

      return courseNo;

  }

  public int getCredits()

  {

      return credits;

  }

  public double getcourseFee()

  {

      return courseFee;

  }

  public void display()

  {

      System.out.println("\n Course Data");

      System.out.println("Course: " + "College Course");

      System.out.println("dpt: " + this.getdpt());

      System.out.println("Course Number: " + this.getcourseNo());

      System.out.println("Credit Hours: " + this.getCredits());

      System.out.println("Course Fee: $" + this.getcourseFee());

  }

}

File: LabCourse.java

public class LabCourse extends clgCourse

{

  private final double LAB_FEE = 50.00;

  private double labCourseFee;

  public LabCourse(String newdpt, int newcourseNo, int newCredits)

  {

      super(newdpt, newcourseNo, newCredits);

      labCourseFee = super.getcourseFee() + LAB_FEE;

  }

  public double getLabCourseFee()

  {

      return labCourseFee;

  }

  public void display()

  {

      System.out.println("\n Course Data");

      System.out.println("Course: " + "Lab Course");

      System.out.println("dpt: " + super.getdpt());

      System.out.println("Course Number: " + super.getcourseNo());

      System.out.println("Credit Hours: " + super.getCredits());

      System.out.println("Course Fee: $" + this.getLabCourseFee());      

  }

}  

File: UseCourse.java

import java.util.Scanner;

public class UseCourse

{

  public static void main(String[] args)

  {

      Scanner keyboard = new Scanner(System.in);

      System.out.print("Enter the dpt of the course: ");

      String dept = keyboard.nextLine();

     

      System.out.print("Enter the number of the course: ");

      int number = keyboard.nextInt();

      System.out.print("Enter the credit hours of the course: ");

      int hours = keyboard.nextInt();

      if(dept.equalsIgnoreCase("BIO") || dept.equalsIgnoreCase("CHM")

              || dept.equalsIgnoreCase("CIS") || dept.equalsIgnoreCase("PHY"))

      {

          LabCourse labCourse = new LabCourse(dept, number, hours);

          labCourse.display();

      }

      else

      {

          clgCourse clgCourse = new clgCourse(dept, number, hours);

          clgCourse.display();

      }

      keyboard.close();

  }

}

Explanation:

Create a getdpt method that returns the dpt of the course .Create a getcourseNo method that returns the number of the course.Create a display method that displays all the data of college course .Check if the user enters any of the lab dpts (BIO, CHM, CIS, or PHY),  then create a LabCourse and then display the course data .Check if the user does not enter any of the lab dpts (BIO, CHM, CIS, or PHY),  then create a clgCourse and then display the course data .

For each of the following languages, state with justification whether it isrecognizableor unrecognizable.(a)LHALT≥376={(〈M〉, x) : machine halts on input after 376 or more steps}(b)LLIKES-SOME-EVEN={〈M〉:Maccepts some even number}(c)L

Answers

Answer:

See the picture attached

Explanation:

c++ design a class named myinteger which models integers. interesting properties of the value can be determined. include these members: a int data field named value that represents the integer's value. a constructor that creates a myinteger object with a specified int value. a constant getter that returns the value

Answers

Answer:

#include <iostream>using namespace std;class myinteger {        private:        int value;            public:        myinteger(int x){            value = x;        }               int getValue(){           return value;       }        };int main(){    myinteger obj(4);    cout<< obj.getValue();    return 0;}

Explanation:

Firstly, we use class keyword to create a class named myinteger (Line 5). Define a private scope data field named value in integer type (Line 7 - 8).

Next, we proceed to define a constructor (Line 11 - 13) and a getter method for value (Line 15 -17) in public scope. The constructor will accept one input x and set it to data field, x. The getter method will return the data field x whenever it is called.

We test our class by creating an object from the class (Line 23) by passing a number of 4 as argument. And when we use the object to call the getValue method, 4 will be printed as output.

Write a function, named "wait_die_scheduler" that takes a list of actions, and returns a list of actions according to the following rules. The actions given to the scheduler will only consist of WRITE and COMMIT actions. (Hence only exclusive locks need be implemented.) Each transaction will end with a COMMIT action. Before examining each action, attempt to perform an action for each of the transactions encountered (ordered by their names). After all the actions have been examined, continue to attempt to perform an action from each transaction until there are no more actions to be done. You will need to add LOCK, UNLOCK, and ROLLBACK actions to the list of actions to be returned, according to the Wait-Die protocol. If releasing more than one lock (for instance after a COMMIT), release them in order by the name of their object. Use the deferred transaction mode (only requesting locks when needed).

Answers

To implement the `wait_die_scheduler` function according to the Wait-Die protocol for handling WRITE and COMMIT actions in transactions, we'll simulate a scheduler that ensures correct behavior with respect to locks and transaction order. The Wait-Die protocol is used to manage concurrency and handle conflicts between transactions efficiently. Below is a Python implementation of this scheduler function:

def wait_die_scheduler(actions):

   # Data structures to track locks and actions

   locks = {}  # Dictionary to track locks by object name

   results = []  # List to collect final actions to be returned

   # Process the list of actions

   for action in actions:

       transaction_name = action[0]

       action_type = action[1]

       object_name = action[2]

       # If action is WRITE or COMMIT

       if action_type == 'WRITE' or action_type == 'COMMIT':

           # Check if the transaction already has a lock on the object

           if object_name in locks and locks[object_name] != transaction_name:

               # Conflict detected, need to resolve based on Wait-Die protocol

               # Check order of transactions for waiting or aborting

               if transaction_name < locks[object_name]:

                   # Current transaction waits (older transaction, so wait)

                   results.append((transaction_name, 'WAIT', object_name))

               else:

                   # Current transaction aborts (newer transaction, so abort)

                   results.append((transaction_name, 'ROLLBACK', object_name))

                   # Release locks held by the aborted transaction

                   results.extend([(locks[obj], 'UNLOCK', obj) for obj in sorted(locks.keys())])

                   locks.clear()  # Clear all locks after rollback

           else:

               # No conflict, acquire lock for the transaction

               locks[object_name] = transaction_name

           # Add the original action to the results

           results.append((transaction_name, action_type, object_name))

           # If action is COMMIT, release locks held by the committed transaction

           if action_type == 'COMMIT':

               results.extend([(locks[obj], 'UNLOCK', obj) for obj in sorted(locks.keys())])

               locks.clear()  # Clear all locks after commit

   # Final pass to release any remaining locks (should not normally occur)

   results.extend([(locks[obj], 'UNLOCK', obj) for obj in sorted(locks.keys())])

   locks.clear()  # Clear all locks after processing all actions

   return results

# Example usage

actions = [

   ('T1', 'WRITE', 'A'),

   ('T2', 'WRITE', 'B'),

   ('T1', 'COMMIT', 'A'),

   ('T2', 'COMMIT', 'B'),

   ('T1', 'WRITE', 'B'),

   ('T1', 'COMMIT', 'B')

]

result_actions = wait_die_scheduler(actions)

for action in result_actions:

   print(action)

Explanation of the `wait_die_scheduler` function:

1. Initialization: We start by defining empty data structures (`locks` and `results`) to track locks on objects and the resulting list of actions.

2. Processing Actions: Iterate through each action in the provided list (`actions`). Each action is a tuple consisting of transaction name, action type (`WRITE` or `COMMIT`), and the object name.

3. Handling WRITE and COMMIT Actions:

  - For a `WRITE` action:

    - Check if the transaction already holds a lock on the object.

    - If there's a conflict (another transaction holds the lock), resolve it based on the Wait-Die protocol by either making the current transaction wait or aborting it.

  - For a `COMMIT` action:

    - Release all locks held by the committed transaction.

4. Building Resulting Actions:

  - Append the original action to the `results` list.

  - If a transaction commits or aborts, add corresponding `UNLOCK` actions for all locks held by the transaction.

5. Final Cleanup: Ensure all locks are released after processing all actions.

This implementation follows the Wait-Die protocol by managing locks, resolving conflicts between transactions, and ensuring correct order of operations according to the protocol rules. Adjustments may be needed based on specific requirements or variations of the Wait-Die protocol for different scenarios.

The input is an N by N matrix of numbers that is already in memory. Each individual row is increasing from left to right. Each individual column is increasing from top to bottom. Give an O(N) worst-case algorithm that decides if a number X is in the matrix.

Answers

Final answer:

An efficient O(N) algorithm can determine if a number X is present in an N x N sorted matrix by starting from the top-right corner and moving left or down through matrix elements based on comparisons with X, eliminating one row or column at a time.

Explanation:

Suppose we have an N x N matrix, where each row is sorted in increasing order from left to right and each column is sorted in increasing order from top to bottom. To determine if a given number X is in this matrix, we can employ an efficient algorithm with a time complexity of O(N), which is much faster than checking every element in the matrix.

The algorithm starts from the top-right corner of the matrix. At each step, if the current element is greater than X, we move one step to the left. If the current element is less than X, we move one step down. If the current element is equal to X, we return true, indicating that X is found in the matrix. If we reach the left border or the bottom border of the matrix without finding X, we return false.

This algorithm works because the matrix is sorted row-wise and column-wise, allowing us to eliminate a row or a column at each step. Hence, we perform at most N steps, leading to a worst-case time complexity of O(N).

Create a class called Clock to represent a Clock. It should have three private instance variables: An int for the hours, an int for the minutes, and an int for the seconds. The class should include a threeargument constructor and get and set methods for each instance variable. Override the method toString which should return the Clock information in the same format as the input file (See below). Read the information about a Clock from a file that will be given to you on Blackboard, parse out the three pieces of information for the Clock using a StringTokenizer, instantiate the Clock and store the Clock object in two different arrays (one of these arrays will be sorted in a later step). Once the file has been read and the arrays have been filled, sort one of the arrays by hours using Selection Sort. Display the contents of the arrays in a GUI that has a GridLayout with one row and two columns. The left column should display the Clocks in the order read from the file, and the right column should display the Clocks in sorted order.

Answers

Answer:

public class Clock

{

private int hr; //store hours

private int min;  //store minutes

private int sec; //store seconds

public Clock ()

{

 setTime (0, 0, 0);

}

public Clock (int hours, int minutes, int seconds)

{

 setTime (hours, minutes, seconds);

}

public void setTime (int hours, int minutes, int seconds)

{

 if (0 <= hours && hours < 24)

      hr = hours;

 else

      hr = 0;

 

 if (0 <= minutes && minutes < 60)

      min = minutes;

 else

      min = 0;

 

 if (0 <= seconds && seconds < 60)

      sec = seconds;

 else

      sec = 0;

}

 

 //Method to return the hours

public int getHours ( )

{

 return hr;

}

 //Method to return the minutes

public int getMinutes ( )

{

 return min;

}

 //Method to return the seconds

public int getSeconds ( )

{

 return sec;

}

public void printTime ( )

{

 if (hr < 10)

      System.out.print ("0");

 System.out.print (hr + ":");

 if (min < 10)

      System.out.print ("0");

 System.out.print (min + ":");

 if (sec < 10)

      System.out.print ("0");

 System.out.print (sec);

}

 

 //The time is incremented by one second

 //If the before-increment time is 23:59:59, the time

 //is reset to 00:00:00

public void incrementSeconds ( )

{

 sec++;

 

 if (sec > 59)

 {

  sec = 0;

  incrementMinutes ( );  //increment minutes

 }

}

 ///The time is incremented by one minute

 //If the before-increment time is 23:59:53, the time

 //is reset to 00:00:53

public void incrementMinutes ( )

{

 min++;

 

if (min > 59)

 {

  min = 0;

  incrementHours ( );  //increment hours

 }

}

public void incrementHours ( )

{

 hr++;

 

 if (hr > 23)

     hr = 0;

}

public boolean equals (Clock otherClock)

{

 return (hr == otherClock.hr

  && min == otherClock.min

   && sec == otherClock.sec);

}

}

Write a function sum them() that sums a set of integers, each of which is the square or cube of a provided integer. Specifically, given an integer n from a list of values, add n2 to the total if the number’s index in nums is even; otherwise, the index is odd, so add n3 to the total.

Answers

Answer:

# sum_them function is defined

def sum_them():

   # A sample of a given list is used

   given_list = [1, 2, 3, 4, 5, 6, 6, 9, 10]

   # The total sum of the element is initialized to 0

   total = 0

   # for-loop to goes through the list

   for element in given_list:

       # if the index of element is even

       # element to power 2 is added to total

       if(given_list.index(element) % 2 == 0):

           total += (element ** 2)

       else:

       # else if index of element is odd

       # element to power 3 is added to total

           total += (element ** 3)

   # The total sum of the element is displayed

   print("The total is: ", total)        

           

# The function is called to display the sum

sum_them()            

Explanation:

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

Image of sample list used is attached.

Part A [10 points] Create a class named Case that represents a small bookbag/handbag type object. It should contain: Fields to represent the owner’s name and color of the Case. This class will be extended so use protected as the access modifier. A constructor with 2 parameters – that sets both the owner’s name and the color. Two accessor methods, one for each property. (getOwnerName, getColor) A main method that creates an instance of this class with the owner’s name set to ‘Joy’ and color set to ‘Green’. Add a statement to your main method that prints this object. Run your main method

Answers

Answer:

class Case //Case class

{

String owner_name,color; //members to store information name and color

Case(String name,String color) //constrictor with two parameters

{

this.owner_name = name; //members initialization

this.color = color;

}

public String getName() //to get name

{

return owner_name;

}

public String getColor() //to get color

{

return color;

}

public String toString()//override string method

{

return "Case Owner: " + owner_name + ", " + "Color: "+ color;

}

}

class Main //test class

{

public static void main(String args[])

{

String na,color;

Case c = new Case("Joy","Green"); //create instance of class Case and set constructor parameters

na = c.getName();

color = c.getColor();

System.out.println(c);//print statement tp print instance of a class

System.out.println(c.toString()); //print with override toString

}

}

Explanation:

def c_to_f(): # FIXME return # FIXME: Finish temp_c = float(input('Enter temperature in Celsius: ')) temp_f = None # FIXME: Call conversion function # temp_f = ?? # FIXME: Print result # print('Fahrenheit:' , temp_f)

Answers

Answer:

def c_to_f(celsius):      return celsius * 9/5 + 32 temp_c = float(input('Enter temperature in Celsius: '))  temp_f = None   temp_f = c_to_f(temp_c)  print('Fahrenheit:' , temp_f)

Explanation:

The first piece of code we can fill in is the formula to convert Celsius to Fahrenheit and return it as function output (Line 2).

The second fill-up code is to call the function c_to_f and pass temp_c as argument (Line 7). The temp_c will be processed in the function and an equivalent Fahrenheit value will be returned from the function and assigned it to temp_f.

The cybersecurity defense strategy and controls that should be used depend on __________. Select one: a. The source of the threat b. Industry regulations regarding protection of sensitive data c. What needs to be protected and the cost-benefit analysis d. The available IT budget

Answers

Answer:

The answer is "Option C"

Explanation:

It is an information warfare-security method, that consists of a set of defense mechanisms for securing sensitive data. It aimed at improving state infrastructure security and stability and provides high-level, top-down, which lays out several new goals and objectives to be met within a certain timeline, and incorrect options can be described as follows:

In option a, These securities can't include threats. Option b, and Option d both are incorrect because It is used in industry but, its part of networking.    

The two mathematical models of language description are generation and recognition. Describe how each can define the syntax of a programming language.

Answers

Answer:

The correct answer to the following question will be "Semantic and Syntax error".

Explanation:

Syntax error:

Corresponds to such a mistake in a pattern sentence structure that is composed in either a specific language of that same coding. Because computer programs have to maintain strict syntax to execute appropriately, any elements of code that would not adhere to the programming or scripting language syntax can result inside a syntax error.

Semantic error:

That would be a logical error. This is because of erroneous logical statements. Write inaccurate logic or code of a program, which results incorrectly whenever the directives are implemented.

So, it's the right answer.

For this lab you will be creating your own struct, called Frog. You will need to create an array of Frog, and prompt the user for information to create Frogs and fill in the array.

(3 pts) First, create a Frog struct (first test). It should have the following fields: Name, Age, and Leg Length. Expect sample input to look like this:

Todd Jones //Name
12 //Age
12.34 //LegLength
(1 pt) After that, ask the user how many frogs they would like to create:

How many frogs do you want?
(2 pts) Next, loop for the supplied number of times, asking for user input:

What is the name of Frog 1?
What is the age of Frog 1?
What is the leg length of Frog 1?
What is the name of Frog 2?
What is the age of Frog 2?
What is the leg length of Frog 2?

Answers

Answer:

The solution code is written in c++

#include <iostream>using namespace std;struct Frog {  string Name;  int Age;  float LegLength;}; int main (){   Frog frog_test;   frog_test.Name = "Todd Jones";   frog_test.Age = 12;   frog_test.LegLength = 12.34;     int num;   cout<<"Enter number of frogs: ";   cin>>num;     Frog frog[num];     int i;   for(i = 0; i < num; i++){             cout<<"What is the name of Frog "<< i + 1 <<" ?";       cin>> frog[i].Name;             cout<<"What is the age of Frog "<< i + 1 <<" ?";       cin>> frog[i].Age;             cout<<"What is the leg length of Frog "<< i + 1 <<" ?";       cin>> frog[i].LegLength;   }}

Explanation:

Firstly, define a Frog struct as required by the question (Line 4 - 8).

We create a test Frog struct (Line 12 - 15).

If we run the code up to this point, we shall see a Frog struct has been build without error.

Next, prompt user to input number of frogs desired (Line 17 -19).

Use the input number to declare a frog array (Line 21).

Next, we can use a for loop to repeatedly ask for input info of each frog in the array (Line 23- 34).

At last, we shall create num elements of Frog struct in the array.

You are tasked to calculate a specific algebraic expansion, i.e. compute the value of f and g for the expression: ???? = (???????? − ???????????? + ???????????? − ????????) ???? = (???????????? + ????????????????) without using any intrinsic multiplication instructions, subroutines, and function calls. More formally, write MIPS assembly code that accepts four positive integers A, B, C, and D as input parameters.

Answers

Answer:

.data

prompt: .asciiz "Enter 4 integers for A, B, C, D respectively:\n"

newLine: .asciiz "\n"

decimal: .asciiz "f_ten = "

binary: .asciiz "f_two = "

decimal2: .asciiz "g_ten = "

binary2: .asciiz "g_two = "

.text

main:

#display prompt

li $v0, 4

la $a0, prompt

syscall

#Read A input in $v0 and store it in $t0

li $v0, 5

syscall

move $t0, $v0

#Read B input in $v0 and store it in $t1

li $v0, 5

syscall

move $t1, $v0

#Read C input in $v0 and store it in $t2

li $v0, 5

syscall

move $t2, $v0

#Read D input in $v0 and store it in $t3

li $v0, 5

syscall

move $t3, $v0

#Finding A^4

#Loop (AxA)

li $t6, 0

L1:

bge $t6, $t0, quit

add $s1, $s1, $t0 # A=S+A => $s1= A^2

addi $t6, $t6, 1 # i=i+1

j L1

quit:

#Loop (A^2 x A^2)

li $t6, 0

L1A:

bge $t6, $s1, quit1A

add $s5, $s5, $s1

addi $t6,$t6, 1

j L1A

#End of Finding A^4

#Finding 4xA^3

quit1A:

#Loop (4xB)

li $t6, 0

L2:

bge $t6, 4, quit2

add $s2, $s2, $t1

addi $t6, $t6, 1

j L2

quit2:

#Loop (BxB)

li $t6 , 0

L2A:

bge $t6, $t1, quit2A #loop2

add $s6, $s6, $t1 #add

addi $t6, $t6, 1 #add immediate

j L2A #loop2

quit2A: # perform proper program termination using syscall for exit

#Loop (BxB)

li $t6 , 0 #load immediate

L2AA:

bge $t6, $s2, quit2AA #loop2

add $t7, $t7, $s6 #add

addi $t6, $t6, 1 #add immediate

j L2AA #loop2

#End ofFinding 4xA^3

#Finding 3xC^2

quit2AA: # perform proper program termination using syscall for exit

#3 Loop (3 x (C x C)) FOR S3

li $t6 , 0 #load immediate

L3:

bge $t6, $t2, quit3 #loop3

add $s3, $s3, $t2 #add

addi $t6,$t6, 1 #add immediate

j L3 #loop3

quit3: # perform proper program termination using syscall for exit

#3 Loop (3 x (C x C)) FOR S3

li $t6 , 0 #load immediate

L3A:

bge $t6, 3, quit3A #loop3

add $s0, $s0, $s3 #add

addi $t6,$t6, 1 #add immediate

j L3A #loop3

#End of Finding 3xC^2

#Finding 2xD

quit3A: # perform proper program termination using syscall for exit

#4 Loop (2 x D) FOR S4

li $t6 , 0

L4:

bge $t6, 2, quit4 #loop4

add $s4, $s4, $t3 #add

addi $t6, $t6, 1 #add immediate

j L4 #Loop4

#End of Finding 2xD

#Finding AxB^2

quit4:

li $t6, 0

li $s1, 0

L5:

bge $t6, $t1, quit5

add $s1, $s1, $t1

addi $t6, $t6, 1

j L5

quit5:

li $t6, 0

li $s2, 0

L6:

bge $t6, $t0, quit6

add $s2, $s2, $s1

addi $t6, $t6, 1

j L6

#End of Finding AxB^2

#Finding C^2XD^3

quit6: #finds C^2

li $t6, 0

li $s1, 0

L7:

bge $t6, $t2, quit7

add $s1, $s1, $t2

addi $t6, $t6, 1

j L7

quit7: #finds D^2

li $t6, 0

li $s6, 0

L8:

bge $t6, $t3, quit8

add $s6, $s6, $t3

addi $t6, $t6, 1

j L8

quit8: #finds D^3

li $t6, 0

li $s7, 0

L9:

bge $t6, $t3, quit9

add $s7, $s7, $s6

addi $t6, $t6, 1

j L9

quit9: #finds C^2XD^3

li $t6, 0

li $s3, 0

L10:

bge $t6, $s1, end

add $s3, $s3, $s7

addi $t6, $t6, 1

j L10

#End of Finding C^2XD^3

end: # perform proper program termination using syscall for exit

#f is $t8

li $t8 , 0

sub $t8, $s5, $t7 # addition

add $t8, $t8, $s0 # subract

sub $t8,$t8, $s4 # subract

#g is $t9

li $t9 , 0

add $t9, $s2, $s3 # addition

#Display

#1st equation

li $v0,4 # display the answer string with syscall having $v0=4

la $a0, decimal # Gives answer in decimal value

syscall # value entered is returned in register $v0

li $v0, 1 # display the answer string with syscall having $v0=1

move $a0, $t8 # moves the value from $a0 into $t8

syscall # value entered is returned in register $v0

li $v0,4 # display the answer string with syscall having $v0=4

la $a0, newLine # puts newLine in between answers

syscall # value entered is returned in register $v0

li $v0,4 # display the answer string with syscall having $v0=4

la $a0, binary # Gives answer in binary

syscall # value entered is returned in register $v0

li $v0, 35

move $a0, $t8 # moves the value from into $a0 from $t8

syscall # value entered is returned in register $v0

li $v0,4 # display the answer string with syscall having $v0=4

la $a0, newLine # puts newLine in between answers

syscall # value entered is returned in register $v0

#2nd equation

li $v0,4 # display the answer string with syscall having $v0=4

la $a0, decimal2 # Gives answer in decimal value

syscall # value entered is returned in register $v0

li $v0, 1 # display the answer string with syscall having $v0=1

move $a0, $t9 # moves the value from $a0 into $t8

syscall # value entered is returned in reg $v0

li $v0,4 # display the answer string with syscall having $v0=4

la $a0, newLine # puts newLine in between answers

syscall # value entered is returned in register $v0

li $v0,4 # display the answer string with syscall having $v0=4

la $a0, binary2 # Gives answer in binary

syscall # value entered is returned in register $v0

li $v0, 35

move $a0, $t9 # moves the value from into $a0 from $t8

syscall # value entered is returned in register $v0

li $v0,4 # display the answer string with syscall having $v0=4

la $a0, newLine # puts newLine in between answers

syscall # value entered is returned in register $v0

#end the program

li $v0, 10

syscall

Question 2. Complete the following conditional statement so that the string 'More please' is assigned to the variable say_please if the number of nachos with cheese in ten_nachos is less than 5. Hint: You should not have to directly reference the variable ten_nachos.

Answers

Answer:

The solution code is written in Python 3:

ten_nachos = [True, True, False, False, False, True, False, True, False, False] count = 0 for x in ten_nachos:    if (x == True):        count += 1 if count < 5:    say_please = "More please"

Explanation:

By presuming the ten_nachos hold an array of True and False values with True referring to nachos with cheese and False referring to without cheese (Line 1).

We create a counter variable, count to track the occurrence of True value in the ten_nachos (Line 3).

Create a for-loop and traverse through the True and False value in the ten_nachos and then check if the current value is True, increment count by 1 (Line 5 - 7).

If the count is less than 5, assign string "More please" to variable say_please (Line 9 -10).

Final answer:

The question requires creating a conditional statement to assign a string to a variable based on a comparison. The statement would look something like 'if nacho_count < 5: say_please = 'More please'' in pseudocode, where 'nacho_count' represents the variable for the number of nachos.

Explanation:

The student's question involves completing a conditional statement in a programming context. The problem provided requires constructing logic that assigns the string 'More please' to a variable say_please based on the condition of the number of nachos with cheese being less than five. This scenario is aligned with conditional programming logic, often taught in computer science classes at the high school level. The completion of the conditional statement can be achieved by setting a variable (presumably counting the number of nachos) and checking if it is less than five.

For the given scenario, assuming the variable counting nachos is nacho_count, the conditional statement in pseudocode would look something like:

if nacho_count < 5:
   say_please = 'More please'

It is important to note that in actual code, the specifics of the syntax will depend on the programming language being used. The underlying concept of using a conditional statement (if statement) to control the flow of a program, however, remains the same across different languages.

Create a class called Employee that includes three instance variables—a first name (type String), a last name (type String) and a monthly salary (double). Provide a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, do not set its value. Write a test app named EmployeeTest that demonstrates class Employee’s capabilities. Create two Employee objects and display each object’s yearly salary. Then give each Employee a 10% raise and display each Employee’s yearly salary again.

Answers

Answer:

public class Employee {

   private String Fname;

   private String Lname;

   private double monthlySalary;

   //Constructor

   public Employee(String fname, String lname, double monthlySalary) {

       Fname = fname;

       Lname = lname;

       this.monthlySalary = monthlySalary;

   }

   //Set and Get Methods

   public String getFname() {

       return Fname;

   }

   public void setFname(String fname) {

       Fname = fname;

   }

   public String getLname() {

       return Lname;

   }

   public void setLname(String lname) {

       Lname = lname;

   }

   public double getMonthlySalary() {

       return monthlySalary;

   }

   public void setMonthlySalary(double monthlySalary) {

       if(monthlySalary>0) {

           this.monthlySalary = monthlySalary;

       }

   }

}

public class EmployeeTest {

   public static void main(String[] args) {

       Employee employeeOne = new Employee("Dave","Jones",1800);

       Employee employeeTwo = new Employee("Junely","Peters",1200);

       double empOnecurrentYrSalary =(employeeOne.getMonthlySalary()*12);

               System.out.println("Employee One Yearly salary is " +

               ""+empOnecurrentYrSalary);

       double empTwocurrentYrSalary =(employeeTwo.getMonthlySalary()*12);

       System.out.println("Employee Two Yearly salary is " +

               ""+empTwocurrentYrSalary);

// Incremments of 10%

        double newSalaryOne = empOnecurrentYrSalary+(empOnecurrentYrSalary*0.1);

        double newSalaryTwo = empTwocurrentYrSalary+(empTwocurrentYrSalary*0.1);

       employeeOne.setMonthlySalary(newSalaryOne);

       employeeTwo.setMonthlySalary(newSalaryTwo);

       System.out.println("Employee One's New Yearly Salary is " +

               ""+(employeeOne.getMonthlySalary()));

       System.out.println("Employee Two's New Yearly Salary is " +

               ""+(employeeTwo.getMonthlySalary()));

   }

}

Explanation:

As required by the question Two Java classes are created Employee and EmployeeTest

The required fields, constructor, get and set methods are all created in the Employee class, pay attention to the comments in the code

In the EmployeeTest, two objects of the class are created as required by the question.

The current salaries are printed as initialized by the constructor

Then an increase of 10% is added and the new salary is printed.

Note the use of the setMonthlySalary and getMonthlySalary for the update and display of the salaries respectively

The following program includes fictional sets of the top 10 male and female baby names for the current year. Write a program that creates: A set all_names that contains all of the top 10 male and all of the top 10 female names. A set neutral_names that contains only names found in both male_names and female_names. A set specific_names that contains only gender specific names. Sample output for all_names: {'Michael', 'Henry', 'Jayden', 'Bailey', 'Lucas', 'Chuck', 'Aiden', 'Khloe', 'Elizabeth', 'Maria', 'Veronica', 'Meghan', 'John', 'Samuel', 'Britney', 'Charlie', 'Kim'} NOTE: Because sets are unordered, they are printed using the sorted() function here for comparison

Answers

Answer:

Following are the program in the Python Programming Language.

male_names = {'kay', 'Dev', 'Sam', 'Karan', 'Broly', 'Samuel', 'Jayd', 'Lucifer', 'Amenadiel', 'Anmol'}

female_names = {'Kally', 'Megha', 'Lucy', 'Shally', 'Bailey', 'Jayd', 'Anmol', 'Beth', 'Veronica', 'Sam'}

#initialize the union from male_names and female_names

all_names = male_names.union(female_names)

#Initialize the similar names from male_names and female_names  

neutral_names = male_names.intersection(female_names)

#initialize the symmetric_difference from male_names and female_names

specific_names = male_names.symmetric_difference(female_names)

#print the results

print(sorted(all_names))

print(sorted(neutral_names))

print(sorted(specific_names))

Output:

['Amenadiel', 'Anmol', 'Bailey', 'Beth', 'Broly', 'Dev', 'Jayd', 'Kally', 'Karan', 'Lucifer', 'Lucy', 'Megha', 'Sam', 'Samuel', 'Shally', 'Veronica', 'kay']

['Anmol', 'Jayd', 'Sam']

['Amenadiel', 'Bailey', 'Beth', 'Broly', 'Dev', 'Kally', 'Karan', 'Lucifer', 'Lucy', 'Megha', 'Samuel', 'Shally', 'Veronica','kay']

Explanation:

The following are the description of the program.

In the above program, firstly we set two list data type variables 'male_names' and 'female_names' and initialize the male and female names in those variables. Then, we set three variables in which we store union, intersection, and symmetric differences and finally print these three variables in a sorted manner.

Write a program to solve a quadratic equation. The program should allow the user to enter the values for a, b, and c. If the discriminant is less than zero, a message should be displayed that the roots are imaginary; otherwise, the program should then proceed to calculate and display the two roots of the eqaution. (Note: Be certain to make use of the squareRoot () function that you developed in this chapter.) (In C language)

Hint: This should not be too hard. You need to get some numbers from the user, do some calculations, check if the discriminate is negative, then use the textbook author’s squareRoot function to finish up the calculations!

program 7.8:

// Function to calculate the absolute value of a number

#include

float absoluteValue(float x)

{

if (x < 0)

x = -x;

return (x);

}

// Function to compute the square root of a number

float squareRoot(float x)

{

const float espsilon = .00001;

float guess = 1.0;

while (absoluteValue(guess * guess - x) >= espsilon)

guess = (x / guess + guess) / 2.0;

return guess;

}

int main(void)

{

printf("squareRoot (2.0) = %f\n", squareRoot(2.0));

printf("squareRoot (144.0) = %f\n", squareRoot(144.0));

printf("SquareRoot (17.5) = %f\n", squareRoot(17.5));

return 0;

}

Answers

Answer:

int main(void) {    float a, b, c, discriminant, root1, root2;    printf("Enter value for a, b and c:");    scanf("%f %f %f", &a, &b, &c);    discriminant = b * b - 4 * a * c;    if(discriminant < 0){        printf("The roots are imaginary");    }else{        root1 = (-b + squareRoot(discriminant)) / (2*a);        root2 = (-b - squareRoot(discriminant)) / (2*a);        printf("Root 1: %f", root1);        printf("Root 2: %f", root2);    }    return 0; }

Explanation:

Firstly, we declare all the required variables (Line 3) and then get user input for a , b and c (Line 4-5).

Next, apply formula to calculate discriminant (Line 7).

We can then proceed to determine if discriminant smaller than 0 (Line 9). If so, display the message to show the roots are imaginary (Line 10).

If not, proceed to calculate the root 1 and root 2 (Line 12-13) and then display the roots (Line 15 -16)

Answer:

// Program to calculate the roots of a quadratic equation

// This program is written in C programming language

// Comments are used for explanatory purpose

// Program starts here

#include<stdio.h>

#include<math.h>

int main()

{

// For a quadratic equation, ax² + bx + c = 0, the roots are x1 and x2

// where d =(b² - 4ac) ≥ 0

// Variable declaration

float a,b,c,d,x1,x2;

// Accept inputs

printf("Enter a, b and c of quadratic equation: ");

scanf("%f%f%f",&a,&b,&c);

// Calculate d

d = (b*b) - (4*a*c);

// Check if d > 0 or not

if(d < 0){ // Imaginary roots exist

printf("The roots are imaginary");

}

else // Real roots exist

{

// Calculate x1 and x2

x1= ( -b + sqrt(d)) / (2* a);

x2 = ( -b - sqrt(d)) / (2* a);

// Print roots

printf("Roots of quadratic equation are: %.3f , %.3f",x1,x2);

}

return 0;

}

return 0;

}

Create a class named Billing that includes three overloaded computeBill() methods for a photo book store. When computeBill() receives a single parameter, it represents the price of one photo book ordered. Add 8% tax, and return the total due. When computeBill() receives two parameters, they represent the price of a photo book and the quantity ordered. Multiply the two values, add 8% tax, and return the total due. When computeBill() receives three parameters, they represent the price of a photo book, the quantity ordered, and a coupon value. Multiply the quantity and price, reduce the result by the coupon value, and then add 8% tax and return the total due. Write a main() method that tests all three overloaded methods. Save the application as Billing.java.

Answers

Answer:

Following are the program in the Java Programming Language.

//define class

public class Billing

{

//define method  

public static double computeBill(double Price)  

{

//declare variable and initialize the rate method

double taxes = 0.08*Price;

//print the output  

return Price+taxes;

}

//override the following function

public static double computeBill(double Price, int quant) {

//declare double type variable

double taxes = 0.08*(Price*quant);

//return the output

return (quant*Price)+taxes;

}

//override the function

public static double computeBill(double Price, int quant,double value) {

//declare double type variable

double taxes = 0.08*(Price*quant);

//return the output

return ((quant*Price)+taxes)-value;

}

//define main method

public static void main(String args[]) {

//call the following function with argument

System.out.println(computeBill(10));

System.out.println(computeBill(10, 2));

System.out.println(computeBill(10, 20, 50));

}

}

Output:

10.8

21.6

166.0

Explanation:

Following are the description of the program.

Define class 'Billing', inside the class we override the following function.Define function 'computeBill()', inside it we calculate tax.Then, override the following function 'computeBill()' and pass the double data type argument 'Price' and integer type 'quant' then, calculate tax.Again, override that function 'computeBill()' and pass the double type arguments 'Price', 'value' and integer type 'quant' then, calculate tax.Finally, define the main method and call the following functions with arguments.

The Billing class has three overloaded computeBill methods to calculate the total price of photo books with 8% tax. The methods vary by one, two, or three parameters for price, quantity, and coupon value respectively. The main method tests all three computeBill methods.

Let's create a Billing class with three overloaded computeBill() methods.

Here is the Java implementation:

public class Billing {
public double computeBill(double price) {
double tax = price * 0.08;
return price + tax;
}
public double computeBill(double price, int quantity) {
double total = price * quantity;
double tax = total * 0.08;
return total + tax;
}
public double computeBill(double price, int quantity, double coupon) {
double total = price * quantity;
total -= coupon;
double tax = total * 0.08;
return total + tax;
}
public static void main(String[] args) {
Billing bill = new Billing();
// Test first method
System.out.println("Total for one book: " + bill.computeBill(50.0));
// Test second method
System.out.println("Total for five books: " + bill.computeBill(50.0, 5));
// Test third method
System.out.println("Total for five books with coupon: " + bill.computeBill(50.0, 5, 20.0));
}
}

Suppose that one byte in a buffer covered by the Internet checksum algorithm needs to be decremented (e.g., a header hop count field). Give an algorithm to compute the revised checksum without rescanning the entire buffer. Your algorithm should consider whether the byte in question is low order or high order

Answers

Answer:

The algorithm required for the question is given below.

Explanation:

Step 1: The data is shown below for the algorithm.

Original checksum.Byte location is decrementable.Price to decrease by what bit.

Step 2: Get a checksum compliment from one.

Step 3: Whether byte is of lesser importance to still be decremented by x.

Subtract x from those bytes.

Step 4: Whether byte is of higher importance to still be decremented by x.

Subtract 2⁸×x from those bytes.

Step 5: Start taking one's outcome compliment to get amended iterator checksum.

Write a method called printGrid that accepts two integers representing a number of rows and columns and prints a grid of integers from 1 to (rows * columns) in column major order. For example, the call printGrid(4, 6); should produce the following output: 1 5 9 13 17 212 6 10 14 18 223 7 11 15 19 234 8 12 16 20 24

Answers

Answer:

See attached pictures.

Explanation:

See attached picture for code with explanation.

Write the routines with the following declarations: void permute( const string & str ); void permute( const string & str, int low, int high ); The first routine is a driver that calls the second and prints all the permutations of the characters in string str. If str is "abc", then the strings that are output are abc, acb, bac, bca, cab, and cba. Use recursion for the second routine.

Answers

Answer:

Here is the first routine:

void permute( const string &str ) {  // function with one parameter

 int low = 0;

 int high = str.length();

 permute(str, low, high);

}    

Or you can directly call it as:

 permute(str, 0, str.length());

Explanation:

The second routine:

void permute( const string &str, int low, int high)  

//function with three parameters

{ string str1 = str;

 if ( low == high ) {  //base case when last index is reached

   for (int i = 0; i <= high; ++i)

     cout << str1[i]; }  //print the strings  

 else {

   for (int i=low; i<high; ++i) {  // if base case is not reached

     string temp = str1;   //fix a character

     swap( str1[i], str1[low] ); //swap the values

     permute( str1, low + 1, high );  //calling recursive function (recursion case)

     swap( str1[i], str1[low] );     }  } } //swap again to go to previous position

In this function the following steps are implemented:

A character is fixed in the first position.

Rest of the characters are swapped with first character.

Now call the function which recursively repeats this for the rest of the characters.

Swap again to go to previous position, call the recursive function again and continue this process to get all permutations and stop when base condition is reached i.e. last index is reached such that high==low which means both the high and low indices are equal.

You can write a main() function to execute these functions.

int main() {

 string str;

 cout << "Enter a string: ";

 cin >> str;

 permute(str);  }

Final answer:

The question requires defining two routines to output all permutations of a given string. The first function 'permute' serves as a driver, while the second 'permute' function is a recursive method that systematically swaps characters to produce each permutation.

Explanation:

Routines to Permute a String:

The task is to write routines to generate all permutations of the characters in a given string. The first function serves as a driver, while the second function uses recursion to perform the actual permutation process.

void permute(const string &str) {
   permute(str, 0, str.size() - 1);
}
void permute(const string &str, int low, int high) {
   if (low == high) {
       cout << str << endl;
   } else {
       for (int i = low; i <= high; i++) {
           // Swap the current index with the low element
           swap(str[low], str[i]);
           // Recursively call permute on the substring
           permute(str, low + 1, high);
           // Swap back for the next iteration
           swap(str[low], str[i]);
       }
   }
}
In the above code, permute(const string &str) is the driver function that calls the recursive function permute(const string &str, int low, int high), initiating the process with the full range of the string (from index 0 to the length of the string minus one).

Within the recursive function, when the low index matches the high index, it indicates that a permutation has been generated, and it gets printed. If not, the function enters a for-loop, where recursive calls are made after swapping the current character with the one at the start of the substring defined by low and high. After the recursive call returns, the characters are swapped back to their original position, allowing for correct generation of subsequent permutations.

Describe a defense in depth strategy from an Information Systems Manager perspective; for a medium size organization with 3 campuses. There is one main campus and two satellite campuses. Campuses need communications amongst all campuses and remote workers need access to company data and email. Explain the following in your defense in depth strategy with the following concepts:
a.Confidentiality,
b.Integrity,
c.Availability,
d.Information Security,
e.Risk management,
e.Vulnerability management

Answers

Answer:

Explanation:

Confidentiality: This involves the protection of the information from being accessed by unauthorized persons within or outside of the organization as an attempt by an outsider to access it could lead to a breach which may not be easily remedied.

Integrity: This is concerned with ensuring that the information provided to the users are from a reliable source and that the information is not being altered en-route.

Availability: This means that the information is readily accessible to the authorized users. Any attempt for the unavailability of service or information could have been a denial of service (DNS) from an attacker (black hat).

Risk management: This is the understanding of the security threats and their interaction at an individual, organizational or community level. This involves assessment of possible threats as well as vulnerability.

Vulnerability Management: This is a measure taken in reducing the flaws in codes or networks. This is one of the most easily figured out concept from the five above as there are vulnerability scanners for open ports, insecure software configurations as well as susceptibility to malware  infections.

In order to paint a wall that has a number of windows, we want to know its area. Each window has a size of 2 ft by 3 ft. Write a program that reads the width and height of the wall and the number of windows,.

Answers

Answer:

6ft

Explanation:

Step 1:

import java.util.Scanner;

class AreaOfRectangle {

public static void main (String[] args)

{

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the length of Rectangle:");

double length = scanner.nextDouble();

System.out.println("Enter the width of Rectangle:");

double width = scanner.nextDouble();

//Area = length*width;

double area = length*width;

System.out.println("Area of Rectangle is:"+area);

}

}

Output

Enter the length of Rectangle:

2

Enter the width of Rectangle:

3

Area of Rectangle is:6.0

For loops: Savings account The for loop calculates the amount of money in a savings account after numberYears given an initial balace of savingsBalance and an annual interest rate of 2.5%. Complete the for loop to iterate from 1 to numberYears (inclusive). Function Save Reset MATLAB DocumentationOpens in new tab function savingsBalance = CalculateBalance(numberYears, savingsBalance) % numberYears: Number of years that interest is applied to savings % savingsBalance: Initial savings in dollars interestRate = 0.025; % 2.5 percent annual interest rate % Complete the for loop to iterate from 1 to numberYears (inclusive) for ( ) savingsBalance = savingsBalance + (savingsBalance * interestRate); end end 1 2 3 4 5 6 7 8 9 10 11 12 Code to call your function

Answers

Answer:

Desired MATLAB code is explained below

Explanation:

function savingsBalance = CalculateBalance(numberYears, savingsBalance)

% numberYears: Number of years that interest is applied to savings

% savingsBalance: Initial savings in dollars

interestRate = 0.025; % 2.5 percent annual interest rate

 

% Complete the for loop to iterate from 1 to numberYears (inclusive)

for (i = 1 : numberYears)

savingsBalance = savingsBalance + (savingsBalance * interestRate);

end

end

The completed for loop in MATLAB iterates from 1 to `numberYears`, updating the `savingsBalance` by adding 2.5% interest each year:

```matlab

for year = 1:numberYears

   savingsBalance = savingsBalance + (savingsBalance * interestRate);

end

```

To complete the `for` loop in the given MATLAB function to calculate the amount of money in a savings account after a specified number of years, you need to iterate from 1 to `numberYears` (inclusive). Here’s the completed function:

```matlab

function savingsBalance = CalculateBalance(numberYears, savingsBalance)

   % numberYears: Number of years that interest is applied to savings

   % savingsBalance: Initial savings in dollars

   interestRate = 0.025; % 2.5 percent annual interest rate

   % Complete the for loop to iterate from 1 to numberYears (inclusive)

   for year = 1:numberYears

       savingsBalance = savingsBalance + (savingsBalance * interestRate);

   end

end

```

In this function:

- The `for` loop iterates from 1 to `numberYears`.

- During each iteration, the `savingsBalance` is updated by adding the interest earned for that year, which is `savingsBalance * interestRate`.

1. Function Purpose: The function `CalculateBalance` takes two input arguments: `numberYears` (the number of years that interest is applied to savings) and `savingsBalance` (the initial savings amount in dollars). Its purpose is to calculate the total savings balance after applying interest over the specified number of years.

2. Interest Rate: The variable `interestRate` is defined within the function to represent the annual interest rate, which is set to 2.5%. This value is expressed as a decimal (0.025) for mathematical calculations.

3. For Loop: The heart of the function lies in the `for` loop, which iterates from 1 to `numberYears` (inclusive). This loop represents each year over which interest is applied to the savings balance.

4. Interest Calculation: Within the loop, the savings balance (`savingsBalance`) is updated in each iteration to reflect the accumulated interest. The formula `savingsBalance = savingsBalance + (savingsBalance * interestRate)` calculates the interest earned for the current year (2.5% of the current balance) and adds it to the existing balance. This process repeats for each year specified by `numberYears`, effectively simulating the accumulation of interest over time.

5. Return Value: Finally, the function returns the updated `savingsBalance` after all iterations of the `for` loop have been completed. This value represents the total savings balance after applying interest for the specified number of years.

Overall, the function provides a straightforward and efficient way to compute the savings balance over time, making it a useful tool for financial calculations.

What is the shortest sequence of MIPS instructions that extracts a field for the constant values of bits 7-21 (inclusive) from register $t0 and places it in the lower order portion of register $t3 (zero filled otherwise)?

Answers

Answer:

What is the shortest sequence of MIPS instructions that extracts a field for the constant values of bits 7-21 (inclusive) from register $t0 and places it in the lower order portion of register $t3 (zero filled otherwise)? - sll$t0, $t3, 9# shift $t3 left by 9, store in $t0

srl $t0, $t0, 15# shift $t0 right by 15

Explanation:

The shortest sequence of MIPS instructions that extracts a field for the constant values of bits 7-21 (inclusive) from register $t0 and places it in the lower order portion of register $t3 (zero filled otherwise) is shown below:

sll$t0, $t3, 9# shift $t3 left by 9, store in $t0

srl $t0, $t0, 15# shift $t0 right by 15

Project Description The Department plans to purchase a humanoid robot. The Chairman would like us to write a program to show a greeting script the robot can use later. Our first task is to use the following script to prototype the robot for presentation: (Robot) Computer: Hello, welcome to Montgomery College! My name is Nao. May I have your name? (Visitor) Human: Taylor (Robot) Computer: Nice to have you with us today, Taylor! Let me impress you with a small game. Give me the age of an important person or a pet to you. Please give me only a number! (Visitor) Human: 2 (Robot) Computer: You have entered 2. If this is for a person, the age can be expressed as 2 years or 24 months or about 720 days or about 17280 hours or about 1036800 minutes or about 62208000 seconds. If this is for a dog, it is 14 years old in human age If this is for a gold fish, it is 10 years old in human age (Robot) Computer: Let's play another game, Taylor. Give me a whole number (Visitor) Human: 4 (Robot) Computer: Very well. Give me another whole number (Visitor) Human: 5 (Robot) Computer: Using the operator +'in C++, the result of 4 + 5 is 9. Using the operator , the result of 4/5 is 0; however, the result of 4.0/5.0 is about 0.8 (Robot) Computer: Do you like the games, Taylor? If you do, you can learn more by taking our classes. If you don't, I am sad. You should talk to our Chairman! Write a program that uses the script above as a guide without roles, i.e. robot computer and visitor human, to prototype robot greeting in C++

Answers

Answer:

C++ code is explained below

Explanation:

#include <iostream>

#include <iomanip>

using namespace std;

int main()

{

// Variables to store inputs

string robot_name = "Nao";

string visitor_name;

int age, first_num, second_num;

// Constant variable initialisation for programmer name

const string programmer_name = "XXXXXXXX";

// Constant variable initialisation for assignment number

const string assignment_num = "123546";

// Constant variable initialisation for due date

const string due_date = "16 August, 2019";

// Displaying robot's name as script

cout << "Hello, welcome to Montgornery College!";

cout << "My name is " << robot_name << " . May I have your name?" << "\n\n";

// Taking visitor's name as input from the visitor

cin >> visitor_name;

// Displaying vistor's name as script

cout << "\n\nNice to have your with us today, " << visitor_name << "! ";

cout << "Let me impress you with a small game.";

cout << "Give me the age of an important person or a pet to you. ";

cout << "Please give me only a number!" << "\n\n";

// Taking human age as input from the visitor

cin >> age;

// Displaying human's age as script

cout << "\n\nYou have entered " << age << ". If this is for a person,";

cout << " the age can be expressed as " << age << " years or ";

// Computing months, days, hours, minutes and seconds from age input

double months = age*12;

double days = months*30;

double hours = days*24;

double minutes = hours*60;

double seconds = minutes*60;

// Computing dogs and fish age from human's age

double dogs_age = 7*age;

double gold_fish_age = 5*age;

// Displaying months, hours, minutes, hours and seconds as script

cout << months << " months or about " << days << " days or";

cout << " about " << fixed << setprecision(0) << hours << " hours or about " << minutes;

cout << " or about " << fixed << setprecision(0) << seconds << " seconds. If this is for a dog.";

// Displaying dogs age and gold fish age as script

cout << " it is " << dogs_age << " years old in human age.";

cout << " If this is for a gold fish, it is " << gold_fish_age;

cout << " years old in human age" << "\n\n";

cout << "Let's play another game, " << visitor_name << "!";

cout << "Give me a whole number." << "\n\n";

// Taking first whole number from the visitor

cin >> first_num;

cout << "\nVery well. Give me another whole number." << "\n\n";

// Taking second whole number from the vistor

cin >> second_num;

// Computing sum and division for displaying in the script

double sum = first_num+second_num;

double division = first_num/second_num;

float floatDivision = (float)first_num/second_num;

// Displaying sum and division script

cout << "\nUsing the operator '+' in C++,";

cout << " the result of " << first_num << " + " << second_num;

cout << " is " << sum << ". Using the operator '/', the result ";

cout << "of " << first_num << " / " << second_num << " is " << division;

cout << "; however, the result of " << first_num << ".0 /" << second_num;

cout << ".0 is about " << floatDivision << "." << "\n\n";

cout << "Do you like the games, " << visitor_name << "?";

cout << " If you do, you can learn more by taking our classes.";

cout << ". If you don't, I am sad, You should talk to our Chairman!" << "\n\n";

// Displaying Programmer Name, Assignment Number and due date to output screen

cout << "Programmer Name : " << programmer_name << endl;

cout << "Assignment Number : " << assignment_num << endl;

cout << "Due Date : " << due_date << endl;

 

return 0;

}

Suppose a process in Host C has a UDP socket with port number 6789. Suppose both Host A and Host B each send a UDP segment to Host C with destination port number 6789. Will both of these segments be directed to the same socket at Host C

Answers

Answer:

Yes, both of these segments (A and B) will be directed to the same socket at Host C .

Explanation:

Suppose both Host A and Host B each send a UDP segment to Host C with destination port number 6789, surely , both of these segments will be directed to the same socket at Host C .

Reason being that,  the operating system will provide the process with the IP details to distinguish between the individual segments arriving at host C- for each of the segments (A and B) recieved at Host C.

Using either a UNIX or a Linux system, write a C program that forks a child process that ultimately becomes a zombie process. This zombie process must remain in the system for at least 10 seconds.

Answers

Answer:

#include <stdlib.h>

#include <sys/types.h>

#include <unistd.h>

int main()

{

// Using fork() creates child process which is  identical to parent

int pid = fork();

 // Creating the Parent process

if (pid > 0)

 sleep(10);

// And then the Child process

else

{

 exit(0);

}

 

return 0;

}

Explanation:

Using a Text editor enter the code in the Answer section and save it as zombie.c. The created process will be able to run for 10 seconds.

Now open the Terminal and type $ cc zombie.c -o zombie to compile the program which is then saved as an executable file.

With a GNU compiler run the following command ./zombie which will give you an output of the parent process and child process to be used testing.

First identify the formula to compute the sales in units at various levels of operating income using the contribution margin approach. ​(Abbreviations used: Avg.​ = average, and CM​ = contribution​ margin.) ( + ) / = Breakeven sales in units

Answers

Answer:

10 stand scooters and 15 chrome scooters

Explanation:

Data:

The margin approach:

(Fixed expenses + Operating income)/ Weighted average CM per unit = Break even sales in units.

Tallying from the tables, the types and quantities that need to be sold will be like this:

Standard scooters  = 10

Chrome scooters    = 15

Which date formats are allowed in Excel for February 14, 2018? Check all that apply.
14-Feb-18
14-Feb
February 14, 2018
2/014/2018
02/14/18
2/14/2018​

Answers

Answer:

1,2,5 and 6

Explanation:

Hope this helps!!!!!!!

Forever friend and helper,

Cammie:)

The date formats which are allowed in Microsoft Excel for February 14, 2018 are:

A. 14-Feb-18.

B. 14-Feb.

E. 02/14/18.

F. 2/14/2018​.

Microsoft Excel can be defined as a software application (program) designed and developed by Microsoft Inc., to avail end users the ability to analyze and visualize spreadsheet documents.

Formatting is simply the appearance of textual information and data in a document such as an Excel spreadsheet.

In Microsoft Excel, an end user can set the display format for the following:

Number.Currency.Percentage.Date.

A date provides information about the day, month and year a document was created, last modified, used, etc.

In Microsoft Excel, the date formats which are allowed for February 14, 2018 are:

14-Feb-18. 14-Feb.02/14/18. 2/14/2018​.

Read more: https://brainly.com/question/23822910

Other Questions
hi anyone able to explain Why does the temperature of a substance remain the same when it is boiling using kinetic particles theory ? Thank you! Syd has $125 in her bank account. She makes a withdrawal of $75. How much does she have now. Solve the quadratic equation: 3x2 + x - 5 = 0 A 12-month insurance policy was purchased on Dec. 1 for $3,600 and the Prepaid insurance account was increased for the payment. 14- Demonstrate the required adjusting journal entry on Dec. 31 by selecting from the choices below Click the answer you think is right. a.Prepaid insurance would be credited for $3,600. b.Cash would be credited for $3,600. c.Insurance expense would be debited for $300. d.Insurance expense would be debited for $3,600. Every Friday, Dr. Cruz would give a quiz in his psychology class. Students quickly learned to be nervous on Friday mornings, just before each quiz. Halfway through the semester, Dr. Cruz stopped giving quizzes on Fridays and the students' anxiety began to diminish with each passing week in which there was no quiz. The decrease in the students' anxiety may be attributed to the process of:____________.A) spontaneous recovery.B) extinction.C) stimulus generalization.D) latent learning. The seventeenth amendment to the constitution was a key progressive reform designed to The parent of a young client with severe hearing loss is quite concerned about the childs future independence because of impaired hearing. Which type of hearing loss is usually irreversible? what are some ways that the french revolution was good Jeff and Rob have a difficult time getting along at work. Most days, Jeff spends a lot of time cracking jokes and goofing off, while Rob constantly nags him and tells him to act like a grown up. On days when Jeff is more reserved, Rob does not nag him, hoping that this will result in improved behavior down the road. This is an example of which form of behavior modification?A. Empowerment.B. Extinction.C. Punishment.D. Avoidance learning.E. Positive reinforcement. On the tariff issue, ________ supported high protective tariffs; on the money question, ________ sought the inflationary consequences of printing greenbacks. Suppose that the warranty cost of defective widgets is such that their proportion should not exceed 5% for the production to be profitable. Being very cautious, you set a goal of having 0.05 as the upper limit of a 90% confidence interval, when repeating the previous experiment. What should the maximum number of defective widgets be, out of 1024, for this goal to be reached. Positivism had an effect on rational choice thought that permeated the opinions of early criminologists, in that it changed the focus of crime from personal choice and decision making to _____________ and __________. Sharon, the human resources director for Tempo Corporation, attempts to comply with the law in dealing withapplicants and employees. One of the challenges Sharon faces is that the legality of an action isa.always clear.b.never clear.c.sometimes clear.d.usually cleard Under Calculate the ratio of the drag force on a jet flying at 1190 km/h at an altitude of 7.5 km to the drag force on a prop-driven transport flying at half that speed and altitude. The density of air is 0.53 kg/m3 at 7.5 km and 0.74 kg/m3 at 3.8 km. Assume that the airplanes have the same effective cross-sectional area and drag coefficient C. Which of these had the biggest economic impact on the united states in the 1960s?a.the communist revolution in cubab.the system of apartheid in south africac.the boycott of american goods in the ussrd.the oil embargo with countries in the middle east? Please help!!!!! I will give brainliest to you!Ever since she was little people so amelia she wouldn't become a doctor starting in ninth grade she decided to prove them wrong. She made Straight-A's all through high school and college. The students around her partied and formed relationships, but amelia barely paid attention. She didn't have time for that kind of nonsense. She would become a doctor and start a career with the bang. Which ending to the story most clearly serves as an anti-climax? A. Suddenly, just as she was about to graduate from medical school, the world ended. B. But then a rival showed up: someone just as studious as her and twice as aggressive. C. However, try as she might, she just couldn't study hard enough to pass the many exams. D. Amelia had to call in a few favors, but ultimately, she was able to become a doctor What region is MOST impacted by desertification? Kalahari Gobi Rainforests Sahel i have an answer just not sure if it :) Korea is a good example of a(n)a.sovereign stateb.nation-state existing in a unified condition.c.ethnicity divided between more than one state.d.colony divided between more than one ethnicity.e.patron-state Which of the following closings is most effective? a.Bring your lunch and join the group! Because the room is limited to 30, please make your reservation with me before March 12. b.Wed love to have you join the Lunch and Learn presentation. Just bring your lunch and participate in the fun! c.We look forward to seeing you at the next Lunch and Learn presentation. This is your opportunity to learn how to eat smart despite the temptation of high-calorie snacks. Chelsea collects sand dollars.The number she has collected is greater than 400 and less than 460.The number in hundreds place is one less than the number in the tens place.The number in the ones place is two more than the number in the tens place.How many sand dollars has Chelsea collected?