C#

Control Structures in C#

Control structures in C# are essential for directing the flow of a program. They enable developers to make decisions and repeat actions based on specific conditions. In this post, we’ll explore if statements for decision-making and various types of loops for iterative processes.

If Statements:

If statements allow you to execute a block of code if a certain condition is true. Here’s a basic example:

int number = 10;

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

Loops:

Loops are used to repeat a block of code multiple times. Let’s explore the for and while loops:

For Loop:

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

While Loop:

int counter = 0;

while (counter < 3)
{
    Console.WriteLine($"Count: {counter + 1}");
    counter++;
}

Conclusion:

Control structures are powerful tools for creating dynamic and flexible programs. If statements help you make decisions, and loops enable repetitive tasks. As you incorporate these structures into your C# projects, you’ll gain more control over the execution flow.

Danilo Cavalcante

Working with web development since 2005, currently as a senior programmer analyst. Development, maintenance, and integration of systems in C#, ASP.Net, ASP.Net MVC, .Net Core, Web API, WebService, Integrations (SOAP and REST), Object-Oriented Programming, DDD, SQL, Git, and JavaScript

Recent Posts

Encapsulation and Abstraction in C#

Encapsulation and abstraction are two pillars of object-oriented programming (OOP) that play a vital role…

4 weeks ago

Polymorphism in C#: Object-Oriented Programming

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects to take on…

4 weeks ago

Understanding Inheritance in C#

Inheritance is a cornerstone of object-oriented programming (OOP) and one of its most powerful features.…

4 weeks ago

Classes and Objects in C#: Object-Oriented Programming

In the world of C# and object-oriented programming (OOP), classes and objects form the backbone…

1 month ago

Collections and LINQ Queries in C#

In modern C# programming, working with data collections is a common task. Understanding how to…

1 month ago

Exception Handling in C#: try-catch, finally, and Custom Exceptions

Exception handling is a critical part of writing robust and maintainable C# applications. It allows…

1 month ago