Control Structure

By Paribesh Sapkota

Control Structures

Control Structures are just a way to specify flow of control in programs. Any algorithm or program can be more clear and understood if they use self-contained modules called as logic or control structures. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions.

Characteristics:

  • Control statements serve to control the execution flow of a program.
  • Control statements in C are classified into selection statements, iteration statements, and jump statements.
  • Selection statements serve to execute code based on a certain circumstance.
  • Iteration statements loop through a code block until a condition is met.
  • Jump statements serve to move control from one section of a program to another.
  • The if statement, for loop, while loop, switch statement, break statement, and continue statement are C’s most widely used control statements.

 

There are three basic types of logic, or flow of control, known as:

  1. Sequence logic, or sequential flow
  2. Selection logic, or conditional flow
  3. Iteration logic, or repetitive flow

Sequential Logic (Sequential Flow)

Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the series of instructions given to the computer. Unless new instructions are given, the modules are executed in the obvious sequence. The sequences may be given, by means of numbered steps explicitly. Also, implicitly follows the order in which modules are written. Most of the processing, even some complex problems, will generally follow this elementary flow pattern.

 

Decision Statements(Selective Control Structure)

In selective control structure, selection is made on the basis of condition. We have options to go when the given condition is true or false. The flow of program statements execution is totally directed by the result obtained from checking condition. Hence, program statements using selective control structures are also called conditional statements. It can mainly be categorized into two types.

  • Conditional Statement
  • Switch-Case Statement

Conditional Statement
It is the most common decision making control structure which controls the flow of program statement execution based on the condition checked. it  can be used in different forms as:

  • if statement
  • if else statement
  • if else if statement (Multipath Conditional Statement/ if-else ladder)
  • nested if else statement

if statement

This is the simplest form of conditional statement in which statements are executed if the test expression (condition) is true. When condition is false there is no option to go within this structure; in such situation control must get out from the structure and statements outside this structure will be executed.

if(expression){  
//code to be executed  
}

Flowchart of if statement in C

#include<stdio.h>    
int main(){    
int number=0;    
printf("Enter a number:");    
scanf("%d",&number);    
if(number%2==0){    
printf("%d is even number",number);    
}    
return 0;  
}

 

Output

Enter a number:4
4 is even number
enter a number:5

Program to find the largest number of the three.

#include <stdio.h>  
int main()  
{  
    int a, b, c;   
     printf("Enter three numbers?");  
    scanf("%d %d %d",&a,&b,&c);  
    if(a>b && a>c)  
    {  
        printf("%d is largest",a);  
    }  
    if(b>a  && b > c)  
    {  
        printf("%d is largest",b);  
    }  
    if(c>a && c>b)  
    {  
        printf("%d is largest",c);  
    }  
    if(a == b && a == c)   
    {  
        printf("All are equal");   
    }  
}

Output

Enter three numbers?
12 23 34
34 is largest

If-else Statement

The if-else statement is a conditional statement used for decision-making. It allows us to execute different blocks of code based on whether a certain condition evaluates to true or false. The basic syntax of the if-else statement is as follows:

if (condition) {
    // Code block to be executed if the condition is true
} else {
    // Code block to be executed if the condition is false
}

Here’s a breakdown of how it works:

  • The condition is an expression that evaluates to either true or false.
  • If the condition is true, the code block immediately following the if statement is executed.
  • If the condition is false, the code block immediately following the else statement is executed.
  • The else block is optional. If it’s not included, the program will simply skip the code block associated with the else statement if the if condition evaluates to false.

 

Flowchart of the if-else statement in C

#include<stdio.h>    
int main(){    
int number=0;    
printf("enter a number:");    
scanf("%d",&number);     
if(number%2==0){    
printf("%d is even number",number);    
}    
else{    
printf("%d is odd number",number);    
}     
return 0;  
}

Output

enter a number:4
4 is even number
enter a number:5
5 is odd number

Program to check whether a person is eligible to vote or not.

