You are on page 1of 14

Lab 3

C# Fundamentals

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

3.1 Arrays
3.1.1 Multidimensional Arrays
3.1.2 Using foreach Loop with Arrays
3.1.3 Jagged Arrays

3.2 Methods

3.3 Classes

Visual Programming Lab Manual 19


3.1 Arrays
An array is a data structure that contains a number of variables of the same type.
In C# an array has the following properties:

An array can be Single-Dimensional, Multidimensional or Jagged.


Arrays are declared with a type: type [] arrayName;

3.1.1 Multidimensional Arrays

Multi-dimensional array declaration:

For example: declarationcreates a two-dimensional array of four rows and two


columns:
int[,] array = new int[4, 2];

Also, the following declaration creates an array of three dimensions.


int[, ,] array1 = new int[4, 2, 3];

Multi-dimensional array initialization:

You can initialize the array upon declaration as shown below

int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };


int[, ,] array3D = new int[,,] { { { 1, 2, 3} }, { { 4, 5, 6 } } };

If you choose to declare an array variable withoutinitialization you must use the
new operator to assign an array to the variable e.g

int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 }}; //OK
array5={{1,2},{3,4},{5,6},{7,8}}; //Error

3.1.2 Using foreach with Arrays

C# also provides the foreach statement. This statement provides a simple, clean way to iterate
through the elements of an array.

Example 3.1 A: The foreach Loop

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };


foreach (int i in numbers)
{
Console.WriteLine(i);
}

Visual Programming Lab Manual 20


Example 3.1B: The foreach Loop

With multidimensional arrays, you can use the same method to iterate through the elements, for
example:

class ForEachLoop
{
static void Main(string[] args)
{
int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
Console.Write("{0} ", i);
}
}
}

Example 3.1C: The foreach Loop

class ForEachLoop
{
static void Main(string[] args)
{
string[] names = {"Ali", "Ahmed", "Maria", "Sara"};

foreach (string person in names)


{
Console.WriteLine("{0} ", person);
}
}
}

Example 3.1D: The foreach Loop


class ForEachLoop2dImensional
{
static void Main(string[] args)
{
string[,] names = new string [,] { {"Raza","Amir"}, {"Saba","Anita"} };
foreach( string str in names)
{
Console.WriteLine(str);
}
Console.ReadLine();
}
}

Visual Programming Lab Manual 21


3.1.3 Jagged Arrays
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of
different dimensions and sizes. A jagged array is sometimes called an "array of arrays."

int[][] jaggedArray = new int[3][];// Jagged array of 3 elements of single dimension

Initialize the elements like this:


jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4];

It is also possible to use initializers to fill the array elements with values,For example:

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 }; jaggedArray[1] = new int[] { 0, 2, 4, 6 };

Initialize the array upon declaration like this:


int[][] jaggedArray2 = new int[][]
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
A jagged array is an array of arrays, and therefore its elements are reference types and are
initialized to null.

Example 3.2 Using a Jagged Array

class ArrayTest
{
static void Main(string[] args)
{
int[][] arr = new int[2][];
arr[0] = new int[5] { 1, 3, 5, 7, 9 };
arr[1] = new int[4] { 2, 4, 6, 8 };
for (int i = 0; i < arr.Length; i++)
{
Console.Write("Element({0}): ", i);
for (int j = 0; j < arr[i].Length; j++)
{
Console.Wr ;
}
Console.WriteLine();
}
Console.ReadLine();
}}

Output
Element(0): 1 3 5 7 9
Element(1): 2 4 6 8

Visual Programming Lab Manual 22


3.2 Methods
A method helps you separate your code into modules that perform a given task. Its template is:

attributes modifiers return-type method-name(parameters )


{
statements
}

Example 3.3: A Simple Method to find Maximum of 3 Numbers

class Program
{
// Maximum method uses Math.Max method

static double Maximum(double x, double y, double z)


{
return Math.Max(x, Math.Max(y, z));
}
static void Main(string[] args)
{
Console.Write("Enter first floating-point value: ");
double number1 = Double.Parse(Console.ReadLine());
Console.Write("Enter second floating-point value: ");
double number2 = Double.Parse(Console.ReadLine());
Console.Write("Enter third floating-point value: ");
double number3 = Double.Parse(Console.ReadLine());
double max = Maximum(number1, number2, number3);
Console.WriteLine("\nMaximum is: " + max);
Console.ReadLine();
}
}

3.2.1 Passing Arrays as Parameters

You can pass an initialized single-dimensional arrayto a method.


