C# Programming Labs

Master arrays, methods, and string manipulation in C#. Build practical skills for .NET development.

Arrays & Methods - Module 2

Learn to work with collections and create reusable code blocks.

Lab 4: Arrays & Collections
Intermediate
Coding Challenge
Your Task: Create a program that works with an array of integers - declaring, initializing, accessing elements, and calculating statistics.

Detailed Requirements:
1. Declare an integer array "numbers" - Initialize with at least 5 values. In C#, arrays are fixed-size collections. You can declare arrays in several ways:
   • int[] numbers = {10, 25, 8, 42, 15}; - Array initializer (most common)
   • int[] numbers = new int[5]; - Creates array with default values (0)
   • int[] numbers = new int[] {10, 25, 8, 42, 15}; - Explicit new keyword

2. Print array length - Use the .Length property: numbers.Length returns the number of elements. This is a property, not a method, so no parentheses!

3. Access individual elements - Arrays are zero-indexed, meaning the first element is at index 0:
   • numbers[0] → First element (10)
   • numbers[4] → Fifth element (15)
   • numbers[numbers.Length - 1] → Last element

4. Loop through all elements - Use a foreach loop (preferred) or traditional for loop:
   • foreach (int num in numbers) { Console.WriteLine(num); }
   • for (int i = 0; i < numbers.Length; i++) { ... }

5. Calculate sum and average - Loop through to add all values, then divide by length for average.

💡 Pro Tips:
• For dynamic-size collections, use List<int> instead of arrays
• Use Array.Sort(numbers) to sort in-place
• Use Array.Reverse(numbers) to reverse order
• LINQ provides shortcuts: numbers.Sum(), numbers.Average(), numbers.Max()

Expected Output:
Array length: 5 First element: 10 Last element: 15 All elements: 10 25 8 42 15 Sum: 100 Average: 20

Requirements Checklist

Declare and initialize an int array with at least 5 values
Print the array length using .Length property
Access and print first element (index 0)
Loop through array using foreach or for
Calculate and print sum of all elements
Calculate and print average
Output
// Click "Run Code" to compile and execute
Hints & Tips
• Array declaration: int[] numbers = {10, 25, 8, 42, 15};
• Get length: numbers.Length (property, no parentheses)
• First element: numbers[0]
• Last element: numbers[numbers.Length - 1]
• Foreach loop: foreach (int n in numbers) { }
• Cast for average: (double)sum / numbers.Length
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 5: Methods & Functions
Intermediate
Coding Challenge
Your Task: Create several methods to perform calculations and demonstrate method concepts including parameters, return values, and method overloading.

Detailed Requirements:
1. Create a method "Add" that takes two integers and returns their sum:
static int Add(int a, int b) { return a + b; }    • static - Method belongs to the class, not an instance
   • int - Return type (what the method gives back)
   • Add - Method name (use PascalCase in C#)
   • (int a, int b) - Parameters (inputs)

2. Create a method "Greet" that takes a name and prints a greeting:
static void Greet(string name) { Console.WriteLine($"Hello, {name}!"); }    • void - No return value (just performs an action)

3. Create an overloaded "Multiply" method:
Method overloading means having multiple methods with the same name but different parameters:
static int Multiply(int a, int b) { return a * b; } static int Multiply(int a, int b, int c) { return a * b * c; }

4. Create a method with a default parameter:
static void PrintMessage(string msg, int times = 1) { for (int i = 0; i < times; i++) Console.WriteLine(msg); }

💡 Pro Tips:
• Methods should do ONE thing well (Single Responsibility)
• Use descriptive names: CalculateTotal() not Calc()
• Return early to avoid deeply nested code
• Consider using out or ref parameters for multiple returns

Expected Output:
Sum: 15 Hello, Alice! Product of 2 numbers: 20 Product of 3 numbers: 60 Message printed once Message printed 3 times

Requirements Checklist

Create Add method with two int parameters returning int
Create Greet method with string parameter (void return)
Create overloaded Multiply methods (2 and 3 parameters)
Call methods from Main and print results
Use return keyword correctly
Code compiles and runs correctly
Output
// Click "Run Code" to compile and execute
Hints & Tips
• Method with return: static int Add(int a, int b) { return a + b; }
• Void method: static void Greet(string name) { ... }
• Call method: int result = Add(5, 3);
• Method overloading: Same name, different parameters
• Methods must be inside the class but outside Main
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 6: String Manipulation
Intermediate
Coding Challenge
Your Task: Master essential string operations in C# including length, case conversion, substring, and searching.

Detailed Requirements:
1. Create a string variable and get its length:
string message = "Hello, C# World!"; int length = message.Length;

2. Convert to uppercase and lowercase:
string upper = message.ToUpper(); // "HELLO, C# WORLD!" string lower = message.ToLower(); // "hello, c# world!" Note: These methods return NEW strings (strings are immutable in C#).

3. Extract substrings:
string sub1 = message.Substring(0, 5); // "Hello" (start, length) string sub2 = message.Substring(7); // "C# World!" (from index 7 to end)

4. Find characters and substrings:
int index = message.IndexOf("C#"); // 7 (position of "C#") bool contains = message.Contains("World"); // true bool starts = message.StartsWith("Hello"); // true bool ends = message.EndsWith("!"); // true

5. Replace and trim:
string replaced = message.Replace("World", "Universe"); string trimmed = " spaces ".Trim(); // "spaces"

6. Split and join:
string[] words = message.Split(' '); // Split by space string joined = string.Join("-", words); // Join with dash

💡 Pro Tips:
• Strings are immutable - methods return new strings
• Use StringBuilder for many concatenations (better performance)
string.IsNullOrEmpty(str) checks for null or ""
string.IsNullOrWhiteSpace(str) also checks for whitespace
• Use @"string" for verbatim strings (ignores escape chars)

Expected Output:
Original: Hello, C# World! Length: 16 Uppercase: HELLO, C# WORLD! Lowercase: hello, c# world! Substring: Hello Contains 'C#': True Index of 'World': 10 Replaced: Hello, C# Universe!

Requirements Checklist

Create a string and print its Length
Use ToUpper() and ToLower()
Use Substring() to extract part of string
Use Contains() or IndexOf() to search
Use Replace() to modify string content
Code compiles and demonstrates all operations
Output
// Click "Run Code" to compile and execute
Hints & Tips
• String length: message.Length (property)
• Uppercase: message.ToUpper()
• Substring: message.Substring(start, length)
• Contains: message.Contains("text")
• Replace: message.Replace("old", "new")
• Remember: String methods return NEW strings!
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below