#include <stdio.h>  
int main()  
{  
    int age;   
    printf("Enter your age?");   
    scanf("%d",&age);  
    if(age>=18)  
    {  
        printf("You are eligible to vote...");   
    }  
    else   
    {  
        printf("Sorry ... you can't vote");   
    }  
}

Output

Enter your age?18
You are eligible to vote...
Enter your age?13
Sorry ... you can't vote

example
#include <stdio.h>

int main() {
    int num = 10;

    if (num > 0) {
        printf("%d is positive.\n", num);
    } else {
        printf("%d is not positive.\n", num);
    }

    return 0;
}

In this example:

  • The condition num > 0 checks if the variable num is greater than 0.
  • If the condition is true (which it is because num is 10), the program executes the code block inside the if statement, printing that 10 is positive.
  • If the condition is false, the program executes the code block inside the else statement (which in this case doesn’t happen).

if else if Statement

The if-else if statement is an extension of the basic if-else statement. It allows you to test multiple conditions and execute different blocks of code based on which condition evaluates to true first. This construct is particularly useful when you have multiple conditions to consider.

The syntax of the if-else if statement is as follows:

if (condition1) {
    // Code block to be executed if condition1 is true
} else if (condition2) {
    // Code block to be executed if condition2 is true
} else if (condition3) {
    // Code block to be executed if condition3 is true
}
...
else {
    // Code block to be executed if none of the above conditions are true
}

Here’s how it works:

  • The program evaluates each condition in sequence until one of them is true.
  • If a condition evaluates to true, the corresponding code block is executed, and the program skips the remaining conditions.
  • If none of the conditions evaluate to true, the code block associated with the else statement (if present) is executed.

Here’s an example:

#include <stdio.h>

int main() {
    int num = 10;

    if (num > 0) {
        printf("%d is positive.\n", num);
    } else if (num < 0) {
        printf("%d is negative.\n", num);
    } else {
        printf("%d is zero.\n", num);
    }

    return 0;
}

In this example:

  • The first condition num > 0 checks if the variable num is greater than 0.
  • If this condition is true, the program prints that 10 is positive.
  • If the first condition is false, the program checks the next condition num < 0, which checks if num is less than 0.
  • If this condition is true, the program prints that 10 is negative.
  • If neither of the conditions is true (which is not the case here), the program executes the code block associated with the else statement, printing that 10 is zero.

 

Program to calculate the grade of the student according to the specified marks.

#include <stdio.h>  
int main()  
{  
    int marks;   
    printf("Enter your marks?");  
    scanf("%d",&marks);   
    if(marks > 85 && marks <= 100)  
    {  
        printf("Congrats ! you scored grade A ...");   
    }  
    else if (marks > 60 && marks <= 85)   
    {  
        printf("You scored grade B + ...");  
    }  
    else if (marks > 40 && marks <= 60)   
    {  
        printf("You scored grade B ...");  
    }  
    else if (marks > 30 && marks <= 40)   
    {  
        printf("You scored grade C ...");   
    }  
    else   
    {  
        printf("Sorry you are fail ...");   
    }  
}

Output

Enter your marks?10
Sorry you are fail ...
Enter your marks?40
You scored grade C ...
Enter your marks?90
Congrats ! you scored grade A ...

Nested if-else in C

A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement. Yes, C allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement.

Syntax of Nested if-else

if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
   else
   {
         // Executes when condition2 is false
}

Flowchart of Nested if-else

Example of Nested if-else

#include <stdio.h>

int main() {
    int num1 = 10;
    int num2 = 5;

    if (num1 > 0) {
        if (num2 > 0) {
            printf("Both numbers are positive.\n");
        } else {
            printf("Num1 is positive, but num2 is not.\n");
        }
    } else {
        if (num2 > 0) {
            printf("Num2 is positive, but num1 is not.\n");
        } else {
            printf("Both numbers are non-positive.\n");
        }
    }

    return 0;
}

