Loading...

OBJECT ORIENTED PROGRAMMING  

>

LEARNING OUTCOME 6

IMPORTANCE OF USING ARRAYS

Arrays:

Arrays are fundamental data structures in C# that provide a structured way to store a fixed-size collection of elements of the same data type. They offer several advantages that make them essential for various programming tasks:

Common Use Cases for Arrays:

Alternatives to Arrays:

Key Points to Consider When Using Arrays:

Example: Calculating Average Temperature in a Month

C#
		int[] temperatures = { 15, 18, 20, 22, 25, 23, 21, 19, 17, 16 }; // Daily temperatures
		double total = 0;
		for (int i = 0; i < temperatures.Length; i++)
		{
			total += temperatures[i]; // Add each temperature to the total
		}
		double averageTemperature = total / temperatures.Length;
		Console.WriteLine("The average temperature for the month is: {0:F2} degrees Celsius", averageTemperature);
		

How to create one-dimensional, two-dimensional (multidimensional), and jagged arrays in C#:

1. One-Dimensional Arrays:

One-dimensional arrays store a collection of elements of the same data type in a contiguous memory block. You can create them in two ways:

2. Two-Dimensional Arrays (Multidimensional Arrays):

Two-dimensional arrays represent a grid-like structure where each element is identified by two indexes, one for the row and one for the column. You can create them similarly to one-dimensional arrays:

3. Jagged Arrays:

Jagged arrays are arrays of arrays, where each inner array can have a different size. They offer flexibility when you don't need a fixed number of elements in each row:

C#
		int[][] jaggedArray = new int[3][]; // Array of 3 arrays (size of each unknown yet)
		jaggedArray[0] = new int[] { 1, 3, 5 }; // First row with 3 elements
		jaggedArray[1] = new int[] { 2, 4 }; // Second row with 2 elements
		jaggedArray[2] = new int[] { 7, 8, 9, 10 }; // Third row with 4 elements
		

Accessing Elements:

MANIPULATING ARRAYS

Here are some common ways to manipulate arrays in C#:

Important Considerations:

SORTING AND SEARCHING ARRAYS in C# (ECMAScript-like Style)

1. Sorting Arrays:

Similar to JavaScript's sort method, C# offers the Array.Sort method to arrange array elements in a specific order.

C#
		int[] numbers = { 5, 2, 8, 1, 3 };
		// Sort elements in ascending order (default behavior)
		Array.Sort(numbers);
		Console.WriteLine("Sorted numbers: {0}", string.Join(", ", numbers));
		// Output: 1, 2, 3, 5, 8
		

2. Sorting with Custom Comparison:

Like JavaScript's comparison function, C# allows you to define a custom comparison function for Array.Sort to control the sorting order.

C#
		string[] names = { "Alice", "Charlie", "Bob" };
		// Function to compare names by length (ascending order)
		int CompareByNameLength(string a, string b)
		{
			return a.Length.CompareTo(b.Length); // Compare string lengths
		}
		Array.Sort(names, CompareByNameLength); // Use custom comparison function
		Console.WriteLine("Sorted names by length: {0}", string.Join(", ", names)); // Output: Bob, Alice, Charlie
		

3. Searching Arrays:

C# provides methods like IndexOf and LastIndexOf to find the index of a specific value within an array.

C#
		int[] numbers = { 10, 20, 30, 20, 40 };
		// Find the first occurrence of 20
		int firstIndex = Array.IndexOf(numbers, 20);
		// Find the last occurrence of 20 (if present)
		int lastIndex = Array.LastIndexOf(numbers, 20);
		Console.WriteLine("First index of 20: {0}", firstIndex); // Output: 1
		Console.WriteLine("Last index of 20: {0}", lastIndex); // Output: 3 (if not found, returns -1)
		

Additional Considerations:

STRUCTURES: User-Defined Value Types

Structures in C# are user-defined data types that group related variables of various data types under a single unit. They act as value types, meaning a copy of the structure's data is created when passed around or assigned, unlike reference types (like arrays) that pass references to the memory location.

Importance of Structures:

Key Characteristics:

Distinguishing Structures from Arrays:

