12
PES INSTITUTE OF TECHNOLOGY (BSC) V MCA, First IA Test, August 2014 Topics in Enterprise Architectures-II Solution Set Faculty: Jeny Jijo 1. Give an anatomy of C# console application program and discuss the variations of main method [10] an anatomy of C# console application program using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleCSharpApp { class Program { static void Main(string[] args) { } } } Given this, update the Main() method of your Program class with the following code statements: class Program { static void Main(string[] args) { // Display a simple message to the user. Console.WriteLine("***** My First C# App *****"); Console.WriteLine("Hello World!"); Console.WriteLine(); // Wait for Enter key to be pressed before shutting down. Console.ReadLine(); } } Here we have a definition for a class type that supports a single method named Main(). By default, Visual Studio 2010 names the class defining Main() Program; however, you are free to change this if you so choose. Every executable C# application (console program, Windows desktop program, or Windows service) must contain a class defining a Main() method, which is used to signify the entry point of the application.

PES INSTITUTE OF TECHNOLOGY (BSC) V MCA, First IA … · The Common Language Specification, ... include the using System.Text directive for creating and manipulating ... using static

Embed Size (px)

Citation preview

PES INSTITUTE OF TECHNOLOGY (BSC)

V MCA, First IA Test, August 2014

Topics in Enterprise Architectures-II

Solution Set

Faculty: Jeny Jijo

1. Give an anatomy of C# console application program and discuss the variations of

main method [10] an anatomy of C# console application program

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace SimpleCSharpApp

{

class Program

{

static void Main(string[] args)

{

}

}

}

Given this, update the Main() method of your Program class with the following code

statements:

class Program

{

static void Main(string[] args)

{

// Display a simple message to the user.

Console.WriteLine("***** My First C# App *****");

Console.WriteLine("Hello World!");

Console.WriteLine();

// Wait for Enter key to be pressed before shutting down.

Console.ReadLine();

}

}

Here we have a definition for a class type that supports a single method named Main(). By

default,

Visual Studio 2010 names the class defining Main() Program; however, you are free to

change this if you

so choose. Every executable C# application (console program, Windows desktop program, or

Windows

service) must contain a class defining a Main() method, which is used to signify the entry

point of the

application.

Formally speaking, the class that defines the Main() method is termed the application object.

While

it is possible for a single executable application to have more than one application object

(which can be

useful when performing unit tests), you must inform the compiler which Main() method

should be used

as the entry point via the /main option of the command-line compiler.Note that the signature

of Main() is adorned with the static keyword, which means that static members are scoped to

the classlevel (rather than the object level) and can thus be invoked without the need to first

create a new class instance.

Variations on the Main() Method

By default, Visual Studio 2010 will generate a Main() method that has a void return value

and an array of

string types as the single input parameter. This is not the only possible form of Main(),

however. It is

permissible to construct your application’s entry point using any of the following signatures

(assuming it

is contained within a C# class or structure definition):

// int return type, array of strings as the parameter.

static int Main(string[] args)

{

// Must return a value before exiting!

return 0;

}

// No return type, no parameters.

static void Main()

{

}

// int return type, no parameters.

static int Main()

{

// Must return a value before exiting!

return 0;

}

Obviously, your choice of how to construct Main() will be based on two questions. First, do

you want

to return a value to the system when Main() has completed and your program terminates? If

so, you need

to return an int data type rather than void. Second, do you need to process any user-supplied,

command-line parameters? If so, they will be stored in the array of strings.

2. Explain the different methods that process command line arguments with suitable

program code? [10] Processing Command-Line Arguments

1) Now that you better understand the return value of the Main() method, let’s examine the

incoming array

of string data. Assume that you now wish to update your application to process any possible

commandline

parameters. One way to do so is using a C# for loop. (Note that C#’s iteration constructs will be

examined in some detail near the end of this chapter.)

static int Main(string[] args)

{

...

// Process any incoming args.

for(int i = 0; i < args.Length; i++)

Console.WriteLine("Arg: {0}", args[i]);

Console.ReadLine();

return -1;

}

2) As an alternative to the standard for loop, you may iterate over an incoming string array using

the

C# foreach keyword. Here is some sample usage.

// Notice you have no need to check the size of the array when using "foreach".

static int Main(string[] args)

{

...

// Process any incoming args using foreach.

foreach(string arg in args)

Console.WriteLine("Arg: {0}", arg);

Console.ReadLine();

return -1;

}

