Conditions and Loops

Conditions and Loops


Conditions and Loops

When software languages were being developed, they thought about how to make the machine make choices and consequently developed conditions whose results change depending on variables.

To avoid writing repetitive operations manually each time when they occur more than once, they also developed loops.

In this article, I will talk about conditions and loops, and I will try to explain them with examples.

Conditions

IF

The "if" statement, which means if in case of a certain condition, is commonly used. The condition is written in parentheses after if, and the command that should run is written in curly brackets.

if(condition){
code}

If the command you want to execute is a single line, you do not need to use curly brackets.

if(condition) desired command;

ELSE

It is used after the IF condition and is the case that occurs when the command inside the IF does not occur.

if(condition){command}else{command}

ELSE IF

By using else and if together, it can be used to check more conditions.

if(condition){command}else if(condition){command}else{command

SWITCH / CASE

If there are many conditions, the switch/case statement can be used.
switch(option){
case 1. option:
    code to be executed if option equals 1.
    break();
case 2. option:
    code to be executed if option equals 2.
    break();
default:
    code to be executed if no option is met.
break();
    ...
}

Loops

For

A command that runs the desired command many times as long as the condition is met.
for
 for(initial value; condition; change)
 {
 code to be executed.
 }

While

A command that runs as long as the condition is met.
 while(condition)
 {
  code to be executed;
 }

Do While

A command used for code that should run at least once even if the condition is not met.
 do{
  code to be executed;
 }while(condition);

For - Each

A loop command that works as many times as the number of elements in the array and iterates through the elements in the array

string[] array = { "Kutlay", "Melek", "Nesrin", "Ahmet", "Murat" };
 
foreach (string element in array)
{
   operation to be performed
}