Control Structure

By Notes Vandar

Control Structure

Control structures in C programming determine the flow of control in a program. They allow for decision-making, looping, and altering the normal sequential execution of statements.

3.1 Selective Structure

        In C programming, Selective Structure (also known as decision-making or conditional control structure) allows the program to choose between different actions based on conditions. It enables the program to take different paths of execution depending on whether a certain condition is true or false.

3.1.1 If statement

The if statement is the simplest form of selection. It executes a block of code only if a specified condition is true. If the condition is false, the code block is skipped.

Syntax:

if (condition) {
// Code to execute if the condition is true
}

  • Example:

    #include <stdio.h>

    int main() {
    int age = 20;
    if (age >= 18) {
    printf(“You are eligible to vote.\n”);
    }
    return 0;
    }

    Explanation: If the condition age >= 18 is true, the message “You are eligible to vote.” is printed.

3.1.2 If-else statement

The if-else statement adds an alternative code block to execute if the condition is false. So, if the condition is true, one block of code executes; otherwise, another block of code is executed.

  • Syntax:

if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

  • Example:

#include <stdio.h>

int main() {
int age = 16;
if (age >= 18) {
printf(“You are eligible to vote.\n”);
} else {
printf(“You are not eligible to vote.\n”);
}
return 0;
}

3.1.3 Nested if-else statement

A nested if-else statement refers to an if-else structure where one or more if-else statements are placed inside another if-else statement. This allows for more complex decision-making by evaluating multiple conditions within conditions.

Syntax of Nested if-else:
if (condition1) {
// Code block to execute if condition1 is true
if (condition2) {
// Code block to execute if condition2 is also true
} else {
// Code block to execute if condition2 is false
}
} else {
// Code block to execute if condition1 is false
if (condition3) {
// Code block to execute if condition3 is true
} else {
// Code block to execute if condition3 is false
}
}

Example of Nested if-else:

Consider a scenario where we need to determine the grade of a student based on their marks, with additional checks to provide specific messages for different ranges.

#include <stdio.h>

int main() {
int marks;

// Input marks from the user
printf(“Enter your marks: “);
scanf(“%d”, &marks);

// Nested if-else to determine grade
if (marks >= 90) {
printf(“Grade: A\n”);
} else {
if (marks >= 75) {
printf(“Grade: B\n”);
} else {
if (marks >= 50) {
printf(“Grade: C\n”);
} else {
printf(“Grade: F\n”);
}
}
}

return 0;
}

Explanation:

  • If the student’s marks are 90 or above, they receive an “A”.
  • If the marks are less than 90 but 75 or above, they receive a “B”.
  • If the marks are less than 75 but 50 or above, they receive a “C”.
  • If the marks are below 50, they receive a “F”

3.1.4 Switch statement

The switch statement provides a way to select one of many code blocks based on the value of an expression. It is often used as an alternative to multiple else if statements when there are many possible discrete values for the expression being tested.

  • Syntax:

switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;

default:
// Code to execute if no case matches
}

  • Example:

#include <stdio.h>

int main() {
int day = 3;

switch (day) {
case 1:
printf(“Monday\n”);
break;
case 2:
printf(“Tuesday\n”);
break;
case 3:
printf(“Wednesday\n”);
break;
case 4:
printf(“Thursday\n”);
break;
case 5:
printf(“Friday\n”);
break;
case 6:
printf(“Saturday\n”);
break;
case 7:
printf(“Sunday\n”);
break;
default:
printf(“Invalid day\n”);
}

return 0;
}

Explanation: Depending on the value of day, the corresponding case is executed. If day = 3, the message “Wednesday” is printed.

 

3.1.5 Conditional operator (:?)

In C programming, the conditional operator (?:), also known as the ternary operator, is a shorthand way of writing an if-else statement. It takes three operands and is used to evaluate a condition and return one of two values depending on whether the condition is true or false.

Syntax of the Conditional Operator:

condition ? expression1 : expression2;
  • condition: A boolean expression (an expression that evaluates to either true or false).
  • expression1: This expression is executed if the condition is true.
  • expression2: This expression is executed if the condition is false.

Example of Conditional Operator:

#include <stdio.h>

int main() {
int a = 10, b = 20;
int max;

// Using the conditional operator to find the larger number
max = (a > b) ? a : b;

printf(“The larger number is: %d\n”, max);

return 0;
}

Explanation: In this example, the conditional operator checks if a is greater than b. If the condition a > b is true, the value of a is assigned to max. Otherwise, the value of b is assigned to max. Since b = 20 is greater than a = 10, the value of b is stored in max.

3.2 Looping structure:

In C programming, a looping structure allows repeated execution of a block of code as long as a specified condition is true. Loops are commonly used when you need to perform repetitive tasks, like iterating through arrays or performing calculations multiple times.

There are three main types of looping structures in C:

  • For loop
  • While loop
  • Do-while loop
  • Nested Loops
  • Loop interrupts

3.2.3 For loop

A for loop is used when you know how many times you need to repeat the block of code.

Syntax:

