361 lesson 1 Introduction to Programming

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

decision table ex: A decision table to calculating discounts.

When an algorithm involves a large number of conditions, a(n) _______________ _____________ is a compact and readable format for presenting the algorithm.

b. Namespace

Which of the following C# features should you use to organize code and create globally unique types? a. Assembly b. Namespace c. Class d. Data type

Answer: c Section Reference: Introducing C# C#, Visual Basic, and C++ are all high-level programming languages. The Common Intermediate Language is low-level programming language used by the .NET Framework language compilers to create an executable file.

Which of the following languages is not considered a high-level programming language? a) C# b) Visual Basic c) Common Intermediate Language d) C++

Answer: c Section Reference: Understanding Exception Handling The correct answer arranges the catch statements from specific exceptions to the general exceptions. If you place the code to catch a general exception before the specific exception, the catch block for that specific statement will never get executed. The C# compiler detects this and flags this situation as error. The exceptions of type Exception are most general and hence should be placed in the last catch block. Next, the exception of type ArithmeticException is more general than DivideByZeroException, OverflowException, and NotFiniteNumberException and should be placed after these specific exceptions.

You are assisting your colleague in solving a compiler error that his code is throwing. Following is the problematic portion of his code: try { bool success = ApplyPicardoRotation(100, 0); // additional code lines here } catch(DivideByZeroException dbze) { //exception handling code } catch(NotFiniteNumberException nfne) { //exception handling code } catch(ArithmeticException ae) { //exception handling code } catch(OverflowException oe) { //exception handling code } To remove the compilation error, which of the following ways should you suggest to rearrange the code? a) try { bool success = ApplyPicardoRotation(100, 0); // additional code lines here } catch(DivideByZeroException dbze) { //exception handling code } catch(ArithmeticException ae) { //exception handling code } catch(OverflowException oe) { //exception handling code } b) try { bool success = ApplyPicardoRotation(100, 0); // additional code lines here } catch(DivideByZeroException dbze) { //exception handling code } catch(Exception e) { //exception handling code } catch(OverflowException oe) { //exception handling code } c) try { bool success = ApplyPicardoRotation(100, 0); // additional code lines here } catch(DivideByZeroException dbze) { //exception handling code } catch(NotFiniteNumberException nfne) { //exception handling code } catch(OverflowException oe) { //exception handling code } catch(ArithmeticException ae) { //exception handling code } d) try { bool success = ApplyPicardoRotation(100, 0); // additional code lines here } catch(DivideByZeroException dbze) { //exception handling code } catch(NotFiniteNumberException nfne) { //exception handling code } catch(Exception e) { //exception handling code } catch(ArithmeticException ae) { //exception handling code }

Answer: a Section Reference: Understanding the while loop When the value of count starts at 1, the while loop executes once for each value of count 1, 2, 3, 4, and 5. When the while condition is changed to (count == 5) or to (count >= 5), the loop will execute 0 times because the initial value of count is 0. Having ++count as a standalone statement is same as count++ and will not cause the results to vary.

You are developing a C# program that needs to perform 5 iterations. You write the following code: 01: int count = 0; 02: while (count <= 5) 03: { 04: Console.WriteLine("The value of count = {0}", count); 05: count++; 06: } When you run the program, you notice that the loop does not iterate five times. What should you do to make sure that the loop is executed exactly five times? a) Change the code in line 01 to int count = 1; b) Change the code in line 02 to: while (count == 5) c) Change the code in line 02 to while (count >= 5) d) Change the code in line 05 to ++count;

Answer: a Section Reference: Understanding Recursion Answer a specifies the correctly formed base and the recursive case. Answer b is incorrect because the expression (n - 1) * Factorial(n) is not progressing towards the base case. Answer c is incorrect because the recursive case is not using the multiplication to get to the final value. Answer d is incorrect because the base case is missing and the method will never terminate.

You are developing a C# program. You write a recursive method to calculate the factorial of a number. Which of the following code segment should you use to generate correct results? a) public static int Factorial(int n) { if (n == 0) { return 1; } else { return n * Factorial(n - 1); } } b) public static int Factorial(int n) { if (n == 0) { return 1; } else { return (n - 1) * Factorial(n); } } c) public static int Factorial(int n) { if (n == 0) { return n; } else { return Factorial(n - 1); } } d) public static int Factorial(int n) { return n * Factorial(n - 1); }

Answer: b Section Reference: Understanding Operators To evaluate this expression, you have to take into account operator precedence. The operators * and / have a higher precedence than + and -. You can also write this expression as 6 + ((4 * 4) / 2) - 1 This simplifies to, 6 + (8) - 1, resulting in 13.

You are developing a C# program. You write the following code line: int x = 6 + 4 * 4 / 2 - 1; What will be the value of the variable x after this statement is executed? a) 19 b) 13 c) 20 d) 14

Answer: b Section Reference: Understanding Repetition Structures You enter the loop each time when the value of count is 0, 1, 2, and 3. So the correct answer is 4. When the value of count reaches 3, the break statement is executed to terminate the loop and transfer the control outside the loop.

You are developing a C# program. You write the following code: 01: int count = 0; 02: while (count < 5) 03: { 04: if (count == 3) 05: break; 06: count++; 07: } How many times will the control enter the while loop? a) 5 b) 4 c) 3 d) 2

If-Else Statement

allows your program to perform one action if the Boolean expression evaluates to true and a different action if the Boolean expression evaluates to false. public static void TestIfElse(int n) { If(n<10) { Console.WriteLine("n is less than 10"); } else if (n < 20) { Console.WriteLine("n is less than 20"); } else if (n < 30) { Console.WriteLine("n is less than 30"); } else { Console.WriteLine("n is equal or greater than 30"); } }

Methods

are code blocks containing a series of statements, can receive input via arguments and can return a value to the caller

break, goto, return, or throw

are control transfer statements that transfer control outside a loop.

Operators

are symbols, such as +,-,*, and /, that specify which operation to perform on or more operands before returning a result.

operands

can be variables, constants, literals, etc

For Loop

combines the three elements of iteration—the initialization expression, the termination condition expression, and the counting expression—into a more readable code. It allows a statement or a statement block to be executed repeatedly until an expression evaluates to false. The for loop is especially useful for creating iterations that must execute a specified number of times. private static void ForTest() { for(int i = 1; i<= 5; i++) { Console.WriteLine("The value of i = {0}", i); } }

Main

is a special method in that it also serves as an entry point to the program. When the runtime executes a program, it always starts at the __________ method.

High-Level Language

languages that allow you to write precise instructions in a human-readable form

Computer programs (programs)

precise and complete instructions for a computer to accomplish a task

Exception Handling Sample

private static void ExceptionTest() { StreamReader sr = null; try { sr = File.OpenText(@"c:\data.txt"); Console.WriteLine(sr.ReadToEnd()); } catch (FileNotFoundException fnfe) { Console.WriteLine(fnfe.Message); } catch(Exception ex) { Console.WriteLine(ex.Message); } }

Rectangles symbolize _______________ on a flowchart

processes or computational operation

If Statement

will execute a given sequence of statements only if the corresponding Boolean expression evaluates to true int number1 = 10; int number2 = 20; if (number2 > number1) { Console.WriteLine("number2 is greater than number1");

Unary operators

work with only one operand. Examples include ++x, x++, or isEven, where x is of integer data type and isEven is of Boolean data type.

Binary operators

work with two operand. Examples include x + y or x > y.

Binary code

A computer program written using the binary number system

9. decision table

9. When an algorithm involves a large number of conditions, a(n) __________ ______ is a compact and readable format for presenting the algorithm.

8. Constants

8. __________ are data fields or local variables whose value cannot be modified.

Array

1. A collection of items in which each item can be accessed by a unique index. int[] numbers = { 1, 2, 3, 4, 5 }; 2. _______ a group of items in which each item can be used by using a unique index.

Exception Handling

1. An ___________ is an unexpected error condition that occurs during program execution. 2. When ______________ occurs, the runtime creates an exception object and "throws" it. 3. Unless you "catch" the exception, the program execution will terminate. 4. Exceptions are an object of the System.Exception class or one of its derived classes. - Example: DivideByZeroException exception object is thrown when the program attempts to divide by zero. - Example: FileNotFoundException exception object is throws when the program cannot find a given file.

Steps of Software Design Life Cycle

1. Analyze requirements 2. Design and evaluation (flowchart) 3. Implementation and Integration 4. Testing 5. Deployment 6. Documentation and Maintenance

Introducing C#

1. Microsoft .NET Framework - An Execution Environment - Reusable Class Libraries - Language Compilers 2. The C# Programming Language - Part of the .NET Framework - High-level Language - Program needs to be compiled before they can be executed. - Case sensitive

Handling Exceptions with try-catch

1. Place the code that throws the exceptions inside a try block. 2. Place the code that handles an exception inside a catch block. 3. You can have more than one catch blocks for each try block. Each catch block handles a specific exception type. 4. A try block must have at least a catch block or a finally block associated with it.

1. switch

1. The ______ statement selects for execution a statement list having an associated label that corresponds to the value of an expression. .

Finally Block

1. _______ __________used in association with the try block. 2. The ______ ______ is always executed regardless of whether an exception is thrown. 3. The ______ ________ is often used to write clean-up code StreamReader sr = null; try { sr = File.OpenText("data.txt"); Console.WriteLine(sr.ReadToEnd()); } finally { if (sr != null) { sr.Close(); } } .

Variable

1. _______ provide temporary storage during the execution of a program. int number = 10; 2. A _________ has a name and a data type. 3. A __________'s data type determine what value it can contain and what kind of opertaions may be performed on it.

Data Types

1. _________ _________specify the type of data that you work with in a program. 2. The __________ ________ defines the size of memory needed to store the data and the kinds of operation that can be performed on the data. 3. Types of data in a program. Common data types are int (integers), char (single character value), float (floating point values).

Constants

1. ______________ are data fields or local variables whose value cannot be modified. 2. Data fields whose value cannot be modified. const int i = 10;

Algorithm

1. __________________ is a set of ordered and finite steps to solve a given problem. 2. Find it useful to express an ____________ as a flowchart or a decision table before developing a formal computer program. 3. Refers to a method for solving problems.

10. flowchart

10. A(n) ___________ is a graphical representation of an algorithm.

2. do-while

2. The __________ loop tests the condition at the bottom of the loop instead of at the top.

3. trinary

3. The only operator that takes three arguments is the _________ operator..

4.for each

4. The ________ loop is the most compact way to iterate through the items in a collection.

5. four

5. On a 32-bit computer, a variable of int data type takes ____ bytes of memory.

6. 0

6. To access the first element of an array, you use an index of _.

7. Recursion

7. _____________ is a programming technique that causes a method to call itself in order to compute a result

Class

A set of data and methods. _____ is defined by using the keyword class followed by the class name. The contents of a _____ are defined between an opening brace { and a closing brace }.

Flowchart

A(n) ____________ is a graphical representation of an algorithm.

Binary number system

At the most basic level, computers use the ________ _________ ________ to represent information and code; each value is represented using only 2 symbols, 0 and 1

Repetition Structures

C# has four different control structures that allow programs to perform repetitive tasks: the while-loop, the do-while loop, the for loop, and the foreach loop.

Diamond symbolize _______________ on a flowchart

Decision making

b. StackOverflowException

If you don't have a base case in your recursive algorithm, you create an infinite recursion. An infinite recursion will cause your program to throw an exception. Which exception will your program throw in such a case? a. OutOfMemoryException b. StackOverflowException c. DivideByZeroException d. InvalidOperationException

c. default

In a switch statement, if none of the case statements match the switch expression, then control is transferred to which statement? a. break b. continue c. default d. return

Parallelogram symbolize _______________ on a flowchart

Input/output

Decision Structures

Introduce decision-making ability into a program. They enable you to branch to different sections of the code depending on the truth value of a Boolean expression. Decision-making control structures in C# are the if, if-else, and switch statements.

a. 25

Review the following code snippet: int n = 20; int d = n++ + 5; What will be the value of d after this code snippet is executed? a. 25 b. 26 c. 27 d. 28

c. number1 number2

Review the following code snippet: int number1 = 10; int number2 = 20; if (number2 > number1) Console.WriteLine("number1"); Console.WriteLine("number2"); What output will be displayed after this code snippet is executed? a. number1 b. number2 c. number1 number2 d. number2 number1

c. 4

Review the following code snippet: private static void WhileTest() { int i = 1; while (i < 5) { Console.WriteLine("The value of i = {0}", i); i++; } } How many times will the while loop be executed in this code snippet? a. 0 b. 1 c. 4 d. 5

Elements of a C# Program

Select common elements of a C# program: Data Types, Variables, Constants, Arrays, Operators, and Methods.

Oval symbolize _______________ on a flowchart

Start/end

try-catch-finally Example

StreamReader sr = null; try { sr = File.OpenText("data.txt"); Console.WriteLine(sr.ReadToEnd()); } catch (FileNotFoundException fnfe) { Console.WriteLine(fnfe.Message); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (sr != null) { sr.Close(); } } }

for-each loop

The __________ ___________ is an enhanced version of the for loop for iterating through collections such as arrays and lists. This results in more readable code. private static void ForEachTest() { int[] numbers = { 1, 2, 3, 4, 5 }; foreach (int i in numbers) { Console.WriteLine("The value of i = {0}", i); } }

switch statement

The ___________ ____________ allows multi-way branching. In many cases, using a _________ __________ can simplify a complex combination of if-else statements. public static void TestSwitch(int op1, int op2, char opr) { int result; switch (opr) { case '+': result = op1 + op2; break; case '-': result = op1 - op2; break; case '*': result = op1 * op2; break; case '/ ': result = op1 / op2; break; default: Console.WriteLine("Unknown Operator"); return; } Console.WriteLine("Result: {0}", result); return; }

ternary

The only operator that takes three arguments is the _______________ operator. There is just one ternary operator, ?:, in C#.

Answer: b Section Reference: Understanding Repetition Structures The control will enter the loop only once. At the end of the first iteration, the condition will fail (because the number 6 is greater than the number 5) and the loop will terminate.

You are developing a C# program. You write the following code: int i = 6; do { if (i == 3) break; Console.WriteLine("The value of i = {0}", i); i++; } while (i <= 5); How many times will the control enter the while loop? a) 0 b) 1 c) 2

Answer: b Section Reference: Understanding Operators The way unary increment and decrement operators work when used as part of an assignment can affect the results. In particular, when the unary increment and decrement operators are used as prefixes, the current value of the identifier is returned before the increment or decrement. On the other hand, when used as a suffix, the value of the identifier is returned after the increment or decrement is complete. When the first statement is executed, the value of x is 10. When the second statement is executed, the value of x and y are both 11. When the final statement is executed, the current value of y (11) is assigned to z before y is incremented by 1.

You are developing a C# program. You write the following code: int x = 10; int y = ++x; int z = y++; What will be the value of the variable z after all the above statements are executed? a) 10 b) 11 c) 12 d) 13

Answer: b STOP START Output fact n > 1? No Yes fact = 1 fact = fact * n Input n n = n - 1 Difficulty: Easy Section Reference: Introducing Flowcharts Here, you enter the loop once each time when the value of n is 5, 4, 3, and 2. So the final result will be 5 * 4 * 3 * 2 = 120.

You are developing an algorithm before you write the C# program. You need to perform some calculations on a number. You develop the following flowchart for the calculation: If the input value of n is 5, what is the output value of the variable fact according to this flowchart? a) 720 b) 120 c) 24 d) 6

Answer: c Section Reference: Introducing Decision Tables When a customer buys 50, the conditions Quantity < 10 and Quantity < 50 are both false but the condition Quantity < 100 is true. So, when you look at the column N, N, and Y, the corresponding value of the discount is 15%.

You are developing an algorithm for a retail Web site. You need to calculate discounts on certain items based on the quantity purchased. You develop the following decision table to calculate the discount: Quantity < 10 Y N N N Quantity < 50 Y Y N N Quantity < 100 Y Y Y N Discount 5% 10% 15% 20% If a customer buys 50 units of an item, what discount will be applicable to the purchase? a) 5 percent b) 10 percent c) 15 percent d) 20 percent

