CS 1335 Midterm

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Is a function's parameter an example of a local or global variable?

A function's parameter is created and value bound when at the start of the function's execution. The parameter lives until the function finishes its execution. So a function's parameter is very similar to a local variable.

Describe the meaning of, and relationship between a function's parameters and arguments.

A function's parameters are the variables provided in the function's declaration that describe the values and types that are passed into the function's activation (call). In the following example, para1 & para2 are parameters of the function sum(). A function's arguments are the values (usually variables containing the value) passed to a parameters when the function is called. In the following example, the variable arg1 & arg2 are the arguments to the function call to sum(). The second call to sum() uses constant values as arguments. Note that the number of, and types of the arguments must match the parameters in the function's declaration.

True AND False evaluate to?

False

T|F The frameRate(N) function causes the Processing runtime to execute at N frames per second.

False. The frameRate() function limits the framerate to not exceed N.

What is the meaning of the return-type 'void'?

The return-type 'void' indicates that the function does not return any value at all.

True OR False evaluate to?

True

What two values will be printed by the following code block? int total = 0; void setup() { println(total); sum(1,3); println(total); } void sum(int a, int b) { int total = a + b; }

0 & 0. Understand why: Although total is declared as a global variable, a local variable with the same name is declared as a local variable in the function sum(). The local variable in sum() will override (mask) the global variable. This means the result of the expression (a+b) is assigned to the local variable and has no effect on the global.

What is the relationship between Classes and Objects in our programs?

An object is an instance of a class. The class is the factory that generates multiple objects e.g. the class Monster generates multiple objects of type Monster. A program has only one class of a given type e.g. Monster, but there can be many instances of Monster objects.

What is the relationship between an object's state and its instance variables?

An object's instance variables define the object's state. A monster object has a position, direction, is alive or dead, etc. that is distinct from all other instances of the class Monster. Each of these states is represented as the values assigned to the instance's variables. A monster's direction or position can be individually changed without effecting the state of other monsters.

Why is the use of action blocks without braces always discouraged? For example: if(a != b) println("A is not B");

Answer Although the code given above is legal (compiles), the use of braces {} around blocks is always suggested. This is because if the developer mistakenly changes to a multi-line block (see following example), they will need to add braces to keep the block from becoming an error. if(a != b) println("ERROR"); println("A is not B"); Without the braces, the second line will always be printed. Note that in practice the bug may not be so obvious as this example. if(a != b){ println("ERROR"); println("A is not B"); } Also, the use of blocks makes the overall program easier to read / understand.

What is the name of the technique that Processing uses to generate smooth transition between animation frames?

Double Buffering is the technique where Processing maintains two internal canvas. The contents of on canvas is actively displayed on the screen. The second canvas is update with the drawing operations. When the draw() function returns, Processing reverses their roles and the painted canvas becomes the displayed canvas.

What two values will a boolean expression always evaluate to?

True or False

What is the meaning of "multi-way" branching?

Multi-way branching is unlike simple two-way branching we see with the IF-ELSE statement i.e. two branches in the program's execution; true branch or false branch. Multi-way branching provides for two, three, four, etc. branches in the program's execution. This is helpful when there is a one of N choice to be made in the application's logic.

Provide a code example of summing the contents of the given integer array using a WHILE loop. Print the sum once the loop is finished. int[] ary = new int[10];

int sum = 0; int idx = 0; while(idx < ary.length) { sum = sum + ary[idx]; idx = idx + 1; } println("The sum is: " + sum);

Write a one line function that draws a line between the current position of the mouse (x&y) and the position of the mouse last time draw() was called.

line(pmouseX, pmouseY, mouseX, mouseY);

What are the four mandatory components of a function's declaration?

1. The function's name. 2. Zero or more parameters including types and unique names. 3. The function's return-type. That is, the type of the value generated and returned by the function. 4. The function's body enclosed in braces i.e. a block of code that is executed when the function is "called".

What are the three advantages of "focused modules" as described in the slides?

1. We create modules with fewer lines of code which makes them individually easier to understand. 2. We create modules whose features / functionality can be modified or extended with less chance of breaking other features implemented by other modules. 3. We create modules that will be more easily reused multiple times in the same program, or that can used in a different program.

Describe the meaning of 'local variable'. What is the local variable's lifetime?