for (initialization; condition; update) {
// Code to be executed
}
  • initialization: Initializes the loop control variable.
  • condition: The loop runs as long as this condition is true.
  • update: Changes the loop control variable after each iteration.

Example:

#include <stdio.h>

int main() {
int i;

// Print numbers from 1 to 5 using for loop
for (i = 1; i <= 5; i++) {
printf(“%d\n”, i);
}

return 0;
}

  • Explanation: The loop starts with i = 1 and runs while i <= 5. After each iteration, i is incremented by 1 (i++).

2. while Loop

A while loop is used when you don’t know in advance how many times the loop should run, but you know the condition that should be checked each time.

Syntax:

while (condition) {
// Code to be executed
}
  • condition: The loop continues to run as long as this condition is true. If the condition is false at the start, the loop is never executed.

Example:

#include <stdio.h>

int main() {
int i = 1;

// Print numbers from 1 to 5 using while loop
while (i <= 5) {
printf(“%d\n”, i);
i++;
}

return 0;
}

  • Explanation: The loop starts with i = 1 and runs while i <= 5. After each iteration, i is incremented by 1.

3. do-while Loop

The do-while loop is similar to the while loop, but the condition is evaluated after the loop body is executed. This guarantees that the code inside the loop runs at least once, regardless of the condition.

Syntax:

do {
// Code to be executed
} while (condition);
  • condition: After each iteration, the condition is evaluated. The loop continues to run as long as this condition is true.

Example:

#include <stdio.h>

int main() {
int i = 1;

// Print numbers from 1 to 5 using do-while loop
do {
printf(“%d\n”, i);
i++;
} while (i <= 5);

return 0;
}

  • Explanation: The code inside the do block runs first, and then the condition i <= 5 is checked. The loop continues until the condition becomes false.

3.2.4 Nested Loops

Nested loops in C refer to having one loop inside another loop. This means that for each iteration of the outer loop, the inner loop executes completely. Nested loops are often used for working with multi-dimensional data structures, like matrices or tables.

Syntax of Nested Loops:

for (initialization1; condition1; update1) { // Outer loop
for (initialization2; condition2; update2) { // Inner loop
// Code to be executed
}
}

The same logic can be applied for other types of loops (while, do-while).


Example of a Nested for Loop:

This example prints a 5×5 matrix of asterisks (*).

  • #include <stdio.h>

    int main() {
    int i, j;

    // Outer loop to handle the number of rows
    for (i = 1; i <= 5; i++) {
    // Inner loop to handle the number of columns
    for (j = 1; j <= 5; j++) {
    printf(“* “);
    }
    // Newline after each row
    printf(“\n”);
    }

    return 0;
    }

    Explanation:

    • The outer loop controls the rows (i from 1 to 5).
    • The inner loop controls the columns (j from 1 to 5).
    • After printing 5 asterisks in a row, the outer loop moves to the next iteration (next row) and repeats the process.

Output:

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

3.2.5 Loop interrupts

Loop interrupts in C programming are control statements that can alter the normal flow of loops by breaking the loop, skipping an iteration, or transferring control to another part of the program. The two primary ways to interrupt a loop in C are through the use of the break and continue statements.

. break Statement

The break statement is used to exit a loop immediately, regardless of the loop condition. It terminates the current loop and transfers control to the statement following the loop.

Syntax:

break;

Example: Using break in a loop

  • #include <stdio.h>

    int main() {
    int i;

    for (i = 1; i <= 10; i++) {
    if (i == 5) {
    break; // Exit the loop when i is 5
    }
    printf(“%d\n”, i);
    }

    return 0;
    }

    Explanation: When i reaches 5, the break statement is triggered, and the loop is exited, so the numbers 1 through 4 are printed.

Output:

1
2
3
4

2. continue Statement

The continue statement is used to skip the current iteration of the loop and move to the next iteration. Unlike break, it does not terminate the loop entirely, but simply skips the remaining code in the current iteration and proceeds with the next iteration.

Syntax:

continue;

Example: Using continue in a loop

#include <stdio.h>

int main() {
int i;

for (i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip the rest of the loop when i is 5
}
printf(“%d\n”, i);
}

return 0;
}

  • Explanation: When i reaches 5, the continue statement skips the printf function and moves to the next iteration, so 5 is not printed.

Output:

1
2
3
4
6
7
8
9
10

3. goto Statement

The goto statement provides an unconditional jump to another part of the program. Although it is not commonly used because it makes the program harder to read, it can be used to exit from deeply nested loops or complex conditional structures.

Syntax:

goto label;
// Code to be skipped
label:
// Code to be executed

Example: Using goto to exit a loop

#include <stdio.h>

int main() {
int i = 1;

while (i <= 10) {
if (i == 5) {
goto exitLoop; // Jump to label when i is 5
}
printf(“%d\n”, i);
i++;
}

exitLoop:
printf(“Loop exited when i was 5.\n”);

return 0;
}

  • Explanation: When i reaches 5, the goto statement jumps to the exitLoop label, exiting the loop without printing 5 or any further iterations.

Output:

1
2
3
4
Loop exited when i was 5.
Important Questions
Comments
Discussion
0 Comments
  Loading . . .