3) Finally, you are also able to access command-line arguments using the static

GetCommandLineArgs()

method of the System.Environment type. The return value of this method is an array of

strings. The first

index identifies the name of the application itself, while the remaining elements in the array

contain the

individual command-line arguments. Note that when using this approach, it is no longer

necessary to

define Main() as taking a string array as the input parameter, although there is no harm in

doing so.

static int Main(string[] args)

{

...

// Get arguments using System.Environment.

string[] theArgs = Environment.GetCommandLineArgs();

foreach(string arg in theArgs)

Console.WriteLine("Arg: {0}", arg);

Console.ReadLine();

return -1;

}

3 Explain the basic building blocks of .NET platform along with the role of Base

class Libraries [10]

The three key (and interrelated)entities that make it all possible in dot net framework are:

the CLR, CTS, and CLS.

From a programmer’s point of view, .NET can be understood as a runtime environment and

a comprehensive base class library. The runtime layer is properly referred to as the Common

Language Runtime, or CLR. The primary role of the CLR is to locate, load, and manage .NET

types on your behalf. The CLR also takes care of a number of low-level details

such as memory management, application hosting, handling threads, and performing various

security checks.

Another building block of the .NET platform is the Common Type System, or CTS. The CTS

specification fully describes all possible data types and programming constructs supported by

the

runtime, specifies how these entities can interact with each other, and details how they are

represented

in the .NET metadata format.

Understand that a given .NET-aware language might not support each and every feature

defined by

the CTS. The Common Language Specification, or CLS, is a related specification that defines

a subset of

common types and programming constructs that all .NET programming languages can agree

on. Thus, if

you build .NET types that only expose CLS-compliant features, you can rest assured that all

.NET-aware languages can consume them. Conversely, if you make use of a data type or

programming construct that is outside of the bounds of the CLS, you cannot guarantee that

every .NET programming language can interact with your .NET code library.

The Role of the Base Class Libraries

In addition to the CLR and CTS/CLS specifications, the .NET platform provides a base class

library that is

available to all .NET programming languages. Not only does this base class library

encapsulate various

primitives such as threads, file input/output (I/O), graphical rendering systems, and

interaction with

various external hardware devices, but it also provides support for a number of services

required by

most real-world applications.

For example, the base class libraries define types that facilitate database access, manipulation

of

XML documents, programmatic security, and the construction of web-enabled as well as

traditional

desktop and console-based front ends. From a high level, you can visualize the relationship

between the

CLR, CTS, CLS, and the base class library, as shown in Fig

Refer the diagram Figure 1-1. The CLR, CTS, CLS, and base class library relationship

in pg 4 of Andrew Troelson Book

4. (a) Explain boxing and Unboxing. Illustrate with a program [05]

C# Type System contains three Types , they are Value Types , Reference Types and Pointer

Types. C# allows us to convert a Value Type to a Reference Type, and back again to Value

Types . The operation of Converting a Value Type to a Reference Type is called Boxing and the

reverse operation is called Unboxing.

Boxing

1: int Val = 1;

2: Object Obj = Val; //Boxing

The first line we created a Value Type Val and assigned a value to Val. The second line , we

created an instance of Object Obj and assign the value of Val to Obj. From the above operation

(Object Obj = i ) we saw converting a value of a Value Type into a value of a corresponding

Reference Type . These types of operation is called Boxing.

UnBoxing

1: int Val = 1;

2: Object Obj = Val; //Boxing

3: int i = (int)Obj; //Unboxing

The first two line shows how to Box a Value Type . The next line (int i = (int) Obj) shows

extracts the Value Type from the Object . That is converting a value of a Reference Type into a

value of a Value Type. This operation is called UnBoxing.

Boxing and UnBoxing are computationally expensive processes. When a value type is boxed, an

entirely new object must be allocated and constructed , also the cast required for UnBoxing is

also expensive computationally.

using System;

namespace prg4

{

class Program

{

static void Main(string[] args)

{

int a = 100;

object o = (object)a;

a = 200;

Console.WriteLine("The value of a:" + a);

Console.WriteLine("The value of o:" + o);

int b = (int)o;

o = 300;

Console.WriteLine("The value of o:" + o);

Console.WriteLine("The value of b:" + b);

Console.ReadLine();

}

}

}

(b) Explain StringBuilder Class with the help of a program [05]

StringBuilder Class

- Mutable: modify a string without creating a new object.

