0% found this document useful (0 votes)
12 views

C# unit1solvedQB

I'm notesb. Dkksieiew. Smsksk

Uploaded by

akshayamith887
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

C# unit1solvedQB

I'm notesb. Dkksieiew. Smsksk

Uploaded by

akshayamith887
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT I

Two Mark Questions

1. What are web browser and web server?

A web browser is application software for accessing websites. When a user requests a web page from a
particular website, the browser retrieves its files from a web server and then displays the page on the user's
screen. Browsers are used on a range of devices, including desktops, laptops, tablets, and smartphones. Ex:
chrome,firefox,opera,IE
A web server is software and hardware that uses HTTP (Hypertext Transfer Protocol) and other protocols to
respond to client requests made over the World Wide Web. The main job of a web server is to display
website content through storing, processing and delivering webpages to users.

2. What is web pages?


Web Pages: A webpage is a digital document that is linked to the World Wide Web and viewable by anyone
connected to the internet has a web browser.
3. What are the Frontend Languages?
The front end is the part of the website users can see and interact with such as the graphical user interface
(GUI)
• HTML: HTML stands for Hypertext Markup Language. It is used to design the front-end portion of web
pages using a markup language.
• CSS: Cascading Style Sheets fondly referred to as CSS is a simply designed language intended to simplify
the process of making web pages presentable.
• JavaScript: JavaScript is a famous scripting language used to create magic on the sites to make the site
interactive for the user.
• AJAX: Ajax is an acronym for Asynchronous Javascript and XML. It is used to communicate with the
server without refreshing the web page and thus increasing the user experience and better performance.

4. What are the Backend Languages?


The backend is the server side of the website. It stores and arranges data, and also makes sure everything
on the client side of the website works fine.
• PHP: PHP is a server-side scripting language designed specifically for web development. Since PHP code
executed on the server-side, so it is called a server-side scripting language.
• Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code
outside a browser.
• Python: Python is a programming language that lets you work quickly and integrate systems more
efficiently.
• Ruby: Ruby is a dynamic, reflective, object-oriented, general-purpose programming language.
• Java: Java is one of the most popular and widely used programming languages and platforms. It is highly
scalable. Java components are easily available.
• JavaScript: JavaScript can be used as both (front end and back end) programming.
• Golang: Golang is a procedural and statically typed programming language having the syntax similar to C
programming language. Sometimes it is termed as Go Programming Language.
• C# :C# is a general-purpose, modern and object-oriented programming language pronounced as “C sharp”.
• DBMS: The software which is used to manage database is called Database Management System (DBMS).

5. What is HTML?
HTML stands for Hypertext Markup Language. It is used to design the front-end portion of web pages using
a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the
Page 1 of 31
link between the web pages. The markup language is used to define the text documentation within the tag
which defines the structure of web pages.
6. What is an HTML Element?
An HTML element is defined by a start tag, some content, and an end tag: Content goes here... The HTML
element is everything from the start tag to the end tag:

7. List the two types of tags in HTML


There are two types of tags in HTML that are:
1. Paired Tags (Opening and Closing Tags)
2. Unpaired Tags (Singular Tag)

8. Write a note on HTML Heading tags

Page 2 of 31
9. Write a note on HTML DIV tag.
The div tag is known as Division tag. The div tag is used in HTML to make divisions of content in the
web page like (text, images, header, footer, navigation bar, etc). Div tag has both open(<div>) and closing
(</div>) tag and it is mandatory to close the tag.
The Div is the most usable tag in web development because it helps us to separate out data in the web
page and we can create a particular section for particular data or function in the web pages.
• Div tag is Block level tag
• It is a generic container tag
• It is used to the group of various tags of HTML so that sections can be created and style can be applied
to them.
As we know Div tag is block-level tag in this example div tag contain entire width. It will be displayed div
tag each time on a new line, not on the same line.
<html>
<head>
<title>gfg</title>
<style type=text/css>

div
{
color: white;
background-color: 009900;
margin: 2px;
font-size: 25px;
}
</style>

</head>

<body>
<div > div tag </div>
<div > div tag </div>
<div > div tag </div>
<div > div tag </div>

Page 3 of 31
</body>
</html>

10. What are HTML Table – Rowspan and – Colspan


The rowspan and colspan are the attributes of <td> tag. These are used to specify the number of rows or
columns a cell should merge. The rowspan attribute is for merging rows and the colspan attribute is for
merging columns of the table in HTML.
These attributes should be placed inside the <td> tag as shown in the image given below

11. Write a note on HTML <a> Tag

Page 4 of 31
12. Write a note on HTML <img> Tag

13. Write a note on HTML Form Tag


<form> is a HTML element to collect input data with containing interactive controls. It provides facilities
to input text, number, values, email, password, and control fields such as checkboxes, radio buttons,
submit buttons, etc., or in other words, form is a container that contains input elements like text, email,
number, radio buttons, checkboxes, submit buttons, etc. Forms are generally used when you want to
collect data from the user.
<form>
<!--form elements-->
</form>

Page 5 of 31
14. What is Client-Side Scripts ?

Client-side scripting is responsible for interaction within a web page. The client-side scripts are firstly
downloaded at the client-end and then interpreted and executed by the browser
The client-side scripting is browser-dependent. i.e., the client-side browser must be scripting enables in
order to run scripts.
Client-side scripting is used when the client-side interaction is used.
Here are some popular client-side scripting languages VBScript, JavaScript, Hypertext Processor(PHP).
15. What is Server-Side Scripts?
Server-side scripting is responsible for the completion or carrying out a task at the server-end and then
sending the result to the client-end.
Server-side scripting is mainly used when the information is sent to a server and to be processed at the
server-end. Some sample uses of server-scripting can be :
• Password Protection. • Browser Customization (sending information as per the requirements of client-end
browser) • Form Processing

16. How do you write comments in C#?

Comments are used in a program to help us understand a piece of code.

Single Line Comments

Single line comments start with a double slash //. The compiler ignores everything after // to the end of the
line. For example,

int a = 5 + 7; // Adding 5 and 7

Multi Line Comments

Multi line comments start with /* and ends with */. Multi line comments can span over multiple lines. For
example,

Page 6 of 31
/*

This is a Hello World Program in C#.

This program prints Hello World.

*/

17. Define literals. List any two literal types used in C#.
The fixed values are called as Literal. Literal is a value that is used by the variables. Values can be either
an integer, float or string, etc.
// Here 100 is a constant/literal.
int x = 100;
Literals can be of the following types:
• Integer Literals
• Floating-point Literals
• Character Literals
• String Literals
• Null Literals
• Boolean Literals
Integer Literals
An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X
for hexadecimal, and there is no prefix id for decimal.
Here are some example of Integer Literals −
20 // int
30u // unsigned int
30l // long
Float Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can
represent floating point literals either in decimal form or exponential form.
Here are some examples of Float Literals −
2.64734
314159E-5F
18. What do you mean by Boxing/Unboxing?

Boxing : means the conversion of a value type on stack to an object type on


heap.The process of Converting a Value Type (char, int etc.) to
a ReferenceType(object) is called Boxing.

Page 7 of 31
Unboxing: process of converting the object type back to the value type.

The process of converting reference type into the value type is known
as Unboxing.

19. Write the syntax of conditional operator used in C# with an example

Syntax:
condition ? statement 1 : statement 2

example
using System;

public class Program


{
public static void Main()
{
int x = 20, y = 10;

var result = x > y ? "x is greater than y" : "x is less than or equal to y";

Console.WriteLine(result);
}
}

Output
x is greater than y

20. Differentiate break and continue statements used in C#?

Both “break” and “continue” are the ‘jump’ statements, that transfer control of the program to another part
of the program.
The main difference between break and continue is that break is used for immediate termination of loop.
On the other hand, ‘continue’ terminate the current iteration and resumes the control to the next iteration of
the loop.

