SWITCH STATEMENT AND LOOPS IN C++
SWITCH STATEMENT:
In C++, theswitch
statement provides a way to make decisions based on the value of a variable or expression. It's particularly useful when you have a variable with discrete, integral values (like integers or characters) and want to execute different code blocks based on its value.
Here’s the basic structure of a switch
statement:
Explanation:
switch (expression)
begins theswitch
statement whereexpression
is evaluated. This expression should result in an integral type (likeint
,char
,enum
, etc.).case value1:
andcase value2:
: These are the different cases that theexpression
might match. If theexpression
matchesvalue1
, the code block followingcase value1:
will be executed. If it matchesvalue2
, the code block followingcase value2:
will be executed, and so on.break;
This statement is used to exit theswitch
block. After executing the code for a matching casecase
, thebreak
statement ensures that the program doesn't continue executing the code for subsequent cases. Ifbreak
is omitted, execution will continue to the nextcase
, potentially causing unintended behavior.default:
(optional): This is used when none of the cases match the value of theexpression
. It's similar to anelse
in anif-else
statement. If nodefault
is specified and no cases match, theswitch
statement simply completes without any specific action.
Example:
In this example, the program will output “Wednesday” because the value of day
is 3, and it matches the case 3:
label in the switch
statement. Thebreak;
statement ensures that once a matching case is found and executed, the switch statement exits without checking further cases. If day
were 6, thedefault
case would execute, printing "Weekend.".
LOOPS:
For Loop:
The for
loop in C++ is a control flow statement used for iterating a specific number of times. It's commonly used when the number of iterations is known beforehand.
Here’s the structure of a for
loop:
Explanation:
initialization
typically initializes a counter variable used in the loop. It runs only once at the beginning of the loop.condition
specifies the condition for executing the loop. It's evaluated before each iteration. If the condition is true, the loop continues; otherwise, it terminates.update
modifies the counter variable or any other variables used in the loop after each iteration.- The code block within curly braces
{}
is the body of the loop, containing the code to be executed repeatedly as long as the condition remains true.
Example:
Explanation of the example:
int i = 0;
initializes the loop counteri
to 0.i < 5;
is the condition. The loop will continue as long asi
is less than 5.++i
incrementsi
by 1 in each iteration (i++
ori += 1
would have the same effect). This is the update step.
In this example, the loop starts with i = 0
and continues until i
becomes equal to 5. The loop body prints the value ofi
each time it runs, resulting in output from 0
to 4
.
While Loop:
while
loop in C++ is a control flow statement used for the repetitive execution of a block of code based on a condition. It continues to execute as long as the condition remains true.
Here’s the structure of a while
loop:
Explanation:
condition
A boolean expression or a condition that controls the loop. If the condition is true, the loop continues to execute; otherwise, it terminates.- The code block within curly braces
{}
is the body of the loop, containing the code to be executed repeatedly as long as the condition remains true.
Example:
Explanation of the example:
int j = 0;
initializes a counter variablej
to 0 before the loop starts.while (j < 5)
specifies the condition for the loop to continue. As long asj
is less than 5, the loop will execute.++j;
incrementsj
by 1 in each iteration. This step is crucial to avoid an infinite loop; without it, the loop will continue indefinitely.
In this example, the loop starts with j = 0
and continues until j
becomes equal to 5. Inside the loop, the value of j
is printed, resulting in output from 0
to4
.
Thewhile
loop is useful when the number of iterations is not known beforehand and the loop needs to execute based on a condition. Ensure that the condition eventually becomes false to avoid infinite loops.
Do While Loop:
do-while
loop in C++ is a control flow statement that executes a block of code at least once and then repeatedly executes the block as long as a specified condition is true.
Here’s the structure of a do-while
loop:
Explanation:
- The code block within curly braces
{}
is the body of the loop, containing the code to be executed. condition
A boolean expression or a condition that controls the loop. The loop continues to execute as long as this condition remains true.- The
do
keyword initiates the loop and guarantees the code block is executed at least once before checking the condition.
Example:
Explanation of the example:
int k = 0;
initializes a counter variablek
to 0 before the loop starts.do { ... }
defines the block of code to be executed. In this case, it simply prints the value ofk
.while (k < 5);
specifies the condition for the loop to continue. As long ask
is less than 5, the loop will execute.++k;
incrementsk
by 1 in each iteration.
In this example, the loop starts withk = 0
, and the value of k
is printed. Then, it incrementsk
by 1 and repeats this process until k
becomes equal to 5. Therefore, the output will be from 0
to 4
.
The do-while
loop is particularly useful when you need to execute a block of code at least once, regardless of the condition. It ensures that the code within thedo
block executes before checking the condition for the first time.
Ranged Based For Loop:
The range-basedfor
loop in C++11 later allows you to iterate over elements in a range, such as arrays, containers, or sequences, without the need for explicit indexing.
Here’s the structure of a range-based for
loop:
Explanation:
element_type
The type of each element in the range. It's often automatically deduced based on the range.element
The variable that will represent each element in the range.range
The collection or sequence over which the loop will iterate.
Example:
Explanation of the example:
vector<int> numbers = {1, 2, 3, 4, 5};
creates a vectornumbers
containing integers.for (int number : numbers)
initiates a loop that iterates over each element in thenumbers
vector.int number
represents each element in the vector andcout << number << " ";
prints each number followed by a space.- The loop iterates through the
numbers
vector, printing each element, resulting in an output1 2 3 4 5
.
The range-basedfor
loop simplifies iteration over containers or sequences by handling the iteration logic internally, making the code cleaner and less error-prone compared to traditional indexed loops.