A local variable is a variable declared in the scope of a code block i.e. the code between an open brace { and closing brace }. This can be the body of a function or the body of control statement such as for or while loops. A local variable is created when the block it is declared within is executed and lives until execution reaches the closing brace of the block the variable is declared within.

What is the name given to the methods responsible for creating a new instance of a class?

A class can provide a special method named the Constructor. Constructors are methods with names identical to the class name. Constructor methods parameters can provide values used to initialize the new object's instance (state) variables.

Describe the meaning of 'global variable'. What is the global variable's lifetime?

A global variable is a variable declared outside the scope of any function's block. A global variable has a global scope meaning that the variable can be referenced from any point in the program and retains its value throughout the program's execution. A global variable is created when the program start and lives until the program is terminated.

How do we implement modules in Processing (and other languages)?

A module is implemented as a function.

What is the "rule" concerning the design of a module?

A module should focus on doing only one thing.

What is the restriction on the names assigned to the sketchbook folder and the program contained in the folder?

A processing program is contained in a folder of the same name. That is, a sketchbook folder name "pongGame" must contain a Processing program file "pongGame.pde".

Briefly describe the meaning and purpose of the "Sketchbook" in Processing.

A sketchbook is a folder created by Processing is meant to hold a program and the resources needed by the program to operate. These resources include the Processing program file (.pde), image, audio, and other media used by the program.

What are the two mandatory components and single optional component of a Processing variable's declaration?

A variable in processing must include a type and a name. The name must be unique in its scope. The third optional component is the initialization expression that follows an equals sign in the same declaration. e.g. int xval = 0;

What is meant by: Every object is its own distinct instance?

Each object is an individual entity distinct from all the other objects in the system. An instance of the class Ship is distinct from an instance of class Monster. Each instance of Monster is distinct from all other monsters.

How do we implement the actions that an object can take? What is the relationship between an object's state and these actions?

Each of an object's possible actions are implemented by the methods defined by the object's class. Actions (methods) include changing the objects state i.e. change the monster's position or direction. Other methods might determine if the monster has collided with the Ship or Missile.

What is an "event handler" function? What are two event handlers functions provided by Processing?

Event hander functions are function we place into our program to be executed when some event occurs. This typically means an interaction by the user e.g. a mouse or keyboard action. The handlers that are activated by Processing's runtime when the designated event occurs. For example, the press of a mouse or keyboard button by the user are two examples of events. The handler are designed to process the event in some application-specific fashion. For example, change to stroke color when the R, G, or B keyboard buttons are pressed. Processing provides the handling function keyPressed() and mousePressed().

Describe why the explicate conversion of a float to an int is allowed.

However, the designers of programming languages recognize that some application allow for the loss of precision and so allow the programmer to explicitly convert the float to int. The idea is if the programmer explicitly forces the conversion, they must be aware of the precision loss and the resulting calculation is correct for their application.

What result will the following code evaluate to? int a = 10; int b = 11; if(a = b) println("point1"); else println("point2");

Kind of a trick question. This code will not compile because the IF statement uses the assignment operator (=) to make the comparison. As compared to the boolean equality operator (==).

Which of the following lines are legal assignments? Hint: There are two. 1. int count = 'a'; 2. double deposit = "100.00"; 3. boolean happy = 1; 4. float feet = 6; 5. int inches = feet / 12; 6. double giant = feet * 3.0;

Lines 4 & 6 are legal. The conversion of int to float is allows as there is no loss of the fractional component. The assignment of a float to a double is allows because there is not loss of precision.

Provide a brief description of how arguments are Passed by Reference.

Pass by Reference means that a pointer to the argument in memory is passed to the function's parameter. Pass by reference is used for parameters of type Arrays and Objects.

Provide a brief description of how arguments are Passed by Value.

Pass by Value means that copies of the argument values will be assigned to each of the function's parameters. Pass by value is used to pass primitive types. Also known as Pass by Copy.

What will be printed by each of the following four print statements? Is this an example of Pass By Reference or By Value? void setup() { int n = 10; println("Point A : " + n); foo(n); println("Point D : " + n); } void foo(int num) { println("Point B : " + num); num = 73; println("Point C : " + num); }

PointA: 10 PointB: 10 PointC: 73 PointD: 10 This is an example of Pass By Value. Note the Foo() parameter is a primitive type.

What will be printed by each of the following four print statements? Is this an example of Pass By Reference or By Value? void setup() { int n[] = new int[1]; n[0] = 10; println("Point A : " + n[0]); foo(n); println("Point D : " + n[0]); } void foo(int[] num) { println("Point B : " + num[0]); num[0] = 73; println("Point C : " + num[0]); }

PointA: 10 PointB: 10 PointC: 73 PointD: 73 This is an example of Pass By Reference. Note the foo() parameter is an array and not a primitive type.

What is the result of executing the following code? Hint: Run this code in Processing and report the result. int idx = 10; int numbers[] = new int[10]; numbers[idx]= 5; println(numbers[idx]); What change is needed to allow this program to set and print a number from the array without error?

Processing will report "ArrayIndexOutOfBoundsException: 10" on line 4. This is because the valid index range for this array is 0-9. Change the value of variable idx to within the range 0-9. Alternatively, you could increase the size of the numbers array to 11.

Explain why a landscape generated by Perlin noise is superior to a landscape generated by random numbers.

Random numbers are 'random' across a sequence of generated values. Imagine that the following figure is a cross-section of a landscape generated by random numbers. The peaks and valleys are sharp and disjoint; nothing like a natural landscape. A sequence of numbers of numbers generated with Perlin noise are pseudo-random. Each number changes from the last in the sequence, but each number remains relatively close to the last in the sequence. This produces smooth transition in the sequence that gently rises and falls over the duration of the sequence. This produces a natural looking landscape.

Describe each action taken by the following four Processing statements. size(200,200); background(0); fill(255); ellipse(100,100,50,50);

Set the size of the canvas to 200x200 pixels. Fill the canvas background with black pixels. Set the color used to draw shapes to white pixels. Draw an ellipse shape at location 100,100 with width 50 and height 50.

Why is the following code illegal? long xxx = 1; int yyy = xxx + 1;

The assignment of a long to an int is illegal because the converting a larger long to a smaller int may result in the loss of precision i.e. from big to small.

Describe how pixels are addressed on the Processing canvas.

The canvas has a fixed width (X) and height (Y) whose size is set by the size() operation. Pixels are addressed using two integers X & Y. The x,y position of a pixel is originated at (0,0) found at the upper left-hand corner of the rectangular canvas. The lower right hand pixel is addressed (width-1),(height-1). Drawing operations outside of the canvas bounds are not shown (clipped).

What is the name of the structure used to describe the things of interest in our program's design?

The class is the structure we use to describe a thing we want to represent in our program's design.

Describe the result of executing the following command in context of part 1. ellipse(200,100, 50,50);

The command will produce a half ellipse centered at the right-edge of the canvas.

What is the name of the operation used to explicitly covert a float to int?

The conversion operation is called a cast e.g. int piInt = (int)3.14159;

Describe the differences between variables declared byte, short, int, and long.

The each of these integer types is both the precision of the numbers they can maintain and the amount of memory each uses. Byte only allows small numbers between ± 127 but uses only a single 8-bit byte. Short allow numbers between ± 32,767 and uses two 8-bit byte. Int allows numbers between ± 2 million (aprox) and uses four 8-bit bytes. Long allows very large numbers ± 263 and uses eight 8-bit bytes.

Describe the difference between the fill() and stroke() functions.

The fill() operation selects the color that will be used to fill the following shape drawing operations e.g. eclipse(). The stroke() operation selects the color that will be used to draw the outline of the following shape drawing operations.

Provide a code example of the suggested method of summing the contents of the given integer array in Processing. Print the sum once the loop is finished. int[] ary = new int[10];

The first example of an Indexed FOR iteration: int sum = 0; for( int idx = 0; idx < ary.length; idx++) { sum = sum + ary[idx]; } println("The sum is: " + sum); A second, more compact form of an Iterator FOR iteration: int sum = 0; for( int val : ary) { sum = sum + val; } println("The sum is: " + sum);

What is the meaning of the four arguments passed to operations used to specify colors e.g. fill().?

The first three arguments are the red, green, & blue components of the desired color. The forth argument is the transparency of the color ranging from 0 (fully transparent) to 255 (opaque).

What is the range of numbers produced by this call to the function random(0,255)?

The function random() expects two arguments min & max. The floating point value X returned will be between min ≤ X < max. So this call will return and X where 0 ≤ X < 255 i.e. 254.9999999.

Describe why the implicit conversion of a float to an int considered an error.

The implicit conversion is an error because a float is converted to an int by truncating the fractional part of the floating point number i.e. the value after the decimal point. This means we lose precision in the calculation being performed thereby producing an incorrect result.