21. List the different types of Method Parameters used.


• Value parameters(pass by value):
• Reference parameters (pass by reference):
• Output parameter .

Page 8 of 31
22. Distinguish between ref and out parameters.

23. List any four method modifiers used .

• Private
• Protected
• Public
• Internal
24. What is variable size array ? Give example.
Variable length arrays are also known as runtime sized or variable sized arrays. The size of such arrays is
defined at run-time. Variably modified types include variable length arrays and pointers to variable length
arrays. Variably changed types must be declared at either block scope or function prototype scope.

25. List any four string methods in C#.


Concat(String, String)
Copy(String)
Equals(String, String)
Compare(String, String)

26. What is enumeration? How it defined in C#?


Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values
to integral constants, that make a program easy to read and maintain.
Page 9 of 31
Enumeration is declared using enum keyword directly inside a namespace, class, or structure.
Syntax:
enum Enum_variable
{
string_1...;
string_2...;
.
.
}
27. Mention two difference between class and structure .
Class Structure

Classes are of reference types. Structs are of value types.

All the reference types are allocated on heap


memory. All the value types are allocated on stack memory.

Class has limitless features. Struct has limited features.

Class is generally used in large programs. Struct are used in small programs.

Classes used new keyword for creating Struct can create an instance, with or without new
instances. keyword.

A Struct is not allowed to inherit from another


A Class can inherit from another class. struct or class.

Long answers questions


1.Explain HTML Text Formatting Tags.
HTML text formatting tags:

1) Bold Text

HTML<b> and <strong> formatting elements


The HTML <b> element is a physical tag which display text in bold font, without any logical importance. If
you write anything within <b>............</b> element, is shown in bold letters.
Example:
<p><b> This isbold text.</b></p>
Page 10 of 31
Output:
This is bold text.
The HTML <strong> tag is a logical tag, which displays the content in bold font and informs the browser
about its logical importance. If you write anything between <strong>???????. </strong>, is shown important
text.
example:
<p><strong>This is an important content</strong>, and this is normal content</p> Output:
This is an important content, and this is normal content

2) Italic Text

HTML <i> and <em> formatting elements


The HTML <i> element is physical element, which display the enclosed content in italic font, without any
added importance. If you write anything within <i>............</i> element, is shown in italic letters.
Example:
<p><i>This is italic text.</i></p>
Output:
This is italic text.
The HTML <em> tag is a logical element, which will display the enclosed content in italic font, with added
semantics importance.
Example:
<p><em>This is an important content</em>, which displayed in italic font.</p>
Output:
This is an important content, which displayed in italic font.
3) HTML Marked formatting
If you want to mark or highlight a text, you should write the content within <mark>.........</mark>.
Example:
<h2> I want to put a <mark> Mark</mark> on your face</h2>
Output:
I want to put a Mark on your face
4) Underlined Text
If you write anything within <u>.........</u> element, is shown in underlined text.
See this example:
<p><u>This is underlined text.</u></p> Output:
This is underlined text.

Page 11 of 31
5) Strike Text
Anything written within <strike>.......................</strike> element is displayed with strikethrough. It is a thin
line which cross the statement.
Example:
<p><strike>Text with strikethrough</strike>.</p>
Output:
Text with strikethrough
6) Superscript Text
If you put the content within <sup>..............</sup> element, is shown in superscript; means it is displayed
half a character's height above the other characters.
Example:
<p>x<sup>2</sup> +y<sup>2</sup></p>
Output:
X +y2
2

7)Subscript Text

If you put the content within <sub>..............</sub> element, is shown in subscript ; means it is displayed
half a character's height below the other characters.

Example:
<p>H<sub>2</sub> O</p>
Output:
H2O
2. Explain HTML Table Tags with an example.
HTML Table