In this example:

  • We have two variables num1 and num2 with values 10 and 5, respectively.
  • We use nested if-else statements to check the positivity of both numbers.
  • If num1 is positive (num1 > 0), we enter the inner if-else statement to check the positivity of num2.
  • If both num1 and num2 are positive, it prints “Both numbers are positive.”
  • If num1 is positive but num2 is not, it prints “Num1 is positive, but num2 is not.”
  • If num1 is not positive (num1 <= 0), we enter the else block of the outer if statement, and similar checks are performed for num2.
  • Finally, if neither num1 nor num2 is positive, it prints “Both numbers are non-positive.”

C Switch Statement

switch statement is a control flow statement used to select one of many code blocks to be executed based on the value of a variable or an expression. It provides an alternative way to express multiple conditional branches compared to using multiple if-else if-else statements. The switch statement is particularly useful when you have a large number of conditions to evaluate.

The basic syntax of the switch statement is as follows:

switch (expression) {
    case constant1:
        // Code block to be executed if expression equals constant1
        break;
    case constant2:
        // Code block to be executed if expression equals constant2
        break;
    // More case statements as needed
    default:
        // Code block to be executed if expression doesn't match any case constant
}

Here’s a breakdown of how it works:

  • The expression is evaluated once and its value is compared with the values of the case constants.
  • If a match is found between the expression and a case constant, the code block associated with that case label is executed.
  • The break statement terminates the switch statement. Without it, control falls through to the next case label. This behavior allows for executing multiple cases together.
  • If no match is found between the expression and any case constant, the code block associated with the default label (if present) is executed. The default case is optional.

Flowchart of switch statement in C

Example of a switch statement in C

#include<stdio.h>  
int main(){    
int number=0;     
printf("enter a number:");    
scanf("%d",&number);    
switch(number){    
case 10:    
printf("number is equals to 10");    
break;    
case 50:    
printf("number is equal to 50");    
break;    
case 100:    
printf("number is equal to 100");    
break;    
default:    
printf("number is not equal to 10, 50 or 100");    
}    
return 0;  
}

Output

enter a number:4
number is not equal to 10, 50 or 100

enter a number:50
number is equal to 50

Break and Default keyword in Switch statement

Let us explain and define the “break” and “default” keywords in the context of the switch statement, along with example code and output.

1. Break Keyword:

The “break” keyword is used within the code block of each case to terminate the switch statement prematurely. When the program encounters a “break” statement inside a case block, it immediately exits the switch statement, preventing the execution of subsequent case blocks. The “break” statement is crucial for avoiding switch statements’ “fall-through” behavior.

Example:

Let’s take a program to understand the use of the break keyword in C.

#include <stdio.h>  
int main() {  
int num = 3;  
  
switch (num) {  
case 1:  
printf("Value is 1\n");  
break; // Exit the switch statement after executing this case block  
case 2:  
printf("Value is 2\n");  
break; // Exit the switch statement after executing this case block  
case 3:  
printf("Value is 3\n");  
break; // Exit the switch statement after executing this case block  
default:  
printf("Value is not 1, 2, or 3\n");  
break; // Exit the switch statement after executing the default case block  
}  
  
return 0;  
}

Output

Value is 3

Explanation:

In this example, the switch statement evaluates the value of the variable num (which is 3) and matches it with case 3. The code block associated with case 3 is executed, printing “Value is 3” to the console. The “break” statement within case 3 ensures that the program exits the switch statement immediately after executing this case block, preventing the execution of any other cases.

Default Keyword:

When none of the case constants match the evaluated expression, it operates as a catch-all case. If no matching case exists and a “default” case exists, the code block associated with the “default” case is run. It is often used to handle circumstances where none of the stated situations apply to the provided input.

Example:

Let’s take a program to understand the use of the default keyword in C.