d. Infinite repetitions

You are learning how to develop repetitive algorithms in C#. You write the following method: private static void ForTest() { for(int i = 1; i < 5;) { Console.WriteLine("The value of i = {0}", i); } } How many repetitions will the for loop in this code perform? a. 0 b. 4 c. 5 d. Infinite repetitions

Answer: d Section Reference: Understanding Repetition Structures The do-while statement performs the test for the termination condition at the bottom of the loop. All other repletion structure performs the test at the top of the loop.

You are writing a C# program and need to select an appropriate repetition structure for your requirement. You need to make sure that the test for the termination condition is performed at the bottom of the loop rather than at the top. Which repletion structure should you use? a) The while statement b) The for statement c) The foreach statement d) The do-while statement

Answer: c Section Reference: Understanding Repetition Structures The foreach statement—an enhanced version of the for statement—is useful for iterating through collections such as arrays and lists. Using foreach statements eliminates the need for maintaining an index to the current item in the list. This improves code readability, makes debugging easier, and minimizes errors.

You are writing a C# program that iterates through a collection such as arrays and lists. You need to make sure that you process each item in the collection once. You also need to ensure that your code is easy to read and debug. Which of the following C# statements provide the best solution for this requirement? a) while b) for c) foreach d) do-while

Answer: b Section Reference: Understanding Repetition Structures The for loop is ideal for creating iterations that must execute a specified number of times. The for loop combines the three elements of iteration—the initialization expression, the termination condition expression, and the counting expression—into a more readable code by placing them outside the loop body. This improves code readability, makes debugging easier and minimizes errors.

You are writing a C# program that needs to iterate a fixed number of times. You need to make sure that your code is easy to understand and maintain even when the loop body contains complex code. Which of the following C# statements provide the best solution for this requirement? a) while b) for c) foreach d) do-while

Answer: d Section Reference: Understanding Data Types The long data type takes double the memory size of the int data type and can store integer values that exceed 12 digits. The int data type is relatively smaller. The float and double data types are more suited for storing floating-point numbers.

You are writing a C# program that needs to manipulate very large integer values that may exceed 12 digits. The values can be positive or negative. Which data type should you use to store a variable like this? a) int b) float c) double d) long

Answer: a Section Reference: Understanding Decision Structures In this code example, no break statement occurs after each case. The break statement terminates the switch statement and transfers control to the next statement outside the switch block. The continue statement is not the right answer because no enclosing loop is included here. The goto and return statements are not correct because they will change the program's intended output.

You are writing a C# program. You write the following method: public static void TestSwitch(int op1, int op2, char opr) { int result; switch (opr) case '+': result = op1 + op2; case '-': result = op1 - op2; case '*': result = op1 * op2; case '/': result = op1 / op2; default: Console.WriteLine("Unknown Operator"); return; } Console.WriteLine("Result: {0}", result); return; } However, when you compile this code, you get the following error message: Control cannot fall through from one case label to another How should you modify the code to make sure that it compiles successfully? a) After each case, add the following code line: break; b) After each case, add the following code line: continue; c) After each case, add the following code line: goto default; d) After each case, add the following code line: return;

