01 Programming Constructs Day 1-1
01 Programming Constructs Day 1-1
Subhash Joshi
Table of Contents
1|Page
Introduction to Programming Constructs
Welcome to the world of programming! Just like any language, there are building blocks that make it
possible to create instructions and programs. In programming, these building blocks are called
constructs. Learning these constructs is the foundation for writing any program.
There are three main types of programming constructs that form the core of any program:
1. Variables: Think of variables as containers that hold data. They can store numbers, text, or
even more complex things like lists or objects. Imagine a variable like a labeled box where
you can keep information you need for your program.
2. Expressions: These are combinations of variables, values, and operators (like +, -, *, /) that
evaluate to a single value. Expressions are like mini-calculations that you can perform within
your program. For example, the expression age + 5 would calculate the sum of someone's
age and 5.
3. Statements: These are the instructions that tell your program what to do. They can involve
assigning values to variables, performing calculations with expressions, or controlling the
flow of the program. Statements are like the sentences in your program that make things
happen.
Imagine you're writing a program to calculate the area of a rectangle. Here's how you might use
variables, expressions, and statements:
1. Variables:
2. Expressions:
o length * width (This expression calculates the area by multiplying the length and
width)
3. Statements:
o area = length * width (This statement calculates the area using the expression and
stores the result in the area variable)
2|Page
By combining these constructs, you've created a small program that calculates the area of a
rectangle!
This is just a basic example, but it demonstrates how variables, expressions, and statements work
together to create the building blocks of any program. As you progress in your learning, you'll
discover more advanced constructs that allow you to build more complex and powerful programs.
There are different types of variables depending on the kind of data they hold (numbers,
text, etc.)
Statements can be used for conditional logic (making decisions) and loops (repeating tasks).
We've just begun exploring the exciting world of programming constructs! As you continue learning,
you'll discover a vast toolbox of constructs that will empower you to create amazing programs.
Conditional Constructs:
If Statements:
o Used for conditional execution of code blocks.
o Syntax: IF (condition) THEN
ELSE
o Example:
IF age >= 18 THEN
PRINT "You are eligible to vote."
ELSE
PRINT "You are not eligible to vote."
END IF
Else if Statements: (Not shown in the image, but commonly used with If statements)
o Used for multiple conditional checks within an if statement.
o Syntax: IF (condition1) THEN
(code)
(code) ...
3|Page
o Example:
Switch Statements:
o Used for multi-way branching based on the value of an expression.
o Syntax:
SWITCH (expression)
o Example:
o
SWITCH (day) {
CASE "Monday":
PRINT "Start of the week!"
CASE "Tuesday": OR CASE "Wednesday": OR "Thursday":
PRINT "Midweek!"
CASE "Friday":
PRINT "TGIF!"
DEFAULT:
PRINT "Weekend!"
}
Looping Constructs:
For Loops:
4|Page
Example:
FOR i = 1 TO 5 // Loop 5 times
PRINT "Iteration:", i
END FOR
While Loops:
Example:
number = 10
WHILE number > 0 // Loop as long as number is greater than 0
PRINT number
number = number - 1 // Decrement number
END WHILE
Do-While Loops: (Not shown in the image, but another looping construct)
Similar to a while loop, but the code block is guaranteed to execute at least once.
Syntax:
DO
} WHILE (condition);
Example:
5|Page
Introduction to Pseudocode
Pseudocode is a powerful tool for programmers. It allows you to represent the logic
and steps of an algorithm in a way that's clear and understandable for humans,
without being tied to the specific syntax of any particular programming language.
Here's a detailed breakdown of what pseudocode is and how it can benefit you:
What is Pseudocode?
Keywords: Pseudocode often uses keywords like IF, FOR, WHILE, FUNCTION, etc.
These keywords have similar meanings to their counterparts in programming
languages, making the logic easier to follow.
Variables: Variables are used to store and manipulate data within the algorithm.
They are typically denoted by a name and a data type (e.g., age: integer, name:
string).
Expressions: Expressions combine variables, values, and operators (+, -, *, /) to
perform calculations and comparisons.
Statements: Statements are instructions that tell the algorithm what to do. They can
involve assigning values to variables, performing calculations with expressions,
making decisions with IF statements, or controlling the flow of the algorithm with
loops (FOR, WHILE).
6|Page
Explain
DECLARE length, width, area (numeric variables)
This pseudocode uses clear variable names, basic keywords, and an expression to
calculate the area. It's easy to understand the logic even without knowing a specific
programming language.
Pseudocode can be used for more complex algorithms as well. Here are some
additional points to consider:
Control Flow: You can use IF statements for conditional logic, allowing the
algorithm to take different paths based on certain conditions.
Loops: FOR and WHILE loops allow you to repeat a set of instructions a specific
number of times or until a certain condition is met. This is useful for iterating through
data or performing repetitive tasks.
Functions: Pseudocode can represent functions, which are reusable blocks of code
that perform specific tasks. This helps modularize your algorithms and improve code
organization.
7|Page
How to write effective pseudocode:
1. Understand the Algorithm:
Before writing pseudocode, ensure you have a clear understanding of the algorithm
you're representing. What problem does it solve? What are the inputs and outputs?
What are the main steps involved?
2. Choose Readability:
The primary goal of pseudocode is clarity. Use clear and concise language that
someone unfamiliar with programming can understand.
3. Basic Structure:
Start with comments or a brief description explaining the purpose of the algorithm.
Declare any variables used in the algorithm, specifying their names and data types
(e.g., integer, string).
4. Control Flow:
Use keywords like IF, ELSE, WHILE, and FOR to control the flow of the algorithm.
Ensure the operators used are appropriate for the data types involved.
Describe how the algorithm receives input data (e.g., READ user_input).
8|Page
7. Formatting and Indentation:
8. Example:
Explain
DECLARE number (integer)
Test your pseudocode by manually stepping through it with sample inputs. This
helps identify potential errors or areas for improvement.
As you gain experience, you can adapt pseudocode to represent more complex
algorithms and data structures.
9|Page
Bubble Sort Algorithm
Algorithm:
traverse from left and compare adjacent elements and the higher one is
placed at right side.
In this way, the largest element is moved to the rightmost end at first.
This process is then continued to find the second largest and place it and
so on until the data is sorted.
First Pass:
The largest element is placed in its correct position, i.e., the end of the array.
Second Pass:
10 | P a g e
Place the second largest element at correct position
Third Pass:
11 | P a g e
bubble sort algorithm in pseudocode:
PROCEDURE BubbleSort(data)
FOR i = 1 TO length(data) - 1
FOR j = i + 1 TO length(data)
IF data[i] > data[j] THEN
SWAP(data[i], data[j])
END IF
END FOR
END FOR
END PROCEDURE
Explanation:
12 | P a g e
Selection sort Algorithm:
Selection sort is a simple and efficient sorting algorithm that works by
repeatedly selecting the smallest (or largest) element from the unsorted
portion of the list and moving it to the sorted portion of the list.
Algorithm
1. Imagine the list has two sections: sorted (on the left) and unsorted (on the right).
2. In each pass, we find the smallest element from the unsorted section.
3. We swap that smallest element with the first element of the unsorted section
(essentially putting it in its sorted position).
4. We repeat steps 2 and 3, gradually moving the sorted section to the right until the
entire list is sorted.
First pass:
For the first position in the sorted array, the whole array is traversed from
index 0 to 4 sequentially. The first position where 64 is stored presently,
after traversing whole array it is clear that 11 is the lowest value.
Thus, replace 64 with 11. After one iteration 11, which happens to be the
least value in the array, tends to appear in the first position of the sorted
list.
Second Pass:
13 | P a g e
For the second position, where 25 is present, again traverse the rest of
the array in a sequential manner.
After traversing, we found that 12 is the second lowest value in the array
and it should appear at the second place in the array, thus swap these
values.
Third Pass:
Now, for third place, where 25 is present again traverse the rest of the
array and find the third least value present in the array.
While traversing, 22 came out to be the third least value and it should
appear at the third place in the array, thus swap 22 with element present
at third position.
Fourth pass:
Similarly, for fourth position traverse the rest of the array and find the
fourth least element in the array
As 25 is the 4th lowest value hence, it will place at the fourth position.
14 | P a g e
Complexity Analysis of Selection Sort
Time Complexity: The time complexity of Selection Sort is O(N2) as there
are two nested loops:
Auxiliary Space: O(1) as the only extra memory used is for temporary
variables while swapping two values in Array. The selection sort never
makes more than O(N) swaps and can be useful when memory writing is
costly.
Explanation:
15 | P a g e
3. The inner loop (j) iterates from one position ahead of the outer loop (i) to the end of
the list.
4. A variable minIndex is initialized to the current position (i). This will store the index of
the currently found minimum element.
5. Inside the inner loop, the element at the current index (j) is compared with the
element at the minIndex.
6. If the element at j is smaller than the element at minIndex, then minIndex is updated
to j. This keeps track of the index of the smallest element encountered so far in the
unsorted part of the list.
7. After the inner loop completes, the element at the current position (i) is swapped
with the element at the minIndex. This effectively places the smallest element from
the unsorted part at its correct position in the sorted part of the list.
8. The outer loop continues, repeating the process for the next element in the unsorted
part of the list.
9. With each iteration, the smallest element is selected and placed in its correct
position, gradually building the sorted list.
16 | P a g e
Insertion Sort Algorithm:
Insertion sort is a simple sorting algorithm that works similarly to the way
you sort playing cards in your hands. The array is virtually split into a sorted
and an unsorted part. Values from the unsorted part are picked and placed in
the correct position in the sorted part.
Algorithm:
17 | P a g e
insertion sort algorithm in pseudocode:
PROCEDURE InsertionSort(data)
FOR i = 1 TO length(data)
temp := data[i] // Store the current element
j := i - 1 // Start comparison with the element before
WHILE j >= 0 AND data[j] > temp DO // Loop until a smaller or equal
element is found
data[j + 1] := data[j] // Shift larger elements to the right
j := j - 1 // Move comparison index to the left
END WHILE
Explanation:
18 | P a g e
What is a flowchart?
A flowchart is a visual representation of a process, algorithm, or system. It uses
symbols and connecting arrows to show the steps involved and the decision points
that determine the flow of execution.
Connector: A small circle used to connect flowchart elements that are spread
across a page for better readability. Lines entering and exiting connectors maintain
the flow.
19 | P a g e
Input/Output: A parallelogram representing user input or data output from the
process.
And more…
Break Down the Steps: Decompose the algorithm into smaller, more
manageable steps. These steps will be represented by rectangles (process
symbols) in the flowchart.
Identify Decisions: Locate any points where the program needs to make a
decision based on certain conditions (e.g., checking if a number is even or odd).
These will be represented by diamonds (decision symbols) in the flowchart.
Connect the Symbols: Use arrows to connect the process and decision
symbols, ensuring a logical flow from start to finish. For decisions, label the
arrows with "Yes" or "No" or the specific condition that determines the path.
20 | P a g e
Interpreting a Flowchart for Programming Logic:
1. Start Symbol: Locate the start symbol, representing the beginning of the
program.
2. Follow the Arrows: Trace the arrows from the start, following decision paths
based on the conditions.
Focus on Clarity: Keep your flowchart simple and easy to understand. Avoid cluttering it
with unnecessary details. Use clear and concise labels for each step and decision point.
Modularize with Subroutines: Break down complex processes into smaller, reusable
subroutines. Represent these subroutines with separate flowchart sections, potentially
using rectangles with dashed lines to indicate they represent a defined process
elsewhere. This improves readability and avoids repetition.
Proper Symbol Usage: Ensure you're using the correct flowchart symbols for each
element. Common symbols include:
o Rectangles for processes
o Diamonds for decisions (Yes/No or True/False)
o Ovals for start and end points
o Parallelograms for input/output
o Arrows to connect symbols and show the flow
Logical Flow: Maintain a clear and logical flow from start to finish. Avoid jumps or
confusing connections between symbols. Use page connectors if necessary to maintain
a clear path across pages.
Review and Refine: Once you have a draft, review it carefully for clarity, accuracy, and
logical flow. Make any necessary adjustments to ensure your flowchart effectively
communicates the process.
21 | P a g e
Using Subroutines in Flowcharts for Repeated Actions:
Subroutines, also known as functions or procedures, are reusable blocks of code
that perform specific tasks. They can be incredibly helpful in flowcharts to avoid
redundancy. Here's how to use them:
1. Identify Repeated Actions: Look for sections of your flowchart that involve the same
steps repeated multiple times.
2. Create a Subroutine Flowchart: Develop a separate flowchart for the repeated action,
treating it as a mini-process. Use clear labels to indicate the subroutine's purpose and
inputs/outputs (if applicable).
3. Call the Subroutine: In your main flowchart, wherever the repeated action needs to be
performed, use a rectangle with a dashed line and label it with the subroutine's name.
This indicates a jump to the separate subroutine flowchart.
4. Benefits: This approach reduces clutter in the main flowchart and improves readability.
It also makes modifications easier, as you only need to change the subroutine flowchart
if the logic changes.
Example:
1)
22 | P a g e
2)
Concurrent Processes:
Parallel Lines: Use separate, parallel lines to represent processes that can execute
concurrently. This visually shows they are happening at the same time.
"FORK" and "JOIN" Symbols: Some flowcharting tools offer specialized symbols like a
"fork" to depict the branching into concurrent processes and a "join" symbol to represent
the point where they come back together.
23 | P a g e
Example:
1)
2)
24 | P a g e
Synchronization:
Example:
25 | P a g e
o Critical Section: A critical section is a part of code that only one process can access at a
time. You can represent it with a rectangle with dashed lines labeled "Critical Section".
Processes entering or leaving the critical section can be shown with arrows and labels (e.g.,
"Enter Critical Section", "Exit Critical Section").
Example:
26 | P a g e
Logical Thinking with Operators and Decision Trees
1. Logical Operators:
Logical operators are used to combine logical expressions (statements that can be
true or false) and create more complex ones. Here are the three main logical
operators:
AND: Represents a conjunction, meaning both conditions must be true for the
overall expression to be true. (Example: It is sunny AND it is warm, then I will go
swimming.)
OR: Represents a disjunction, meaning at least one condition must be true for
the overall expression to be true. (Example: It is raining OR it is snowing, then I
will bring an umbrella.)
Truth Tables:
A truth table shows the outcome of a compound logical expression based on the
truth values of its individual components. Here's an example truth table for AND, OR,
and NOT:
27 | P a g e
2. Decision Trees for Problem Solving:
A decision tree is a tree-like structure that visually represents a sequence of
decisions and their possible consequences. It helps solve problems by asking a
series of questions and branching the path based on the answers.
Root Node: The starting point of the tree, representing the initial question or
decision.
Branches: Lines connecting nodes, showing the flow based on the answer
(Yes/No or specific values).
Leaf Nodes: The terminal points of the tree, representing the final outcome or
solution based on the decision path.
Examples 1:
Root Node
Internal Node
28 | P a g e
Example 2:
29 | P a g e
Benefits of Decision Trees:
Connectors: Small circles used to connect flowchart elements across pages for
better readability.
30 | P a g e
Functions and Modular Design
Modular design is a fundamental concept in programming that involves breaking
down complex programs into smaller, independent, and reusable pieces of code
called functions. This approach offers several advantages:
Reduced Redundancy: By creating reusable functions, you avoid writing the same code
multiple times.
Enhanced Readability: Functions encapsulate specific tasks, making the code more
readable and self-documenting.
Return Values: Functions can optionally return a value (output) based on their
calculations or operations.
Naming: Use clear and descriptive names that reflect the function's purpose.
Examples:
31 | P a g e
// In the main program
DECLARE num1 (numeric), num2 (numeric)
//Get values for num1 and num2
SET total_sum = calculate_sum(num1, num2)
PRINT "The sum is:", total_sum
This example defines a function calculate_sum that takes two numbers as input and
returns their sum.
FUNCTION check_eligibility(age)
DECLARE is_eligible (boolean)
RETURN is_eligible
END FUNCTION
IF eligible THEN
PRINT "You are eligible."
ELSE
PRINT "You are not eligible."
END IF
This example defines a function check_eligibility that takes an age as input and
returns a boolean value (True/False) indicating eligibility based on an age condition.
FUNCTION greet_user(name)
DECLARE greeting (string)
SET greeting = "Hello, " + name + "!"
RETURN greeting
END FUNCTION
This example defines a function greet_user that takes a name as input and returns a
greeting string by concatenating "Hello, " with the name.
32 | P a g e
4. Function with Loop:
FUNCTION calculate_average(numbers[])
DECLARE total (numeric)
DECLARE count (numeric)
SET total = 0
SET count = 0
FOR i = 1 TO LENGTH(numbers)
SET total = total + numbers[i]
SET count = count + 1
END FOR
Code Reusability: The core principle of modular programming is to create functions and
modules that can be used in multiple parts of your code or even in other programs.
Information Hiding: Functions and modules can encapsulate their internal logic and
data, only exposing essential elements through parameters and return values. This
promotes better code organization and reduces the risk of unintended side effects.
33 | P a g e
Modular Programming in C:
C doesn't have built-in features for modular programming like some other languages
(e.g., Modula-2), but you can achieve modularity using functions and header files.
Here's how:
Break down your program into smaller, well-defined functions that perform
specific tasks.
Create header files (.h files) to define the interface for your functions.
o Type definitions: If you're using custom data structures, define them in the
header file.
3. Separation of Concerns:
The source code file (.c file) contains the actual implementation of the functions
declared in the header file.
This separation keeps the interface (what the function does) separate from the
implementation (how the function does it).
By including the header file in other source code files, you can use the functions
without needing to know their internal details.
34 | P a g e
Example:
C
#ifndef CALCULATE_AREA_H
#define CALCULATE_AREA_H
#endif
==============================================================
C
#include "calculate_area.h"
===============================================================
C
#include "calculate_area.h"
int main() {
double length = 5.0;
double width = 3.0;
return 0;
}
==============================================================
In this example, the calculate_area function is defined in a separate source file but
its prototype is declared in the header file, allowing other code to use it without
needing its implementation details.
Remember:
35 | P a g e