String builder s1=new StringBuilder(“abc”);

String builder s1=new StringBuilder();

- Mutable strings are also known as dynamic strings

- The System.Text namespace contains the StringBuilder class , so we must

include the using System.Text directive for creating and manipulating mutable

strings

- Dynamic object that allows you to expand the number of characters in the string that

it encapsulates, you can specify a value for the maximum number of characters that it

can hold.

Default capacity of a StringBuilder is 16.

StringBuilder Constructor:

1) StringBuilder s=new StringBuilder();

Default capacity of a StringBuilder is 16. The buffer will be resized if more

characters are added.

2) StringBuilder s=new StringBuilder(100);

If the number of characters to be stored in the current instance exceeds this capacity

value, the StringBuilder object allocates additional memory to store them.

3) StringBuilder s=new StringBuilder(“This is test message”);

Console.WriteLine(“{0}”,s.capacity)

using System;

using System.Text;

class Sample

{

public static void Main()

{

StringBuilder sb1 = new StringBuilder("abc");

StringBuilder sb2 = new StringBuilder("abc", 16);

Console.WriteLine(“{0},{1}", sb1.Length, sb1.Capacity);

Console.WriteLine(“{0},{1}", sb2.Length, sb2.Capacity);

sb1.EnsureCapacity(50);

Console.WriteLine(“{0},{1}", sb1.Length, sb1.Capacity);

sb1.Length = 0; sb2.Capacity = 51;

Console.WriteLine(“{0}, {1}", sb1.Length, sb1.Capacity);

Console.WriteLine(“{0}, {1}", sb2.Length, sb2.Capacity); } }

5) What are static methods and static variable? Explain the different ways of

using static keywords in C# with an example of each [10]

A C# class may define any number of static members using the static keyword. When you do

so, the

member in question must be invoked directly from the class level, rather than from an object

reference.

To illustrate the distinction, consider your good friend System.Console. As you have seen,

you do not

invoke the WriteLine() method from the object level:

// Error! WriteLine() is not an object level method!

Console c = new Console();

c.WriteLine("I can't be printed...");

but instead simply prefix the class name to the static WriteLine() member:

// Correct! WriteLine() is a static method.

Console.WriteLine("Thanks...");

Defining Static Methods

Assume you have a new Console Application project named StaticMethods and have inserted

a class

named Teenager that defines a static method named Complain(). This method returns a

random string,

obtained in part by calling a static helper function named GetRandomNumber():

class Teenager

{

public static Random r = new Random();

public static int GetRandomNumber(short upperLimit)

{

return r.Next(upperLimit);

}

public static string Complain()

{

string[] messages = {"Do I have to?", "He started it!",

"I'm too tired...", "I hate school!",

"You are sooooooo wrong!"};

return messages[GetRandomNumber(5)];

}

}

Notice that the System.Random member variable and the GetRandomNumber() helper

function method

have also been declared as static members of the Teenager class, given the rule that static

members such

as the Complain() method can operate only on other static members.

■Like any static member, to call Complain(), prefix the name of the defining class:

static void Main(string[] args)

{

Console.WriteLine("***** Fun with Static Methods *****\n");

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

Console.WriteLine(Teenager.Complain());

Console.ReadLine();

}

Defining Static Field Data

In addition to static methods, a class (or structure) may also define static field data such as the

Random

member variable seen in the previous Teenager class. Understand that when a class defines

nonstatic

data (properly referred to as instance data), each object of this type maintains an independent

copy of

the field. For example, assume a class that models a savings account is defined in a new

Console

Application project named StaticData

// A simple savings account class.

class SavingsAccount

{

public double currBalance;

public SavingsAccount(double balance)

{

currBalance = balance;

}

}

When you create SavingsAccount objects, memory for the currBalance field is allocated for

each

object. Static data, on the other hand, is allocated once and shared among all objects of the

same class

category. To illustrate the usefulness of static data, add a static point of data named

currInterestRate to

the SavingsAccount class, which is set to a default value of 0.04:

// A simple savings account class.

class SavingsAccount

{

public double currBalance;

// A static point of data.

public static double currInterestRate = 0.04;

public SavingsAccount(double balance)

{

currBalance = balance;

}

}

If you were to create three instances of SavingsAccount in Main() as follows:

static void Main(string[] args)

{

Console.WriteLine("***** Fun with Static Data *****\n");

SavingsAccount s1 = new SavingsAccount(50);

SavingsAccount s2 = new SavingsAccount(100);

SavingsAccount s3 = new SavingsAccount(10000.75);

Console.ReadLine();

}

6) List and explain method access modifiers and method parameter modifiers [10] Method access modifiers are(explain )

1) Public

2) Private(default)

3) Protected

4) Internal

5) Protected Internal