Answer: a Section Reference: Understanding Methods When a method doesn't return a value back to the calling code, it is indicated by using the void keyword in the method declaration.

You are writing a method named PrintReport that doesn't return a value to the calling code. Which keyword should you use in your method declaration to indicate this fact? a) void b) private c) int d) string

Answer: b Section Reference: Understanding Arrays Any array item can be directly accessed by using an index. In the .NET Framework, array indexes are zero-based, meaning that to access the first element of an array, you use the index 1; to access the second element, you use the index 2; and so on. In the given case, as you need to access the second element, you use the expression numbers[2].

You are writing code for a business application by using C#. You write the following statement to declare an array: int[] numbers = { 1, 2, 3, 4, 5 }; Now, you need to access the second item in this array (the number 2). Which of the following expression should you use? a) numbers[0] b) numbers[1] c) numbers[2] d) numbers[3]

Answer: d Section Reference: Understanding Exception Handling You need to make sure that the SqlConnection object is closed properly whether an exception occurred. The finally block is always executed and therefore is the best place to place such a code. The other answers are incorrect because code in these blocks can execute sometime but is not guaranteed to execute in every situation.

You have written a C# method that opens a database connection by using the SqlConnect object. The method retrieves some information from the database and then closes the connection. You need to make sure that your code fails gracefully when there is a database error. To handle this situation, you wrap the database code in a try-catch-finally block. You use two catch blocks—one to catch the exceptions of type SqlException and the second to catch the exception of type Exception. Which of the following places should be the best choice for closing the SqlConnection object? a) Inside the try block, before the first catch block b) Inside the catch block that catches SqlException objects c) Inside the catch block that catches Exception objects d) Inside the finally block

