The Blueprint of Software: Decoding Flowcharts, Runtime Errors, and C Language Essentials (Part 2)
Assalamu alaykum, Vaira. How are you? In the last episode, I talked about my programming language; today we'll go into more detail. So, let's get started.
Steps for Creating a Program
A program is written to solve a specific problem. The general steps in program development are:
Problem Specification
Problem Analysis
Program Planning
Program Development or Coding
Program Implementation
Program Documentation
Program Maintenance
A Brief Description of the Program Creation Steps
1. Problem Specification: The problem the program is intended to solve.
2. Problem Analysis: Reviewing and analyzing what needs to be done to solve the problem. If there are multiple solutions, it is necessary to review which one is most suitable for the user.
3. Program Design: This step begins after the problem analysis. Program design is the process of creating a complete plan for the program using algorithms and flowcharts. Program design is the most important step in program development.
4) Program Development or Coding: Writing a program in a language that the computer can understand is called coding. Considering the flowchart and other necessary details created for problem-solving, one must arrange the instructions in a computer language to write the program, i.e., to code.
5) Program Implementation: After writing the program, the entire program is tested. At this stage, necessary corrections are made to fully complete the program.
6) Program Documentation: After debugging, if the program works correctly, it is called a “run program.” This program must be documented for future reference. This documentation is called the program's write-up or documentation. Having the documentation makes it easier to understand the updated version later.
7) Program Maintenance: - Updating, modifying, and enhancing a program for various needs and for its improvement are all part of program maintenance.
Algorithm
If you pay close attention, you will notice that we mentioned a word called ‘algorithm’ a little while ago. What exactly is an algorithm? An algorithm is a logical and sequential description for solving a problem. The word ‘algorithm’ comes from the name of the Muslim mathematician ‘Musa al-Khwarizmi’. A programmer writes an algorithm to solve a problem by dividing it into small, sequential steps. An algorithm is an important part of any program. The algorithm determines the order in which the program will run.
Advantages of an algorithm:
It greatly helps to write algorithms in a simple and clear manner.
It helps to easily understand the program's purpose.
It helps in modifying and extending the program.
It helps in identifying program errors.
It helps to write complex programs easily and concisely.
You will understand the concept more easily by looking at the two examples below.
Example 1: Algorithm for calculating the area of a triangle
Step 1: Start.
Step 2: Accept the values for the triangle's base and height.
Step 3: Area of the triangle = \(\frac{1}{2} \times \text{base} \times \text{height}\) Calculate the area using the formula.
Step 4: Display the area of the triangle.
Step 5: End.
Example 2: Algorithm for finding the sum and average of the whole and even numbers up to 100
Step 1: Start.
Step 2: Initialize the sum and average to 0, and the counter variable to 2.
Step 3: Add the counter variable to the sum.
Step 4: Increment the counter variable by 2.
Step 5: Continue the process of steps 3 and 4 until the counter value reaches 100.
Step 6: Calculate the average by dividing the sum by 50.
Step 7: Display the sum and the average.
Step 8: End.
This is essentially how a program is created using an algorithm. Now, let's look at the flowchart.
Flowchart
A flowchart is an image-based method that uses symbols to solve a specific problem. Simply put, a flowchart is a graphical representation of an algorithm. Flowcharts are effective for easily explaining a problem after it has been analyzed. A flowchart helps you understand a program in less time and easily grasp the flow of the program. Several geometric symbols are used in flowcharts. Let's first learn about these symbols.
Description of Various Symbols
┌───────────────────────────┐ │ │ └───────────────────────────┘(Processing): This symbol is used for processing (e.g., to indicate mathematical calculations and equals).
┌───────────────────────────┐ / / / / └───────────────────────────┘ (Input): Input is provided for processing, and the result is displayed as output.
╭───────────────────────────╮ │ │ ╰───────────────────── ──────╯ (Start/End): Indicates the start/end of the program. The terminal symbol can be used multiple times in a program.
/\ / \ / \ \ / \ / \/ (Decision): This always asks a question, which has two possible answers (Yes or No).
O (Junction): Used as a connection symbol. When a large flowchart doesn't fit on one page, the connection symbol is used to draw the rest of it on another page.
→, ↓, ↑, ← (Flow direction): Indicates the flow direction of the program. It shows where to go next after executing an operation.
┌─┬───────────────────────┬─┐ │ │ │ └─┴───────────────────────┴─┘ (Subroutine): This symbol can be used to identify a section or subroutine of the main program. A program can contain multiple routines or subroutines.
┌───────────────────────┐ │ │- - - - └───────────────────────┘ (Description/Note): This symbol is used to describe an activity. It is also known as the note symbol.
Let's look at an example!
A flowchart for making tea
Let's say we need to create a flowchart for making a cup of tea with an electric kettle. For this flowchart, the problem analysis and algorithm would be as follows:
Problem Statement: The ingredients—a kettle, sugar, tea, milk, water, a spoon, a cup, etc.—are provided. The tea must be prepared by turning on the kettle.
Algorithm: Take an appropriate amount of water in the kettle and place it on the heater. Now, turn on the heater's switch. When the water heats up, add the correct amount of sugar, tea, and milk, strain the tea through a strainer into a cup, and the tea is ready.
Flowchart: The flowchart for the algorithm is shown in the figure below.
( Start )
│
▼
[/ Get the necessary items: /]
[/ Heater, kettle, tea, sugar, milk /]
│
▼
┌───────────────────────────────┐
│ Pour the appropriate amount of water into the kettle │
│ Place it on the heater with tea │
└───────────────────────────────┘
│
▼
┌────────────────────────── ─────┐
│ Turn on the heater switch │
└───────────────────────────────┘
│
▼
(○) <────────────────────── ────────┐
│ │
▼ │
┌───────────────────────────────┐ │
│ Wait a moment │ │
└───────────────────────────────┘ │
│ │
▼ │
/\ │
/ \ │
/water\ │
/ hot \─────── [ No ] ────────────────┘
\ok?/
\ /
\ /
\/
│
[ Yes ]
▼
┌───────────────────────────────┐
│ Strain the tea with a strainer │
└───────────────── ──────────────┘
│
▼
┌───────────────────────────────┐
│ Add milk and sugar to taste │
└───── ──────────────────────────┘
│
▼
┌───────────────────────────────┐
│ Serve tea in the cup │
└─── ────────────────────────────┘
│
▼
( End )
Let's see another example in the same way
Algorithm and Flowchart for adding 5 numbers
Algorithm:
Algorithm and Flowchart for Adding 5 Numbers
Algorithm:
Step 1: Start.
Step 2: Accept the 5 numbers.
Step 3: Add the 5 numbers.
Step 4: Print the sum.
Step 5: End.
Now, looking at the flowchart
( START )
│
▼
[/ Input A, B, C, D, E /]
│
▼
┌────────────── ─────┐
│ S = A + B + C + D + E │
└───────────────────┘
│
▼
[/ PRINTS /]
│
▼
( STOP )
I hope you understand the concept. Let's look at some more examples.
Algorithm and Flowchart for Calculating the Area of a Circle
Algorithm:
Step 1: Start.
Step 2: Accept the radius r of the circle as input. We will set the value of π to be π = 3.14.
Step 3: Calculate the area using \(Area = \pi * r * r\).
Step 4: Display the value of Area as the result.
Step 5: End.
Flowchart
( Start )
│
▼
[/ Input r /]
│
▼
┌─ ───────────────────────┐
│ Area = π * r * r │
└────────────────────────┘
│
▼
[/ Print Area /]
│
▼
( End )
Similarly, the algorithm and flowchart for finding the largest number among three numbers
Algorithm:
Step 1: Start.
Step 2: Accept three numbers A, B, C.
Step 3: Is A > B true?
(a) If yes, go to step 4.
(b) Otherwise, go to step 5.
Step 4: Is A > C true?
(a) If yes, print A.
(b) Otherwise, print C.
Step 5: Is B > C true?
(a) If yes, print B.
(b) Otherwise, print C.
Step 6: End.
Flowchart
( Start )
│
▼
[/ Input A, B, C /]
│
▼
/\
/ \
/ A>\
┌── [No] / B? \ [Yes] ──┐
│ \ / │
│ \ / │
│ \/ │
▼ ▼
/\ /\
/ \ / \
/ B>\ / A>\
┌── / C? \ ──┐ ┌── / C? \ ──┐
│ \ / │ │ \ / │
[Yes] \ / [No] [No] \ / [Yes]
│ \/ │ │ \/ │
▼ ▼ ▼ ▼
[/Print B/] [/Print C/] [/Print C/] [/Print A/]
│ │ │ │
└─────────────┼────┬─────┴─────────────┘
│
▼
(○)
│
▼
( End )
Calculate the product of the numbers from 1 to n
Algorithm
Step 1: Start.
Step 2: Accept the value of n as input.
Step 3: Set Sum = 1 and i = 1.
Step 4: Is i <= n true?
a. If yes, go to step 5.
b. If no, go to step 6.
Step 5: Set Sum = Sum * i and i = i + 1, and go back to step 4.
Step 6: Display the value of Sum as the result.
Step 7: End.
Flowchart
( Start )
│
▼
[/ Input n /]
│
▼
┌───────────────────┐
│ Sum = 1, i = 1 │
└───── ──────────────┘
│
▼
(○) <──────────────────────────────┐
│ │
▼ │
/\ │
/ \ │
/i<= \ │
/ n? \─────── [ No ] ───> [/ Print Sum /]
\ / │
\ / ▼
\ / ( End )
\/
│
[ Yes ]
▼
┌───────────────────┐
│ Sum = Sum * i │
└─────────────────── ┘
│
▼
┌───────────────────┐
│ i = i + 1 │
└───────────────────┘
│
└─ ─────────────────────────────────┘
Let's perform a more complex calculation based on the example above.
Algorithm and flowchart for determining the roots of the quadratic equation \(ax^2 + bx + c = 0\).
Algorithm
Step 1: Start the program.
Step 2: Accept the values of a, b, and c as input.
Step 3: If a is not zero, go to step 7.
Step 4: The equation will be linear and will have one root, which is \(-c/b\).
Step 5: Display the result.
Step 6: End program.
Step 7: Let \(D = b^2 - 4ac\).
Step 8: If D is not 0, go to step 11.
Step 9: The two roots will be equal and are \(-b/2a\).
Step 10: Go to step 13.
Step 11: If D is not greater than 0, go to step 15.
Step 12: The two roots will have different values, and they are \(\frac{-b+\sqrt{D}}{2a}\) and \(\frac{-b-\sqrt{D}}{2a}\)
Step 13: Display the values of the roots.
Step 14: Go to step 16.
Step 15: Display the imaginary values of the roots.
Step 16: End the program.
Flowchart for a Quadratic Equation
( Start )
│
▼
[/ Input a, b, c /]
│
▼
/\
/ \
/a=0?\ ─── [Yes] ───> ┌──────────┐
\ / │ x = -c/b │
\ / └──────────┘
\/ │
│ ▼
[ No ] [/ Print x /]
│ │
▼ │
┌────────────────┐ │
│ D = b² - 4ac │ │
└────────────────Ref │
│ │
▼ │
/\ │
/ \ │
/D=0?\ │
┌── [Yes]/ \── [No] ──┐ │
│ \ / │ │
│ \ / │ │
│ \/ ▼ │
│ /\ │
│ / \ │
│ /Sign\ │
│ /of D?\ │
│ (+) / \ (-) │
▼ / \ ▼
┌────────────────────────┐ ▼ └─> [/ Print “Roots” /]
│ x₁ = -b/2a , x₂ = -b/2a│ ┌────────────────┐ [/ are Unreal" /]
└────────────────────────┘ │x₁=(-b+√D)/2a │ │
│ │x₂=(-b-√D)/ 2a │ │
│ └────────────────┘ │
│ │ │
└────────────┬──── ─────┘ │
│ │
▼ │
(○) │
│ │
▼ │
[/ Print x₁, x₂ /] │
│ │
└─────────────┬────────────────┘
│
▼
( End )
Program Design Model
Now let's discuss program design models. We know that writing a program is often a time-consuming and labor-intensive task. To create a program quickly and efficiently, it must be designed first. Design refers to the program's structure. Various types of programming designs or models are used to write simple and elegant programs. Below, a discussion is provided on a few widely used program design models.
Linear-sequential model
In this approach, the work for one phase of the entire project lifecycle must be completed in its entirety. The phases must be completed sequentially, one after the other. Examples include the Waterfall model, V-model, etc. The most widely used of these is the Waterfall model.
Waterfall Model
The simplest model in the software development life cycle (SDLC), it follows a linear process. According to this model, one phase of the SDLC process must be completed before the next phase can begin. The entire project is divided into several distinct and sequential phases. This ensures that all work is carried out smoothly, and every phase of this model must be completed perfectly. It is not possible to leave previous work unfinished in this model.
Iterative Model
In this model, the phases are repeated in a cyclical manner. In each iteration, work is performed on every phase. Additionally, based on client feedback and suggestions, some phases may be revisited. The Spiral Model is an example of this type of approach.
Parallel Process Model
In this type of model, tasks are performed simultaneously. The Unified Process Model is an example of this type.
Characteristics of a General Program
Programs are generally written to solve problems. The programming process is completed in 7 stages. If you write your program in these 7 stages, the likelihood of errors will be lower. Additionally, the qualities of a general program are as follows:
1. Identification: This includes the program's subject or objective, the programmer's name, the program's duration, a description of the various constants and variables used in the program, etc.
2. Specification: This section contains the program's description, the problem-solving strategy, decisions, reasoning, etc.
3. Input: The program should have a facility for data input.
4. Process: The program should have a facility for data processing.
5. Output: There should be a provision for providing the results.
6. Correct and Logical: The program must be correct and logical.
7. Simple and Concise: The program should be as simple and concise as possible, with no unnecessary loops.
8. Modification and Error Correction: There should be an easy way to modify, refine, and correct errors in the program, etc.
Program Debugging
At various points in the discussion, we have talked about program debugging. But what exactly is program debugging? Errors can occur in a program for various reasons during its creation. A program error is called a bug. The process of finding and correcting program errors is called debugging. No program can be used until all errors are eliminated. There are three types of errors that can occur in a program. For example:-
1. Data error: Inputting incorrect data into the computer is called a data error. The computer cannot process incorrect data. For example, if you enter 24 instead of 42, the computer will not display an error message.
2. Logical Error: A flaw in the program's logic is called a logic error. If the logic is incorrect, the result is wrong. The computer cannot detect logic errors. For example, if M < N is written instead of M > N, or T = A + B is written instead of T = A - B, it is a logic error. In this case as well, the computer does not display any error message.
3. Syntax Error: A syntax error is a grammatical mistake in a programming language. For example: spelling mistakes, missing commas or brackets, failing to declare a variable's value, etc. When translating with a compiler, the error is easily detected, and the computer displays an error message.
Note: What is a runtime error?
A runtime error is when, after compilation, a situation arises during execution that the computer cannot perform, or the operating system prevents it from doing so. The main cause can be running out of allocated memory or attempting something that is not practically possible. For example—dividing a number by zero.
If you pay close attention, you'll notice that we discussed the C programming language a little while ago. Now, we will learn where this C language is primarily used.
Uses of the C Language
More than 90 percent of the computers and operating systems in use today are written in C. Because it allows for a combination of assembly and high-level language programming techniques, C is known as a middle-level language. The C language can easily solve highly complex problems. The C language is often called the father of computer languages. The types of programs written with this language include:
1. Operating systems
2. Language Compilers
3. Language Interpreters
4. Assemblers
5. Database Programs
6) Text Editors
7. Computer Games
8. Computer Viruses and Antiviruses
9) Utilities
10. Network Drivers.
'C' is called the mother of languages. This is because it is a mid-level language. In this language, you get the benefits of a high-level language, and you can also write programs comparable to those of a low-level language. Programs in all other languages can be written using the C language. Now, let's look at its structure.
Structure of a C Program
A C program is a program composed of one or more functions, including a main() function. The basic structure of a C program is shown in the figure below;-
Basic Structure of a C Program
┌─────────────────────────────── ──────────────────────────────┐
│ Documentation Section │
├───────────────────────────────────────────────── ────────────┤
│ Link Section │
├───────────────────────────────────────────────────────────── ┤
│ Definition Section │
├──────────────────────────────────────────────────────── ─────┤
│ Global Declaration Section │
├─────────────────────────────────────────────────────────────┤
│ main () Function Section │
│ { │
│ ┌───────────────────────────┐ │
│ │ Declaration Part │ │
│ ├───────────────────────────┤ │
│ │ Executable Part │ │
│ └───── ──────────────────────┘ │
│ } │
├──────────────────────────────────────────────────── ─────────┤
│ Subprogram Section │
│ { │
│ ┌───────────────────────────┐ │
│ │ Function 1 │ │
│ ├───────────────────────────┤ │
│ │ Function 2 │ ──> User-defined functions │
│ ├───────────────────────────┤ │
│ │ - │ │
│ ├────────────────────── ─────┤ │
│ │ Function n │ │
│ └───────────────────────────┘ │
│ } │
└─────────────────────────────────────────────────────────────┘
1. Documentation Section: Optional sections of a C program contain necessary comments. They have no role in the program's execution. // is used for single-line comments. For example:
// This is my code
However, for multiple-line comments, you use /* at the beginning and */ at the end, like this:
/* This is my first program, I have written my comment to clarify my program */
2. Linkage Section; - This section includes the necessary header files for the various functions used in the program. It is a mandatory part of a C program. The syntax for including a header file is: #include <Header_file_name>
For example, to include the header file for the printf() function, you would write:
#include <stdio.h>
3. Definition Section: Sometimes constants are used inside a user-defined function or the main() function. These constants are declared using #define. For example: #define pi 3.14
4. Global Declaration Section: Variables that are used in any function or throughout the entire program are called global variables. This section is used to declare global variables.
5. Main Function Section: A C program revolves around the main() function. This function has two parts: the declaration section and the execution section. In the declaration section of the main function, variables of various types, arrays, pointers, files, etc., are typically declared. The execution section must contain at least one statement. However, each statement must be followed by a semicolon (;). The entire function is enclosed by the second pair of parentheses or {} is enclosed. main() is the mandatory part of a C program.
Subprogram Section: This section contains user-defined functions. These functions are typically placed at the end of the main() function, but they can also be written before main(). The subprogram section is an optional part of the program.
Disadvantages of the C Language
1. The C language is a case-sensitive language. In C, all programs are typically written in lowercase letters. This means that C programs distinguish between lowercase and uppercase letters.
2. The C language ignores spaces or blank spaces.
3. In C, variables must be declared correctly.
4. The header files for library functions must be declared.
5. The C language does not support object-oriented programming features.
6) It is not possible to perform checking at runtime.
7. It lacks sufficient library functions to handle modern programming environments.
Sample C Language Program
When the program is run, the computer will ask for any three numbers. After you enter the three numbers, it will display their average. First, you need to think about how the program will work. The steps of the program will be;
┌───────────────────────────────┐
│ Take input of three numbers │
└────────────────────────── ─────┘
│
▼
┌───────────────────────────────┐
│ Add the three numbers and divide by 3 │
│ Divide to find the average │
└───────────────────────────────┘
│
▼
┌───── ──────────────────────────┐
│ Displays the result │
└───────────────────────────────┘
To write the program:
1. Open the Code Block compiler and select File > New > Empty file (or press Ctrl + Shift + N).
2. In the empty window, write the program statements step-by-step. The cursor will blink in the upper-left corner of the screen. As you type from the keyboard, the characters will appear at the cursor's position.
Type /* Program of Summation and average */ from the keyboard and press the Enter key. Move to the next line and type #include <stdio.h>. Continue this way to type the entire program.
#include <stdio.h>
main() {
int a, b, c, sum;
float avg;
printf("Enter three integer value: ");
scanf("%d%d%d", &a, &b, &c);
sum = a + b + c;
avg = (float)sum / 3;
printf("\nThe summation of three number is = %d", sum);
printf("\nAverage of three number is = %.2f", avg);
}
#include <stdio.h>
main() {
int a, b, c, sum;
float avg;
printf("Enter three integer value: ");
scanf("%d%d%d", &a, &b, &c);
sum = a + b + c;
avg = (float)sum / 3;
printf("\nThe summation of three number is = %d", sum);
printf("\nAverage of three number is = %.2f", avg);
}
Output:
Enter three integer value 158, 66, 21
The summation of three number is = 125
Average of three number is = 65
Save the output: Click the File menu and select Save. The Save As dialog box will appear. Type Program_avg_01 and click the OK button. It will be saved as Program_avg_01.c.
Compile: To compile the C program written in Code::Blocks, click on the Build menu and select “Build and Run.” The program will be compiled and converted into machine code. If there are any errors, they will be displayed for you to correct. Make the necessary corrections and save the file again.
Result: Clicking the Build menu and selecting ‘Run’, or pressing Ctrl + F10, will run the program. When the program runs, it will prompt you to enter three numbers. There are many more topics we will cover in the next installment. Until then, everyone take care.
God bless.