Feature Arrays Structures
Data Type Fixed-size collection of elements of the same type Group of variables of possibly different data types
Value vs. Reference Type Reference type (stores memory address) Value type (stores actual data)
Passing Mechanism Passes reference to the underlying data block Passes a copy of the entire structure's data
Memory Efficiency Can be less efficient for large datasets More efficient for small datasets
Inheritance Can inherit from other arrays or classes Cannot inherit from other structures or classes
Default Constructor Has a default constructor that initializes to zeros No default constructor (needs explicit definition)
Methods and Operators Generally don't have methods or operators Can optionally have methods and operators

When to Use Structures:

Example:

C#
		struct Point
		{
			public int X;
			public int Y;
			// You could define methods here to perform operations on points (e.g., calculate distance)
		}
		

Examples using Structures in C#

1. Representing Employee Data:

This example defines a structure named Employee to store employee information:

C#
		struct Employee
		{
			public string Name { get; set; } // Public properties for data access
			public int ID { get; set; }
			public double Salary { get; set; }
			// You could define methods here to perform operations on employees (e.g., calculate bonus)
		}
		

Potential Exam Question:

Write a function that takes an array of Employee structures and returns the employee with the highest salary. (Implement the function logic using a loop and conditional statements to compare salaries)

2. Point Structure with Distance Calculation Method:

This example creates a Point structure with a method to calculate the distance between two points:

C#
		struct Point
		{
			public int X { get; set; }
			public int Y { get; set; }
			public double CalculateDistanceTo(Point otherPoint)
			{
				int xDiff = X - otherPoint.X;
				int yDiff = Y - otherPoint.Y;
				return Math.Sqrt(xDiff * xDiff + yDiff * yDiff); // Calculate distance using Pythagorean theorem
			}
		}
		

Potential Exam Question:

Write a program that prompts the user for the coordinates of two points and then uses the Point structure and its method to calculate and display the distance between them.

DEFINING AND INSTANTIATING STRUCTURES IN C#

1. Defining a Structure:

C#
			struct MyStructureName // Name of your structure
			{
			 // Declare member variables (data types)
			 public int someInteger;
			 public string someString;
			 public double someDouble;
			 // You can also include methods and operators within structures
			(less common)
			}
			

2. Instantiating (Creating) a Structure Instance:

A. Using a Structure Variable:

C#
			MyStructureName myStructure; // Declare a structure variable
			// Assign values to member variables using dot notation
			myStructure.someInteger = 10;
			myStructure.someString = "Hello";
			myStructure.someDouble = 3.14;
			

B. Using the new Keyword:

C#
			MyStructureName myStructure = new MyStructureName(); // Create an instance with default values
			// Alternatively, assign initial values during creation (optional)
			MyStructureName anotherStructure = new MyStructureName { someInteger = 20, someString = "World" };
			

Example:

C#
			struct Book
			{
			 public string Title;
			 public string Author;
			 public int YearPublished;
			 public void PrintDetails() // Optional method to display book information
			 {
			 Console.WriteLine("Title: {0}", Title);
			 Console.WriteLine("Author: {0}", Author);
			 Console.WriteLine("Year Published: {0}", YearPublished);
			 }
			}
			class MainClass
			{
			 static void Main(string[] args)
			 {
			 // Create a Book structure instance
			 Book myBook; // Declare a variable
			 myBook.Title = "The Hitchhiker's Guide to the Galaxy";
			 myBook.Author = "Douglas Adams";
			 myBook.YearPublished = 1979;
			 // Another way to create an instance with initial values
			 Book anotherBook = new Book { Title = "Pride and Prejudice", Author = "Jane Austen", YearPublished = 1813 };
			 // Call the PrintDetails method (if defined)
			 myBook.PrintDetails();
			 anotherBook.PrintDetails();
			 }
			}
			

Important Note:

MANIPULATING STRUCTURES

1. Accessing and Modifying Member Variables:

C#
			struct Point
			{
			 public int X;
			 public int Y;
			}
			Point myPoint;
			myPoint.X = 5; // Set the X coordinate
			myPoint.Y = 10; // Set the Y coordinate
			

2. Passing Structures to Functions:

C#
			struct Product
			{
			 public string Name;
			 public double Price;
			}
			void ApplyDiscount(Product product, double discountPercentage)
			{
			 product.Price *= (1 - discountPercentage / 100); // Modify the copy within the function
			}
			Product myProduct = new Product { Name = "Shirt", Price = 19.99 };
			ApplyDiscount(myProduct, 10); // Won't affect the original price in myProduct
			Console.WriteLine("Product price after discount (outside function): {0:F2}", myProduct.Price); // Remains 19.99
			

3. Returning Structures from Functions:

C#
			struct Rectangle
			{
			 public int Width;
			 public int Height;
			}
			Rectangle CalculateArea(int width, int height)
			{
			 return new Rectangle { Width = width, Height = height };
			}
			Rectangle myRectangle = CalculateArea(5, 10);
			Console.WriteLine("Rectangle area: {0}", myRectangle.Width * myRectangle.Height);
			

4. Using Methods Within Structures (Optional):

C#
			struct Point3D
			{
			 public int X;
			 public int Y;
			 public int Z;
			 public double CalculateDistanceTo(Point3D otherPoint)
			 {
			 // ... (code to calculate distance using 3D coordinates)
			 }
			}
			Point3D point1 = new Point3D { X = 1, Y = 2, Z = 3 };
			Point3D point2 = new Point3D { X = 4, Y = 5, Z = 6 };
			double distance = point1.CalculateDistanceTo(point2);
			Console.WriteLine("Distance between points: {0:F2}", distance);
			

Important Considerations:

COMBINING STRUCTURES WITH NESTED STRUCTURES IN C#

Nested structures: allow you to create complex data hierarchies by placing structures within other structures.

Example: Representing a Customer with an Address:

C#
			struct Address
			{
			 public string Street;
			 public string City;
			 public string State;
			 public string ZipCode;
			}
			struct Customer
			{
			 public string Name;
			 public string Email;
			 public Address BillingAddress; // Nested structure member
			}
			

Accessing Nested Member Variables:

C#
			Customer customer1 = new Customer();
			customer1.Name = "John Doe";
			customer1.Email = "john.doe@example.com";
			customer1.BillingAddress.Street = "123 Main St";
			customer1.BillingAddress.City = "Anytown";
			// ... and so on for other address fields
			

Benefits of Nested Structures:

Example Usage:

Important Considerations:

STRUCTURES AND ARRAYS

Structures and arrays are both fundamental data structures in C#, but they serve different purposes:

ARRAYS:

STRUCTURES:

Combining Structures and Arrays:

Here are two ways to combine structures and arrays in C#:

  1. Array of Structures:
    • You can create an array to hold multiple structures of the same type: This allows you to manage collections of related data objects.
    C#
    struct Point
    {
     public int X;
     public int Y;
    }
    Point[] points = new Point[5]; // Array to hold 5 Point structures
    // Access and modify elements using the index and dot notation
    points[0].X = 10;
    points[0].Y = 20;
    // Loop through the array to access each Point structure
    for (int i = 0; i < points.Length; i++)
    {
     Console.WriteLine("Point {0}: ({1}, {2})", i + 1, points[i].X,
    points[i].Y);
    }
    
  2. Structure with an Array Member:
    • A structure can have a member variable that is itself an array: This can be useful for modeling complex entities with variable-length data.
    C#
    struct Student
    {
     public string Name;
     public int[] Scores; // Array of integer scores
    }
    Student student1;
    student1.Name = "Alice";
    student1.Scores = new int[3] { 90, 85, 92 }; // Assign scores to the array member
    // Access individual scores using the dot notation and array index
    int firstScore = student1.Scores[0];
    

Choosing Between Arrays and Structures:

Example:

PASSING ARRAYS TO FUNCTIONS

  1. Arrays as Reference Types:
    • Arrays in C# are reference types: This means when you pass an array to a function, you're not passing the actual array data itself, but rather a reference (memory location) to the array's data.
    • Any changes made to the array elements: within the function will be reflected in the original array because they both point to the same underlying data.
    C#
    void ModifyArray(int[] numbers)
    {
     numbers[0] = 100; // Modify the first element
    }
    int[] myNumbers = { 1, 2, 3 };
    ModifyArray(myNumbers);
    Console.WriteLine("Modified array: {0}", string.Join(", ", myNumbers));
    // Output: 100, 2, 3
    
  2. Multidimensional Arrays:
    • The concept of passing by reference applies to multidimensional arrays as well: You're passing a reference to the first element of the array, and all dimensions are accessible within the function.
  3. Caution with Array Modifications:
    • Be mindful: that if you intend to keep the original array unmodified, you shouldn't directly modify the elements within the function. Consider creating a copy of the array or using techniques to avoid unintended side effects.
  4. Passing by Reference vs. Passing by Value:
    • In contrast to arrays: (reference types), structures (value types) are passed by value. When you pass a structure to a function, a copy of the structure's data is created and passed, so changes within the function don't affect the original structure.

Key Points:

MODULARIZATION

Benefits of Modularization:

Modularization, also known as modular programming, is a fundamental software design technique that involves breaking down a program into smaller, independent, and reusable units called modules (functions, classes, or components). Here are the key advantages it offers:

Built-in vs. User-Defined Functions:

In programming languages, functions are essential building blocks that encapsulate a specific task or calculation. They typically accept input (parameters), perform operations, and optionally return an output (return value).

Example (Python):

Python
# Built-in functions (standard library)
print("Hello, world!") # `print()` for output
result = abs(-5) # `abs()` for absolute value
numbers = [3, 1, 4, 2]
sorted_numbers = sorted(numbers) # `sorted()` for sorting
# User-defined function
def calculate_area(length, width):
 """Calculates the area of a rectangle."""
 return length * width
area = calculate_area(5, 10)
print(f"Area of rectangle: {area}")

In essence, modularization helps break down a complex program into manageable, reusable pieces, while built-in functions provide common building blocks you can leverage, and user-defined functions allow you to create your own custom functionalities to address specific needs within your program.

DEFINING AND INVOKING FUNCTIONS IN C#

1. Defining Functions:

The general syntax for defining a function in C# is:

C#
access_modifier return_type function_name(parameter_list)
{
 // Function body containing statements and logic
 return value_to_return (optional); // Return statement (if applicable)
}

Let's break down the components:

Example:

C#
public double CalculateArea(int length, int width) // Public function for calculating area
{
 return length * width; // Returns the area (double)
}

2. Invoking Functions:

Once you've defined a function, you can call it (invoke it) from another part of your code using its name followed by parentheses.

C#
double area = CalculateArea(5, 10); // Invoke the CalculateArea function with arguments (5, 10)
Console.WriteLine("Area: {0}", area);

3. Important Points:

Here are some more examples of defining and invoking functions in C# to showcase different functionalities:

  1. Function with String Manipulation:
    C#
    string GreetUser(string name)
    {
     return $"Hello, {name}!"; // String interpolation for greeting
    }
    string userName = "Alice";
    string greeting = GreetUser(userName);
    Console.WriteLine(greeting); // Output: Hello, Alice!
    
  2. Function with Default Parameter Value:
    C#
    int AddNumbers(int num1, int num2 = 10) // num2 has a default value of 10
    {
     return num1 + num2;
    }
    int sum1 = AddNumbers(5, 15); // Explicit arguments
    int sum2 = AddNumbers(8); // Use default value for num2 (8 + 10 = 18)
    Console.WriteLine("Sum with explicit arguments: {0}", sum1);
    Console.WriteLine("Sum with default value: {0}", sum2);
    
  3. Function with Conditional Logic:
    C#
    bool IsEvenNumber(int number)
    {
     return number % 2 == 0; // Check if number is divisible by 2 (even)
    }
    int userNumber = 12;
    bool isEven = IsEvenNumber(userNumber);
    if (isEven)
    {
     Console.WriteLine("{0} is an even number.", userNumber);
    }
    else
    {
     Console.WriteLine("{0} is an odd number.", userNumber);
    }
    

These examples demonstrate how functions can handle various tasks, including string manipulations, setting default parameter values, and implementing conditional logic. You can create more complex functions as needed to break down your program's functionality into manageable units.

PASSING PARAMETERS TO FUNCTIONS

In C#, passing parameters to functions allows you to provide data for the function to process. Here's a breakdown of the concept:

  1. Function Parameters:
    • When defining a function: you can specify parameters within the parentheses following the function name.
    • Each parameter has a data type: (e.g., int, string, double) and a name that acts as a placeholder within the function.
    C#
    void PrintMessage(string message) // Parameter: message (string)
    {
     Console.WriteLine(message);
    }
    
  2. Passing Arguments:
    • When invoking (calling) the function: you provide actual values (arguments) for each parameter in the same order they are defined.
    • These arguments are passed: to the function's internal variables (parameters) for processing.
    C#
    string myMessage = "Hello, world!";
    PrintMessage(myMessage); // Pass the value of myMessage as the argument
    
  3. Important Points:
    • The number of arguments you pass: must match the number of parameters defined in the function.
    • The data types of the arguments: must be compatible with the parameter types.
    • C# is a pass-by-value language: for value types (like int, double). A copy of the argument value is passed to the function, so changes within the function don't affect the original variable.
    • For reference types: (like string, arrays), a reference (memory location) is passed. Modifications within the function can affect the original variable.

