0% found this document useful (0 votes)
128 views33 pages

Arrays and Method-1

Here are some key properties and functions of the Array class in C#: Properties: - Length - Returns the total number of elements in the array. int length = arr.Length; - Rank - Returns the number of dimensions of the multdimensional array. int rank = arr.Rank; - IsFixedSize - Returns whether the array has a fixed size or not. bool isFixed = arr.IsFixedSize; - IsReadOnly - Returns whether the array is read-only or not. bool isReadOnly = arr.IsReadOnly; Functions: - Sort() - Sorts the elements of the array in ascending order. Array.Sort(arr); - Clear() - Sets all elements of the

Uploaded by

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

Arrays and Method-1

Here are some key properties and functions of the Array class in C#: Properties: - Length - Returns the total number of elements in the array. int length = arr.Length; - Rank - Returns the number of dimensions of the multdimensional array. int rank = arr.Rank; - IsFixedSize - Returns whether the array has a fixed size or not. bool isFixed = arr.IsFixedSize; - IsReadOnly - Returns whether the array is read-only or not. bool isReadOnly = arr.IsReadOnly; Functions: - Sort() - Sorts the elements of the array in ascending order. Array.Sort(arr); - Clear() - Sets all elements of the

Uploaded by

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

Method/ Functions

• A method is a block of code which only runs


when it is called.
• You can pass data, known as parameters, into a
method.
• Methods are used to perform certain actions,
and they are also known as functions.
• Why use methods? To reuse code: define the
code once, and use it many times.
• A method is defined with the name of the
method, followed by parentheses 
class Program
{ static void MyMethod()
{ // code to be executed }
}

Example Explained
•MyMethod() is the name of the method
•static means that the method belongs to the Program class and
•not an object of the Program class.
•void means that this method does not have a return value.
Calling a method

static void MyMethod() {


Console.WriteLine("I just got executed!"); }
static void Main(string[] args) {
MyMethod();
}
C# Method Parameters

• Parameters and Arguments


• Information can be passed to methods as
parameter. Parameters act as variables inside
the method.
• They are specified after the method name,
inside the parentheses. You can add as many
parameters as you want, just separate them
with a comma.
static void MyMethod(string fname)
{ Console.WriteLine(fname + " Refsnes"); }
static void Main(string[] args)
{ MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
}
Default Parameter Value

• You can also use a default parameter value, by


using the equals sign (=). If we call the method
without an argument, it uses the default value
("Norway"):
static void MyMethod(string country = "Norway")
{ Console.WriteLine(country);
}
static void Main(string[] args)
{ MyMethod("Sweden");
MyMethod("India");
MyMethod();
MyMethod("USA");
}
Multiple Parameters
static void MyMethod(string fname, int age)
{ Console.WriteLine(fname + " is " + age);
} static void Main(string[] args)
{ MyMethod("Liam", 5);
MyMethod("Jenny", 8);
MyMethod("Anja", 31);
}

static int MyMethod(int x, int y)


{ return x + y; }
static void Main(string[] args)
{ int z = MyMethod(5, 3);
Console.WriteLine(z);
}
C# Method Overloading

• With method overloading, multiple methods


can have the same name with different
parameters:
Example
int MyMethod(int x)
float MyMethod(float x)
double MyMethod(double x, double y)
Overloading an example
static int PlusMethodInt(int x, int y)
{ return x + y;
}
static double PlusMethodDouble(double x, double y)
{ return x + y; }
static void Main(string[] args)
{ int myNum1 = PlusMethodInt(8, 5);
double myNum2 = PlusMethodDouble(4.3, 6.26);
Console.WriteLine("Int: " + myNum1);
Console.WriteLine("Double: " + myNum2); }
We can overload one method for both int and double

static int PlusMethod(int x, int y)


{ return x + y; }
static double PlusMethod(double x, double y)
{ return x + y; }
static void Main(string[] args)
{ int myNum1 = PlusMethod(8, 5);
double myNum2 = PlusMethod(4.3, 6.26);
Console.WriteLine("Int: " + myNum1);
Console.WriteLine("Double: " + myNum2); }
Practical
Arrays
• What is an arrays
• Array is a collection of variable of same data type
• Arrays a kind of data structure that can store a fixed-size
sequential collection of elements of the same type.
• An array is a systematic arrangement of similar objects,
usually in rows and columns.
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
 The value of array is accessed using index position of array
 Always the first index position of arrays is zero
• syntax: data type[] arr = new arr[]
 There is single dimensions arrays and
 Multidimensional arrays and ( n by m) dimension arrays.
Defining arrays
• To declare an array, define the variable type with square brackets:
• string[] cars;
• You can assign values to individual array elements, by using the index
number, like −
• double[] balance = new double[10]; balance[0] = 4500.0;
• You can assign values to the array at the time of declaration, as shown −
• double[] balance = { 2340.0, 4523.69, 3421.0};
• You can also create and initialize an array, as shown −
• int [] marks = new int[5] { 99, 98, 92, 97, 95};
• You may also omit the size of the array, as shown −
• int [] marks = new int[] { 99, 98, 92, 97, 95};
• You can copy an array variable into another target array variable. In such
case, both the target and source point to the same memory location −
• int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks;
• A variable that holds an array of strings.
• string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
• To create an array of integers, you could write:
• int[] myNum = {10, 20, 30, 40};
Accessing Array Elements
• An element is accessed by indexing the array name.
This is done by placing the index of the element within
square brackets after the name of the array.
• For example,
• string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
• Console.WriteLine(cars[0]);
• double salary = balance[9];
• To change the value of a specific element, refer to the
index number:
• string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
• cars[0] = "Opel";
• Console.WriteLine(cars[0]); // Now outputs Opel
instead of Volvo
Loop through Arrays
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.Length; i++)
{ Console.WriteLine(cars[i]);
}

