Form 5 C# Study Guide
Comprehensive Programming Examples with Answers
1. ALGORITHMS
An algorithm is a step-by-step procedure to solve a problem. Below are examples demonstrating
algorithmic thinking in C#.
Example 1 - Simple Addition Algorithm
Problem: Calculate the sum of two numbers input by the user.
using System;
class AdditionAlgorithm
{
static void Main()
{
[Link]("Enter first number: ");
int num1 = [Link]([Link]());
[Link]("Enter second number: ");
int num2 = [Link]([Link]());
int sum = num1 + num2;
[Link]($"Sum = {sum}");
}
}
Example 2 - Finding Maximum of Three Numbers
Problem: Find the largest number among three inputs.
using System;
class FindMaximum
{
static void Main()
{
[Link]("Enter three numbers: ");
int a = [Link]([Link]());
int b = [Link]([Link]());
int c = [Link]([Link]());
int max = a;
if (b > max) max = b;
if (c > max) max = c;
[Link]($"Maximum = {max}");
}
}
Example 3 - Swapping Two Variables
Problem: Swap values of two variables without losing data.
using System;
class SwapNumbers
{
static void Main()
{
[Link]("Enter first number: ");
int a = [Link]([Link]());
[Link]("Enter second number: ");
int b = [Link]([Link]());
[Link]($"Before: a={a}, b={b}");
int temp = a;
a = b;
b = temp;
[Link]($"After: a={a}, b={b}");
}
}
Example 4 - Calculate Average of 5 Numbers
Problem: Calculate the average of 5 numbers using an accumulator.
using System;
class CalculateAverage
{
static void Main()
{
int sum = 0;
for (int i = 1; i <= 5; i++)
{
[Link]($"Enter number {i}: ");
sum += [Link]([Link]());
}
double average = sum / 5.0;
[Link]($"Average = {average}");
}
}
Example 5 - Check Even or Odd
Problem: Determine if a number is even or odd using the modulus operator.
using System;
class EvenOrOdd
{
static void Main()
{
[Link]("Enter a number: ");
int num = [Link]([Link]());
if (num % 2 == 0)
[Link]("Even number");
else
[Link]("Odd number");
}
}
2. IF-THEN SELECTION
The IF-THEN statement executes code only when a condition is true.
Example 1 - Positive Number Check
using System;
class PositiveCheck
{
static void Main()
{
[Link]("Enter a number: ");
int num = [Link]([Link]());
if (num > 0)
[Link]("Positive number");
}
}
Example 2 - Pass/Fail Grade
using System;
class PassFail
{
static void Main()
{
[Link]("Enter marks: ");
int marks = [Link]([Link]());
if (marks >= 50)
[Link]("PASS" +
"");
else
[Link]("FAIL");
}
}
Example 3 - Voting Eligibility
using System;
class VotingEligibility
{
static void Main()
{
[Link]("Enter your age: ");
int age = [Link]([Link]());
if (age >= 18)
[Link]("You are eligible to vote.");
}
}
Example 4 - Tax Calculation
using System;
class TaxCalculation
{
static void Main()
{
[Link]("Enter income: ");
double income = [Link]([Link]());
if (income > 10000)
{
double tax = income * 0.10;
[Link]($"Tax = {tax}");
}
}
}
Example 5 - Maximum of Two Numbers
using System;
class MaxOfTwo
{
static void Main()
{
[Link]("Enter two numbers: ");
int a = [Link]([Link]());
int b = [Link]([Link]());
if (a > b)
[Link]($"Maximum = {a}");
if (b > a)
[Link]($"Maximum = {b}");
if (a == b)
[Link]("Both are equal");
}
}
3. NESTED IF-THEN-ELSE
Nested IF statements allow checking multiple conditions in sequence.
Example 1 - Grade Classification
using System;
class GradeClassification
{
static void Main()
{
[Link]("Enter marks (0-100): ");
int marks = [Link]([Link]());
if (marks >= 90)
[Link]("Grade: A");
else if (marks >= 80)
[Link]("Grade: B");
else if (marks >= 70)
[Link]("Grade: C");
else if (marks >= 60)
[Link]("Grade: D");
else
[Link]("Grade: F");
}
}
Example 2 - BMI Category
using System;
class BMICategory
{
static void Main()
{
[Link]("Enter weight (kg): ");
double weight = [Link]([Link]());
[Link]("Enter height (m): ");
double height = [Link]([Link]());
double bmi = weight / (height * height);
if (bmi < 18.5)
[Link]("Underweight");
else if (bmi < 25)
[Link]("Normal weight");
else if (bmi < 30)
[Link]("Overweight");
else
[Link]("Obese");
}
}
Example 3 - Number Comparison
using System;
class NumberCompare
{
static void Main()
{
[Link]("Enter three numbers: ");
int a = [Link]([Link]());
int b = [Link]([Link]());
int c = [Link]([Link]());
if (a > b)
{
if (a > c)
[Link]($"Largest = {a}");
else
[Link]($"Largest = {c}");
}
else
{
if (b > c)
[Link]($"Largest = {b}");
else
[Link]($"Largest = {c}");
}
}
}
Example 4 - Electricity Bill
using System;
class ElectricityBill
{
static void Main()
{
[Link]("Enter units consumed: ");
int units = [Link]([Link]());
double bill = 0;
if (units <= 100)
bill = units * 0.50;
else if (units <= 200)
bill = 50 + (units - 100) * 0.75;
else if (units <= 300)
bill = 125 + (units - 200) * 1.20;
else
bill = 245 + (units - 300) * 1.50;
[Link]($"Bill = ${bill:F2}");
}
}
Example 5 - Leap Year Check
using System;
class LeapYear
{
static void Main()
{
[Link]("Enter a year: ");
int year = [Link]([Link]());
if (year % 4 == 0)
{
if (year % 100 == 0)
{
if (year % 400 == 0)
[Link]("Leap year");
else
[Link]("Not a leap year");
}
else
[Link]("Leap year");
}
else
[Link]("Not a leap year");
}
}
4. FOR LOOP ITERATION
The FOR loop repeats code a specific number of times.
Example 1 - Print Numbers 1 to 10
using System;
class PrintNumbers
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
[Link](i + " ");
}
[Link]();
}
}
Example 2 - Sum of First N Numbers
using System;
class SumOfNNumbers
{
static void Main()
{
[Link]("Enter N: ");
int n = [Link]([Link]());
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += i;
}
[Link]($"Sum = {sum}");
}
}
Example 3 - Factorial Calculation
using System;
class Factorial
{
static void Main()
{
[Link]("Enter a number: ");
int n = [Link]([Link]());
int fact = 1;
for (int i = 1; i <= n; i++)
{
fact *= i;
}
[Link]($"{n}! = {fact}");
}
}
Example 4 - Multiplication Table
using System;
class MultiplicationTable
{
static void Main()
{
[Link]("Enter a number: ");
int n = [Link]([Link]());
for (int i = 1; i <= 10; i++)
{
[Link]($"{n} x {i} = {n * i}");
}
}
}
Example 5 - Sum of Even Numbers
using System;
class SumEvenNumbers
{
static void Main()
{
[Link]("Enter N: ");
int n = [Link]([Link]());
int sum = 0;
for (int i = 2; i <= n; i += 2)
{
sum += i;
}
[Link]($"Sum of even numbers = {sum}");
}
}
5. WHILE LOOP (Sum Until 0)
The WHILE loop continues as long as the condition is true. Useful for sentinel-controlled loops.
Example 1 - Sum Numbers Until 0 is Entered
using System;
class SumUntilZero
{
static void Main()
{
int sum = 0;
int num;
[Link]("Enter numbers (0 to stop): ");
num = [Link]([Link]());
while (num != 0)
{
sum += num;
num = [Link]([Link]());
}
[Link]($"Total sum = {sum}");
}
}
Example 2 - Count Digits
using System;
class CountDigits
{
static void Main()
{
[Link]("Enter a number: ");
int num = [Link]([Link]());
int count = 0;
while (num > 0)
{
num /= 10;
count++;
}
[Link]($"Number of digits = {count}");
}
}
Example 3 - Reverse a Number
using System;
class ReverseNumber
{
static void Main()
{
[Link]("Enter a number: ");
int num = [Link]([Link]());
int reversed = 0;
while (num > 0)
{
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
[Link]($"Reversed = {reversed}");
}
}
Example 4 - Find GCD
using System;
class FindGCD
{
static void Main()
{
[Link]("Enter two numbers: ");
int a = [Link]([Link]());
int b = [Link]([Link]());
while (a != b)
{
if (a > b)
a -= b;
else
b -= a;
}
[Link]($"GCD = {a}");
}
}
Example 5 - Power Calculation
using System;
class PowerCalculation
{
static void Main()
{
[Link]("Enter base and exponent: ");
int baseNum = [Link]([Link]());
int exp = [Link]([Link]());
int result = 1;
while (exp > 0)
{
result *= baseNum;
exp--;
}
[Link]($"Result = {result}");
}
}
6. DO-WHILE LOOP
The DO-WHILE loop executes at least once before checking the condition.
Example 1 - Menu-Driven Program
using System;
class MenuDriven
{
static void Main()
{
int choice;
do
{
[Link]("1. Say Hello");
[Link]("2. Say Goodbye");
[Link]("3. Exit");
[Link]("Enter choice: ");
choice = [Link]([Link]());
switch (choice)
{
case 1: [Link]("Hello!"); break;
case 2: [Link]("Goodbye!"); break;
}
} while (choice != 3);
}
}
Example 2 - Input Validation
using System;
class InputValidation
{
static void Main()
{
int age;
do
{
[Link]("Enter age (1-120): ");
age = [Link]([Link]());
} while (age < 1 || age > 120);
[Link]($"Valid age: {age}");
}
}
Example 3 - Sum of 5 Numbers
using System;
class SumFiveNumbers
{
static void Main()
{
int sum = 0;
int i = 1;
do
{
[Link]($"Enter number {i}: ");
sum += [Link]([Link]());
i++;
} while (i <= 5);
[Link]($"Sum = {sum}");
}
}
Example 4 - Guess the Number
using System;
class GuessNumber
{
static void Main()
{
Random rand = new Random();
int secret = [Link](1, 101);
int guess;
do
{
[Link]("Guess (1-100): ");
guess = [Link]([Link]());
if (guess < secret)
[Link]("Too low!");
else if (guess > secret)
[Link]("Too high!");
} while (guess != secret);
[Link]("Correct!");
}
}
Example 5 - Fibonacci Sequence
using System;
class Fibonacci
{
static void Main()
{
[Link]("Enter number of terms: ");
int n = [Link]([Link]());
int a = 0, b = 1;
[Link]($"{a} {b}");
for (int i = 2; i < n; i++)
{
int c = a + b;
[Link]($" {c}");
a = b;
b = c;
}
[Link]();
}
}
7. LINEAR SEARCH ALGORITHM
Linear search checks each element sequentially until the target is found.
Example 1 - Basic Linear Search
using System;
class LinearSearch
{
static void Main()
{
int[] arr = {10, 20, 30, 40, 50};
[Link]("Enter number to search: ");
int target = [Link]([Link]());
int found = -1;
for (int i = 0; i < [Link]; i++)
{
if (arr[i] == target)
{
found = i;
break;
}
}
if (found != -1)
[Link]($"Found at index {found}");
else
[Link]("Not found");
}
}
Example 2 - Linear Search with Count
using System;
class LinearSearchCount
{
static void Main()
{
string[] names = {"Alice", "Bob", "Charlie", "David", "Bob"};
[Link]("Enter name to search: ");
string target = [Link]();
int count = 0;
for (int i = 0; i < [Link]; i++)
{
if (names[i] == target)
count++;
}
[Link]($"Found {count} time(s)");
}
}
Example 3 - Linear Search with All Positions
using System;
class LinearSearchAll
{
static void Main()
{
int[] arr = {5, 3, 7, 3, 9, 3};
[Link]("Enter number: ");
int target = [Link]([Link]());
[Link]("Found at positions: ");
for (int i = 0; i < [Link]; i++)
{
if (arr[i] == target)
[Link](i + " ");
}
[Link]();
}
}
Example 4 - Search in Unsorted Array
using System;
class SearchUnsorted
{
static void Main()
{
int[] arr = {45, 12, 89, 34, 67};
[Link]("Enter number: ");
int target = [Link]([Link]());
bool found = false;
for (int i = 0; i < [Link]; i++)
{
if (arr[i] == target)
{
found = true;
break;
}
}
[Link](found ? "Found" : "Not Found");
}
}
Example 5 - Linear Search with Menu
using System;
class SearchMenu
{
static void Main()
{
int[] arr = new int[10];
[Link]("Enter 10 numbers:");
for (int i = 0; i < 10; i++)
arr[i] = [Link]([Link]());
[Link]("Enter number to find: ");
int target = [Link]([Link]());
[Link]("Array: " + [Link](", ", arr));
int pos = [Link](arr, target);
[Link](pos >= 0 ? $"At index {pos}" : "Not found");
}
}
8. BINARY SEARCH ALGORITHM
Binary search works on sorted arrays by repeatedly dividing the search interval in half.
Example 1 - Basic Binary Search
using System;
class BinarySearchBasic
{
static void Main()
{
int[] arr = {10, 20, 30, 40, 50, 60, 70};
[Link]("Enter number to search: ");
int target = [Link]([Link]());
int left = 0, right = [Link] - 1;
int result = -1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] == target)
{
result = mid;
break;
}
else if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
[Link](result >= 0 ? $"Found at {result}" : "Not found");
}
}
Example 2 - Binary Search Using Array Class
using System;
class BinarySearchLibrary
{
static void Main()
{
int[] arr = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
[Link]("Enter number: ");
int target = [Link]([Link]());
int result = [Link](arr, target);
if (result >= 0)
[Link]($"Found at index {result}");
else
[Link]("Not found");
}
}
Example 3 - Binary Search with Count
using System;
class BinarySearchCount
{
static void Main()
{
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
[Link]("Enter number: ");
int target = [Link]([Link]());
int left = 0, right = [Link];
int count = 0;
while (left < right)
{
int mid = (left + right) / 2;
count++;
if (arr[mid] <= target)
left = mid + 1;
else
right = mid;
}
[Link]($"Found in {count} comparisons");
}
}
Example 4 - First and Last Occurrence
using System;
class FirstLastOccurrence
{
static void Main()
{
int[] arr = {1, 2, 2, 2, 3, 4, 5};
[Link]("Enter number: ");
int target = [Link]([Link]());
int first = -1, last = -1;
for (int i = 0; i < [Link]; i++)
{
if (arr[i] == target)
{
if (first == -1) first = i;
last = i;
}
}
[Link]($"First: {first}, Last: {last}");
}
}
Example 5 - Search in Character Array
using System;
class BinarySearchChars
{
static void Main()
{
char[] letters = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
[Link]("Enter letter: ");
char target = [Link]([Link]());
int left = 0, right = [Link] - 1;
bool found = false;
while (left <= right)
{
int mid = (left + right) / 2;
if (letters[mid] == target)
{
found = true;
[Link]($"Found at position {mid}");
break;
}
else if (letters[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
if (!found)
[Link]("Not found");
}
}
9. BUBBLE SORT ALGORITHM
Bubble sort repeatedly swaps adjacent elements if they are in the wrong order.
Example 1 - Basic Bubble Sort
using System;
class BubbleSortBasic
{
static void Main()
{
int[] arr = {64, 34, 25, 12, 22, 11, 90};
int n = [Link];
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
[Link]("Sorted array: ");
foreach (int num in arr)
[Link](num + " ");
}
}
Example 2 - Bubble Sort (Descending)
using System;
class BubbleSortDesc
{
static void Main()
{
int[] arr = {5, 2, 8, 1, 9, 3};
for (int i = 0; i < [Link] - 1; i++)
{
for (int j = 0; j < [Link] - i - 1; j++)
{
if (arr[j] < arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
[Link]("Descending order: ");
foreach (int num in arr)
[Link](num + " ");
}
}
Example 3 - Bubble Sort with Step Counter
using System;
class BubbleSortSteps
{
static void Main()
{
int[] arr = {30, 10, 20, 50, 40};
int steps = 0;
for (int i = 0; i < [Link] - 1; i++)
{
for (int j = 0; j < [Link] - i - 1; j++)
{
steps++;
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
[Link]($"Total swaps: {steps}");
}
}
Example 4 - Optimized Bubble Sort
using System;
class BubbleSortOptimized
{
static void Main()
{
int[] arr = {1, 2, 3, 4, 5};
bool swapped;
for (int i = 0; i < [Link] - 1; i++)
{
swapped = false;
for (int j = 0; j < [Link] - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
[Link]("Sorted!");
}
}
Example 5 - String Bubble Sort
using System;
class BubbleSortStrings
{
static void Main()
{
string[] names = {"Charlie", "Alice", "Bob", "David"};
for (int i = 0; i < [Link] - 1; i++)
{
for (int j = 0; j < [Link] - i - 1; j++)
{
if ([Link](names[j], names[j + 1]) > 0)
{
string temp = names[j];
names[j] = names[j + 1];
names[j + 1] = temp;
}
}
}
foreach (string name in names)
[Link](name);
}
}
10. FORMATTING OUTPUT
C# provides various ways to format console output for better readability.
Example 1 - String Formatting
using System;
class StringFormatting
{
static void Main()
{
string name = "John";
int age = 25;
double salary = 5000.50;
[Link]("Name: " + name);
[Link]($"Age: {age}");
[Link]([Link]("Salary: {0:C2}", salary));
}
}
Example 2 - Table Formatting
using System;
class TableFormatting
{
static void Main()
{
[Link]("{0,-10} {1,10} {2,10}", "Name", "Age", "Score");
[Link]("--------------------------");
[Link]("{0,-10} {1,10} {2,10}", "Alice", 25, 95.5);
[Link]("{0,-10} {1,10} {2,10}", "Bob", 30, 87.3);
}
}
Example 3 - Decimal Formatting
using System;
class DecimalFormatting
{
static void Main()
{
double num = 123.456789;
[Link]($"Default: {num}");
[Link]($"Fixed: {num:F2}");
[Link]($"General: {num:G4}");
[Link]($"Currency: {num:C}");
[Link]($"Percentage: {0:P1}", 0.75);
}
}
Example 4 - Alignment and Padding
using System;
class AlignmentPadding
{
static void Main()
{
[Link]("|{0,-10}|{1,10}|", "Left", "Right");
[Link]("|{0,-10}|{1,10}|", "Data1", 100);
[Link]("|{0,-10}|{1,10}|", "Data2", 200);
[Link]($"{|12345678,-15:X}");
[Link]($"{|12345678,15:X}");
}
}
Example 5 - Invoice Format
using System;
class InvoiceFormat
{
static void Main()
{
[Link]("================================");
[Link](" INVOICE ");
[Link]("================================");
[Link]("{0,-20} {1,10} {2,10}", "Item", "Qty", "Amount");
[Link]("--------------------------------");
[Link]("{0,-20} {1,10} {2,10:C2}", "Apple", 5, 25.00);
[Link]("{0,-20} {1,10} {2,10:C2}", "Banana", 3, 9.00);
[Link]("================================");
[Link]("{0,-20} {1,10} {2,10:C2}", "TOTAL", "", 34.00);
}
}
11. MATH OPERATIONS
C# provides the Math class with various mathematical functions.
Example 1 - Basic Math Functions
using System;
class BasicMath
{
static void Main()
{
[Link]("Enter a number: ");
double num = [Link]([Link]());
[Link]($"Absolute: {[Link](num)}");
[Link]($"Square Root: {[Link](num):F2}");
[Link]($"Power (2^3): {[Link](2, 3)}");
[Link]($"Ceiling: {[Link](num)}");
[Link]($"Floor: {[Link](num)}");
}
}
Example 2 - Trigonometry
using System;
class Trigonometry
{
static void Main()
{
double angle = [Link] / 4; // 45 degrees
[Link]($"Sine: {[Link](angle):F4}");
[Link]($"Cosine: {[Link](angle):F4}");
[Link]($"Tangent: {[Link](angle):F4}");
[Link]($"Radians to Degrees: {[Link](angle):F2}");
}
}
Example 3 - Random Numbers
using System;
class RandomNumbers
{
static void Main()
{
Random rand = new Random();
[Link]($"Random int (1-100): {[Link](1, 101)}");
[Link]($"Random double: {[Link]():F4}");
for (int i = 0; i < 5; i++)
{
[Link]([Link](10) + " ");
}
}
}
Example 4 - Min, Max, and Clamp
using System;
class MinMaxClamp
{
static void Main()
{
int a = 15, b = 8;
[Link]($"Min: {[Link](a, b)}");
[Link]($"Max: {[Link](a, b)}");
[Link]($"Clamp 150 (0-100): {[Link](150, 0, 100)}");
[Link]($"Clamp 50 (0-100): {[Link](50, 0, 100)}");
}
}
Example 5 - Scientific Calculator
using System;
class ScientificCalc
{
static void Main()
{
[Link]($"Log(10): {[Link](10):F4}");
[Link]($"Log10(100): {Math.Log10(100):F4}");
[Link]($"Exp(2): {[Link](2):F4}");
[Link]($"PI: {[Link]:F6}");
[Link]($"E: {Math.E:F6}");
}
}
12. 1D ARRAYS
Arrays store multiple values of the same type in a single variable.
Example 1 - Declaration and Initialization
using System;
class ArrayDeclaration
{
static void Main()
{
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
for (int i = 0; i < [Link]; i++)
[Link](numbers[i] + " ");
}
}
Example 2 - Array with Initialization
using System;
class ArrayInit
{
static void Main()
{
string[] fruits = {"Apple", "Banana", "Orange", "Mango"};
[Link]("Array Length: " + [Link]);
[Link]("First fruit: " + fruits[0]);
[Link]("Last fruit: " + fruits[[Link] - 1]);
foreach (string fruit in fruits)
[Link](fruit);
}
}
Example 3 - Sum and Average
using System;
class ArraySumAverage
{
static void Main()
{
int[] marks = {85, 90, 75, 95, 80};
int sum = 0;
foreach (int mark in marks)
sum += mark;
double average = (double)sum / [Link];
[Link]($"Sum: {sum}");
[Link]($"Average: {average:F2}");
}
}
Example 4 - Find Maximum and Minimum
using System;
class ArrayMinMax
{
static void Main()
{
int[] arr = {45, 12, 89, 34, 67};
int max = arr[0], min = arr[0];
foreach (int num in arr)
{
if (num > max) max = num;
if (num < min) min = num;
}
[Link]($"Maximum: {max}");
[Link]($"Minimum: {min}");
}
}
Example 5 - Array Copy and Reverse
using System;
class ArrayCopyReverse
{
static void Main()
{
int[] original = {1, 2, 3, 4, 5};
int[] copy = new int[[Link]];
[Link](original, copy, [Link]);
[Link](copy);
[Link]("Original: " + [Link](", ", original));
[Link]("Reversed copy: " + [Link](", ", copy));
}
}
13. 2D ARRAYS
2D arrays are arrays of arrays, useful for representing matrices or tables.
Example 1 - Basic 2D Array
using System;
class Basic2DArray
{
static void Main()
{
int[,] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
[Link](matrix[i, j] + " ");
[Link]();
}
}
}
Example 2 - Matrix Addition
using System;
class MatrixAddition
{
static void Main()
{
int[,] A = {{1, 2}, {3, 4}};
int[,] B = {{5, 6}, {7, 8}};
int[,] C = new int[2, 2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
C[i, j] = A[i, j] + B[i, j];
[Link]("Result:");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
[Link](C[i, j] + " ");
[Link]();
}
}
}
Example 3 - Row and Column Sum
using System;
class RowColSum
{
static void Main()
{
int[,] arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; i++)
{
int rowSum = 0;
for (int j = 0; j < 3; j++)
rowSum += arr[i, j];
[Link]($"Row {i} sum: {rowSum}");
}
for (int j = 0; j < 3; j++)
{
int colSum = 0;
for (int i = 0; i < 3; i++)
colSum += arr[i, j];
[Link]($"Col {j} sum: {colSum}");
}
}
}
Example 4 - Identity Matrix Check
using System;
class IdentityMatrix
{
static void Main()
{
int[,] matrix = {
{1, 0, 0},
{0, 1, 0},
{0, 0, 1}
};
bool isIdentity = true;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if ((i == j && matrix[i, j] != 1) ||
(i != j && matrix[i, j] != 0))
isIdentity = false;
[Link](isIdentity ? "Identity Matrix" : "Not Identity");
}
}
Example 5 - Student Marks Table
using System;
class StudentMarks
{
static void Main()
{
string[] students = {"Alice", "Bob", "Charlie"};
string[] subjects = {"Math", "Science", "English"};
int[,] marks = {
{85, 90, 78},
{92, 88, 95},
{77, 82, 80}
};
[Link]("Student\t");
foreach (string s in subjects)
[Link](s + "\t");
[Link]();
for (int i = 0; i < 3; i++)
{
[Link](students[i] + "\t");
for (int j = 0; j < 3; j++)
[Link](marks[i, j] + "\t");
[Link]();
}
}
}
14. METHODS (Procedures)
Methods (procedures) perform actions but do not return values.
Example 1 - Simple Procedure
using System;
class SimpleProcedure
{
static void PrintMessage()
{
[Link]("Hello from method!");
}
static void Main()
{
PrintMessage();
[Link]("Main continues...");
PrintMessage();
}
}
Example 2 - Method with Parameters
using System;
class MethodParameters
{
static void PrintTriangle(int rows)
{
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
[Link]("* ");
[Link]();
}
}
static void Main()
{
PrintTriangle(5);
}
}
Example 3 - Multiple Parameters
using System;
class MultipleParameters
{
static void CalculateRectangle(int length, int width)
{
int area = length * width;
int perimeter = 2 * (length + width);
[Link]($"Area: {area}");
[Link]($"Perimeter: {perimeter}");
}
static void Main()
{
[Link]("Enter length: ");
int l = [Link]([Link]());
[Link]("Enter width: ");
int w = [Link]([Link]());
CalculateRectangle(l, w);
}
}
Example 4 - Method Overloading
using System;
class MethodOverloading
{
static void Display(int num) => [Link]($"Int: {num}");
static void Display(double num) => [Link]($"Double: {num}");
static void Display(string text) => [Link]($"String: {text}");
static void Main()
{
Display(10);
Display(3.14);
Display("Hello");
}
}
Example 5 - Void Method with ref Parameter
using System;
class RefParameter
{
static void DoubleValue(ref int num)
{
num *= 2;
}
static void Main()
{
int value = 5;
DoubleValue(ref value);
[Link]($"Value is now: {value}");
}
}
15. METHODS (With Return Value)
Functions return values to the caller using the return statement.
Example 1 - Function with Return
using System;
class FunctionReturn
{
static int Square(int num)
{
return num * num;
}
static void Main()
{
[Link]("Enter a number: ");
int n = [Link]([Link]());
int result = Square(n);
[Link]($"Square = {result}");
}
}
Example 2 - Function with Multiple Returns
using System;
class MultipleReturns
{
static string CheckGrade(int marks)
{
if (marks >= 90) return "A";
if (marks >= 80) return "B";
if (marks >= 70) return "C";
if (marks >= 60) return "D";
return "F";
}
static void Main()
{
[Link]("Enter marks: ");
int m = [Link]([Link]());
[Link]($"Grade: {CheckGrade(m)}");
}
}
Example 3 - Calculate Area and Perimeter
using System;
class AreaPerimeter
{
static double Area(double length, double width) => length * width;
static double Perimeter(double length, double width) => 2 * (length + width);
static void Main()
{
double l = 5.5, w = 3.2;
[Link]($"Area: {Area(l, w):F2}");
[Link]($"Perimeter: {Perimeter(l, w):F2}");
}
}
Example 4 - Recursive Function
using System;
class RecursiveFactorial
{
static long Factorial(int n)
{
if (n <= 1) return 1;
return n * Factorial(n - 1);
}
static void Main()
{
[Link]("Enter a number: ");
int n = [Link]([Link]());
[Link]($"{n}! = {Factorial(n)}");
}
}
Example 5 - Prime Number Check
using System;
class PrimeCheck
{
static bool IsPrime(int n)
{
if (n <= 1) return false;
for (int i = 2; i <= [Link](n); i++)
if (n % i == 0) return false;
return true;
}
static void Main()
{
[Link]("Enter a number: ");
int n = [Link]([Link]());
[Link](IsPrime(n) ? "Prime" : "Not Prime");
}
}
16. FILE WRITING ([Link])
Write data to text files using StreamWriter.
Example 1 - Basic File Writing
using System;
using [Link];
class FileWriting
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("[Link]"))
{
[Link]("Hello, World!");
[Link]("This is file writing in C#.");
}
[Link]("File written successfully!");
}
}
Example 2 - Write User Input to File
using System;
using [Link];
class WriteUserInput
{
static void Main()
{
[Link]("Enter your name: ");
string name = [Link]();
using (StreamWriter writer = new StreamWriter("[Link]"))
{
[Link]($"Name: {name}");
[Link]($"Date: {[Link]}");
}
[Link]("Saved!");
}
}
Example 3 - Write Array to File
using System;
using [Link];
class WriteArray
{
static void Main()
{
int[] numbers = {10, 20, 30, 40, 50};
using (StreamWriter writer = new StreamWriter("[Link]"))
{
foreach (int num in numbers)
[Link](num);
}
[Link]("Array written to file!");
}
}
Example 4 - Write Multiple Lines
using System;
using [Link];
class WriteMultipleLines
{
static void Main()
{
string[] lines = {
"Line 1",
"Line 2",
"Line 3",
"Line 4",
"Line 5"
};
[Link]("[Link]", lines);
[Link]("Lines written!");
}
}
Example 5 - Append to File
using System;
using [Link];
class AppendToFile
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("[Link]", true))
{
[Link]($"Entry at {[Link]}");
}
[Link]("Entry appended!");
}
}
17. FILE READING
Read data from text files using StreamReader or File class.
Example 1 - Basic File Reading
using System;
using [Link];
class FileReading
{
static void Main()
{
using (StreamReader reader = new StreamReader("[Link]"))
{
string line;
while ((line = [Link]()) != null)
{
[Link](line);
}
}
}
}
Example 2 - Read All Lines
using System;
using [Link];
class ReadAllLines
{
static void Main()
{
string[] lines = [Link]("[Link]");
for (int i = 0; i < [Link]; i++)
[Link]($"{i + 1}: {lines[i]}");
}
}
Example 3 - Read and Count
using System;
using [Link];
class ReadAndCount
{
static void Main()
{
string[] lines = [Link]("[Link]");
[Link]($"Total lines: {[Link]}");
int totalChars = 0;
foreach (string line in lines)
totalChars += [Link];
[Link]($"Total characters: {totalChars}");
}
}
Example 4 - Read Numbers and Sum
using System;
using [Link];
class ReadNumbersSum
{
static void Main()
{
string[] lines = [Link]("[Link]");
int sum = 0;
foreach (string line in lines)
sum += [Link](line);
[Link]($"Sum: {sum}");
}
}
Example 5 - Check File Exists
using System;
using [Link];
class CheckFileExists
{
static void Main()
{
[Link]("Enter filename: ");
string filename = [Link]();
if ([Link](filename))
{
string content = [Link](filename);
[Link]($"Content length: {[Link]}");
}
else
{
[Link]("File not found!");
}
}
}
18. ERROR HANDLING (Try-Catch)
Exception handling prevents program crashes when errors occur.
Example 1 - Basic Try-Catch
using System;
class BasicTryCatch
{
static void Main()
{
try
{
[Link]("Enter a number: ");
int num = [Link]([Link]());
[Link]($"You entered: {num}");
}
catch (FormatException)
{
[Link]("Error: Please enter a valid number!");
}
}
}
Example 2 - Division with Error Handling
using System;
class DivisionHandling
{
static void Main()
{
try
{
[Link]("Enter dividend: ");
int a = [Link]([Link]());
[Link]("Enter divisor: ");
int b = [Link]([Link]());
int result = a / b;
[Link]($"Result: {result}");
}
catch (DivideByZeroException)
{
[Link]("Error: Cannot divide by zero!");
}
catch (FormatException)
{
[Link]("Error: Invalid number format!");
}
}
}
Example 3 - File Operations with Try-Catch
using System;
using [Link];
class FileTryCatch
{
static void Main()
{
try
{
[Link]("Enter filename: ");
string filename = [Link]();
string content = [Link](filename);
[Link]($"Content:\n{content}");
}
catch (FileNotFoundException)
{
[Link]("Error: File not found!");
}
catch (Exception ex)
{
[Link]($"Error: {[Link]}");
}
}
}
Example 4 - Finally Block
using System;
class FinallyBlock
{
static void Main()
{
try
{
[Link]("Enter number: ");
int num = [Link]([Link]());
[Link]($"Square: {num * num}");
}
catch (Exception ex)
{
[Link]($"Error: {[Link]}");
}
finally
{
[Link]("Program execution complete.");
}
}
}
Example 5 - Array Bounds Checking
using System;
class ArrayBoundsCheck
{
static void Main()
{
int[] arr = {1, 2, 3, 4, 5};
try
{
[Link]("Enter index (0-4): ");
int index = [Link]([Link]());
[Link]($"Value: {arr[index]}");
}
catch (IndexOutOfRangeException)
{
[Link]("Error: Index out of bounds!");
}
catch (FormatException)
{
[Link]("Error: Invalid index!");
}
}
}