Provide a code example of the suggested method of summing the contents of the given two-dimensional integer array in Processing. Print the sum once the loop is finished. int[][] ary = new int[10][20];

The key to this problem is understanding that a two dimensional array is an array of references to many arrays (see slides). int sum = 0; for (int rowIdx = 0; rowIdx < ary.length; rowIdx++) { for (int colIdx = 0; colIdx < ary[rowIdx].length; colIdx++) { sum = sum + ary[rowIdx][colIdx]; } } println("Sum is " + sum);

Describe the effect of the noFill() operation.

The noFill() operation will create a transparent interior for the following shape drawing operations.

What is the primary drawback of using arrays as lists or containers of value / objects?

The primary drawback is that an array size (length) is fixed when it is declared. We are unable to increase the length of an array after it has been created. This is a problem because we often need a list to be of a variable length. For example, a graphics editor that maintains a list of shapes that are entered and removed by the user.

What is the range of index value that can correctly access the following array definition? int numbers[] = new int[10];

The range is 0-9. (Not 1-10). This is because in programming languages based on the C language, array indexing are zero-based meaning the first entry is indexed: numbers[0]. Given that the array size is 10, this allows for a range of 10 entries starting with 0.

What are the three properties we assign to each class?

The three properties of a class are: 1. The class name. 2. The class attributes. 3. The class methods (actions).

What are the two methods of multi-way branching in Processing described in the slides?

The two methods are: IF / ELSE IF / ELSE statements allow for multiple boolean conditions, each of which make one of the several choices to be implemented. The SWITCH statement allows for the comparison of a single variable against several possible values.

Describe the purpose of, and execution of, the two important functions found in most Processing programs.

These functions are void setup() {} and void draw() {}. The purpose of the setup() function is to initialize the program on startup. This function is used to create and assign initial values to variables used by the program. Setup() is only called once when the program is started. The purpose of the draw() function is to repeatedly draw & redraw the canvas to present an animation. The Processing runtime engine will call draw() which is design to draw a single frame of the animation. After the draw() function returns (completes), Processing runtime will call draw() again, and again. It is often the case that the draw() function will first erase the contents of the canvas using the background() function, and then use shape drawing operations (ellipse, rect, etc) to create the next animation frame. During the execution of draw(), the Processing program may use user input from the mouse and keyboard to direct the animation. For example, draw a shape at the mouse position. Create a new shape when a mouse or keyboard button is pressed.

What are the three things we describe when analyzing a problem using object-oriented principles?

These three things for every object in the problem domain 1. The names of the objects in our problem. 2. For each object, the attributes of those objects. 3. For each object, the actions taken by the objects or taken on the objects.

Explain how the two conditions in the following IF statement will be evaluated? String name = null; if((name != null) && (name.length() >= 1)) { println("The entered name is " + name); }

This IF statement has two boolean expressions separated by an AND. The second expression will not be evaluated (executed) if the first expression evaluates to False. The advantage here is that if the variable name is null, the second expression will not generate a null-pointer error because it will not be evaluated. The null-pointer error would be generated when null.length() is evaluated. Note that the NULL check must be the first expression in the statement.

Explain how the two conditions in the following IF statement will be evaluated? String name = null; if((name == null) || (name.length() == 0)) { println("The entered name is invalid"); }

This IF statement has two boolean expressions separated by an OR. The second expression will not be evaluated (executed) if the first expression evaluates to True. Note that the NULL check must be the first expression in the statement.

Describe the reason for the compilation error in the following code? int xpos = 0; void drawEllipse(int xpos, int ypos) { int xpos = 0; ellipse(xpos,ypos,20,20); }

This code has two declarations of variables in the same scope. The variable int xpos is declared as both a parameter in the function drawEllipse() and as a local variable in the function. void drawEllipse(int xpos, int ypos) { int xpos = 0; ellipse(xpos,ypos,20,20); } Note that the global variable makes no difference because it is in the global and not the local scope.

Provide an example of the syntax used to initialize a new instance of a class.

This state creates a new Monster with the given location and assigns a reference to the new object to the reference variable m1.


Set pelajaran terkait

Psychology: Development Issues, Prenatal Development and the Newborn (Module 13)

View Set

Earth and Space Science chapter 17 Test

View Set

Chapter 9 - Human Rights and Fair Housing

View Set