C# Parameter Modifiers

Parameter Modifier Meaning in Life

(None) If a parameter is not marked with a parameter modifier, it is assumed

to be

passed by value, meaning the called method receives a copy of the

original

data.

Out Output parameters must be assigned by the method being called, and

therefore are passed by reference. If the called method fails to assign

output parameters, you are issued a compiler error.

Ref The value is initially assigned by the caller and may be optionally

reassigned by the called method (as the data is also passed by

eference).

No compiler error is generated if the called method fails to assign a ref

parameter.

Params This parameter modifier allows you to send in a variable number of

arguments as a single logical parameter. A method can have only a

single

params modifier, and it must be the final parameter of the method. In

reality, you may not need to use the params modifier all too often,

however be aware that numerous methods within the base class libraries do

makeuse of this C# language feature.

7) What are jagged arrays? Write a program to find the sum of all elements in a

jagged array of 5 inner arrays [10]

Variable-size Array/Jagged Array (Array of arrays (or) inner arrays):

Declaration: byte[][] scores;

byte[][] scores = new byte[5][];

for (int x = 0; x < scores.Length; x++)

{

scores[x] = new byte[4];

}

Initialization of jagged array:

* int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

* int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

* int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

using System;

namespace prg9

{

class Program

{

static void Main(string[] args)

{

int[][][] arr = new int[2][][];

int sum = 0;

arr[0] = new int[2][];

arr[1] = new int[3][];

Console.WriteLine("Enter size");

for (int ot = 0; ot <= 1; ot++)

for (int j = 0; j < arr[ot].Length; j++)

arr[ot][j] = new int[(int.Parse(Console.ReadLine()))];

Console.Write("Enter element:");

for (int ot = 0; ot <= 1; ot++)

for (int i = 0; i < arr[ot].Length; i++)

for (int j = 0; j < arr[ot][i].Length; j++)

arr[ot][i][j] = int.Parse(Console.ReadLine());

for (int ot = 0; ot <= 1; ot++)

{

for (int i = 0; i < arr[ot].Length; i++)

{

for (int j = 0; j < arr[ot][i].Length; j++)

{

Console.Write("\n The given value=" + arr[ot][i][j]);

sum += arr[ot][i][j];

}

}

}

Console.WriteLine("\n\n Sum of jagged array =" + sum);

Console.ReadLine();

}

}

}

8) Write Program in C# to multiply 2 matrices using Rectangular arrays.

[10]

using System;

namespace prg8

{

class mat

{

public static void Main(String[] args)

{

int p = 0, q = 0;

Console.WriteLine("enter the order of 1st matrix");

p = int.Parse(Console.ReadLine());

q = int.Parse(Console.ReadLine());

int[,] matrix1 = new int[p, q];

int r = 0, s = 0;

Console.WriteLine("enter the order of 2nd matrix");

r = int.Parse(Console.ReadLine());

s = int.Parse(Console.ReadLine());

int[,] matrix2;

matrix2 = new int[r, s];

if (q != r)

{

Console.WriteLine(" matrix multiplication not possible");

Console.ReadLine();

Environment.Exit(0);

}

else

Console.WriteLine("enter{0} numbers", (p * q));

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

{

for (int j = 0; j < q; j++)

{

Console.WriteLine("elements[{0},{1}]", i, j);

matrix1[i, j] = int.Parse(Console.ReadLine());

}

}

Console.WriteLine("enter{0} numbers", (r * s));

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

{

for (int j = 0; j < s; j++)

{

Console.WriteLine("elements[{0},{1}]", i, j);

matrix2[i, j] = int.Parse(Console.ReadLine());

}

}

Console.WriteLine("product of two matracis");

int[,] resultmat = new int[p, s];

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

{

for (int j = 0; j < s; j++)

{

resultmat[i, j] = 0;

for (int k = 0; k < r; k++)

resultmat[i, j] += matrix1[i, k] * matrix2[k, j];

}

}

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

{

for (int j = 0; j < s; j++)

{

Console.WriteLine("{0}", resultmat[i, j]);

}

Console.WriteLine(" ");

}

Console.ReadLine();

}

}

}