HTML table tag is used to display data in tabular form (row * column). There can be many columns in a
row.
We can create a table to display data in tabular form, using <table> element, with the help of <tr> , <td>,
and <th> elements. In Each table, table row is defined by <tr> tag, table header is defined by <th>, and table
data is defined by <td> tags.
HTML tables are used to manage the layout of the page e.g. header section, navigation bar, body content,
footer section etc. But it is recommended to use div tag over table to manage the layout of the page .
HTML Table Tags

Tag Description
<table> It defines a table.
<tr> It defines a row in a table.
<th> It defines a header cell in a table.
Page 12 of 31
<td> It defines a cell in a table.
<caption> It defines the table caption.
<colgroup> It specifies a group of one or more columns in a table for formatting.
<col> It is used with <colgroup> element to specify column properties for each column.
<tbody> It is used to group the body content in a table.
<thead> It is used to group the header content in a table.
<tfooter> It is used to group the footer content in a table.

Example:
<!DOCTYPE>
<html>
<body>
<table>
<tr><th>First_Name</th><th>Last_Name</th><th>Marks</th></tr>
<tr><td>Sonoo</td><td>Jaiswal</td><td>60</td></tr>
<tr><td>James</td><td>William</td><td>80</td></tr>
<tr><td>Swati</td><td>Sironi</td><td>82</td></tr>
<tr><td>Chetna</td><td>Singh</td><td>72</td></tr>
</table>
</body>
</html>

Output:

3. Explain HTML Lists With an Example.


HTML Lists:
HTML Lists are used to specify lists of information. All lists may contain one or more list elements. There
are three different types of HTML lists:
1. Ordered List or Numbered List (ol)
2. Unordered List or Bulleted List (ul)
3. Description List or Definition List (dl)

HTML Ordered List or Numbered List

In the ordered HTML lists, all the list items are marked with numbers by default. It is known as numbered
list also. The ordered list starts with <ol> tag and the list items start with <li> tag.

Page 13 of 31
<ol>

<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>

</ol>

Output:

1. Aries
2. Bingo
3. Leo
4. Oracle

HTML Unordered List or Bulleted List

In HTML Unordered list, all the list items are marked with bullets. It is also known as bulleted list also. The
Unordered list starts with <ul> tag and list items start with the <li> tag. Example:

<ul>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>

<li>Oracle</li></ul>

Output:
o Aries
o Bingo
o Leo
o Oracle

HTML Description List or Definition List


HTML Description list is also a list style which is supported by HTML and XHTML. It is also known as
definition list where entries are listed like a dictionary or encyclopedia.
The definition list is very appropriate when you want to present glossary, list of terms or other name-value
list.
The HTML definition list contains following three tags:
1. <dl> tag defines the start of the list.
2. <dt> tag defines a term.
3. <dd> tag defines the term definition (description).

Example:
Page 14 of 31
<dl>
<dt>Aries</dt>
<dd>-One of the 12 horoscope sign.</dd>
<dt>Bingo</dt>
<dd>-One of my evening snacks</dd>
<dt>Leo</dt>
<dd>-It is also an one of the 12 horoscope sign.</dd>
<dt>Oracle</dt>
<dd>-It is a
multinational
technology
corporation
Output:
Aries
-One of the 12 horoscope sign.
Bingo
-One of my evening snacks Leo
-It is also an one of the 12 horoscope sign.
Oracle
-It is a multinational technology corporation.

4. Explain HTML <Frame> Tag.


• HTML Frames are used to divide the web browser window into multiple section
• The HTML tag that divides awe browser screen into two or more recognizable unique regions is the
<FRAMESET>….</FRAMESET> tags
• Each unique region is called Frame
The <FRAMESET TAG>
• The splitting of a browser screen into frames is done using <FRAMESET>….</FRAMESET> tags
• To create frames inside <FRAMESET> tag we use <FRAME> tag.(unpaired tag)
• <body> tag is not required.
• Frameset requires one of the following two attributes
• 1.Rows- divide the screen into multiple rows
• 2.Cols- divide the screen into multiple columns
• Example:
• <FRAMESET Rows=“33%,33%,33%”> --
Divides the browser screen into 3 equal horizontal sections
Example:
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset rows = "30%,*"> --Divides the browser screen into 2 rows
<frameset cols = "50%,50%">--split the 1st row into 2 columns