foreach (type variableName in arrayName)


{
// code block to be executed
}

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


foreach (string i in cars)
{ Console.WriteLine(i); }
exaplanation
• The example above can be read like this: for
each string element (called i - as in index)
in cars, print out the value of i.
• If you compare the for loop and foreach loop,
you will see that the foreach method is easier
to write, it does not require a counter (using
the Length property), and it is more readable.
Sorting array
// Sort a string
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Array.Sort(cars);
foreach (string i in cars)
{ Console.WriteLine(i);
}

// Sort an int
int[] myNumbers = {5, 1, 8, 9};
Array.Sort(myNumbers);
foreach (int i in myNumbers)
{ Console.WriteLine(i); }
Others utility of Array

using System;
using System.Linq;
namespace MyApplication
{ class Program
{ static void Main(string[] args)
{ int[] myNumbers = {5, 1, 8, 9};
Console.WriteLine(myNumbers.Max());
// returns the largest value
Console.WriteLine(myNumbers.Min());
// returns the smallest value Console.WriteLine(myNumbers.Sum());
// returns the sum of elements }
}
}
Other Ways to Create an Arrays
// Create an array of four elements, and add values later
string[] cars = new string[4];
// Create an array of four elements and add values right
away
string[] cars = new string[4] {"Volvo", "BMW", "Ford",
"Mazda"};
// Create an array of four elements without specifying the
size
string[] cars = new string[] {"Volvo", "BMW", "Ford",
"Mazda"};
// Create an array of four elements, omitting the new
keyword,
and without specifying the size
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
There are 3 types of arrays in C#
1. Single Dimensional Array:
– To create single dimensional array, you need to use square brackets [] after the
type.

2. Multidimensional Array
– The multidimensional array is also known as rectangular arrays in C#. It can be
two dimensional or three dimensional. The data is stored in tabular form (row *
column) which is also known as matrix.
– To create multidimensional array, we need to use comma inside the square
brackets. For example:
– int[,] arr=new int[3,3];//declaration of 2D array  
– int[,,] arr=new int[3,3,3];//declaration of 3D array

3. Jagged Array
– In C#, jagged array is also known as "array of arrays" because its elements are
arrays. The element size of jagged array can be different.
– Let's see an example to declare jagged array that has two elements.
– int[][] arr = new int[2][];  
Multi dimensional Arrays
Full Class Array program
The Array class is the base class of all the arrays in C sharp programming.
 Array class is defined within the system namespace.
 Array class provides number of predefined functions and properties to work with.
Its function makes array much easier and simpler to work.

Properties Explanation Example


Returns the length of array.
Length int i = arr1.Length;
Returns integer value.
Returns total number of
Rank items in all the dimension. int i = arr1.Rank;
Returns integer value.
Check whether array is
IsFixedSize fixed size or not. Returns bool i = arr.IsFixedSize;
Boolean value
Check whether array is
IsReadOnly ReadOnly or not. Returns bool k = arr1.IsReadOnly;
Boolean value

Q2:Give a clear explanation and example of array properties


Function Explanation Example
Sort Sort an array Array.Sort(arr);
Clear an array by removing
Clear Array.Clear(arr, 0, 3);
all the items
Returns the number of
GetLength arr.GetLength(0);
elements
Returns the value of
GetValue arr.GetValue(2);
specified items
Returns the index position
IndexOf Array.IndexOf(arr,45);
of value
Copy array elements to
Copy Array.Copy(arr1,arr1,3);
another elements

Q2:Give a clear explanation and example of major 5 array functions


Sr.No. Methods & Description
1 Clear
Sets a range of elements in the Array to zero, to false, or
to null, depending on the element type.

2 Copy(Array, Array, Int32)


Copies a range of elements from an Array starting at the
first element and pastes them into another Array
starting at the first element. The length is specified as a
32-bit integer.
3 CopyTo(Array, Int32)
Copies all the elements of the current one-dimensional
Array to the specified one-dimensional Array starting at
the specified destination Array index. The index is
specified as a 32-bit integer.
4 GetLength
Gets a 32-bit integer that represents the number of
Quiz
 Qu2:Write a program to create two multidimensional arrays of
same size. Accept value from user and store them in first array.
Now copy all the elements of first array are second array and
print output.
 Qu2:Write a program to create three multidimensional arrays
of same size. Accept value from user and store them in first
array. Now copy all the elements of first array are second array
and print output.
 Qu1:Write a program to copy one array’s elements to another
array without using array function.
 Qu2:Reverse a string using array.
Hint: accept string value and store in a string variable str. Then
convert str into array as follow:
char[] ch=str.ToCharArray;
Random numbers
• The Random class in C# provides defined methods
that generate random integers. The most widely
used method to generate random integers from
the Random class is Next().
• The Random.Next() method has three overloaded
forms:

• Next(): Returns a random int value within the range -
2,147,483,648 < = value < = 2,147,483,
647−2,147,483,648<=value<=2,147,483,647
• int num = random.Next(); 
Next(int max): Returns a random int value less than max
• // Returns a random integer less than 50
int num = random.Next(50); 
Next(int min, int max): Returns an int in the range min < =
value < maxmin<=value<max
• // Returns an `int` value greater in the range 10 <= value < 50
int num = random.Next(10,50)
class RandomGenerator
{
    static void Main()
    {
      System.Random random = new System.Random(); 
      System.Console.WriteLine(random.Next());
      System.Console.WriteLine(random.Next(50));
      System.Console.WriteLine(random.Next(10,50));
    }
}

You might also like