1.
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?
Correct Answer
A. Flowchart
Explanation
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.
2.
Which of the following languages is not considered a high-level programming language?
Correct Answer
C. Common Intermediate Language
Explanation
C#, Visual Basic, and C++ are all high-level programming languages. The Common Intermediate Language is a low-level programming language used by the .NET Framework language compilers to create an executable file. Common Intermediate Language is the lowest-level human-readable computer language.
3.
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?
Correct Answer
B. Numbers[1]
Explanation
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].
4.
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?
Correct Answer
B. 11
Explanation
If ++ precedes the variable, e.g. ++counter, the value returned is the value in counter after it has been incremented.
If ++ follows the variable, e.g. counter++, the value returned is the value in counter before it has been incremented.
So y will take the value 11 at line 2.
A line 3, z will take the value of y before it is incremented so z will be 11 also
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.
5.
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?
Correct Answer
A. Void
Explanation
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.
6.
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?
Correct Answer
D. Switch
Explanation
The switch statement allows multi-way branching. In many cases, using a switch statement can simplify a complex combination of if-else statements.
7.
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?
Correct Answer
C. Foreach
Explanation
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.
8.
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?
Correct Answer
A. Change the code in line 01 to
int count = 1;
Explanation
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.
9.
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?
Correct Answer
B. 13
Explanation
To evaluate this expression, you have to take into account operator precedence. The operators * and / have 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.
10.
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?
Correct Answer
D. Long
Explanation
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.
11.
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?
Correct Answer
D. Inside the finally block
Explanation
You need to make sure that the SqlConnection object is closed properly whether an exception occurred. The final 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.
12.
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 rearranging the code?
Correct Answer
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
}
Explanation
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.
13.
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?
Correct Answer
A. Public static int Factorial(int n)
{
if (n == 0)
{
return 1;
}
else
{
return n * Factorial(n - 1);
}
}
Explanation
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.
14.
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?
Correct Answer
B. 4
Explanation
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.
15.
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?
Correct Answer
B. 1
Explanation
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.
16.
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 repetition structure should you use?
Correct Answer
D. The do-while statement
Explanation
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.
do
{
// code
}
while x
17.
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?
Correct Answer
A. After each case, add the following code line:
break;
Explanation
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.
18.
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?
Correct Answer
C. 15 percent
Explanation
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%.
19.
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?
Correct Answer
B. 120
Explanation
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.
20.
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?
Correct Answer
B. For
Explanation
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.
21.
You are developing code for a method that calculates the discount for the items sold. You name the method CalculateDiscount. The method defines a variable, percentValue of the type double. You need to make sure that percentValue is accessible only within the CalculateDiscount method. What access modifier should you use when defining the percentValue variable?
Correct Answer
A. Private
Explanation
The private modifier restricts the access to the class in which the member was defined. The protected modifier restricts the access to the containing class and to any class derived directly or indirectly from the containing class. The internal modifier restricts the access to the code in the same assembly. The public modifier does not restrict access.
22.
You are developing code that defines an InitFields method. The method takes two parameters of data type double and does not return any value to the calling code. Which of the following code segments would you use to define the InitFields method?
Correct Answer
B. Public void InitFields(double l, double w)
{
length = l;
width = w;
}
Explanation
If a method does not intend to return any value, its return type is specified by the keyword void. As the method takes two parameters of data type double, the parameter list must declare two variables of type double.
23.
You created a class named GeoShape. You defined a method called Area in the GeoShape class. This method calculates the area of a geometric shape. You want the derived classes of GeoShape to supersede this functionality to support the area calculation of additional geometric shapes. When the method Area is invoked on a GeoShape object, the area should be calculated based on the runtime type of the GeoShape object. Which keyword should you use with the definition of the Area method in the GeoShape class?
Correct Answer
B. Virtual
Explanation
Use the virtual keyword to define the Area method. When a virtual method is invoked, the runtime type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
24.
Suppose that you defined a class Scenario that defines functionality for running customized pivot transform on large data sets. You do not want the functionality of this class to be inherited into derived classes. What keyword should you use to define the Scenario class?
Correct Answer
A. Sealed
Explanation
Use the sealed keyword to define the Scenario class. When applied to a class, the sealed modifier prevents other classes from inheriting from it.
25.
You need to provide printing functionality to several of your classes. Each class’s algorithm for printing will likely be different. Also, not all the classes have an “is-a” relationship with each other. How should you support this functionality?
Correct Answer
D. Create a common interface that all classes implement.
Explanation
You should create a common interface that is implemented by all classes. Interfaces are used to establish contracts through which objects can interact with each other without knowing the implementation details.
26.
You are writing code for a class named Book. You should be able to get a list of all books sorted by the author’s last name. You need to write code to define this behavior of a class. Which of the following class elements should you use?
Correct Answer
A. Method
Explanation
A method defines the behavior of a class. You can write a method that returns a list of all books sorted by the author’s last name.
27.
Suppose that you are writing code for a class named Product. You need to make sure that the data members of the class are initialized to their correct values as soon as you create an object of the Product class. The initialization code should always be executed. What should you do?
Correct Answer
B. Create a constructor in the Product class to initialize data members.
Explanation
Constructors are special class methods that are executed when a new instance of a class is created. Constructors are used to initialize the object’s data members.
28.
You are creating a new class named Sphere derived from the Shape class. The Shape class has the following code:
class Shape
{
public virtual void Area()
{
// additional code...
}
}
The Area method in the Shape class should provide new functionality but also hide the Shape class implementation of the Area method. Which code segment should you use to accomplish this?
Correct Answer
B. Class SpHere : Shape
{
public new void Area()
{
// additional code ...
}
}
Explanation
The new keyword creates a new member of the same name in the derived class and hides the base class implementation. The override keyword is not the correct answer because it replaces a base class member in a derived class.
29.
You are creating a new class named Polygon. You write the following code:
class Polygon : IComparable
{
public double Length { get; set; }
public double Width { get; set; }
public double GetArea()
{
return Length * Width;
}
public int CompareTo(object obj)
{
// to be completed
}
}
You need to complete the definition of the CompareTo method to enable comparison of the Polygon objects. Which of the following code segments should you use?
Correct Answer
A. Public int CompareTo(object obj)
{
Polygon target = (Polygon)obj;
double diff = this.GetArea() - target.GetArea();
if (diff == 0)
return 0;
else if (diff > 0)
return 1;
else return -1;
}
Explanation
The return value of the CompareTo method indicates the result of comparing the given parameter with the current object. According to the documentation of the CompareTo method,
If the instance is equal to the parameter, CompareTo returns 0.
If the parameter value is less than the instance or if the parameter is null, a positive value is returned.
If the parameter value is greater than the instance, a negative value is returned.
If the parameter is not of the compatible type, an ArgumentException is thrown.
30.
You are writing code for a new method named Process:
void Draw(object o)
{
}
The code receives a parameter of type object. You need to cast this object into the type Polygon. At times, the value of o that is passed to the method might not be a valid Polygon value. You need to make sure that the code does not generate any System.InvalidCastException errors while doing the conversions. Which of the following lines of code should you use inside the Draw method to accomplish this goal?
Correct Answer
C. Polygon p = o as Polygon;
Explanation
The as operator is similar to the cast operation but, in the case of as, if the type conversion is not possible, null is returned rather than an exception raised. An exception may be generated with the code in the other answer choices.
31.
You are writing code to handle events in your program. You define a delegate named PolygonHandler like this:
public delegate void PolygonHandler(Polygon p);
You also create a variable of the PolygonHandler type as follows:
PolygonHandler handler;
Later in the program, you need to add a method named CalculateArea to the method invocation list of the handler variable. The signature of the CalculateArea method matches the signature of the PolygonHandler method. Any code that you write should not affect any existing event-handling code. Given this restriction, which of the following code lines should you write?
Correct Answer
C. Handler += CalculateArea;
Explanation
You need to use the += operator rather than the simple assignment operator (=) to attach the event handler. By using the += operator, you ensure that this event handler will be added to a list of event handlers already attached with the event.
32.
You are developing a C# application. You create a class of the name Widget. You use some third-party libraries, one of which also contains a class of the name Widget. You need to make sure that using the Widget class in your code causes no ambiguity. Which C# keyword should you use to address this requirement?
Correct Answer
A. Namespace
Explanation
Use the namespace keyword. A namespace is a language element that allows you to organize code and create globally unique class names.
33.
You are reviewing a C# program that contains the following class:
public class Rectangle
{
public double Length {get; set;}
public double Width { get; set; }
}
The program executes the following code as part of the Main method:
Rectangle r1, r2;
r1 = new Rectangle { Length = 10.0, Width = 20.0 };
r2 = r1;
r2.Length = 30;
Console.WriteLine(r1.Length);
What will be the output when this code is executed?
Correct Answer
C. 30
Explanation
The class Rectangle is a reference type, and the content of variable r1 is actually a reference to a memory location that holds a Rectangle object. So, after the r2 = r1; statement,
both r1 and r2 point to the same memory location and in turn the same Rectangle object. In other words, there is only one rectangle object in memory, and both r1 and r2 are referring to it. When the Length property is modified, the change applies to both objects r1 and r2.
34.
You are reviewing a C# program. The program contains the following class:
public struct Rectangle
{
public double Length {get; set;}
public double Width { get; set; }
}
The program executes the following code as part of the Main method:
Rectangle r1, r2;
r1 = new Rectangle { Length = 10.0, Width = 20.0 };
r2 = r1;
r2.Length = 30;
Console.WriteLine(r1.Length);
What will be the output when this code is executed?
Correct Answer
A. 10
Explanation
The struct is a value rather than a reference type, so both r1 and r2 maintain their own copies of data. So, after the r2 = r1; statement, both r1 and r2 point to different memory locations. When the Length property for r2 object is modified, the change doesn’t affect the object r1.
35.
You are developing a C# application. You need to decide whether to declare a class member as static. Which of the following statements is true about static members of a class?
Correct Answer
D. The static keyword is used to declare members that do not belong to individual objects but to a class itself.
Explanation
The static keyword is used to declare members that do not belong to individual objects but to a class itself. A static member cannot be referenced through an instance object. Instead, a static member is referenced through the class name. It is not possible to use the this keyword reference with a static method or property because the this keyword can be used only to access instance objects.
36.
Suppose that you are a new C# developer and are reviewing object-oriented programming fundamentals. Which of the following statements is not true?
Correct Answer
A. A class is a concrete instance of an object.
Explanation
A class is not a concrete instance of an object. Instead, an object is a concrete instance of a class. The facts in the other answer choices are all correct.
37.
You are C# developer who is developing a Windows application. You develop a new class that must be accessible to all the code packaged in the same assembly. Even the classes that are in the same assembly but do not directly or indirectly inherit from this class must be able to access the code. Any code outside the assembly should not be able to access the new class. Which access modifier should you use to declare the new class?
Correct Answer
D. Internal
Explanation
For the private access modifier, access is restricted only to the containing class.
For the public access modifier, access is not restricted.
For the protected access modifier, access is restricted only to the derived classes.
For the internal access modifier, access is restricted only to the code in the same assembly.
38.
You are C# developer who is developing a Windows application.
You need to provide a common definition of a base class that can be shared by multiple derived classes.
Which keyword should you use to declare the new class?
Correct Answer
D. Abstract
Explanation
The abstract classes provide a common definition of a base class that can be shared by multiple derived classes.
The sealed classes, on the other hand, provide complete functionality but cannot be used as base classes.
The virtual and interface keywords cannot be applied to a class.
39.
You are C# developer who is developing a Windows application. You write the following code:
Object o;
Later in the code, you need to assign the value in the variable o to an object of Rectangle type. You expect that at runtime the value in the variable o is compatible with the Rectangle class. However, you need to make sure that no exceptions are raised when the value is assigned. Which of the following code should you use?
Correct Answer
C. Rectangle r = o as Rectangle;
Explanation
In case of simple cast operation, the runtime checks whether the value of the variable o is compatible with the Rectangle class.
If, at execution time, the value of o is not compatible with the Rectangle class, the runtime throws a System.InvalidCastException.
The as operator is similar to the cast operation but, in the case of as, if the type conversion is not possible, null is returned rather than an exception raised.
40.
You are C# developer who is developing a Windows application. You need to provide derived classes the ability to share common functionality with base classes but still define their own unique behavior. Which object-oriented programming concept should you use to accomplish this functionality?
Correct Answer
C. PolymorpHism
Explanation
Polymorphism is the ability of derived classes to share common functionality with base classes but still define their own unique behavior.
Inheritance is a feature of object-oriented programming that allows you to develop a class once, and then reuse that code over and over as the basis of new classes.