Branches and Loops

Make decisions using the if statement

// if statement is executed
int a = 5;
int b = 6;
if (a + b > 10)
{
    Console.WriteLine("The answer is greater than 10.");
}

// if statement is skipped
b = 3;
if (a + b > 10)
{
    Console.WriteLine("The answer is greater than 10.");
}

Make if and else work together

// if/else
int a = 5;
int b = 3;
if (a + b > 10)
{
    Console.WriteLine("The answer is greater than 10.");
}
else
{
    Console.WriteLine("The answer is not greater than 10.");
}

// and
a = 5;
b = 3;
int c = 4;
if ((a + b + c > 10) && (a == b))
{
    Console.WriteLine("The answer is greater than 10");
    Console.WriteLine("And the first number is equal to the second");
}
else
{
    Console.WriteLine("The answer is not greater than 10");
    Console.WriteLine("Or the first number is not equal to the second");
}

// or
a = 5;
b = 3;
c = 4;
if ((a + b + c > 10) || (a == b))
{
    Console.WriteLine("The answer is greater than 10");
    Console.WriteLine("Or the first number is equal to the second");
}
else
{
    Console.WriteLine("The answer is not greater than 10");
    Console.WriteLine("And the first number is not equal to the second");
}

Use loops to repeat operations

// while loop
int counter = 0;
while (counter < 10)
{
    Console.WriteLine($"Hello World! The counter is {counter}");
    counter++; // or counter += 1, just like Python
}

// do/while loop
counter = 0;
do
{
    Console.WriteLine($"Hello World! The counter is {counter}");
    counter++; 
} while (counter < 10);

Work with the for loop

// for loop
for (int counter = 0; counter < 10; counter++)
{
    Console.WriteLine($"Hello World! The counter is {counter}");
}

Created nested loops

// Nested loop
for (int row = 1; row < 11; row++)
{
  for (char column = 'a'; column < 'k'; column++)
  {
    Console.WriteLine($"The cell is ({row}, {column})");
  }
}

Combine branches and loops

// Find the sum of all integers 1 through 20 that are divisible by 3
int result = 0;

for (int i = 1; i <= 20; i++)
{
    if (i % 3 == 0)
    {
        result += i;
    }
}

Console.WriteLine($"The answer is {result}"); // The answer is 63

Last updated