Page 15 of 31
Create Vertical frames:

Page 16 of 31
5.What are the Advantages and Disadvantages of Client Side Scripts.

Advantages of Client-side scripts: • Allow for more interactivity by immediately


responding to users’ actions.
• Execute quickly because they do not require a trip to the server.
• May improve the usability of Web sites for users whose browsers support scripts.
• Can give developers more control over the look and behaviour of their Web widgets.
• Can be substituted with alternatives (for example, HTML) if users’ browsers do not support scripts
• Are reusable and obtainable from many free resources.

Disadvantages
• Not all browsers support scripts, therefore, users might experience errors if no alternatives have been
provided.
• Different browsers and browser versions support scripts differently, thus more quality assurance testing
is required.
• More development time and effort might be required (if the scripts are not already available through
other resources).
• Developers have more control over the look and behaviour of their Web widgets; however, usability
problems can arise if a Web widget looks like a standard control but behaves differently or vice-versa.

6.What are the Advantages and Disadvantages of Server Side Scripts.

Advantages of server-side scripts:


• User can create one template for the entire website
• The site can use a content management system which makes editing simpler.
• Generally quicker to load than client-side scripting
• User is able to include external files to save coding.
• Scripts are hidden from view so it is more secure. Users only see the HTML output.
• User does not need to download plugins like Java or Flash.

Disadvantages:
• Many scripts and content management systems tools require databases in order to store dynamic data.
• It requires the scripting software to be installed on the server.
• The nature of dynamic scripts creates new security concerns, in some cases making it easier for hackers
to gain access to servers exploiting code flaws.

Page 17 of 31
7.Explain the Structure of C# Program .

The Documentation section consists of a set of comments giving the name of the program. Comments must
include:
• Why and what of classes

• How of algorithms

The Directive section will include all those namespaces that contain classes
required by the application. The directive section tells the compiler to look in the
namespace specified for these unresolved classes.

An interface is similar to a class but contains only abstract members. The


interface section is used when we want to implement the concept of multiple
inheritances.

A C# program may contain multiple class definitions. Classes are the primary and
essential elements of a C# program. These classes are used to map the objects of
real-world problems.

Every C# application program requires a Main() method as it is the starting point,


the class containing the Main() is the essential part of the program.
The Main() method creates objects of various classes and establishes
communication between them. At the end of Main(), the program terminates and
control passes back to the operating system.

8. Explain Boxing and Unboxing with Example.

• Boxing and unboxing is an important concept in C#.

Page 18 of 31
• C# Type System contains three data types: Value Types (int, char,
etc), ReferenceTypes (object) and Pointer Types.

• Boxing : means the conversion of a value type on stack to an object type on


heap.

• The process of Converting a Value Type (char, int etc.) to


a ReferenceType(object) is called Boxing.

Example :

• int num = 23; // 23 will assigned to num

• Object Obj = num; // Boxing

Description :

• First declare a value type variable (num), which is integer type and
assigned it with value 23. Now create a references object type (obj) and
applied Explicit operation which results in num value type to be copied and
stored in object reference type object.

Unboxing: process of converting the object type back to the value type.

The process of converting reference type into the value type is known
as Unboxing.

It is explicit conversion process.

int num = 23; // value type is int and assigned value 23

Object Obj = num; // Boxing

int i = (int)Obj; // Unboxing

Description :

• Declaring a value type variable (num), which is integer type and

with integer value 23. Now, create a reference object type (obj).The explicit
operation for boxing create an value type integer i and applied casting
method.

• When unboxing a value, ensure that value type is large enough to hold the
value of the object. Otherwise, the operation may result in runtime error.

