Constructs used in structured programming

[1] Structured programming is a programming paradigm that emphasizes the use of a structured control flow in algorithms and programs. It is based on the idea that an algorithm or program should be broken down into smaller, self-contained blocks of code, or “constructs,” that can be easily understood and maintained.

There are several constructs commonly used in structured programming, including:

  1. Sequential control: This construct is used to specify that a set of statements should be executed in a specific order, one after the other.
  2. Selection control: This construct is used to specify that a certain set of statements should be executed only if a certain condition is met. Selection control is often implemented using if and else statements.
  3. Iteration control: This construct is used to specify that a certain set of statements should be executed repeatedly, either a fixed number of times or until a certain condition is met. Iteration control is often implemented using for and while loops.
  4. By using these and other structured programming constructs, algorithms and programs can be made more readable, maintainable, and efficient. Structured programming is widely used in many programming languages and is considered to be a fundamental concept in computer science.

Sequential control or sequence statements

Sequential control, also known as sequence statements, is a construct used in programming to specify that a set of statements should be executed in a specific order, one after the other.

Here is an example of sequential control in C:

#include <stdio.h>

int main()
{
    // Sequence of statements
    printf("Hello, world!\n");
    printf("I am learning C programming.\n");
    printf("This is a sequential control example.\n");

    return 0;
}

In this example, the statements printf(“Hello, world!\n”);, printf(“I am learning C programming.\n”);, and printf(“This is a sequential control example.\n”); are executed in sequence, one after the other. The first statement is executed first, followed by the second statement, and so on.

Sequential control is a basic construct used in many programming languages and is often used to specify a simple sequence of statements that should be executed in order.

Selection Control or Selection Statements


Selection control, also known as selection statements, is a construct used in programming to specify that a certain set of statements should be executed only if a certain condition is met.

There are two main types of selection statements in C: if statements and switch statements.

Here is an example of an if statement in C:

#include <stdio.h>

int main()
{
    int a = 5;
    int b = 10;

    // If statement
    if (a < b)
    {
        printf("a is less than b\n");
    }
    else
    {
        printf("a is not less than b\n");
    }

    return 0;
}

In this example, the if statement checks the condition a < b. If the condition is true, the statement printf(“a is less than b\n”); is executed. If the condition is false, the statement printf(“a is not less than b\n”); is executed instead.

Selection control is a useful construct for making decisions and branching the flow of an algorithm or program based on certain conditions. It is widely used in many programming languages.

The various types of if statements

There are several types of if statements that can be used in programming:

  1. Simple if statement: This is the most basic form of the if statement and is used to execute a single statement or block of statements if a certain condition is true. It has the following syntax:
if (condition)
{
    // statements to be executed
}

2. ifelse statement: This form of the if statement is used to execute a different set of statements if the condition is false. It has the following syntax:

if (condition)
{
    // statements to be executed if condition is true
}
else
{
    // statements to be executed if condition is false
}



3. cascading if or ifelse ifelse statement:

Cascading if statements, also known as “chained if statements” are a series of if statements that are connected using the else if construct.

This form of the if statement is used to test multiple conditions and execute different sets of statements based on the results. It has the following syntax:


if (condition 1)
{
    // statements to be executed if condition 1 is true
}
else if (condition 2)
{
    // statements to be executed if condition 2 is true
}
...
else if (condition n)
{
    // statements to be executed if condition n is true
}
else
{
    // statements to be executed if all conditions are false
}

When are the various types of if statements used?

Here is a table showing when you might want to use a simple if statement, an ifelse statement, or an ifelse ifelse statement:

StatementWhen to use
Simple if– When you want to execute a single statement or block of statements if a certain condition is true
– When you only need to check one condition
– When you don’t need to execute any statements if the condition is false
if-else– When you want to execute a different set of statements if the condition is false
– When you only need to check one condition and have two possible outcomes
if-else if-else– When you want to check multiple conditions and execute different sets of statements based on the results
– When you have multiple possible outcomes and need to check multiple conditions
– When you want to specify a default action to be taken if all conditions are false
Nested if statements (if statements inside of other if statements)

Nested if statements are if statements that are placed inside the block of another if statement. They are used to test multiple conditions within the same block of code.

Here is an example of nested if statements in C:

#include <stdio.h>

int main()
{
    int a = 5;
    int b = 10;

    // Nested if statements
    if (a < b)
    {
        if (a % 2 == 0)
        {
            printf("a is even and less than b\n");
        }
        else
        {
            printf("a is odd and less than b\n");
        }
    }
    else
    {
        printf("a is not less than b\n");
    }

    return 0;
}

