Control Statements:
Control Statements are used to control the flow of program. They allow us to make decisions, iterations, and perform different actions based on conditions. Some Control statements include:
1. If Statements:
The if
statement is used to execute a block of code if a certain condition is true.
Syntax:
if (condition)
{
// code
}
2. If-else Statements:
The if-else
statement is used to execute one block of code if a condition is true and another block of code if the condition is false.
Syntax:
if (condition)
{
// Code executed when condition is true
}
else
{
// Code executed when condition is false
}
3. If else if else
The if-else if-else
statement is used when there are multiple conditions to be checked.
Syntax:
if (condition1)
{
// Code executed if condition1 is true
}
else if (condition2)
{
// Code executed when condition2 is true
}
else
{
// Code executed when none of the conditions are true
}
4. switch Statement:
The switch
statement is used to evaluate a variable against multiple possible constant values.
Syntax:
switch (variable)
{
case value1:
// Code to be executed if variable equals value1
break;
case value2:
// Code to be executed if variable equals value2
break;
// More cases...
default:
// Code to be executed if none of the cases match
break;
}
5. while Loop:
The while
loop is used to repeatedly execute a block of code as long as a condition is true.
Syntax:
while (condition)
{
// Code to be executed in each iteration
}
6. do-while Loop:
The do-while
loop is similar to the while
loop, but it guarantees that the block of code is executed at least once before checking the condition.
Syntax:
do
{
// Code to be executed in each iteration
}
while (condition);
7. for Loop:
The for
loop is used to iterate a specific number of times.
Syntax:
for (initialization; condition; increment)
{
// Code to be executed in each iteration
}
8. foreach Loop:
The foreach
loop is used to iterate over elements in a collection (e.g., arrays, lists).
Syntax:
foreach (var item in collection)
{
// Code to be executed for each item in the collection
}