When unboxing , we need to use explicit cast. This is because in the case of
unboxing an object could be casted to any type.

Page 19 of 31
9. What are the various forms of If Statements. Explain with example .

Simple IF Statement:

The If….Else Statement:

The If……Else Statement is an extension of the Simple If Statement.The


General Form is

If(boolean expression)

True-block statement (s)

else

False-block statement(s)

Statement-x;

Nesting of If….Else Statements:

Page 20 of 31
The Else If Ladder:

10.Explain the following loops with syntax and example.

i)While ii)do……While iii) For iv) for each

i)While:

Page 21 of 31
• The while loop loops through a block of code as long as a specified
condition is True:

• Syntax

• while (condition) { // code block to be executed }

• int i = 0;

• while (i < 5)

• {

• Console.WriteLine(i);

• i++;

• }

ii) Do……while :

• The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat
the loop as long as the condition is true.

do {

// code block to be executed

while (condition);

The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the
condition is tested:

int i = 0;
do

Console.WriteLine(i);

i++;

Page 22 of 31
while (i < 5);

iii)for:

The ‘for’ loop is Entry Controlled Loop.

Syntax:

For(initialization;test-condition; Increment/decrement)

//code block to be executed

Example:

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

Console.WriteLine(i);

iv)For each:

The foreach statement is similar to the for statement. It enable us to Iterate the
elements in arrays.

Syntax:

Foreach(type variable in expression)

Body of the loop

Example:

int[] X={10,20,30,40};

Foreach(int I in X)

{
Page 23 of 31
Console.Write(“ “ +i);

11.Explain with example how Methods are Declared in C#.

• Methods are declared inside the body of the class.

• Syntax:

<Access Specifier><Return Type><Method Name>(formal-parameterList)

Method Body

Declaration has 5 parts:

 Access Specifier − This determines the visibility of a variable or a method


from another class.

 Return type − A method may return a value. The return type is the data
type of the value the method returns. If the method is not returning any
values, then the return type is void.

 Method name − Method name is a unique identifier and it is case sensitive.


It cannot be same as any other identifier declared in the class.

 Parameter list − Enclosed between parentheses, the parameters are used to


pass and receive data from a method. The parameter list refers to the type,
order, and number of the parameters of a method. Parameters are optional;
that is, a method may contain no parameters.

 Method body − This contains the set of instructions needed to complete


the required activity. Body of the method is Enclosed in {}

Example :

int Product (int x, int y)

return (x*y);

Page 24 of 31
12.What are method Parameters? Explain any Two Types.

• Value parameters(pass by value):

By default methods are passed by value in c#.

When the method is invoked, the value of actual parameters is called to the formal
parameters.

In this mechanism, when a method is called, a new storagelocation is created for


each value parameter.Hence, the changes made to the parameter inside
themethod(formal parameter) have no effect on the argument(actual parameter).

• Reference parameters (pass by reference):

Parameter can be passed to methods by reference using the keyword ‘ref’.

Reference parameter doesn’t create a new storage location.The reference


parameters represent the same memory location as the actual parameters that are
supplied to the method.

• Output parameter .

Output parameter is used to pass result back to the calling function.

Output parameters are similar to reference parameters, except that they transfer
data out of the method rather than into it.

If we want to return more than 1 value from a method we use this.

This is achieved by declaring the parameter with out keyword.

It is similar to ref keyword, output parameter doesn’t create new memory location.
But the main difference between ref and out keyword is that ref needs that the
variable must be initialized before it passed to the method. But out parameter
doesn’t require the variables to be initialized before it passed to the method.

13.What are Parameter Arrays? Explain with example.


We can define methods that can handle variable number of arguments using parameter array.

At times, while declaring a method, you are not sure of the number of arguments
passed as a parameter. C# param arrays (or parameter arrays) come into help at
such times.

Parameter arrays are declared using the keyword params.

Example:
static void display( params int[] X)

Page 25 of 31
{

Console.Write(“ array elements are: “);

foreach( int i in X)

Console.Write(i+ “”);

Static void main()

int []a = { 11,22 33};

display(a);

display();

display(22,33);

Page 26 of 31
14. With example explain declaring and initializing one dimensional and two-

dimensional arrays in C#.

Create an Array

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each
value.

To declare an array, define the variable type with square brackets:

string[] cars;

We have now declared a variable that holds an array of strings.

To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly
braces:

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

or create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

example
using System;

namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
}
}
}
Output
Page 27 of 31
volvo