Answer: a Section Reference: Introducing Algorithms A flowchart is a graphical representation of an algorithm that lists, in the correct order, all the necessary steps to perform the operation. A flowchart is simple to create and understand and is not ambiguous.

You need to gain a better understanding of the solution before writing the program. You decide to develop an algorithm that lists all necessary steps to perform an operation in the correct order. Any technique that you use should minimize complexity and ambiguity. Which of the following techniques should you use? a) flowchart b) decision table c) C# program d) A paragraph in English

Answer: d Section Reference: Understanding Decision Structures The switch statement allows multi-way branching. In many cases, using a switch statement can simplify a complex combination of if-else statements.

You need to provide complex multi-way branching in your C# program. You need to make sure that your code is easy to read and understand. Which of the following C# statements should you use? a) case b) break c) if-else d) switch

a. byte

You need to store values ranging from 0 to 255. You also need to make sure that your program minimizes memory use. Which data type should you use to store these values? a. byte b. char c. short d. int

c. Within a finally block

You need to write code that closes a connection to a database and you need to make sure this code is always executed regardless of whether an exception is thrown. Where should you write this code? a. Within a try block b. Within a catch block c. Within a finally block d. Within the Main method

b. 2

You write the following code snippet: int[] numbers = {1, 2, 3, 4}; int val = numbers[1]; You also create a variable of the RectangleHandler type like this: RectangleHandler handler; What is the value of the variable val after this code snippet is executed? a. 1 b. 2 c. 3 d. 4

