0% found this document useful (0 votes)
85 views17 pages

Lab 2 Getting Started With C#: The Objective of This Lab Is To Understand The Following Concepts

Uploaded by

nisrine omri
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)
85 views17 pages

Lab 2 Getting Started With C#: The Objective of This Lab Is To Understand The Following Concepts

Uploaded by

nisrine omri
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/ 17

Lab 2

Getting Started with C#

The objective of this lab is to understand the following concepts:

2.1 C# Data Types


2.1.1 The Boolean Type
2.1.2 Integral Type
2. 1.3 Floating Types
2.1.4 String Types

2.2 Simple I/O


2.2.1Data Input and Conversion
2.2.2 Data Output Formatting

2.3 C# Control Structures


2.3.1 if statement
2.3.2 switch statement
2.3.3 while, do and for loop

Visual Programming Lab Manual 11


2.1 Simple Data Types

The C# simple types consist of the Boolean type and three numeric types - Integrals,
Floating Point, Decimal, and String. The term "Integrals" refers to the classification of types
that include sbyte, byte, short, ushort, int, uint, long, ulong, and char.

2.1.1 The Boolean Type

Boolean types are declared using the keyword, bool. They have two values: true or false,
which are official keywords.

2.1.2 Integral Types

In C#, an integral is a category of types. For anyone confused because the word Integral sounds
like a mathematical term, from the perspective of C# programming, these are actually defined
as Integral types in the C# programming language specification. They are whole numbers,
either signed or unsigned, and the char type. The char type is a Unicode character, as defined
by the Unicode Standard.

The Size and Range of C# Integral types


Type Size (in bits) Range

sbyte 8 -128 to 127

byte 8 0 to 255

short 16 -32768 to 32767

ushort 16 0 to 65535

int 32 -2147483648 to 2147483647

uint 32 0 to 4294967295

long 64 -9223372036854775808 to 9223372036854775807

ulong 64 0 to 18446744073709551615

char 16 0 to 65535

Visual Programming Lab Manual 12


2.1.3 Floating Point and Decimal Types

A C# floating point type is either a float or double. They are used any time you need to
represent a real number, as defined by IEEE 754. Decimal types should be used when
representing financial or money values. Floating point types are used when you need to
perform operations requiring fractional representations.

The Floating Point and Decimal Types with Size, precision and Range
Type Size (in bits) precision Range
float 32 7 digits 1.5 x 10-45 to 3.4 x 1038
double 64 15-16 digits 5.0 x 10-324 to 1.7 x 10308
decimal 128 28-29 decimal 1.0 x 10-28 to 7.9 x 1028
places

2.1.4 The string Type

A string is a string of text characters. You typically create a string with a string literal, enclosed
in quotes: "This is an example of a string."

C# Character Escape Sequences


Escape Sequence Meaning
\' Single Quote
\" Double Quote
\\ Backslash
\0 Null, not the same as the C# null value
\a Bell
\b Backspace
\f form Feed
\n Newline
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab

2.2 Input and Output


C# programs generally use the input/output services provided by the run-time library of the .NET
Framework. The statement, System.Console.WriteLine ("Hello World!"); uses the WriteLine
method, one of the output methods of the Console class in the run-time library. It displays its
string parameter on the standard output stream followed by a new line.

using System;
Console.WriteLine("Hello World!");

Visual Programming Lab Manual 13


2.2.1 Data Input and Conversion

Console.ReadLine() //Used to get a value from the user input


string myString = Console.ReadLine();

int myInt = Int32.Parse( myString ); //Convert from string to the correct data type using
Int32.Parse()
Or
// convert from string to the correct data type using
Convert.ToInt32()
int myInt = Convert.ToInt32( myString );

2.2.2 Data Output and Formatting

Console.WriteLine(variableName) will print the variable. You can use the values of some
variables at some positions of a string:

Example 2.1

string str = "bahria";


string str1="university";
int n = 5;
Console.WriteLine(3+5+n);
Console.WriteLine(3+""+5);
//anything after inverted comma's is taken as a string
Console.WriteLine("annie"+5+8);
Console.WriteLine(3+5+""+7+8);
Console.WriteLine(str+""+str1);
Console.ReadLine();

You can control the output format by using the format specifiers:

Format Description Examples Output


Specifier
C or c Currency $2.50
-2.5); ($2.50)
D or d Decimal 00025
E or e Scientific 2.500000E+0.1
F or f Fixed-point 25.00
25
G or g General 2.5
N or n Number Con 2,500,000.00
X or x Hexadecimal FA

Visual Programming Lab Manual 14


2.3 Control Statements - Selection

2.3.1 The if Statement:

An if statement allows you to take different paths of logic, depending on a given condition.

Example 2.2: If Statement

static void Main(string[] args)


{
int marks = 90;
if (marks >= 87)
{
Console.WriteLine("You scored A Grade");
}
else if (marks < 87 && marks > 75)
{
Console.WriteLine("You scored B+ Grade");
}
else
{
Console.WriteLine("you did not get A or B+ Grade");
}
Console.ReadLine();
}

2.3.2 The switch Statement

Another form of selection statement is the switch statement, which executes a set of logic
depending on the value of a given parameter.

C# Branching Statements

Branching Description
statement
break Leaves the switch block
continue Leaves the switch block, skips remaining logic in enclosing loop, and goes back
to loop condition to determine if loop should be executed again from the
beginning. Works only if switch statement is in a loop.
goto Leaves the switch block and jumps directly to a label of the form
"<labelname>:"
return Leaves the current method.
throw Throws an exception.

Visual Programming Lab Manual 15


2.3.3 The while, do-while and for Loop

Example 2.3: The While Loop

class WhileLoop
{
public static void Main(string[] args)
{
int myInt = 0;
while (myInt < 10)
{
Console.Write("{0} ", myInt);
myInt++;
}
Console.ReadLine();
}
}

The do Loop

A do loop is similar to the while loop, except that it checks its condition at the end of the loop.

Example: 2.4: The Do Loop


using System;
class DoLoop
{
public static void Main(string[] args)
{
string myChoice;
do
{
Console.WriteLine("My Address Book\n");
Console.WriteLine("A - Add New Address");
Console.WriteLine("D - Delete Address");
Console.WriteLine("M - Modify Address");
Console.WriteLine("V - View Addresses");
Console.WriteLine("Q - Quit\n");
Console.WriteLine("Choice (A,D,M,V,or Q): ");

myChoice = Console.ReadLine();// Retrieve the user's choice

switch(myChoice)
{
case "A": case "a":
Console.WriteLine("You wish to add an address.");
break;
case "D": case "d":

Visual Programming Lab Manual 16


Console.WriteLine("You wish to delete an address.");
break;
case "M": case "m":
Console.WriteLine("You wish to modify an address.");
break;
case "V": case "v":
Console.WriteLine("You wish to view the address list.");
break;
case "Q": case "q":
Console.WriteLine("Bye.");
break;
default:
Console.WriteLine("{0} is not a valid choice", myChoice);
break;
}
Console.Write("press Enter key to continue...");
Console.ReadLine();
Console.ReadLine();
} while (myChoice != "Q" && myChoice != "q"); // Keep going until the user wants to quit
}
}

The for Loop

A for loop works like a while loop, except that the syntax of the for loop includes initialization
and condition modification

for(<initializer list>; <boolean expression>; <iterator list>) { <statements> }.

Example 2.5: The For Loop

class ForLoop
{
static void Main(string[] args)
{
for (int i=0; i < 20; i++)
{
if (i == 10)
break;

if (i % 2 == 0) continue;
Console.Write("{0} ", i);
}
Console.ReadLine();
}
}

Visual Programming Lab Manual 17


DEBUGGING IN VISUAL STUDIO

The objective of Debugging is to understand the following concepts:


4.1 Syntax Errors

A syntax error is due to a misuse of the C# language in


your code. C# is case-sensitive and C# has a set of
keywords that you should (must) not use to name your
variable. Both rules are easy to violate if you write your
code using a normal text editor like Notepad.

Fortunately, the built-in Code Editor of Microsoft Visual


Studio makes it extremely easy to be aware of syntax
errors as soon as they occur:

When you start typing code, the IntelliSense starts


building a list of words that match the first characters
and those that include the characters already typed:

If you mistype a word or a keyword, the Code


Editor would indicate the error by underlining the
word. If you place the mouse on it, a message
would display the reason for the error:

If you declare a variable, or once you have declared


a variable, whenever you want to use it, as soon as
you start typing its name, the IntelliSense would
display a list that includes that variable.

4.2 Logic Errors


A logic error occurs when the program (the code) is written fine but the result it produces is not
reliable. With a logic error, the Code Editor does not see anything wrong in the document and
therefore cannot point out a problem. One of the techniques you can use is referred to as
debugging.

Visual Programming Lab Manual 34


4.3 Debugging Fundamentals
A logic error is called a bug. Debugging is the process of examining code to look for bugs or to
identify problems. Debugging is the ability to monitor the behavior of a variable, a class, or its
members throughout a program. Microsoft Visual Studio provides many features to perform
debugging operations.

One of the tools you can use is the Standard toolbar that is equipped with various debugging
buttons:

4.3.1 Starting and Continuing With Debugging

There are different ways you can launch the


debugging process:
On the main menu, you can click Debug -> Start
Debugging
You can press F5

In some cases, you can suspend debugging. When this has happened, to resume debugging:

o On the main menu, you can click Debug -> Continue


o On the Standard toolbar, you can click the Continue button
o You can press F5

4.3.2 Stopping the Debugging

There are various debugging approaches available in Microsoft Visual Studio. Sometimes you
will want to suspend or stop debugging.

To end debugging at any time:

On the main menu, click Debug -> Stop Debugging


On the Standard toolbar, click the Stop Debuggingbutton

4.4 Debugging Statements

4.4.1 Executing One Statement at a Time

Just as done when reading code with your eyes, the most basic way to monitor code is to execute
one line at a time and see the results displayed before your eyes. To support this operation, the
debugger provides what is referred to as stepping into.

To execute code one line at a time, while the file that contains it is displaying:

Visual Programming Lab Manual 35


On the main menu, click Debug -> Step Into
On the Standard toolbar, click the
Step Into button
Press F11

4.4.2 Executing One Method at a Time

The Step Into feature is a good tool to monitor the behavior of variables inside a method.. Instead
of executing one line at a time, the debugger allows you to execute a whole method at a time or
to execute the lines in some methods while skipping the others. To support this, you use a feature
named Step Over.

To step over a method, while debugging:

On the main menu, click Debug -> Step Over


On the Standard toolbar, click the Step Over button
Press F10

4.4.3 Running to a Point

When executing a program, you can specify a section or line where you want the execution to
pause, for any reason you judge necessary.

To execute code up to a certain point

Right-click the line and click Run to Cursor


Click Debug->Run To Cursor

4.5 Break Points


A breakpoint on a line is the code where you want the execution to suspend. You must explicitly
specify that line by creating a breakpoint. You can as well create as many breakpoints as you
want. You can also remove a breakpoint you don't need anymore.

To create a breakpoint, first identify the line of code where you want to add it. Then:

In the left margin corresponding to the line, click


On the main menu, click Debug -> Toggle Breakpoint
Right-click the line, position the mouse on Breakpoint, and click Insert Breakpoint
Click anything on the line and press F9

.After using a breakpoint, you can remove it. To delete a breakpoint:

Click the breakpoint in the margin


Right-click the line that has the breakpoint, position the mouse on Breakpoint, and click
Delete Breakpoint

Visual Programming Lab Manual 36


Click anything on the line that has the breakpoint:
o On the main menu, click Debug -> Toggle Breakpoint
o Press F9 .

4.5.1 Stepping to Breakpoints

You can combine the Step Into and/or the Step Over feature with breakpoints. That is, you can
examine each code line after line until you get to a specific line. This allows you to monitor the
values of variables and see their respective values up to a critical section. To do this, first create
one or more breakpoints, then proceed with steps of your choice.

4.6 The Watch Windows


A Watch window is an investigation window. After breakpoint has been hit, the next thing you
want to do is to investigate the current object and variables values. There are various types of
watch windows like Autos, Local, etc.

For example the code is

4.6.1 Locals

It automatically displays the list of variables within the scope of current methods. If your
debugger currently hits a particular breakpoint and if you open the "Autos" window, it will show
you the current scope object variable along with the value.

Visual Programming Lab Manual 37


4.6.2 Autos

These variables are automatically detect by the VS debugger during the debugging. VisualStudio
determines which objects or variables are important for the current code statement and based on
that, it lists down the "Autos" variable.

4.6.3 Watch Window

Watch windows are used for adding variables as per requirement. It displays variables that you
have added. You can add as many variables as you want into the watch window. To add
variables in the watch window, you need to "Right Click" on variable and then select "Add
To You can also use Drag and Drop to add variables in watch windows or Add Quick
watch by pressing Shift+F9. If you want to delete any variable from watch window, just right
click on that variable and select "Delete Watch". From the debug window, you can also edit the
variable value at run time.

4.6.4 Immediate Window


Immediate window is very much common and a favorite with all developers. It's very much
helpful in debug mode of the application if you want to change the variable values or execute
some statement without impacting your current debugging steps. You can open the Immediate
window from menu Debug>Window>Immediate Window.

Visual Programming Lab Manual 38


4.6.5 Call Stack
If you have multiple method calling or nested calling all over your application and during
debugging, you want to check from where this method has invoked, "Call Stack" comes into
the picture. The Call Stack Window shows that current method call nesting.

Visual Programming Lab Manual 39


Exercise 2.5
Take out the syntax and logical errors from the code given below.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace sep18

class Program

static int Highest(int[] marks)

int highest = marks[0];

for (int k = 1; k < 9; k++)

if (marks[k] > highest)

highest = marks[k];

return highest;

static int Lowest(int[] marks)

int lowest = marks[0];

for ( j = 1; j < 10; j--) {

if (marks[j] < lowest)

lowest = marks[j];

return lowest;

}
static void Main(string[] args)

string[] names = new string[10];

int[] marks = new int[10];

string[] enroll = new string [14];

for ( i = 0; i < 10; i++)

//take input here

Console.WriteLine("Enter your name: ");

names[i] = Console.ReadLine();

Console.WriteLine("Enter your marks: ");

marks[i] = int.Parse(Console.ReadLine());

Console.WriteLine("Enter your enroll:");

enroll[i] = Console.ReadLine();

Console.Clear();

Console.WriteLine("Enroll" + "\t\t" + "name" + "\t" + "marks");

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

Console.WriteLine(enroll[j] + "\t\t" + names[j] + "\t" + marks[j]);

Console.WriteLine("\n");

Console.WriteLine("\n");

int hmarks = 0;

hmarks = highest(marks);

Console.WriteLine("The Highest marks are=" + hmark);

int lmarks = 0;

lmarks = lowest(marks);

Console.WriteLine("The Lowest marks are=" + lmark); } } }

You might also like