CSE 1322 - Programming Problem Solving II

¡Supera tus tareas y exámenes ahora con Quizwiz!

Recursion represents a powerful programming technique in which a method makes a call to itself from within its own method body.

True

Inheritance through an extended / derived class supports code reuse.

True (Inheritance PP pg. 9)

The "new" operator

•Right now, we have two "dead" dogs •new -Brings instances "to life" -Calls the class's constructor -Opens up enough space in memory to fit an instance of that class

For the following program, trace the code and show how the final value is derived (i.e. the values of the parameters and/or local variables in each instance of the recursive call): public class TestRec2{ public static void main(String []args) { int number = 10; PRINT( pblmOne(number)); } public static int pblmOne(int myNum){ if (myNum < 2) return 3; else return 2 + pblmOne(myNum-2); } }

13

Consider the situation where no other data structure like arrays, linked list is available to you. Then how many stacks are needed to implement a queue.

2

A thread is an incomplete program

False

On a multiprocessor machine, a thread could be processed in multiple processors.

False

Parallel programming is a process of running multiple tasks on a single processor.

False

The LinkedLIst<T> class is a dynamic implementation of a doubly-linked list. Its elements contain a certain value and only one pointer which points to the next element.

False

Threading is a quick way to "split" a program into multiple dependent parts.

False

Using recursion for a linear sequence such as Factorial is efficient.

False

A class inherits only the methods from its super classes.

False (PP Part I - Inheritance pg. 42)

The unique feature of an abstract class is that a subclass that extends it also needs to have the abstract reserved word in its declaration.

False (PP Part III - Abstract pg. 5)

Recursion can occur whenever a method calls any other method

False *Method calling itself

Two of the basic operations of a queue are Push and Dequeue.

False Two of the basic operations of a queue is Enqueue and Dequeue

An infinite recursion will never happen as long as there is a valid base case.

False jjj. pg. 554 If the method does not make progress toward its bound in this way, the result will be an infinite recursion. •Requirements •Must have the recursive call •Must have a terminating condition •Must make progress towards terminating

Child C is able to inherit from two different Parents A and B in Java and C#.

False (Inheritance PP pg. 24)

Which of the following is not a valid state of Thread Life Cycle?

New State

When a set of methods have the same name but different types/number of parameters in the same class, they are called:

Overloaded methods

Since toString () is a method that is in the Object class, any call to the toString () method refers to the toString ( ) method in the Object class unless specifically overridden in the child class

True

Stacks and queues are typically implemented internally as an array or a linked list.

True

Streams are opened before we can begin working with them and are closed after they have served their purpose. Closing the stream is very important and must not be left out, because you risk losing data, damaging the file, to which the stream is opened

True

The base case (bottom of recursion) is also known as the stopping state.

True

The code within the finally block is always executed, no matter how the program flow leaves the try block. This guarantees that the finally block will be executed even if an exception is thrown or a return statement is executed within the try block.

True

The main() method always has a thread that can create additional threads

True

The stack provides 3 major operations: push (add an element at the top of the stack), pop (take the last added element from the top of the stack) and peek (get the element from the top of the stack without removing it).

True

The stack trace contains detailed information about the exception including where exactly it occurred in the program. The stack trace is very useful for programmers when they try to understand the problem causing the exception.

True

The try-catch construct consists of one try block and one or more catch blocks. The try block contains the code that could throw exceptions.

True

Use of an ArrayList is preferred when we have to add / remove elements dynamically.

True

The goal of object-oriented programming is to encapsulate all attributes and methods a real-life object needs to perform its duties.