#include <stdio.h>  
int main() {  
int num = 5;  
  
switch (num) {  
case 1:  
printf("Value is 1\n");  
break;  
case 2:  
printf("Value is 2\n");  
break;  
case 3:  
printf("Value is 3\n");  
break;  
default:  
printf("Value is not 1, 2, or 3\n");  
break; // Exit the switch statement after executing the default case block  
}  
  
return 0;  
}

Output

Value is not 1, 2, or 3

Explanation:

In this example, the switch statement examines the value of the variable num (which is 5). Because no case matches the num, the program performs the code block associated with the “default” case. The “break” statement inside the “default” case ensures that the program exits the switch statement after executing the “default” case block.

Both the “break” and “default” keywords play essential roles in controlling the flow of execution within a switch statement. The “break” statement helps prevent the fall-through behavior, while the “default” case provides a way to handle unmatched cases.

Nested switch case statement

We can use as many switch statement as we want inside a switch statement. Such type of statements is called nested switch case statements. Consider the following example.

#include <stdio.h>  
int main () {  
  
   int i = 10;  
   int j = 20;  
   
   switch(i) {  
     
      case 10:   
         printf("the value of i evaluated in outer switch: %d\n",i);  
      case 20:  
         switch(j) {  
            case 20:  
               printf("The value of j evaluated in nested switch: %d\n",j);  
         }  
   }  
     
   printf("Exact value of i is : %d\n", i );  
   printf("Exact value of j is : %d\n", j );  
   
   return 0;  
}

Output

the value of i evaluated in outer switch: 10
The value of j evaluated in nested switch: 20
Exact value of i is : 10
Exact value of j is : 20 


C Loops

In C programming, loops are used to execute a block of code repeatedly until a specified condition is met. There are three main types of loops in C: for, while, and do-while. Each loop has its own syntax and use cases.

for Loop:

The for loop is used when you know how many times you want to execute a block of code. It consists of three parts: initialization, condition, and increment/decrement. syntax
for (initialization; condition; increment/decrement) {
    // Code to be executed repeatedly
}

Flowchart of for Loop

 

example:
wap to display number from 1 t0 10 using for loop in c

#include <stdio.h>

int main() {
    int i;

    // Using a for loop to display numbers from 1 to 10
    for (i = 1; i <= 10; i++) {
        printf("%d\n", i);
    }

    return 0;
}

In this program:

  • We declare an integer variable i to use as the loop counter.
  • The for loop is initialized with i = 1 to start from 1.
  • The loop condition is i <= 10, meaning the loop will continue as long as i is less than or equal to 10.
  • After each iteration, i is incremented by 1 (i++).
  • Inside the loop, we print the value of i using printf.
  • The loop continues until i reaches 10, and then the program terminates.

while Loop: The while loop is used when you want to execute a block of code as long as a condition is true. It evaluates the condition before executing the block of code.

syntax

while (condition) {
    // Code to be executed repeatedly
}

Flowchart of while loop in C

 

example:

  1. Display your name 10 times on the screen using a while loop:
#include <stdio.h>

int main() {
    int count = 0;

    // Displaying the name 10 times using a while loop
    while (count < 10) {
        printf("Your Name\n");
        count++;
    }

    return 0;
}

2. Display the series from 10 to 1 using a while loop:

#include <stdio.h>

int main() {
    int num = 10;

    // Displaying the series from 10 to 1 using a while loop
    while (num >= 1) {
        printf("%d ", num);
        num--;
    }

    return 0;
}

3. Calculate and display the sum of odd natural numbers up to n using a while loop:

#include <stdio.h>

int main() {
    int n, sum = 0, num = 1;

    printf("Enter a number: ");
    scanf("%d", &n);

    // Calculating and displaying the sum of odd natural numbers up to n
    while (num <= n) {
        sum += num;
        num += 2; // Incrementing num by 2 to get the next odd number
    }

    printf("Sum of odd natural numbers up to %d is: %d\n", n, sum);

    return 0;
}

 

do-while Loop: The do-while loop is similar to the while loop, but it evaluates the condition after executing the block of code, so the block of code is guaranteed to execute at least once.

syntax

do {
    // Code to be executed repeatedly
} while (condition);

do…while Loop Flowchart

example:

  1. Calculate and display the series 1,8,27,… up to the 10th term using a do-while loop:
    #include <stdio.h>
    
    int main() {
        int term = 1;
        int num = 1;
    
        // Displaying the series up to the 10th term using a do-while loop
        do {
            printf("%d ", num);
            num = num * term;
            term++;
        } while (term <= 10);
    
        return 0;
    }
    

    2. Display the series 15,9,… up to the 20th term using a do-while loop:

    #include <stdio.h>
    
    int main() {
        int term = 1;
        int num = 15;
    
        // Displaying the series up to the 20th term using a do-while loop
        do {
            printf("%d ", num);
            num = num - 6;
            term++;
        } while (term <= 20);
    
        return 0;
    }
    

    3. Display the multiplication table of any number given by the user using a do-while loop:

    #include <stdio.h>
    
    int main() {
        int num, i = 1;
    
        printf("Enter a number: ");
        scanf("%d", &num);
    
        printf("Multiplication table of %d:\n", num);
    
        // Displaying the multiplication table using a do-while loop
        do {
            printf("%d x %d = %d\n", num, i, num * i);
            i++;
        } while (i <= 10);
    
        return 0;
    }
    

    Continue Statement

    The C continue statement resets program control to the beginning of the loop when encountered. As a result, the current iteration of the loop gets skipped and the control moves on to the next iteration. Statements after the continue statement in the loop are not executed.

Syntax of continue in C

The syntax of continue is just the continue keyword placed wherever we want in the loop body.

continue;

Use of continue in C

The continue statement in C can be used in any kind of loop to skip the current iteration. In C, we can use it in the following types of loops:

  • Single Loops
  • Nested Loops

Using continue in infinite loops is not useful as skipping the current iteration won’t make a difference when the number of iterations is infinite.

// C program to explain the use
// of continue statement with for loop
#include <stdio.h>
int main()
{
    // for loop to print 1 to 8
    for (int i = 1; i <= 8; i++) {
        // when i = 4, the iteration will be skipped and for
        // will not be printed
        if (i == 4) {
            continue;
        }
        printf("%d ", i);
    }
    printf("\n");
    int i = 0;
    // while loop to print 1 to 8
    while (i < 8) {
        // when i = 4, the iteration will be skipped and for
        // will not be printed
        i++;
        if (i == 4) {
            continue;
        }
        printf("%d ", i);
    }
    return 0;
}

Output

1 2 3 5 6 7 8 
1 2 3 5 6 7 8

Example 2: C Program to use continue in a nested loop

The continue statement will only work in a single loop at a time. So in the case of nested loops, we can use the continue statement to skip the current iteration of the inner loop when using nested loops.

C

// C program to explain the use
// of continue statement with nested loops
#include <stdio.h>
int main()
{
    // outer loop with 3 iterations
    for (int i = 1; i <= 3; i++) {
        // inner loop to print integer 1 to 4
        for (int j = 0; j <= 4; j++) {
            // continue to skip printing number 3
            if (j == 3) {
                continue;
            }
            printf("%d ", j);
        }
        printf("\n");
    }
    return 0;
}

Output

0 1 2 4 
0 1 2 4 
0 1 2 4

Flowchart of continue in C

Break Statement 

The break in C is a loop control statement that breaks out of the loop when encountered. It can be used inside loops or switch statements to bring the control out of the block. The break statement can only break out of a single loop at a time.

Syntax of break in C

break;

Use of break in C

The break statement in C is used for breaking out of the loop. We can use it with any type of loop to bring the program control out of the loop. In C, we can use the break statement in the following ways:

  • Simple Loops
  • Nested Loops
  • Infinite Loops
  • Switch case
Important Questions
Comments
Discussion
0 Comments
  Loading . . .