C# Example: Checking a condition, branching based on the result - Biz Tech

C# Example: Checking a condition, branching based on the result

Listen
 
using System;

class Program
{
    static void Main(string[] args)
    {
        int number = 7;

        if (number % 2 == 0)
        {
            Console.WriteLine(number + " is even.");
        }
        else
        {
            Console.WriteLine(number + " is odd.");
        }

        if (number < 0)
        {
            Console.WriteLine(number + " is negative.");
        }
        else if (number == 0)
        {
            Console.WriteLine(number + " is zero.");
        }
        else
        {
            Console.WriteLine(number + " is positive.");
        }

        bool isPrime = true;
        for (int i = 2; i <= number / 2; i++)
        {
            if (number % i == 0)
            {
                isPrime = false;
                break;
            }
        }

        if (isPrime)
        {
            Console.WriteLine(number + " is prime.");
        }
        else
        {
            Console.WriteLine(number + " is not prime.");
        }
    }
}
 
 

This example checks a condition (number % 2 == 0), branches based on the result using an if-else statement, performs different actions based on the branch (Console.WriteLine()), and repeats the process for two additional conditions (number < 0 and number % i == 0). The following steps are performed:

  1. Define an int variable number with the value 7.
  2. Check if number is even using the condition number % 2 == 0.
  3. If number is even, output a message to the console saying that number is even using Console.WriteLine().
  4. If number is odd, output a message to the console saying that number is odd using Console.WriteLine().
  5. Check if number is negative, zero, or positive using an if-else if-else statement.
  6. Output a message to the console saying whether number is negative, zero, or positive using Console.WriteLine().
  7. Use a for loop to check if number is prime by iterating over all numbers between 2 and number / 2.
  8. If number is prime, output a message to the console saying that number is prime using Console.WriteLine().
  9. If number is not prime, output a message to the console saying that number is not prime using Console.WriteLine().

Note that there are many other types of conditional statements and logical operators you can use, such as switch, &&, ||, and ternary operators (?:). This example is just one possible multi-step process for working with conditional statements.