True (jjj. pg. 134 "To reiterate a point made at the outset, object-oriented programming is a process of constructing objects that will interact with each other. Object oriented programs must ensure that the objects themselves are well designed in terms of their ability to carry out their designated functions. Good design in this sense requires careful selection of instance variables and careful design of methods to ensure that the object can carry out its assigned tasks."

The "queue" data structure is created to model queues, for example a queue of waiting for printing documents. Such queues are very convenient and are naturally modeled via the structure "queue". In queues we can add elements only on the back and retrieve elements only at the front.

True Yes. We can add the element into queue at front and remove the element from queue at back.

A recursive method must have a valid base case to exit, otherwise the method execution will keep repeating.

True •Requirements •Must have the recursive call •Must have a terminating condition •Must make progress towards terminating

toString( )(Java) or ToString() (C#) is a method that is in the Object class that is inherited by all Java / C# classes.

True (Inheritance PP pg. 17 / jjj pg. 377 "This is a method that is defined in the Object class and inherited by all Java objects.")

Which one of the following is an application of Queue Data Structure?

When data is transferred asynchronously (data not necessarily received at same rate as sent) between two processes When a resource is shared among multiple consumers Load Balancing **All of the above

Abstract methods are used in defining

classes that need no methods implemented (jjj pg. 171 "An abstract method is one that consists entirely of its signature; it lacks an implementation—that is, it does not have a method body.")

The following declaration of a StreamReader requires the file to be stored in which location. StreamReader reader = new StreamReader("test.txt");

in the same location of the program

Consider the following fxyz() method: fxyz(1) = 1 fxyz(N) = fxyz( (N + 1)/2 ) + fxyz(N / 2), for N >1 Which of the following Java methods correctly implements it?

int fxyz( int N ) { if ( N==1 ) { return 1; } else { return fxyz( (N+1)/2 ) + fxyz( N/2 ) ; } }

Consider the following code: public class A { private int x; private int y; public A (int a, int b) { x = a; y = b; } public String toString( ) { return x + " " + y; } } Consider that B is a class that extends A. B contains a third int instance variable, z. Class B should display x, y, and z with spaces in between. Which of the following would best override the toString ( ) or ToString() method for B?

public String toString( ) { return super.toString( ) + " " + z; }

Stack is a restrictive data type in a sense that we cannot

remove from the bottom

The reserved word super (java) or base (C#). <method name> is used call the method which is defined in

the parent class

Sloppy Definitions

• public: anyone (or anything) can see it from anywhere! That is, anything outside the class. • private: can only be seen/called inside the class. • Note, variables, methods and even classes can be marked either public or private

Static methods

•A method marked static: -Can call these methods like normal, BUT... -...don't have to create an instance to use the method! -Can't access non-static attributes -Is called using <Class Name>.<Method Name>

Defining the class

•Constructor: -same name as class -public visibility -default and overloaded •Class instance variables -Should normally be private •Methods: -public, private or protected -return or not •Properties (C#) -get -set

Designing the Constructor

•Constructors will vary, depending on design •Ask questions: -Are all Dogs born with the same rabid state? (yes - they are all born non-rabid) -Are all Dogs born with the same weight? (no - they are born with different weights) -Are all Dogs born with the same name? (no - they all have different names) •If ever "no", then you need information passed in as parameters.

Default Constructors

•In many languages, there's a default constructor • If you don't create one, it's created for you AND • IT'S INVISIBLE! AND • It takes no parameters AND • It sets variables/attributes: -To zero (0) for numbers -To FALSE for booleans -To NULL (empty) for objects like strings

The static keyword

•Only attributes and methods can be marked static •Static attributes: -Previously, each instance/object had it's own independent set of variables -With static all instances share one variable -Good for counting the number of instances

Array processing

•The simplest processes involve searching ( finding a value, finding the largest or smallest ),or finding a sum, product or average. •Remember to initialize properly. •Note the pattern in the next examples: we use a loop! *remember to use "new" to allocate memory for your object.

The Constructor

•This is a special method -Used to give initial values to ALL attributes -Is activated when someone creates a new instance of the class •Doesn't have a return type •In most languages, the name of this method MUST be the same name as the class

The "Driver"

•Usually put this in a whole new file! •The Driver contains main •It's the controlling algorithm •Steps: -Type in the skeleton -Create a couple of instances of classes -Start telling them what to do

General Rules

•Variables/attributes are normally marked private -public variables can be tampered with and abused! •Methods are most often marked public -However, some methods should be marked as private

A common point of confusion

•We see a lot of keywords like this and self •What is that? •A reference to something inside the class we're coding in •Commonly used to resolve ambiguity of variables:

Common data types

•byte, short, int, long, double, float, char, •C#: bool, string / String •Java: boolean, String

Arrays

•can't use until memory is allocated with new. •In C#, the [] must be between the data type and the object reference while in java the [] can be between the or after the name.

class Dog { }

•created a new (complex) data type! • created the "concept" of a Dog We don't have any Dogs yet, just the concept

A class:

•has attributes (which are just variables) • has a constructor which is used to initialize attributes • has other methods (like eat and growl) • is a blueprint (template) for creating objects • creates a new data type

An object:

•is an instance of a class • has a state (variables) that is independent from others

The "." operator

"Dot" operator used to -Get to an instances attributes -Get to an instances methods -Basically get inside the instance Format: <instance>.<attribute or method>

Which of the following points is/are true about Array List data structure when it is compared with array?

**(Wrong answer) Array List has better cache locality that can make them better in terms of performance

In a singly-linked list the elements keep information about their next element.

True

Pressing a GUI button normally causes an event to occur.

True

Object-Oriented Programming (OOP) is based...

...on the concept of classes, from which objects are created. Remember: •Classes are "templates" •Objects are instances of those templates

Suppose, there is a 5-element queue Q (from front to back: 1, 2, 3, 4, 5, 6), and an empty stack S. If you remove the elements one-by-one from the queue Q and insert them into the stack S, then remove them one-by-one from the stack S and re-insert them into the queue Q. Then, finally how the queue will looks like (from back to front)?

1, 2, 3, 4, 5, 6 **NOT** 6, 5, 4, 3, 2, 1

Consider the following definition of myFunc(): myFunc(0,N) = N myFunc(P,Q) = myFunc(P-1, Q+1) According to the above definition, what is myFunc(2,4)?

6 Given, myFunc(P, Q) = myFunc(P-1, Q+1). This should be continued until the first argument becomes 0. So, myFunc(2, 4) = myFunc(1, 5) = myFunc(0, 6) Now, myFunc(0, N) = N. So, the Final answer comes out to be 6. So the first option is correct. I hope it helps. For any doubt, feel free to ask in comments, and give upvote if u get the answer.

Consider a definition of fxyz(): fxyz(1) = 1 fxyz(n) = fxyz( (n + 1)/2 ) + fxyz(n / 2), for n >1 According to this definition, what is fxyz(8)?

8

For the following program, trace the code and show how the final value is derived (i.e. the values of the parameters and/or local variables in each instance of the recursive call): Here, a and b are parameters for the recursive function pblm2(). Which of the following answer choices, given below, for num1 and num2 respectively, allows this recursive function to terminate.

? 1, 2 ?

Objects

An object: • is an entity in the real world that can be distinctly identified • might represent a particular dog, employee, student, etc. • has a unique identity, state, and behavior. •

Animal is a parent class that has a method sound() which returns "eek". And the following child classes have methods that do as given below: Sheep has a method sound() that returns "Baa" Horse doesn't have a method sound() Cow has a method sound() that returns "Maa" Duck doesn't have a method sound() Dog has a method sound() that returns "Bow-wow" Java: System.out.print(mySheep.sound() + "\t"); System.out.print(myHorse.sound() + "\t"); System.out.print(myCow.sound() + "\t"); System.out.print(myDuck.sound() + "\t"); System.out.print(myDog.sound()); C#: Console.Write(mySheep.sound() + "\t"); Console.Write(myHorse.sound() + "\t"); Console.Write(myCow.sound() + "\t"); Console.Write(myDuck.sound() + "\t"); Console.Write(myDog.sound()); What is the output from the above code, assuming all the objects have been created?

Baa eek Maa eek Bow-wow As the parent class has already a sound() function the child classes Sheep ,Cow, Dog has overridden the sound() function. Soz when the sound function is called in the classes like Duck and Horse the sound function from the parent class is executed, hence "eek" is printed.

Override of the ToString method

C#: public override string ToString( ) { } Java: @Override public string toString() { }

Consider the following code for class XYZ public class XYZ { private int myNum; public XYZ (int n1) { myNum = n1; } // getter, setter and modifier methods go here } Which of the following statements is TRUE about class XYZ

Correct: Class XYZ inherits from the Object class A subclass cannot inherit from class XYZ (Inheritance PP pg. 37-38)

A method override occurs when two methods in the same class have the exact same method signature.

Correct: False True (Inheritance PP pg. 17

A UML diagram is used to ...

Depict objects and object oriented concepts (jjj pg. 11 "Throughout this text, we will use the notation shown in Figure 5 to depict objects and to illustrate object-oriented concepts. The notation is known as the Unified Modeling Language, or UML for short, and it is a standard in the object-oriented programming community")

What does the following recursive function do for a given Linked List with first node as head? void myFunc(Node head) { if(head == NULL) return; myFunc(head.next); print(head.data + " "); }

Displays all nodes of linked list in reverse order

Which of the following statements is NOT true for a thread?

Every runnable process contains at least two threads

A process contains only one path of execution called a thread

False

A stack is a data structure where we add elements on the top and remove the element, which has been added first.

False

In general, a singly-linked list allows:

Insertions and removals anywhere

Which of the following sorting algorithms can be used to sort a random linked list with minimum time complexity?

Merge Sort

Which of the following is NOT true for Moore's Law?

Moore's Law predicted the doubling of transistor capacity per square inch of integrated circuit every year.

In a doubly-linked lists each element contains its value and two pointers - to the previous and to the next element.

True

In a multithreaded program many threads run concurrently within a single program/process.

True

A class can inherit multiple interfaces

True

A method should only handle exceptions which it expects and which it knows how to process. All the other exceptions must be left to the calling method.

True

A stream is an ordered sequence of bytes, which is send from one application or input device to another application or output device.

True

In GUI coordinate system, which of the following positions refers to the coordinates (0,0)?

The top left corner of the GUI box

Always close the streams and files you work with! Leaving an open stream or file leads to loss of resources and can block the work of other users or processes in your system.

True

An exception is a notification that something interrupts the normal program execution. Exceptions provide a programming paradigm for detecting and reacting to unexpected events.

True

C#'s ReadLine, Write and WriteLine and Java's nextLine, print and println work the same with stream readers/writers as they do with console.

True

Frequently inserting and removing items from a collection (especially a large number of items), can lead to low performance. In such cases it is advisable to use linked lists.

True

If a recursive method has no base case, i.e. bottom, or if the base case is never reached, it will become infinite and the result will be StackOverflowException.

True

Traversing an array

Use a for, while or do-while starting at index 0 and going to the last element C#: Use a for, while or do-while starting at index 0 and going thru .Length-1 Java: Use a for, while or do-while starting at index 0 and going thru .length-1

How would you access elements of an aggregated object (such as a collection) sequentially without exposing the underlying structure of the object?

Using an iterator The main intent of an iterator is to access the elements of an aggregate object sequentially without exposing its underlying representation.

Classes

Using classes, we're actually creating new data types! A class represents the concept of things in the real world, like Dogs. Classes follow a template, and have: • a name • variables (often called "attributes") • functions (which are now called "methods", "behaviors" or "member functions")

Suppose, there is a recursive Java/C# method, foo() . Then is it always possible to write an iterative efficient non-recursive version of the method foo() ?

Yes, always possible

Suppose, there is an iterative Java/C# method, foo() . Then is it always possible to write a recursive version of the method foo() ?

Yes, always possible

In the worst case, what is the number of comparisons needed to search a singly-linked list of length n for a given element?

n

Constructor Chaining

• It's possible for one constructor to leverages/calls another • You can do this as many times as you want

Accessors/Modifiers

• Main idea: create methods to access and change attributes • Also called "getters" and "setters" • Why is this cool? Can put in protections to prevent bad data

Implementation

• Overloading the constructor involves using the same method/function name - Vary the number of parameters; AND/OR - Vary the type of parameters

Multiple Constructors (a.k.a. overloading)

• We can have more than one constructor • Remember, constructors are used to initialize our objects • We can use parameters with the constructor to customize the initialization • Sometimes we have more or less data to use in the customization • We'd like to be able to pass in only what we know

Method Returns

•The return type of a method indicates the type of value that the method sends back to the calling location. •The return statement halts execution within the method and (optionally) returns a value •A method that does not return a value has a void return type •A return statement specifies the value that will be returned return expression; •Its expression must conform to the return type


Conjuntos de estudio relacionados

Chapter 38: Assessment of Digestive and Gastrointestinal Function - ML3

View Set

Chapter 4 and 5 Medical Terminology

View Set

Popular Music (MUH3025) Module 8 Quiz

View Set

911 Driving School Test review #1

View Set

Pediatric Nursing - Cardiac Disorders

View Set

[TieuGia] PSM I Course_Question Bank_v1.0

View Set