Example: Value vs. Reference Type Parameter Passing:

C#
void ModifyValue(int x) // Parameter: x (int, value type)
{
 x = 100; // Modify the copy of x within the function
}
void ModifyString(string message) // Parameter: message (string, reference type)
{
 message += " (modified)"; // Modify the original string through the reference
}
int myNumber = 5;
string myString = "Original message";
ModifyValue(myNumber);
Console.WriteLine("myNumber after function call (value type): {0}",
myNumber); // Output: 5 (original value preserved)
ModifyString(myString);
Console.WriteLine("myString after function call (reference type): {0}",
myString); // Output: Original message (modified)

Key Takeaways:

FUNCTION CALL

In C#, there's generally one primary way to call (invoke) a function: using the function name followed by parentheses. Here's a breakdown of the mechanics:

Function Call Syntax:

C#
function_name(argument1, argument2, ..., argumentN);

Example:

C#
void GreetUser(string name)
{
    Console.WriteLine("Hello, {0}!", name);
}
string userName = "Alice";
GreetUser(userName); // Calling the function with an argument

Additional Considerations:

SCOPE OF AN IDENTIFIER

The scope of an identifier in C# refers to the part of your program where that identifier (variable name, function name, etc.) is valid and accessible. It determines where you can use the identifier without causing errors or ambiguity.

There are three main types of scope in C#:

1. Class Level Scope:

C#
class MyClass
{
    public string className = "My Class"; // Class-level variable
    public void MyMethod()
    {
        Console.WriteLine("Class name from method: {0}", className); // Accessing class-level variable
    }
}

2. Method Level Scope (Local Scope):

C#
void PrintMessage(string message) // Parameter (local to the function)
{
    int counter = 0; // Local variable (only accessible within PrintMessage)
    Console.WriteLine(message);
}

3. Block Level Scope:

C#
if (true)
{
    int blockVariable = 10; // Only accessible within this if block
    Console.WriteLine("Value inside if: {0}", blockVariable);
}
Console.WriteLine("BlockVariable is not accessible here (out of scope)"); // Error: blockVariable not defined

Key Points:

Example (Scope Conflicts):

C#
string globalMessage = "Global message"; // Global variable
class MyClass
{
    public string globalMessage = "Class-level message"; // Different variable with the same name
    public void MyMethod()
    {
        string globalMessage = "Method-level message"; // Yet another variable with the same name
        Console.WriteLine("Accessing global message: {0}", globalMessage); // Prints "Method-level message"
        Console.WriteLine("Accessing class-level message: {0}", this.globalMessage); // Accesses class-level using 'this' keyword
    }
}

FUNCTION OVERLOADING

Function overloading is a powerful feature in C# that allows you to define multiple functions with the same name but different parameter lists (number, types, or order of parameters). The compiler determines which function to call based on the types and number of arguments provided during invocation.

Benefits of Function Overloading:

Syntax:

C#
return_type function_name(parameter_list1)
{
    // Function body
}
return_type function_name(parameter_list2)
{
    // Function body (different from the first function)
}

Example:

C#
class Calculator
{
    public int Add(int x, int y)
    {
        return x + y;
    }
    public double Add(double x, double y)
    {
        return x + y;
    }
    public string Add(string message1, string message2)
    {
        return message1 + message2;
    }
}

In this example, the Add function is overloaded to handle integer addition, double addition, and string concatenation. The compiler selects the appropriate function based on the argument types during invocation.

Defining Functions as Methods in Classes

In object-oriented programming (OOP) languages like C#, functions are typically defined as methods within classes. A method is a function encapsulated within a class, often operating on the data (member variables) of that class.

Syntax:

C#
access_modifier return_type method_name(parameter_list)
{
    // Method body containing statements and logic
}

Example:

C#
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public void Greet()
    {
        Console.WriteLine("Hello, my name is {0}!", Name);
    }
}

Here, the Person class has two member variables (Name and Age) and a Greet method that introduces the person using the Name member variable.

End of Outcome Quiz

1 of 20

    Quiz Score

    Percentage: 0%

    Answered Questions: 0

    Correct Answers: 0

    Faults: