Back to all articles

DotNet

C# Conditions, Loops, and Methods Explained with Simple Examples

Learn how conditions, loops, and methods work in C# with simple beginner-friendly examples, including if/else, for, foreach, while, and reusable methods.

8 min read

0 comments

When you start learning C#, storing values in variables is only the beginning.

Real applications need to make decisions, repeat tasks, and reuse logic without writing the same code again and again.

That is where three important concepts come in:

  • Conditions
  • Loops
  • Methods

These are fundamental not only for C# development but also for problem-solving, interviews, and DSA.

In this article, we’ll understand each of them with simple examples.

---

1. Conditions in C#

Conditions allow a program to make decisions.

For example, suppose we want to check whether a person is eligible to vote.

int age = 20;

if (age >= 18)
{
    Console.WriteLine("Eligible to vote");
}
else
{
    Console.WriteLine("Not eligible");
}

Here, C# checks this condition:

age >= 18

If the condition is true, the if block runs.

If it is false, the else block runs.

This is one of the simplest examples of decision-making in programming.

---

Using else if

Sometimes we have more than two possible outcomes.

For example, we may want to assign grades based on marks.

int marks = 75;

if (marks >= 80)
{
    Console.WriteLine("Grade A");
}
else if (marks >= 60)
{
    Console.WriteLine("Grade B");
}
else
{
    Console.WriteLine("Grade C");
}

The conditions are checked from top to bottom.

In this example:

marks >= 80

is false.

The next condition:

marks >= 60

is true, so the output will be:

Grade B

Once C# finds a matching branch, it does not check the remaining branches.

---

Common Conditional Operators

Here are some operators you will frequently use in conditions:

OperatorMeaning
------------------------------------------------------------------------
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
&&Both conditions must be true
``At least one condition must be true
!Reverses a boolean value

One common beginner mistake is confusing = with ==.

int age = 20;

Here, = means assignment.

But:

age == 20

means comparison.

It checks whether age is equal to 20.

---

Example: Employee Bonus Eligibility

Suppose an employee qualifies for a bonus if:

  • the employee is active
  • and the salary is below 60000

We can write:

bool isActive = true;
decimal salary = 50000m;

if (isActive && salary < 60000)
{
    Console.WriteLine("Eligible");
}
else
{
    Console.WriteLine("Not eligible");
}

The && operator means both conditions must be true.

This makes conditions very useful for implementing real business rules.

---

2. Loops in C#

Loops allow us to repeat a block of code.

Without loops, imagine printing numbers from 1 to 100 manually.

That would be repetitive and unnecessary.

Instead, we can use a loop.

C# provides several types of loops, but three of the most common are:

  • for
  • foreach
  • while

---

The for Loop

A for loop is useful when you know how many times you want to repeat something.

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}

Output:

1
2
3
4
5

A for loop has three important parts:

for (int i = 1; i <= 5; i++)

Initialization

int i = 1

This creates the loop counter.

Condition

i <= 5

The loop continues while this condition is true.

Increment

i++

This increases the value of i by one after each iteration.

---

Printing Even Numbers

Suppose we want to print only even numbers between 1 and 20.

for (int number = 1; number <= 20; number++)
{
    if (number % 2 == 0)
    {
        Console.WriteLine(number);
    }
}

The % operator returns the remainder after division.

For example:

8 % 2

returns:

0

So this condition:

number % 2 == 0

checks whether a number is even.

This pattern is extremely common in beginner coding problems.

---

The foreach Loop

Use foreach when you want to visit every item inside a collection.

For example:

int[] numbers = { 10, 20, 30 };

foreach (int number in numbers)
{
    Console.WriteLine(number);
}

Output:

10
20
30

A nice way to read this is:

For each number inside numbers, execute this code.

foreach is especially useful when you do not need to manage an index manually.

---

Calculating the Sum of an Array

Consider this array:

int[] numbers = { 10, 20, 30, 40 };

We can calculate the total like this:

int sum = 0;

foreach (int number in numbers)
{
    sum += number;
}

Console.WriteLine(sum);

Output:

100

Here:

sum += number;

is a shorter way of writing:

sum = sum + number;

---

The while Loop

A while loop continues as long as its condition remains true.

int count = 1;

while (count <= 3)
{
    Console.WriteLine(count);
    count++;
}

Output:

1
2
3

The condition is checked before every iteration.

One important thing to remember is that the condition should eventually become false.

Otherwise, you can create an infinite loop.

For example:

int count = 1;

while (count <= 3)
{
    Console.WriteLine(count);
}

Here, count never changes.

So the condition remains true forever.

---

3. Methods in C#

Methods help us organize and reuse code.

Instead of writing the same logic multiple times, we can place it inside a method and call that method whenever needed.

For example:

public static decimal CalculateAnnualSalary(decimal monthlySalary)
{
    return monthlySalary * 12;
}

This method calculates annual salary based on monthly salary.

We can call it like this:

decimal annualSalary = CalculateAnnualSalary(50000m);

Console.WriteLine(annualSalary);

Output:

600000

---

Understanding the Method Structure

Look at this method again:

public static decimal CalculateAnnualSalary(decimal monthlySalary)

Each part has a purpose.

public

Defines the accessibility of the method.

static

Allows us to call the method without creating an object of the class.

decimal

This is the return type.

It tells us that the method returns a decimal value.

CalculateAnnualSalary

This is the method name.

Good method names should clearly describe what the method does.

decimal monthlySalary

This is a parameter.

A parameter is a value passed into a method.

---

What Does return Do?

The return keyword sends a result back to the code that called the method.

return monthlySalary * 12;

If monthlySalary is:

50000

the method returns:

600000

---

void vs Return Types

Not every method needs to return a result.

For example:

public static void ShowMessage()
{
    Console.WriteLine("Hello");
}

The void keyword means:

This method does not return a value.

But this method:

public static decimal CalculateAnnualSalary(decimal monthlySalary)
{
    return monthlySalary * 12;
}

returns a decimal.

So the return type depends on what the method is supposed to do.

---

Creating an IsEven Method

Now let's combine methods and operators.

Suppose we want to check whether a number is even.

public static bool IsEven(int number)
{
    return number % 2 == 0;
}

Now we can call it like this:

Console.WriteLine(IsEven(8));
Console.WriteLine(IsEven(7));

Output:

True
False

The method returns a bool because the result can only be true or false.

---

Putting Everything Together

Here is a small example using conditions, loops, and methods together:

internal class Day02_ConditionsLoopsMethods
{
    public static void Run()
    {
        bool isActive = true;
        decimal salary = 50000m;

        if (isActive && salary < 60000)
        {
            Console.WriteLine("Eligible");
        }
        else
        {
            Console.WriteLine("Not eligible");
        }

        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine(i);
        }

        int[] numbers = { 10, 20, 30, 40 };

        int sum = 0;

        foreach (int number in numbers)
        {
            sum += number;
        }

        Console.WriteLine($"Total: {sum}");

        Console.WriteLine(IsEven(8));
    }

    public static bool IsEven(int number)
    {
        return number % 2 == 0;
    }
}

This small program already demonstrates three important programming concepts:

  • decision-making using conditions
  • repetition using loops
  • reusable logic using methods

---

When Should You Use Each One?

Use a condition when your program needs to make a decision.

For example:

If user is active → allow access
Otherwise → deny access

Use a for loop when you need a counter or index.

Use a foreach loop when you want to process every element in a collection.

Use a while loop when repetition depends mainly on a condition.

Use a method when a piece of logic represents a clear task and may be reused.

---

Final Thoughts

Conditions, loops, and methods are some of the most important building blocks in C#.

They may look simple at first, but almost every real application uses them extensively.

Conditions help your program decide.

Loops help your program repeat work efficiently.

Methods help keep your code reusable, readable, and organized.

If you are learning C#, don't just memorize the syntax.

Try changing the values in the examples and predict the output before running the program.

For example:

  • What happens if salary becomes 70000?
  • What happens if the loop starts from 0?
  • What happens if IsEven() receives 11?
  • Can you create an IsPositive() method yourself?

Small experiments like these are one of the best ways to build programming confidence.

Keep coding, keep experimenting, and most importantly, keep asking why the code works.

Comments

Join the discussion. Please keep comments respectful and relevant.

Loading comments...