Tuesday 30 January 2024

Understanding Structured Programming: A Foundation for Code Clarity and Control

 

Structured programming is a way of writing computer programs that focuses on making them clear and easy to understand. It does this by using lots of smaller parts called subroutines or functions, along with blocks of code and loops (like "for" and "while" loops).

 

In a structured program, the main program is split into many functions, and each one does a specific job. These functions can also use other functions. This approach helps in making programs that are of better quality, easier to read, and faster to develop.

 

Prior to structured programming

Before structured programming became popular in the late 1950s and early 1960s, most programming was done in a unstructured way. This wasn't really a single, organized method, but more like a mix of different ways of writing programs that didn't have the organized and clear rules that structured programming brought in. Here are some main points about unstructured programming:

 

1.   Using a lot of GOTO statements: In unstructured programming, there was a big emphasis on GOTO statements. These let the program jump around to different parts at any time. This often led to messy and complicated "spaghetti code" that was hard to follow, with lots of jumps and connections. This made it really tough to understand, fix, and look after the code.

2.   Limited use of control flow statements: In unstructured programming, even though control structures like if-else were available, they weren't used as much or in a standard way like in structured programming. This resulted in using GOTO statements for simple decisions and loops, which added to the complexity and made the program harder to manage.

3.   Widespread use of global variables: In unstructured programming, there was a strong reliance on global variables, which any part of the program could access. This approach, without specific scopes, limited the program's modularity and created strong links between different parts of the code. As a result, it was easier to accidentally change things and cause unpredictable outcomes.

4.   No modularity: Programs in unstructured programming were often composed of big, single-piece blocks of code with little organization. This approach made it difficult to use the same code again in different parts or to work together effectively on the same project. As a result, it was harder to develop and maintain these programs efficiently.

5.   Emphasis on machine architecture: Unstructured programming often reflected the underlying architecture of the computers of the time, focusing on direct manipulation of memory and hardware details. This made code less portable and adaptable to different machines and operating systems. Example: Assembly language is a low-level language directly interacts with the computer's hardware and instructions.

While unstructured programming played a key role in the early days of computing, it ultimately reached its limitations due to the issues mentioned above. The adoption of structured programming with its emphasis on clarity, control, and modularity represented a significant step forward in software development, leading to more reliable, maintainable, and efficient code.

 

Problems with Unstructured Programming

1.   Tangled Code: Programs often didn't have a well-defined structure, looking more like a jumbled mix of GOTO statements and jumps. This made them hard to follow, maintain, and fix.

2.   Unpredictable Flow: The overuse of GOTO statements created chaotic and hard-to-predict paths through the code, which raised the chances of mistakes and surprising outcomes.

3.   Problems with Data Handling: The common use of global variables created strong dependencies and accidental changes in the code, leading to errors and unstable programs.

4.   Ineffecient Development: The repetitive nature of the code and the lack of organized sections made it harder to work efficiently and collaborate with others.

 

Key concepts of structured programming

1.   Structured programming guides how a program runs using three key concepts or tools:

 

a.    Sequential execution: The program runs commands in the exact order they appear in the code.

b.    Conditional statements (if-else): This lets the program choose between different actions depending on certain conditions. If a condition is met, it follows one group of commands; if not, it takes a different path.

c.    Loops (for, while): These are used to repeat actions in the program several times, usually until a specific condition is fulfilled.

2.   Use of Subroutines or Functions: In structured programming, there's a strong focus on using subroutines, also called functions or procedures. This approach helps in reusing code and keeping it organized into separate modules. Each subroutine is designed to perform a particular task and can be tested separately from the rest of the program, making it easier to manage and debug.

3.   Using Local Variables and Scope: Structured programming involves using local variables within specific subroutines or code blocks. This method helps keep different parts of the program separate, cutting down on interdependencies and the likelihood of mistakes. In this setup, each section or function has its own defined scope.

4.   Clear Control Flow: Structured programming uses loops and conditional structures for controlling program flow, rather than relying on goto statements, which can create messy code. This approach enhances the readability of the code. While programming languages might still have goto statements, their use is generally limited. For more insights, you can read the paper https://homepages.cwi.nl/~storm/teaching/reader/Dijkstra68.pdf  to get more information

5.   Breaking Down the Problem: In structured programming, you start by outlining the big picture of your program and then gradually split it into smaller, more specific parts. This step-by-step refinement helps in handling complex programs more easily, making them easier to understand and develop.

6.   Use of Global Variables: In structured programming, global variables are often used to hold data that different functions within the program might need. This is straightforward for small programs, but in larger ones, it can lead to issues and make the code more difficult to manage.

 

Example of structured programming

Imagine writing a program to calculate the area of different shapes. Using structured programming, you could define separate functions for calculating the area of a square, rectangle, triangle, and so on. Each function would take the necessary dimensions as input and return the calculated area. The main program could then prompt the user for the desired shape and dimensions, call the appropriate function, and display the result.

 

ShapeAreaCalculator.c 

#include <stdio.h>

// Function prototypes
double squareArea(double side);
double rectangleArea(double length, double width);
double triangleArea(double base, double height);
void calculateAndDisplayArea();

int main() {
    // Call the function that handles the area calculation and display
    calculateAndDisplayArea();
    return 0;
}

// Function to calculate the area of a square
double squareArea(double side) {
    return side * side;
}

// Function to calculate the area of a rectangle
double rectangleArea(double length, double width) {
    return length * width;
}

// Function to calculate the area of a triangle
double triangleArea(double base, double height) {
    return 0.5 * base * height;
}

// Function to handle user input, calculate and display the area
void calculateAndDisplayArea() {
    int choice;
    double area, side, length, width, base, height;

    printf("Choose a shape to calculate the area:\n");
    printf("1. Square\n2. Rectangle\n3. Triangle\n");
    printf("Enter your choice (1-3): ");
    scanf("%d", &choice);

    switch (choice) {
        case 1: // Square
            printf("Enter the length of the side of the square: ");
            scanf("%lf", &side);
            area = squareArea(side);
            printf("Area of the square: %.2lf\n", area);
            break;

        case 2: // Rectangle
            printf("Enter the length and width of the rectangle: ");
            scanf("%lf %lf", &length, &width);
            area = rectangleArea(length, width);
            printf("Area of the rectangle: %.2lf\n", area);
            break;

        case 3: // Triangle
            printf("Enter the base and height of the triangle: ");
            scanf("%lf %lf", &base, &height);
            area = triangleArea(base, height);
            printf("Area of the triangle: %.2lf\n", area);
            break;

        default:
            printf("Invalid choice.\n");
    }
}

Sample Output

Choose a shape to calculate the area:
1. Square
2. Rectangle
3. Triangle
Enter your choice (1-3): 2
Enter the length and width of the rectangle: 10 35
Area of the rectangle: 350.00

 

This program defines calculateAndDisplayArea function encapsulates the logic for prompting the user, receiving input, calculating the area, and displaying the result. Based on the user input, the call goes to squareArea, rectangleArea, triangleArea functions.

 

Popular structured programming languages

1.   C,

2.   Pascal,

3.   Ada,

4.   ALGOL,

5.   PL/I (Programming Language One).

 

Even though Java and Python supports object-oriented features, its core structure reflects a strong foundation in structured programming principles.

 

Benefits of Structured Programming

1.   Code is easy to understand and debug: The code is well-arranged and follows a straightforward path, which makes it simpler to grasp the program's operations and pinpoint potential errors.

2.   Modular and Reusable: Functions can be reused in different programs, reducing redundancy and promoting code maintainability.

3.   Enhanced Readability: Programs written with this approach are easier to read and understand.

4.   Easier Testing and Debugging: The modular nature and separation of different parts of the program make testing and fixing issues more straightforward.

 

Drawbacks of Structured Programming

1.   Handling Complexity: As programs become bigger and more complex, managing global variables and function calls can become challenging.

2.   Less expressive: Compared to object-oriented and functional programming, structured programs are less expressive and might not be used for solving certain types of problems.

3.   Limited code reusability: Although structured programming allows for subroutine reuse within the same program, it doesn't naturally offer ways to easily reuse code across multiple programs. This is in contrast to Object-Oriented Programming (OOP), which focuses on objects and inheritance to facilitate code reuse.

 

In summary, structured programming laid the groundwork for further advancements in programming techniques, including object-oriented and functional programming.

 

 

                                                             System Design Questions

No comments:

Post a Comment