Switch Block

_________ __________what is in the switch, can include one or more case statements or a default statement

do-while loop

__________ _____________repeatedly executes a block of statements until a specified Boolean expression evaluates to false. The __________ loop tests the condition at the bottom of the loop. In contrast, if you want the loop to execute one or more times, choose the do-while loop private static void DoWhileTest() { int i = 1; do { Console.WriteLine("The value of i = {0}", i); i++; } while (i <= 5); }

Recursion

______________ is a programming technique that causes a method to call itself in order to compute a result. public static int Factorial(int n) { If(n==0) { return 1; // base case } else { Return n * Factorial(n-1) // recursive case } As seen in the above exercise, a recursive solution has two distinct parts: 1. Base case: This is the part that specifies the terminating condition and doesn't call the method again. The base case in the Factorial method is n == 0. If you don't have a base case in your recursive algorithm, you create an infinite recursion. An infinite recursion will cause your computer to run out of memory and throw a System. StackOverflowException exception. 2. Recursive case: This is the part that moves the algorithm toward the base case. The recursive case in the Factorial method is the else part, where you call the method again but with a smaller value progressing toward the base case.

while-loop

_______________ repeatedly executes a block of statements until a specified Boolean expression evaluates to false. If you want the loop to execute zero or more times, choose the while loop. private static void WhileTest() { int i = 1; while(i<=5) Console.WriteLine("The value of i = {0}", i); i++; } }


संबंधित स्टडी सेट्स

Chapter 10 - Key Issue 3: Where Is Agriculture Distributed?

View Set

Praxis Elementary Education C.K. (5018) Reading and Language Arts

View Set

7th Grade Social Studies - Canada

View Set