Lab9 - Arrays C#

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

LAB 9 Arrays

Topics
 Array of data types
 Accessing array elements
 Initializing array elements

Array of data types


An array is an indexed collection of objects, all of the same type. We can declare a C# array with the following
syntax:
type[] array_name;
For example:
int[] myIntArray;

Actually, here we have not declared an array yet. Technically, we are declaring a variable (myIntArray) that
will hold a reference to an array of integers.
The square brackets ([]) tell the C# compiler that we are declaring and array, and the type specified the type of
the elements it will contain. In the above example, myIntArray is an array of integers.
We can instantiate an array using the new keyword. For example:
myIntArray = new int[5];
This declaration creates and initializes an array of five integers, all of which are initialize to the value 0.
It is important to distinguish between the array itself (which is the collection of elements) and the elements of
the array. myIntArray is the array (or, more accurately, the variable that hold the reference to the array); its
elements are five integers it hold.

Accessing array elements


We access elements of an array using the index operator ([]). Arrays are zero-based, which means that the
index of the first element is always 0 – in this case, myIntArray[0]. Arrays are objects and thus have properties.
One of the more useful of these is Length, which tell us how many objects are in an array. Array objects can be
indexed from 0 to Length-1. That is, if there are five elements in and array, their indexes are 0, 1, 2, 3, 4.
The example 1 illustrates the usage of a simple array of integer. In this example, a class named OneDimArray is
a blueprint for creating a simple array of five integers. In the Main method, we first instantiate two objects, i.e.,
a and b, both holds the arrays of five integers. We then access the elements in the array a using
a.myIntArray[i], and use the property Length to refer to the number of elements in that array. For the second
array b, we call the method Power3 to initialize all of its elements, and employ the method PrintArray to write
out its elements. The foreach looping statement allows us to iterate through all the elements in an array. Notice
that a and b in this example are not the same array.

Computer & Programming: Arrays 1/9 Powered by MIKETM


//Example 1
using System;
namespace MyArray {
public class OneDimArray {
int[] myIntArray;
const int dim = 5;

OneDimArray () {
myIntArray = new int[dim];
}

static void Power3 (OneDimArray t) {


for (int i=0; i<dim; i++)
t.myIntArray[i]=i*i*i;
}

static void PrintArray (OneDimArray t) {


int i=0;
foreach (int j in t.myIntArray)
Console.WriteLine("myIntArray[{0}] = {1}", i++, j);
}

public static void Main() {


OneDimArray a = new OneDimArray();
OneDimArray b = new OneDimArray();

//one dimension array a


for (int i=0; i<dim; i++)
a.myIntArray[i] = i*i;
for (int i=0; i<a.myIntArray.Length; i++)
Console.WriteLine("myIntArray[{0}] = {1}",
i, a.myIntArray[i]);

//another one dimension array b


Power3(b);
Console.WriteLine("Now,");
PrintArray(b);

Console.ReadLine();
}
}
}

Initializing array elements


It is possible to initialize the contents of an array at the same time it is instantiated by providing a list of values
delimited by curly braces ({}). C# provides a longer and a shorter syntax like these:
int[] myIntArray = new int[5] {2, 4, 6, 8, 10};
int[] myIntArray = {2, 4, 6, 8, 10};
There is no practical difference between these two statements, and most programmers will use the shorter
syntax. However, in some rare circumstances we have to use the longer syntax – specifically, if the C# compiler
is unable to infer the correct type for the array.


Reader should type and debug all the example codes found in this document to examine the output.
Computer & Programming: Arrays 2/9 Powered by MIKETM
Exercise 1
1: using System;
2: namespace Exercise1
3: {
4: class Fibonacii
5: {
6: static void Main (string[] args)
7: {
8: int[] fib;
9: int num = 0;
10:
11: Console.Write ("Enter the number of terms: ");
12: num = Int32.Parse (Console.ReadLine ());
13:
14: fib = new int[num];
15: for (int i=0; i<fib.Length; i++) {
16: fib[i] = fib[i-1] + fib[i-2];
17: }
18:
19: for (int i=0; i<fib.Length; i++)
20: Console.Write ("{0} ", fib[i]);
21:
22: Console.ReadLine();
23: }
24: }
25: }

1.1 Run the above program with input 1. What happens and why?

1.2 Replace the statement in line 16 with the following statements. Try running the program again with the
inputs 1, 2, 5, 10 and 20, respectively, for each run, and then re-examine the results.
if ((i==0) || (i==1))
fib[i] = 1;
else
fib[i] = fib[i-1] + fib[i-2];

Input Output
1
2
5
10
20
1.3 According to the outputs from 1.2, what does the above program do?

Computer & Programming: Arrays 3/9 Powered by MIKETM


Exercise 2
1: using System;
2: namespace Exercise2
3: {
4: class CountLetter
5: {
6: public const int ALPHASIZE = 26;
7: public const int DIGITSIZE = 10;
8:
9: static void Main (string[] args)
10: {
11: int[] digitArray = new int[DIGITSIZE];
12: int[] alphaArray = new int[ALPHASIZE];
13: int other = 0;
14: string input = "";
15:
16: Console.Write ("Enter a string or a sentence: ");
17: input = Console.ReadLine();
18:
19: for (int i=0; i<input.Length; i++) {
20: if ((input[i] >= '0') && (input[i] <= '9'))
21: digitArray[input[i] -'0']++;
22: else if ((input[i] >= 'a') && (input[i] <= 'z'))
23: alphaArray[input[i] -'a']++;
24: else
25: other++;
26: }
27:
28: for (int i=0; i<digitArray.Length; i++) {
29: if (digitArray[i] != 0)
30: Console.WriteLine("There are {0} digits of {1}.",
31: digitArray[i], (char)('0' +i));
32: }
33:
34: for (int i=0; i<alphaArray.Length; i++) {
35: if (alphaArray[i] != 0)
36: Console.WriteLine("There are {0} letters of {1}.",
37: alphaArray[i], (char)('a' +i));
38: }
39:
40: if (other != 0)
41: Console.WriteLine("There are {0} other characters.", other);
42:
43: Console.ReadLine ();
44: }
45: }
46: }
47:

2.1 Run the program with input string “hello world 555” What is the output of the program?

Computer & Programming: Arrays 4/9 Powered by MIKETM


2.2 According to the output in 2.1, what does the above program do?

2.3 Try another input “Hello WORLD 555”, how does the output differ from the output in 2.1?

2.4 Rewrite the above program to make the program count an uppercase letter as a lowercase one. For
example, one ‘A’ and one ‘a’ will be counted as two ‘a’. Write the part of the changed code below.

Computer & Programming: Arrays 5/9 Powered by MIKETM


Exercise 3
1: using System;
2: namespace Exercise3
3: {
4: class DecToHex
5: {
6: static void Main (string[] args)
7: {
8: const int BASE = 16;
9:
10: char[] table = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
11: 'A', 'B', 'C', 'D', 'E', 'F'};
12: int number = 0;
13: string s = "";
14:
15: Console.Write("Enter number: ");
16: number = Int32.Parse(Console.ReadLine());
17: while (number>0) {
18: s = table[number % BASE] + s;
19: number /= BASE;
20: }
21:
22: Console.WriteLine("Output = {0}", s);
23: Console.ReadLine();
24: }
25: }
26: }

3.1 Run the program with the input 234, what is the output of the program?

3.2 Modify the above program to convert decimal numbers into octal (base 8) ones.

Computer & Programming: Arrays 6/9 Powered by MIKETM


Exercise 4
1: using System;
2: namespace Exercise4
3: {
4: class CalSquare
5: {
6: static void getInput (int[] n) {
7: for (int i=0; i<n.Length; i++) {
8: Console.Write("Enter num{0}: ", i+1);
9: n[i] = Int32.Parse(Console.ReadLine());
10: }
11: }
12:
13: static void printOutput (int[] n) {
14: Console.Write("Output = ");
15: for (int i=0; i<n.Length; i++)
16: Console.Write("{0} ", n[i]);
17: Console.WriteLine();
18: }
19:
20: static void calSquare (int[] n, int[] s) {
21: s = new int[n.Length];
22: for (int i=0; i<n.Length; i++)
23: s[i] = n[i] * n[i];
24: }
25:
26: static void Main (string[] args)
27: {
28: const int SIZE = 5;
29: int[] num = new int[SIZE];
30: int[] sqr = new int[SIZE];
31:
32: getInput(num);
33: Console.Write("num >> ");
34: printOutput(num);
35:
36: calSquare(num, sqr);
37: Console.Write("sqr >> ");
38: printOutput(sqr);
39:
40: Console.ReadLine();
41: }
42: }
43: }

4.1 Run the program with five inputs: 1, 2, 3, 4, and 5. What is the output of the program?

4.2 Replace the method declaration in line 20 as follows:


static void calSquare (int[] n, out int[] s)

And replace the statement in line 36 as the following statement:


calSquare (num, out sqr)

Then try running the program again with same inputs: 1, 2, 3, 4, and 5. What is the output of the
program?
Computer & Programming: Arrays 7/9 Powered by MIKETM
4.3 Why does the output in 4.1 differ from the one in 4.2?

Exercise 5
5.1 The following program takes five numbers as user input. It then finds the minimum value, maximum
value, as well as computes the average and standard deviation.
Complete all the blank areas of this program. (You must not change other contents of the program) Each
method is defined to operate as follows:
getInput  gets a list ( l ) of input from user.
findMin  returns the minimum value in the list l .
findMax  returns the maximum value in the list l .
n

 l[i]
CalAvg  returns the average value of the list l as x  i 1
.
n
n

 (l[i]  x ) 2

CalSD  returns the standard deviation of the list l as S .D.  i 1


.
n
1: using System;
2: namespace Exercise5
3: {
4: class myList
5: {
6: static void getInput(int[] l) {
7: for (int i=0; i<l.Length; i++) {
8: Console.Write("Input: ", i+1);
9: l[i] = Int32.Parse(Console.ReadLine());
10: }
11: }
12: findMin ( ) {
13:
14:
15:
16:
17:
18:
19:

Computer & Programming: Arrays 8/9 Powered by MIKETM


20: }
21:
22: findMax ( ) {
23:
24:
25:
26:
27:
28:
29:
30: }
31:
32: calAvg ( ) {
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43: }
44:
45: calSD ( ) {
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56: }
57:
58: static void Main (string[] args)
59: {
60: const int SIZE = 5;
61: int[] list = new int[SIZE];
62:
63: getInput(list);
64: Console.WriteLine("Min: {0}", findMin( ));
65: Console.WriteLine("Max: {0}", findMax( ));
66: Console.WriteLine("Avg: {0}", calAvg( ));
67: Console.WriteLine("SD: {0}", calSD( ));
68: Console.ReadLine();
69: }
70: }
71: }
72:

Computer & Programming: Arrays 9/9 Powered by MIKETM

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy