Programming Fundamentals for Engineers CH. 4,5-1
Programming Fundamentals for Engineers CH. 4,5-1
Fundamentals
For Engineers
CH. 4,5
Prepared by
Aly Reda
@alyredaabdalla
Table of Content
Chapter 4 1
Procedural Programming in C# 1
Define the Method 2
Method Return Types 3
Passing Parameters to Methods 4
Function Overloading 5
Stack vs. Heap in C# 5
Value Types vs. Reference Types in C# 6
Garbage Collection (GC) in .NET 7
Chapter 5 8
Classes 8
Arrays in C# 8
1D Array 9
2D Array 10
Working with Arrays 11
Scope in C# 11
Chapter 4
Procedural Programming in C#
• Modules: In C#, modules are typically represented by namespaces. Namespaces are logical groupings
of related classes, interfaces, structs, enums, and other elements. They help organize code and prevent
naming conflicts.
• Functions: Functions in C# are called methods. Methods are blocks of code that perform specific
tasks and can be reused throughout your program. They can have parameters and return values.
• Main() Function: The entry point of a C# program is always the Main() method. By convention, it's
usually named in lowercase (Main()).
Example
C#
namespace MyNamespace
{
class Program
{
static void Main()
{
Print(); // Calling Print Function to print “Hello world!”
}
}
}
In this example:
• The code is organized within a namespace called MyNamespace.
• The Print() method is defined within the Program class.
• The Main() method is the entry point of the program and calls the Print() method.
Points
• While C# supports procedural programming, it also incorporates object-oriented programming
features. This allows you to combine both paradigms for more flexible and modular code.
• Namespaces are essential for organizing your code and preventing naming conflicts.
• Methods are the building blocks of procedural programming in C#.
• The Main() method is the entry point of your C# program.
1
Define the Method
• Choose a meaningful name for the method that reflects its purpose.
• Specify the return type (if any) of the method.
• Define the parameters (if any) that the method will accept.
• Write the code that will be executed within the method's body.
Example:
This code calls the Sum method with arguments 5 and 3, assigns the result to the result variable, and then
prints the result to the console.
Considerations
• You can define methods within classes or outside of classes.
• Methods can have different access modifiers (e.g., public, private, protected) to control their visibility.
• Methods can be overloaded, meaning you can have multiple methods with the same name but different
parameters.
• Methods can be recursive, meaning they can call themselves.
2
Method Return Types
• A method's return type specifies the type of value that the method will return to the calling code.
• If a method does not return a value, its return type is void.
• If a method returns a value, its return type must match the type of the value being returned.
Examples
Void Method
3
String Return Type
Types of Parameters
• Value parameters: The values of value parameters are copied into the method. Changes made to
value parameters within the method do not affect the original values passed to the method.
• Reference parameters: Reference parameters pass a reference to the original variable to the method.
Changes made to reference parameters within the method affect the original variable.
Example:
4
Function Overloading
• Function overloading is the ability to have multiple methods with the same name but different
parameters.
• The compiler determines which method to call based on the number and types of arguments passed to
it.
• Overloading is useful for creating methods that perform similar tasks but with different input or output
parameters.
Example
static int Sum(int num1, int num2) // Passing int & return int
{
return num1 + num2;
}
static double Sum(double num1, double num2) // Passing double & return double
{
return num1 + num2;
Heap Memory
• Storage: Stores reference types (e.g., string, object, custom classes, arrays).
• Allocation: Allocated dynamically using the new keyword or other allocation methods.
• Access: Values are accessed indirectly through references.
5
Feature Stack Heap
Storage Value types Reference types
Allocation Automatic Dynamic (using new)
Access Direct Indirect (through references)
Lifetime Short-lived Can have a longer lifetime
Reference Types
• Storage: Store a reference to an object on the heap.
• Copying: When a reference type is assigned or passed as an argument to a method, a copy of the
reference is created, not a copy of the object itself.
• Examples: string, object, custom classes, arrays.
6
Feature Value Types Reference Types
How it works
1. Allocation: Objects are created on the heap using new.
2. Tracking: GC keeps track of references to objects.
3. Collection: Objects without references are marked for deletion and their memory is reclaimed.
7
Chapter 5
THIS CHAPTER DOESN’T INCLUDE DEMO VIDEOS CONTENT OR SUMMARY PLEASE
RETURN TO VIDEOS TO WATCH IT
Thanks,
Classes
• Definition: A blueprint or template that defines the structure and behavior of objects.
• Purpose: To encapsulate related data and methods into a single unit, promoting code organization,
reusability, and maintainability.
• Components:
• Properties: Variables that represent the data attributes of an object.
• Methods: Functions that define the behavior or actions an object can perform.
• Constructors: Special methods used to initialize objects.
• Destructors: Methods called when an object is garbage collected.
•
Objects
• Definition: Instances of a class, representing specific examples of that class.
• Relationship: Objects are created from classes and inherit their properties and methods.
• Example: If a Human class is defined, creating a Human1 object would represent a specific person.
Properties
• Definition: Variables that define the characteristics or attributes of an object.
• Types:
• Auto-implemented properties: Automatically generate both getter and setter methods.
• Full properties: Manually define getter and setter methods for more control.
• Example: A Human class might have properties like Name, Age, and Address.
Methods
• Definition: Functions that define the behavior or actions an object can perform.
• Purpose: To manipulate object data, interact with other objects, or provide functionality.
• Example: A Human class might have methods like Walk(), Talk(), and CalculateAge().
Arrays in C#
Arrays are a collection of elements of the same data type, stored in contiguous memory locations. They are
accessed using an index, which starts from 0.
8
Value
• Each element in an array has a value associated with it.
• The value can be any data type supported by C#, such as int, double, string, or a custom class.
Index
• The index is an integer value used to access a specific element in an array.
• It starts from 0, so the first element in an array has an index of 0.
Zero-Based Indexing
• C# arrays use zero-based indexing, meaning the first element has an index of 0, the second has an
index of 1, and so on.
• This is a common convention in many programming languages.
Array Dimensions
• One-dimensional array: A simple array with a single row of elements.
• Multidimensional array: An array with multiple dimensions, allowing you to store data in a grid-like
structure.
• Two-dimensional array: A common type of multidimensional array, often used to represent matrices
or tables.
1D Array
1. Creating an array of integers
int[] arr = new int[5]; // This creates an array named arr that can hold 5 integer values.
2. Assigning values to the array
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; // assign values to each element of the array using their indices.
3. Creating an array of strings
string[] names = { "Aly", "Ahmed", "Mazen", "Ziad", "Nasr" }; //This creates an array named names that
contains 5 string values.
4. Printing the elements using a for loop:
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
} //This code iterates through each element of the arr array and prints its value to the console.
9
Example
Console.WriteLine("Integer array:");
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
Console.WriteLine("\nString array:");
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i]);
}
2D Array
• Definition: A multidimensional array with two dimensions, representing a grid or matrix.
• Elements: Each element in a 2D array is identified by two indices: a row index and a column index.
• Declaration: Declared using the following syntax:
Example
int[,] arr = new int[2, 2]; //This creates a 2x2 integer array named arr.
10
Working with Arrays
Important function for arrays in C#
Example
int[] numbers = { 1, 2, 3, 4, 5 };
Arr.Sum
• Purpose: Calculates the sum of all elements in an array.
int sum = numbers.Sum(); // sum will be 15
Arr.Max:
• Purpose: Returns the maximum value in an array.
int max = numbers.Max(); // max will be 5
Arr.Min:
• Purpose: Returns the minimum value in an array.
int min = numbers.Min(); // min will be 1
Arr.ElementAt(index):
• Purpose: Returns the element at a specified index in an array.
int thirdElement = numbers.ElementAt(2); // thirdElement will be 3
Arr.First():
• Purpose: Returns the first element in an array.
int first = numbers.First(); // first will be 1
Arr.Last():
• Purpose: Returns the last element in an array.
int last = numbers.Last(); // last will be 5
Scope in C#
Scope refers to the region of code where a variable or other identifier is visible and can be accessed. In C#,
there are three main levels of scope:
1. Class Level
• Description: Variables declared within a class but outside of any method or property have class-level
scope. They are accessible throughout the entire class, including within methods, properties, and
constructors.
• Accessibility: Variables declared with public access modifiers are accessible from anywhere within
the assembly and can be accessed from other assemblies if they are marked as public. Variables
declared with private access modifiers are only accessible within the class itself.
2. Method Level
• Description: Variables declared within a method have method-level scope. They are accessible only
within that method and any nested blocks within it.
• Accessibility: These variables are implicitly private and cannot be accessed from outside the method.
11
3. Block Level
• Description: Variables declared within a block (e.g., within a for, if, or while statement) have block-
level scope. They are accessible only within that block and any nested blocks within it.
• Accessibility: These variables are implicitly private and cannot be accessed from outside the block.
Class Level Within the entire class public and private fields
Method Level Within the method Local variables declared inside the method
Block Level Within the block Variables declared inside a block (e.g., for, if)
12