Presentation is loading. Please wait.

Presentation is loading. Please wait.

Review of Classes and Arrays

Similar presentations


Presentation on theme: "Review of Classes and Arrays"— Presentation transcript:

1 Review of Classes and Arrays
Lecture 3 Review of Classes and Arrays Richard Gesick

2 Defining the class Methods: Constructor: Properties
public, private or protected return or not Properties get set Constructor: same name as class public visibility default and overloaded Class instance variables Should normally be private

3 Class definition and default constructor
public class Trophy { private string name; private int points = 10; public Trophy() name = "Yeah that's a problem"; points = 0; }

4 Overloaded Constructor
public Trophy (string n, int p) { name = n; points = p; }

5 public string Name { get return name; }
Properties public int Points { get { return points; } set if (value > 0) points = value; } public string Name { get return name; }

6 Override of the toString method
public override string ToString( ) { return name + " (" + points + ")"; }

7 Arrays Trophy [] troph; … troph = new Trophy[10]; or
Trophy [] troph = new Trophy[10]; can't use until memory is allocated with new.

8 Array example Trophy[] data_storage; int sum = 0;
Console.Write("How many trophies: "); int trophie_count; trophie_count = Int32.Parse(Console.ReadLine()); data_storage = new Trophy [trophie_count];

9 Traversing an array Use a for, while or do-while starting at index 0 and going thru .Length-1 for(int i=0; i< data_storage.Length;i++) { do something } Or use a foreach loop foreach(Trophy t in data_storage) { do something as long as it doesn't add or remove members of the array }

10 program sample 1

11 Enumerated types public enum <typeName>{constant1, constant2, … , constantN}; public enum PowerType {Strength, Fly, Speed, MindControl, BugVision}; enum allows us to define a new "type", but this is actually just a place holder for integers.

12 program sample 2

13 Array processing The simplest processes involve searching ( finding a value, finding the largest or smallest ),or finding a sum, product or average. Remember to initialize properly.

14 Array processing 2 int[] nums = new int[10]; …
float average = FindAverage(nums); int min = FindMin(nums); remember to use "new" to allocate memory for your object.

15 finding the min private static int FindMin (int[] A) {
int temp = A[0]; for (int i = 1; i < 10; i++) { if (temp > A[i]) temp = A[i]; } return temp; notice that the parameters (in this case "nums") when you invoke a method can be called something else in the method itself (in this case "A").  Parameters match in position and type, so the name doesn't matter.

16 finding a sum and or average
private static float FindAverage (int [] B) { int sum = 0; for (int i = 0; i < 10; i++) { sum += B[i]; } return sum / 10f;

17 program sample 3


Download ppt "Review of Classes and Arrays"

Similar presentations


Ads by Google