In this example, the inner if statement tests the condition a % 2 == 0 and the outer if statement tests the condition a < b. The inner if statement is executed only if the outer if statement’s condition is true.

Nested if statements can be useful for testing multiple conditions within the same block of code and allowing for more complex decision-making in algorithms and programs. However, they can also make code more difficult to read and understand, so it’s important to use them judiciously.

The Switch Statement

A switch statement is a control flow construct used in programming to specify multiple branching statements based on the value of an expression. It is often used as an alternative to a series of ifelse statements, particularly when there are multiple possible outcomes and a large number of conditions to check.

Here is an example of a switch statement in C:

int main()
{
    int a = 5;

    // Switch statement
    switch (a)
    {
        case 1:
            printf("a is 1\n");
            break;
        case 2:
            printf("a is 2\n");
            break;
        case 3:
            printf("a is 3\n");
            break;
        default:
            printf("a is not 1, 2, or 3\n");
    }

    return 0;
}

In this example, the switch statement checks the value of the variable a. If the value of a is 1, the statement printf(“a is 1\n”); is executed. If the value of a is 2, the statement printf(“a is 2\n”); is executed. If the value of a is 3, the statement printf(“a is 3\n”); is executed. If the value of a is none of these, the statement printf(“a is not 1, 2, or 3\n”); is executed.

Switch statements can be more efficient than a series of ifelse statements when there are many possible outcomes, as they use a faster lookup method to determine which branch to take. However, they are generally less flexible than ifelse statements and can only be used with a limited set of data types.

Comparison of selection Constructs

Here is a table comparing the if statement and the switch statement:

if statementswitch statement
Syntaxif (condition) { statements; }switch (expression) { case value: statements; break; … default: statements; }
Data typesCan be used with any data typeCan only be used with certain data types (integer, character, and enumerated types)
Multiple conditionsCan test multiple conditions using ifelse ifelseCan test multiple conditions using case and break
Range of valuesCan test for any range of valuesCan only test for specific values or ranges
EfficiencyMay be less efficient than a switch statement when there are many possible outcomesMay be more efficient than an if statement when there are many possible outcomes
FlexibilityMore flexible than a switch statementLess flexible than an if statement

In general, you might use an if statement when you need to test multiple conditions or check for a range of values, or when you are working with data types that are not supported by switch statements. You might use a switch statement when you have a large number of possible outcomes and want to take advantage of its faster lookup method, or when you are working with integer, character, or enumerated data types.

Iteration Constructs

Iteration constructs, also known as looping constructs, are programming constructs that allow a set of statements to be repeated multiple times. There are several types of iteration constructs in most programming languages, including for loops, while loops, and dowhile loops.

Iteration constructs are useful for repeating a set of statements multiple times and are widely used in many programming languages. They can be used to iterate through data structures such as arrays and lists, or to perform tasks repeatedly until a certain condition is met.

There are several types of iteration constructs that are commonly used in programming:

  1. for loops:
    for loops are used to execute a set of statements a specific number of times. They have the following syntax:

    for (initialization; condition; increment)

{

                         //statements to be executed

}

The initialization statement is executed before the loop starts. The condition is tested at the beginning of each iteration. If the condition is true, the statements in the loop are executed. If the condition is false, the loop is terminated. The increment statement is executed at the end of each iteration.

Here is an example of a for loop in C:

#include <stdio.h>

int main()
{
    int i;

    // For loop
    for (i = 0; i < 10; i++)
    {
        printf("%d\n", i);
    }

    return 0;
}

In this example, the for loop iterates 10 times, starting at 0 and ending at 9. On each iteration, the value of i is printed to the screen.

  1. while loops:
    while loops are used to execute a set of statements while a certain condition is true. They have the following syntax:
while (condition) 
{ 
// statements to be executed 
} 

The condition is tested at the beginning of each iteration. If the condition is true, the statements in the loop are executed. If the condition is false, the loop is terminated.

Example:

#include <stdio.h>

int main()
{
    int i = 0;

    // While loop
    while (i < 10)
    {
        printf("%d\n", i);
        i++;
    }

    return 0;
}

This while loop iterates 10 times, starting at 0 and ending at 9. On each iteration, the value of i is printed to the screen, and then i is incremented by 1.

  1. dowhile loops: dowhile loops are similar to while loops, but the condition is tested at the end of each iteration instead of at the beginning. They have the following syntax:
do 
{ 

// statements to be executed 

}while (condition); 

The statements in the loop are executed first, and then the condition is tested. If the condition is true, the loop is repeated. If the condition is false, the loop is terminated.

Here is a simple example of a dowhile loop in C:

int main()
{
    int i = 0;

    // Do-while loop
    do
    {
        printf("%d\n", i);
        i++;
    }
    while (i < 10);

    return 0;
}