For example: PrintArray(theArray);

The method called in the line above could be defined as:


void PrintArray(int[] arr)
{// method code }

You can also initialize and pass a new array in onestep. For example:
PrintArray(new int[] { 1, 3, 5, 7, 9 });

Visual Programming Lab Manual 23


Example 3.4

In the following example, a string array is initialized and passed as a parameter to the PrintArray
method, where its elements are displayed:

class ArrayClass
{
static void PrintArray(string[] arr)
{
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i]);
Console.WriteLine();
}
static void Main(string[] args)
{
string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
PrintArray(weekDays);
}
}

Output:
Sun Mon Tue Wed Thu Fri Sat

Example 3.5 Parameter Arrays

Parameter arrays allow a variable number of arguments to be passed to a method, and must be a
single-dimensional array.

void ShowNumbers (params int [] numbers)


{
foreach (int x in numbers)
Console.Write (x + " ");
Console.WriteLine();
}

static void Main (string[] args)


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

Output:
123
45

Visual Programming Lab Manual 24


Example 3.6: Generating and displaying random numbers in a windows form application.

class Program
{
static int[] genRandom (int[] arr)
{
Random r = new Random();
for (int i = 0; i < 20; i++)
{
arr[i] = r.Next(1, 100);//giving range between 1 and 100
}
return arr;
}
static void Display(int[] arr)
{
string output = " ";
for (int i = 0; i < 20; i++)
{
if (i % 5 != 0)//want to print on a newline after 5 numbers have been printed
output += arr[i] + ",";
else
output += "\n";
}
MessageBox.Show(output.ToString());
}

static void Main()


{
int[] number = new int[20];
number=genRandom(number);
Display(number);
}
}

Example 3.7: Function call without using ref Keyword

static void add( int p ) {++p;}


static void Main (string[] args)
{
int x = 8;
add( x ); // a copy of x is made
Console.WriteLine( x );
}

Output: 8

Visual Programming Lab Manual 25


Example 3.8: Function call with using ref Keyword

static void add( ref int p ) {++p;}


static void Main (string[] args)
{
int x = 8;
add( ref x ); // x is ref
Console.WriteLine( x );
}

Output: 9

Example 3.9: Swapping strings using reference Keyword

static void SwapStrings (ref string s1, ref string s2)


// Any changes on parameters will affect the original variables.
{
string temp = s1;
s1 = s2;
s2 = temp;
Console.WriteLine("Inside method: {0} {1}", s1, s2);
}
static void Main(string[] args)
{

Console.WriteLine("Inside Main, before swapping: {0} {1}", str1, str2);


// Passing strings by reference
SwapStrings (ref str1, ref str2);
Console.WriteLine("Inside Main, after swapping: {0} {1}", str1, str2);
}

Example 3.10: Function call with using out Keyword

static void Split( int timeLate, out int days, out int hours, out minutes )
{
days = timeLate / 10000;
hours = (timeLate / 100) % 100;
minutes = timeLate % 100;
}
static void Main (string[] args)
{
int d, h, m;
Split( 12345, out d, out h, out m );

Visual Programming Lab Manual 26


3.4 Classes

Classes are declared by using the keyword class followed by the class name and a set of class
members surrounded by curly braces.

Example 3.11: A Simple C# Class

class OutputClass
{
string myString;
public OutputClass(string inputString) // Constructor
{
myString = inputString;
}
public void printString()
{
Console.WriteLine("{0}", myString);
}
// Destructor
~OutputClass()
{
// Some resource cleanup routines
}
}

class ExampleClass // Program start class


{// Main begins program execution
public static void Main(string[] args)
{
// Instance of OutputClass
OutputClass outCl = new OutputClass("This is printed by the output class.");
// Call Output class' method
outCl.printString();
}
}

Type Member Access Modifiers

Access Modifier Description (who can access)


Private Only members within the same type. (default for type members)
Protected Only derived types.
Internal Only code within the same assembly. Can also be code external to object
as long as it is in the same assembly. (default for types)
protected internal Either code from derived type or code in the same assembly. Combination
of protected OR internal.
Public Any code. No inheritance, external type, or external assembly restrictions.

Visual Programming Lab Manual 27


Example 3.12 Declaring a Method with a public Access Modifier
//Windows Form Application

namespace publicAccessModifierLab3
{
class BankAccountPublic
{
public decimal GetAmount()
{
return 1000.00m;
}
}

class Program
{
static void Main(string[] args)
{
BankAccountPublic bankAcctPub = new BankAccountPublic();
// call a public method
decimal amount = bankAcctPub.GetAmount();
MessageBox.Show("amount is"+"="+amount.ToString());
}
}
}

Visual Programming Lab Manual 28


Example 3.13: The TIME Class

Create a Windows Form application consisting of the Time Class. The state of a time object can
be represented by:
hour, minute, second: integers
We might define the following methods:
aTime1 constructor, to set up the object
aSetTime method, to set time
aToUniversalString method, to convert the time to a string representing the time in 24
hour format
aToStandardString method, to convert the time to a string representing the time in 12
hour format

// Class Time1 maintains time in 24-hour format.


public class Time1
{
private int hour; // 0-23
private int minute; // 0-59
private int second; // 0-59
// Time1 constructor initializes instance variables to zero to set default time to midnight

public Time1()
{
SetTime( 0, 0, 0 );
}

// Set new time value in 24-hour format. Perform validity checks on the data.
public void SetTime( int hourValue, int minuteValue, int secondValue )
{
hour = ( hourValue >= 0 && hourValue < 24 ) ? hourValue : 0;
minute = ( minuteValue >= 0 && minuteValue < 60 ) ? minuteValue : 0;
second = ( secondValue >= 0 && secondValue < 60 ) ? secondValue : 0;
}
// convert time to universal-time (24 hour) format string
public string ToUniversalString()
{
e, second );
}
// convert time to standard-time (12 hour) format string
public string ToStandardString()
{

( ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ),


minute, second, ( hour < 12 ? "AM" : "PM" ) );
}
} // end class Time1

