Professional Documents
Culture Documents
C# Fundamentals
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
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
C# also provides the foreach statement. This statement provides a simple, clean way to iterate
through the elements of an array.
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);
}
}
}
class ForEachLoop
{
static void Main(string[] args)
{
string[] names = {"Ali", "Ahmed", "Maria", "Sara"};
It is also possible to use initializers to fill the array elements with values,For example:
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
class Program
{
// Maximum method uses Math.Max method
You can also initialize and pass a new array in onestep. For example:
PrintArray(new int[] { 1, 3, 5, 7, 9 });
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
Parameter arrays allow a variable number of arguments to be passed to a method, and must be a
single-dimensional array.
Output:
123
45
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());
}
Output: 8
Output: 9
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 );
Classes are declared by using the keyword class followed by the class name and a set of class
members surrounded by curly braces.
class OutputClass
{
string myString;
public OutputClass(string inputString) // Constructor
{
myString = inputString;
}
public void printString()
{
Console.WriteLine("{0}", myString);
}
// Destructor
~OutputClass()
{
// Some resource cleanup routines
}
}
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());
}
}
}
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
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()
{
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.
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.
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.
ComputeCircumference(); Circu
Exercise 3.7
Create a console application where write a program to print the table given below with the help
of: