Gmetrix Domain#1 Textbook

Introduction to Programming – C#

1. Algorithms and Flowcharts

  • Algorithm: A set of ordered, finite steps to solve a problem.

  • Can be represented as:

    • Flowchart: Visual representation of the algorithm.

    • Decision table: A table showing conditions and outcomes.

  • Helps plan programs before coding, making the logic clearer.


2. Variables and Data Types

  • Variable: Placeholder for storing values.

    • Has a name and data type.

    • Determines what operations can be performed on it.

  • Constants: Values that cannot be changed after assignment.

  • Example data types:

    • int (4 bytes on 32-bit systems)

    • byte (0–255)

    • char (single character)

  • Arrays use zero-based indexing (array[0] = first element).


3. Control Structures

3.1 Conditional Branching
  • if-else statement: Executes code based on Boolean conditions.

  • switch statement:

    • Selects code to execute based on the value of an expression.

    • case labels can fall through if no code is specified.

    • default handles unmatched cases.

3.2 Loops (Repetition)
  • while loop:

    • Tests the condition before executing the loop body.

    • Structure:

      while(condition) { statements }
      
    • If the condition is initially false, the loop may not execute at all.

  • do-while loop:

    • Tests the condition after executing the loop body (executes at least once).

    • Structure:

      do { statements } while(condition);
      
  • for loop:

    • Compact loop with initializer, condition, and termination expression.

    • Example:

      for(int i=1; i<=5; i++) { Console.WriteLine(i); }
      
    • Can create infinite loops if expressions are omitted: for(;;) { }

  • foreach loop:

    • Iterates over collections (arrays, lists) without worrying about indexing.

    • Syntax:

      foreach(ElementType element in collection) { statements }
      

4. Methods

  • Methods allow reusable code and modular design.

  • Recursive methods: A method that calls itself.

    • Base case: Stops recursion to prevent infinite calls.

    • Recursive case: Calls the method with a smaller or simpler input.

    • Example (factorial):

      public static int Factorial(int n)
      {
          if(n == 0) return 1; // Base case
          return n * Factorial(n - 1); // Recursive case
      }
      

5. Exception Handling

  • Exception: Runtime error detected during program execution.

  • Without handling, an exception stops the program.

  • Use try-catch-finally blocks to handle exceptions safely:

    • try: Contains code that might throw an exception.

    • catch: Handles specific or generic exceptions.

    • finally: Always executes, for cleanup (closing files, releasing resources, resetting variables).

  • Order matters: List specific exceptions first, then generic ones.

  • Example:

    StreamReader sr = null;
    try
    {
        sr = File.OpenText("data.txt");
        Console.WriteLine(sr.ReadToEnd());
    }
    catch(FileNotFoundException fnfe)
    {
        Console.WriteLine(fnfe.Message);
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        if(sr != null) sr.Close();
    }
    
  • This ensures:

    • The file is always closed, even if an exception occurs.

    • Errors are handled gracefully without crashing the program.

  • Common exceptions:

    • DivideByZeroException – dividing by zero.

    • StackOverflowException – infinite recursion.

    • FileNotFoundException – missing file.

  • Best practice: Always include a finally block if you need to release resources.


6. Operators

  • Ternary operator (? :): Takes three arguments for inline conditional expressions.

  • Standard operators: arithmetic (+, -, *, /), relational (==, !=, >, <), logical (&&, ||), assignment (=, +=).


7. Practical Scenarios

7.1 Decision Table Example
  • If quantity determines discount:

public static double CalculateDiscount(int quantity)
{
    if(quantity < 10) return 0.05;
    else if(quantity < 50) return 0.10;
    else if(quantity < 100) return 0.15;
    else return 0.20;
}
7.2 Factorial (Iteration & Recursion)
  • Iterative:

int fact = 1;
while(n > 1) { fact *= n; n--; }
  • Recursive:

int Factorial(int n) => (n == 0) ? 1 : n * Factorial(n - 1);
7.3 Handling Arithmetic Exceptions
public static double Divide(int x, int y)
{
    try { return x / y; }
    catch(ArithmeticException ae) { Console.WriteLine(ae.Message); return 0; }
    catch(Exception e) { Console.WriteLine(e.Message); return 0; }
}
7.4 Recursive Utility Example
  • Count significant digits in an integer:

public static int CountDigits(int n)
{
    if(n == 0) return 0;
    return 1 + CountDigits(n / 10);
}

8. Key Takeaways

  • Algorithms are the blueprint for coding.

  • Choose if-else vs. switch based on readability and condition type.

  • Loops simplify repetitive tasks:

    • while = pre-condition check

    • do-while = post-condition check

    • for = count-controlled iteration

    • foreach = collection iteration

  • Recursion must have a base case to avoid infinite recursion.

  • Always handle exceptions to prevent program crashes.

  • finally ensures resources are released even if an exception occurs.

  • Decision tables help organize complex conditional logic for readability.