Each of these iteration constructs has its own use cases and can be useful in different situations. for loops are useful when you know how many times you want to iterate in advance, while loops are useful when you want to iterate as long as a certain condition is true, and dowhile loops are useful when you want to execute the statements in the loop at least once before testing

Bounded and Unbounded iteration

Bounded iteration is a type of iteration that has a fixed number of iterations. An example of bounded iteration is finding the sum of the numbers in an array.

Here is an example of bounded iteration in C to find the sum of the numbers in an array:

#include <stdio.h>

int main()
{
    int numbers[5] = {1, 2, 3, 4, 5};
    int sum = 0;
    int i;

    // Bounded iteration
    for (i = 0; i < 5; i++)
    {
        sum += numbers[i];
    }

    printf("Sum: %d\n", sum);

    return 0;
}

In this example, the for loop iterates 5 times, starting at 0 and ending at 4. On each iteration, the value of numbers[i] is added to the sum variable. At the end of the loop, the value of sum is printed to the screen.

Unbounded iteration is a type of iteration that has an unknown number of iterations. An example of unbounded iteration is a guessing game where the player keeps guessing a number until they guess the correct answer.

Here is an example of unbounded iteration in C to implement a guessing game:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int secret = rand() % 100; // Generate a random number between 0 and 99
    int guess;

    // Unbounded iteration
    while (1)
    {
        printf("Guess a number: ");
        scanf("%d", &guess);

        if (guess == secret)
        {
            printf("You guessed the secret number!\n");
            break;
        }
        else if (guess < secret)
        {
            printf("Your guess is too low.\n");
        }
        else
        {
            printf("Your guess is too high.\n");
        }
    }

    return 0;
}


In this example, the while loop iterates indefinitely until the player guesses the correct number. On each iteration, the player is prompted to enter a guess, and the value of the guess is checked against the secret number. If the guess is correct, the loop is terminated and a message is printed to the screen. If the guess

Comparison of Iteration constructs

Here is a table comparing the different iteration constructs:

for loopwhile loopdo-while loop
Syntaxfor (initialization; condition; increment) { statements; }while (condition) { statements; }do { statements; } while (condition);
Testing conditionAt the beginning of each iterationAt the beginning of each iterationAt the end of each iteration
TerminationWhen the condition is falseWhen the condition is falseWhen the condition is false
Number of iterationsFixed number of iterationsUnknown number of iterationsUnknown number of iterations
Use casesWhen you know how many times you want to iterate in advanceWhen you want to iterate as long as a certain condition is trueWhen you want to execute the statements in the loop at least once before testing the condition

Each of these iteration constructs has its own use cases and can be useful in different situations. for loops are useful when you know how many times you want to iterate in advance, while loops are useful when you want to iterate as long as a certain condition is true, and dowhile loops are useful when you want to execute the statements in the loop at least once before testing the condition.

Sentinel value

A sentinel value is a special value that is used to indicate the end of a sequence of data. It is often used in combination with iteration constructs, such as while loops or dowhile loops, to allow the loop to terminate when the sentinel value is encountered.

Here is an example of using a sentinel value in a while loop in C to read a sequence of numbers from the user and sum them up:

#include <stdio.h>

int main()
{
    int sum = 0;
    int number;

    printf("Enter numbers to sum, or -1 to stop: ");
    scanf("%d", &number);

    // While loop with sentinel value
    while (number != -1)
    {
        sum += number;
        scanf("%d", &number);
    }

    printf("Sum: %d\n", sum);

    return 0;
}

In this example, the while loop iterates as long as the value of number is not -1. On each iteration, the value of number is added to the sum variable and then the user is prompted to enter another number. When the user enters -1, the loop is terminated and the value of sum is printed to the screen.

Sentinel values can be useful in situations where the number of data items is unknown or variable, as they allow the loop to terminate when the end of the data is reached. However, it is important to choose a sentinel value that cannot occur as a valid data item in order to avoid any confusion.


[1] TA-Note

Ways of representing algorithms

There are several ways in which algorithms can be represented:

  1. Narrative form : An algorithm can also be represented using narrative form, such as English or another human language. This representation is often used to describe algorithms in a way that is easy for humans to understand, but it can be difficult to translate into a programming language.

  2. Pseudocode: Pseudocode is a way of representing an algorithm using a combination of natural language and programming language constructs. It is often used to represent algorithms in a way that is easy for humans to understand, but that can also be easily translated into a programming language.
  3. Flowcharts: A flowchart is a graphical representation of an algorithm that uses symbols to represent different parts of the algorithm, such as input, output, decision-making, and loops. Flowcharts are often used to represent algorithms in a way that is easy for humans to understand and visualize.

Narrative form

Narrative form is a way of representing an algorithm using a story or a sequence of events. This representation is often used to describe algorithms in a way that is easy for humans to understand, but it can be difficult to translate into a programming language.

For example, an algorithm for sorting a list of numbers could be represented in narrative form as follows:

  1. Start with an unsorted list of numbers.
  2. Compare the first two numbers in the list. If the first number is larger than the second number, swap their positions.
  3. Compare the second and third numbers in the list. If the second number is larger than the third number, swap their positions.
  4. Continue comparing and swapping pairs of numbers until the end of the list is reached.
  5. Repeat the process until the list is sorted in ascending order.

Here is an example of an algorithm in narrative form that explains the steps for using a menu system to withdraw money from an ATM:

  1. Start at the main menu of the ATM.
  2. Choose the “Withdraw” option from the menu.
  3. Enter the amount of money you want to withdraw.
  4. Confirm the amount of money you want to withdraw.
  5. If the ATM has enough money to dispense the requested amount, it will dispense the cash and return to the main menu. If the ATM does not have enough money, it will display an error message and return to the main menu.
  6. If you want to make another transaction, return to the main menu and choose a different option. If you are finished, choose the “Exit” option from the menu to end the transaction and return to the main menu.

Narrative form is often used to describe algorithms in a way that is easy for humans to understand, but it is not as precise as other forms of representation, such as pseudocode or programming language.

Pseudocode

Pseudocode is a way of representing an algorithm using a combination of natural language and programming language constructs. It is often used to represent algorithms in a way that is easy for humans to understand, but that can also be easily translated into a programming language.

Here is an example of pseudocode for calculating the simple interest on a loan:

START CalculateSimpleInterest(principal, rate, time)

    INPUT: float principal, float rate, float time

    OUTPUT: float interest

    interest <- principal * rate * time

    RETURN interest

END

This pseudocode represents an algorithm that calculates the simple interest on a loan given the principal amount, interest rate, and time period. It starts by calculating the interest as the product of the principal, rate, and time. It then returns the value of interest as the output of the algorithm.

In this pseudocode, principal, rate, and time are the input variables, and interest is the output variable. The keyword START indicates the start of the algorithm, and the keyword END indicates the end of the algorithm. The keyword INPUT specifies the input variables, and the keyword OUTPUT specifies the output variable. The keyword RETURN is used to return the output of the algorithm.

Flowchart

Flowchart symbols are graphical symbols used to represent different parts of an by showing the flow from one step to another. Here are some common flowchart symbols and their meanings:

  1. Oval or Circle: The oval or circle symbol represents the start or end of an algorithm.
  2. Rectangle: The rectangle symbol represents a process step or action.
  3. Diamond: The diamond symbol represents a decision point or branching point in the algorithm. It is used to represent a decision that must be made, with different branches leading to different outcomes based on the decision.
  4. Arrow: The arrow symbol represents the flow of the algorithm and is used to connect different symbols in the flowchart.
  5. Parallelogram: The parallelogram symbol represents input or output in the algorithm.
  6. Terminal: The terminal symbol represents the start or end of a subprocess within the main algorithm.
  7. Process: The process symbol represents a process step that involves some kind of manipulation or calculation.
  8. Predefined Process: The predefined process symbol represents a process step that involves using a predefined function or procedure.
  9. Off-page Connector: The off-page connector symbol represents a connection to a separate page or subprocess within the main algorithm.

Flowchart symbols are used to represent the different steps and decisions in an algorithm in a way that is easy for humans to understand and visualize. They are an important tool for representing algorithms and are widely used in a variety of fields.

Algorithms compared

Here is a table showing the advantages and disadvantages of algorithms represented in different forms:

FormAdvantagesDisadvantages
Narrative– Easy for humans to understand– Not precise
– Can be used to describe complex algorithms in an intuitive way– Difficult to translate into a programming language
– Can be used to communicate algorithms to people who are not familiar with programming languages
Pseudocode– Easy for humans to understand– Still, it is not  a real programming language, so it may require some translation to be implemented in a computer program
– Can be easily translated into a programming language
– Allows for a high level of precision and detail
Flowchart– Easy for humans to understand and visualize– May require more time and effort to create than pseudocode or narrative forms
– Can be used to communicate algorithms to people who are not familiar with programming languages– May not be as precise as pseudocode
– Can be helpful for understanding and debugging algorithms

As you can see, each form of representation has its own advantages and disadvantages. The form that is most suitable for a given situation will depend on the needs and goals of the person representing the algorithm.


[1] TA-Note