0% found this document useful (0 votes)
2 views

Programming Fundamentals for Engineers CH. 4,5-1

The document covers programming fundamentals for engineers, focusing on procedural programming in C# and object-oriented programming concepts. Key topics include method definitions, return types, parameter passing, memory management, and classes. It also discusses arrays, their usage, and scope in C#.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Programming Fundamentals for Engineers CH. 4,5-1

The document covers programming fundamentals for engineers, focusing on procedural programming in C# and object-oriented programming concepts. Key topics include method definitions, return types, parameter passing, memory management, and classes. It also discusses arrays, their usage, and scope in C#.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Programming

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!”
}

static void Print()


{
Console.WriteLine("Hello world!"); // Printing “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:

public static int Sum(int num1, int num2)


{
return num1 + num2;
} // This method, named Sum, takes two integer parameters and returns their sum.

Call the Method


• To call the method, you need to provide the necessary arguments (if any) and assign the return value
(if any) to a variable.
Example:
int result = Sum(5, 3); // Calling Function and store value in result
Console.WriteLine("The sum is: " + result);

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.

Example with Overloading


static int Sum(int num1, int num2)
{
return num1 + num2;
}

static double Sum(double num1, double num2)


{
return num1 + num2;
} //This code defines two overloaded methods named CalculateSum, one for integers and one for doubles.

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.

Void Return Type


• Methods with a void return type do not return any value.
• They are often used for procedures that perform actions but do not produce a result.
• Examples of void methods include methods that print to the console, modify variables, or perform file
operations.
Data Type Return Types
• Methods can return values of any valid C# data type, including:
• Primitive data types (e.g., int, double, bool, char)
• Reference types (e.g., string, object, custom classes)
• The return type of a method must match the type of the value being returned using the return
statement.
The return Statement
• The return statement is used to exit a method and optionally return a value.
• If the method's return type is void, the return statement can be used without specifying a value.
• If the method's return type is a data type, the return statement must specify a value of that type.

Examples

Void Method

static void PrintMessage()


{
Console.WriteLine("Hello, world!");
return; // Optional
}

Integer Return Type

static int Sum(int num1, int num2)


{
int sum = num1 + num2;
return sum; // Must be used if you want to return value
}

3
String Return Type

static string Hellouser(string name)


{
string greeting = "Hello, " + name + "!";
return greeting;
}

• The return type of a method is an essential part of its signature.


• Methods with a void return type do not return any value.
• Methods with a data type return type must return a value of that type using the return statement.
• The return type of a method must match the type of the value being returned.
Passing Parameters to Methods
• Parameters are values that are passed to a method when it is called.
• They allow you to make methods more flexible and reusable by providing different input values.
• When a method is called, the values of the arguments passed to it are copied into the corresponding
parameters of the method.

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:

static int Sum(int num1, int num2) // Value parameters


{
return num1 + num2;
}

static void SwapNumbers(ref int x, ref int y) // Reference parameters


{
int temp = x;
x = y;
y = temp;
}

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;

• Parameters allow you to make methods more flexible and reusable.


• Value parameters are copied into the method, while reference parameters pass a reference to the
original variable.
• Output parameters are used to return multiple values from a method.
• Function overloading allows you to have multiple methods with the same name but different
parameters.
• The compiler determines which overloaded method to call based on the number and types of
arguments passed to it.

Stack vs. Heap in C#


Stack Memory
• Storage: Stores value types (e.g., int, double, bool, char, structs, enums) directly.
• Allocation: Automatically allocated and deallocated by the runtime system.
• Access: Values can be accessed directly using their variable names.

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

Memory Management Automatic Manual (garbage collection or Dispose())

Value Types vs. Reference Types in C#


Value Types
• Storage: Stored directly on the stack.
• Copying: When a value type is assigned or passed as an argument to a method, a copy of its value is
created.
• Examples: int, double, bool, char, struct, enum.

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

Storage Stack Heap

Copying Copies the value Copies the reference

Equality Comparison Compares values Compares references

Null Assignment Cannot be null (unless nullable) Can be null

Garbage Collection (GC) in .NET


GC is a process in .NET that automatically reclaims memory that is no longer in use. It helps prevent memory
leaks and improves application performance.

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.

• Automatic: GC handles memory management automatically.


• Generational: GC divides the heap into generations to optimize collection.
• Best Practices: Use Dispose() for unmanaged resources, avoid excessive object creation, and consider
value types.

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

int[] arr = new int[5];


arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

string[] names = { "Aly", "Ahmed", "Mazen", "Ziad", "Nasr" };

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:

Syntax: data_type[,] array_name = new data_type[rows, columns];


• data_type: The data type of the elements in the array.
• array_name: The name of the array.
• rows: The number of rows in the array.
• columns: The number of columns in the array.

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.

Scope Level Accessibility Example

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

You might also like