Visual Programming Lab Manual 29


// TimeTest1 uses creates and uses a Time1 object
class TimeTest1 //class Program renamed to TimeTest1
{
static void Main( string[] args )
{
Time1 timeObj1 = new Time1();
string output;
// assign string representation of time to output
output = "Initial universal time is: " + timeObj1.ToUniversalString() +
"\nInitial standard time is: " + timeObj1.ToStandardString();
// attempt valid time settings
timeObj1.SetTime( 13, 27, 6 ); output += "\n\nAfter attempting invalid settings: " +
"\nUniversal time: " + timeObj1.ToUniversalString() +
"\nStandard time: " + timeObj1.ToStandardString();

// append new string representations of time to output


output += "\n\nUniversal time after SetTime is: " +
timeObj1.ToUniversalString() +
"\nStandard time after SetTime is: " +
timeObj1.ToStandardString();
// attempt invalid time settings
timeObj1.SetTime( 99, 99, 99 );
timeObj1.ToStandardString();
MessageBox.Show( output, "Testing Class Time1" );

} // end method Main


} // end class TimeTest1

Visual Programming Lab Manual 30


Lab Exercise # 3
Exercise 3.1
Create a Console application in which you input 10 numbers from the user and save them in an
array, and then print the odd numbers and even numbers in a form of a table.

ODD EVEN
1 2
3 4
5 6
7 8
9 10
Exercise 3.2
Create a Console application, in which user enters a string and the program finds out if that string
is a palindrome or not.

(a palindrome starts and ends with the same letter)

Exercise 3.3
Create a console application in which you
a) Input student s names, enrollment number and their marks. Store them in separate arrays.
b) Display the name of the student with highest marks and lowest marks with the help of a
function
Hint: Create two functions one for highest marks and one for lowest marks

Exercise 3.4
Create a console application in which you store numbers in an array using Random Function,
and Sort them using Bubble sort with the help of a function.

[Hint] Random r=new Random();


int number=r.next(1,100); //giving range between 1 to 100

Exercise 3.5
Create a console application in which you sum up two arrays in a third array and display the
array with the help of a function. Take the values of the both arrays from the user.

[Hint] Create a function void AddArray(int[] arr1,int[] arr2) which takes two arrays as input
and saves the result in a third array then displays it. e.g. int[] theArray = { 1, 3, 5, 7, 9 };
PrintArray(theArray);

Exercise 3.6
Write a program to calculate the area and circumference of a circle with the help of a class. Take
the radius of the circle from the user.

Visual Programming Lab Manual 31


Class Circle
2

ComputeCircumference(); Circu

Exercise 3.7
Create a console application where write a program to print the table given below with the help
of:

a) 2-Dimensional arrays e.g string[,] arr = new string[3,3];


b) Jagged Arrays e.g string[][] arr = new string[3][]{};

Times in seconds Real-World-Location Predicted Location


0 1.3 miles -
1 1.5 miles -

Visual Programming Lab Manual 32

You might also like