Summary of Step 3 and Step 4: C# Basics


Step 3: If-Statements (Making Decisions)

In Step 3, you learned how to make decisions in your program using if-statements. This allows your program to run different code depending on certain conditions.

  • If-Statement: Executes a block of code if a specified condition is true.

    • Example:
int age = 18;
if (age >= 18)
{
Console.WriteLine("You are old enough to drive!");
}
else
{
Console.WriteLine("You are not old enough to drive.");
}

Else If: Used to check additional conditions if the first if condition is false.

  • Example:

if (score >= 90)
{
Console.WriteLine(“You got an A!”);
}
else if (score >= 80)
{
Console.WriteLine(“You got a B!”);
}
else
{
Console.WriteLine(“You need to study more.”);
}

Logical Operators: You can check multiple conditions with && (AND) and || (OR).

  • Example:
if (age >= 13 && age <= 19)
{
Console.WriteLine("You are a teenager.");
}

Logical Operators: You can check multiple conditions with && (AND) and || (OR).

  • Example:
if (age >= 13 && age <= 19)
{
Console.WriteLine("You are a teenager.");
}

Step 4: Loops (Repeating Code)

In Step 4, you learned how to use loops to repeat code multiple times, making your programs more efficient.

  • For Loop: Repeats a block of code a specific number of times.

    • Example:
       
      for (int i = 0; i < 5; i++) { Console.WriteLine("Iteration " + i); }
  • While Loop: Repeats a block of code while a condition is true.

    • Example:
       
      int i = 0; while (i < 5) { Console.WriteLine(i); i++; }
  • Do-While Loop: Similar to the while loop but guarantees that the code inside the loop runs at least once.

    • Example:
      int i = 0; do { Console.WriteLine(i); i++; } while (i < 5); 
       

Key Takeaways:

  • If-statements help your program make decisions based on conditions.
  • Loops allow your program to repeat code, which is useful when you need to do the same task multiple times (e.g., printing numbers or iterating over a list).

Both if-statements and loops are essential tools for creating interactive and efficient programs.