Two-Dimensional Array Declaration

Here's how we declare a 2D array in C#.

int[ , ] x = new int [2, 3];

Here, x is a two-dimensional array with 2 elements. And, each element is also an array with 3 elements.
Note: The single comma [ , ] represents the array is 2 dimensional.

Two-Dimensional Array initialization

In C#, we can initialize an array during the declaration. For example,

int[ , ] x = { { 1, 2 ,3}, { 3, 4, 5 } };

Here, x is a 2D array with two elements {1, 2, 3} and {3, 4, 5}. We can see that each element of the array is
also an array.
Example

using System;

namespace MultiDArray {
class Program {
static void Main(string[] args) {

//initializing 2D array
int[ , ] numbers = {{2, 3}, {4, 5}};

// access first element from the first row


Console.WriteLine("Element at index [0, 0] : "+numbers[0, 0]);

// access first element from second row


Console.WriteLine("Element at index [1, 0] : "+numbers[1, 0]);
}
}
}

output

Element at index [0, 0] : 2


Element at index [1, 0] : 4

Page 28 of 31
In the above example, we have created a 2D array named numbers with rows {2, 3} and {4, 5}.
Here, we are using the index numbers to access elements of the 2D array.

• numbers[0, 0] - access the first element from the first row (2)
• numbers[1, 0] - access the first element from the second row (4)

15.Explain any three string methods in C# with example.

1. Concat()-The String Concat() method concatenates (joins) strings and returns


them.

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str0 = "Ice";


string str1 = " cream";

// concatenates str0 and str1


string result = String.Concat(str0 + str1);

Console.WriteLine(result);

Console.ReadLine();
}
}
}

// Output: Ice cream

2. Compare()-The Compare() method compares two strings in the alphabetical


order.

The syntax of the string Compare() method is:

String.Compare(string str1, string str2)

Here, Compare() is a method of class String.


he Compare() method takes the following parameters:
• str1 - first string for comparison
• str2 - second string for comparison

Page 29 of 31
The Compare() method returns:
• 0 - if the strings are equal
• positive integer - if the first string comes after the second string in the alphabetical order
• negative integer - if the first string comes before the second string in the alphabetical order
Example

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str1 = "C#";


string str2 = "Programiz";

// compares str1 with str2


// returns -1 because C# comes before Programiz in alphabetical order
int result = String.Compare(str1, str2);

Console.WriteLine(result);

Console.ReadLine();
}
}
}

// Output: -1

3.ToUpper()- The String ToUpper() method converts all characters in the


string to uppercase.

The syntax of the string ToUpper() method is:

ToUpper()

Here, ToUpper() is a method of class String.


The ToUpper() method returns:
• a copy of the string after converting it to uppercase

Example

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
Page 30 of 31
string str = "chocolate";

// converts str to upper case


string result = str.ToUpper();

Console.WriteLine(result);

Console.ReadLine();
}
}
}

// Output: CHOCOLATE

16. With example explain enumeration declaration and initialization


in C#.
An enumeration is a set of named integer constants. An enumerated type is
declared using the enum keyword.

Declaring enum Variable


The general syntax for declaring an enumeration is −
enum <enum_name> {
enumeration list
};
Where,
• The enum_name specifies the enumeration type name.
• The enumeration list is a comma-separated list of identifiers.
Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that
precedes it. By default, the value of the first enumeration symbol is 0. For example −
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

Page 31 of 31

You might also like