0% found this document useful (0 votes)
5 views

01 Programming Constructs Day 1-1

Uploaded by

My Notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

01 Programming Constructs Day 1-1

Uploaded by

My Notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

STUDENT GUIDE

Programming Constructs and Algorithms for


Problem Solving

Subhash Joshi
Table of Contents

Introduction to Programming Constructs ............................................................................................... 2


Variables, Expressions, and Statements in Action .............................................................................. 2
Conditional Constructs: ................................................................................................................... 3
Introduction to Pseudocode ................................................................................................................... 6
How to write effective pseudocode:................................................................................................... 8
Bubble Sort Algorithm....................................................................................................................... 10
Algorithm: ........................................................................................................................................ 10
How does Bubble Sort Work? ..................................................................................................... 10
Selection sort Algorithm: .................................................................................................................. 13
How does Selection Sort Algorithm work? ................................................................................ 13
Insertion Sort Algorithm: ................................................................................................................. 17
What is a flowchart? ............................................................................................................................. 19
Basic Flowchart Symbols: .................................................................................................................. 19
Creating a Flowchart for Programming Logic: .................................................................................. 20
Efficient Flowcharting Techniques: ................................................................................................... 21
Using Subroutines in Flowcharts for Repeated Actions:................................................................... 22
Flowchart Symbols for Concurrency and Synchronization: .............................................................. 23
Logical Thinking with Operators and Decision Trees ............................................................................ 27
Flowchart Symbols for Decision Making: .......................................................................................... 30
Functions and Modular Design ............................................................................................................. 31
Fundamentals of Function Design: ................................................................................................... 31
Modular Programming Concepts: ..................................................................................................... 33
Modular Programming in C: .............................................................................................................. 34

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.

Overview of Programming Constructs

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.

Variables, Expressions, and Statements in Action


Let's see how these constructs work together with a simple example:

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:

o length (to store the length of the rectangle)

o width (to store the width of the rectangle)

o area (to store the calculated area)

2. Expressions:

o length * width (This expression calculates the area by multiplying the length and
width)

3. Statements:

o length = 10 (This statement assigns the value 10 to the length variable)

o width = 5 (This statement assigns the value 5 to the width variable)

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.

Here are some additional points to consider:

 There are different types of variables depending on the kind of data they hold (numbers,
text, etc.)

 Operators can be used for arithmetic operations, comparisons, and more.

 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

(code to execute if condition is true)

ELSE

(code to execute if condition is false)

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)

ELSE IF (condition2) THEN

(code) ...

ELSE (code to execute if none of the conditions are true)

3|Page
o Example:

IF grade >= 90 THEN


PRINT "Excellent!"
ELSE IF grade >= 80 THEN
PRINT "Very Good!"
ELSE IF grade >= 70 THEN
PRINT "Good!"
ELSE
PRINT "You can do better."
END IF

 Switch Statements:
o Used for multi-way branching based on the value of an expression.
o Syntax:

SWITCH (expression)

CASE value1: (code to execute) ;

CASE value2: (code to execute) ...

DEFAULT: (code to execute if no case matches)

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:

Used for repeated execution of a code block a specific number of times.

Syntax: FOR (initialization; condition; increment/decrement)

code to execute repeatedly

4|Page
Example:
FOR i = 1 TO 5 // Loop 5 times
PRINT "Iteration:", i
END FOR

While Loops:

Used for repeated execution of a code block as long as a condition is true.

Syntax: WHILE (condition)

code to execute repeatedly

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

code to execute repeatedly

} WHILE (condition);

Example:

guess = 0 // Initialize guess variable


DO {
PRINT "Guess a number between 1 and 10:"
READ user_guess
} WHILE (user_guess != secret_number) // Loop until the guess is correct
PRINT "Congratulations! You guessed the number!"

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?

 Informal Language: Pseudocode uses a mix of natural language keywords and


programming-like constructs to describe the algorithm's flow. It reads more like a
written explanation than actual code.
 Not Executable: Pseudocode is not meant to be directly run by a computer. It's a
communication and planning tool for humans.
 Focus on Logic: Pseudocode helps you focus on the core idea and steps involved
in an algorithm, without getting bogged down in the intricacies of a specific
programming language.

Benefits of Using Pseudocode:

 Improved Communication: Pseudocode allows you to clearly explain algorithms to


others, even if they don't have a programming background.
 Planning and Design: By writing pseudocode first, you can plan the logic of your
program before translating it into a specific coding language. This helps identify
potential issues early on.
 Problem-Solving: Pseudocode helps you focus on the core steps and decision
points in an algorithm, which can be valuable for debugging and improving your
problem-solving approach.

Key Elements of 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).

Example: Calculating Area of a Rectangle

Here's a simple example demonstrating pseudocode for calculating the area of a


rectangle:

6|Page
Explain
DECLARE length, width, area (numeric variables)

READ length // Get user input for length


READ width // Get user input for width

area = length * width // Calculate area using expression

PRINT "The area of the rectangle is:", area // Display result

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.

Avoid complex programming syntax or jargon specific to a particular language.

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.

IF statements allow for conditional execution based on certain conditions.

WHILE loops repeat a block of code as long as a condition is true.

FOR loops repeat a block of code a specific number of times.

5. Calculations and Comparisons:

Use expressions involving variables, values, and operators (+, -, *, /) to perform


calculations and comparisons.

Ensure the operators used are appropriate for the data types involved.

6. Input and Output:

Describe how the algorithm receives input data (e.g., READ user_input).

Specify how the algorithm produces output (e.g., PRINT result).

8|Page
7. Formatting and Indentation:

Use indentation to visually represent the structure of your code. Consistent


indentation improves readability and helps distinguish between nested loops and
conditional statements.

Add comments throughout your pseudocode to explain complex logic or specific


steps.

8. Example:

Here's a pseudocode example for calculating the factorial of a number:

Explain
DECLARE number (integer)

READ number // Get user input for the number

IF number < 0 THEN


PRINT "Error: Factorial is not defined for negative numbers."
ELSE
factorial := 1 // Initialize factorial to 1
FOR i = 1 TO number
factorial := factorial * i // Calculate factorial using loop
END FOR
PRINT "The factorial of", number, "is:", factorial
END IF

Tips and Best Practices:

Keep your pseudocode concise and focused on the essential logic.

Use meaningful variable names that reflect their purpose.

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

Bubble Sort is the simplest sorting algorithm that works by repeatedly


swapping the adjacent elements if they are in the wrong order. This
algorithm is not suitable for large data sets as its average and worst-case
time complexity is quite high.

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.

How does Bubble Sort Work?

Input: arr[] = {6, 3, 0, 5}

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:

Place the remaining two elements at their correct positions.

 Total no. of passes: n-1


 Total no. of comparisons: n*(n-1)/2

Complexity Analysis of Bubble Sort:

Time Complexity: O(N2)

Auxiliary Space: O(1)

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:

1. The BubbleSort procedure takes a list of data as input.


2. It iterates through the list using two nested loops. The outer loop (i) iterates from the
beginning of the list to the second-last element.
3. The inner loop (j) iterates from one position ahead of the outer loop (i) to the end of
the list.
4. Inside the inner loop, the elements at indices i and j are compared.
5. If the element at i is greater than the element at j, they are swapped using
a SWAP function (not shown here, but assumed to exist). This effectively moves the
larger element towards the end of the list.
6. The outer loop continues, repeating the comparison and swapping process for each
element in the list.
7. With each iteration of the outer loop, the largest element in the unsorted part bubbles
to the end of the list.
8. The process continues until the entire list is sorted.

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.

How does Selection Sort Algorithm work?

arr[] = {64, 25, 12, 22, 11}

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:

 One loop to select an element of Array one by one = O(N)


 Another loop to compare that element with every other Array element =
O(N)
 Therefore overall complexity = O(N) * O(N) = O(N*N) = O(N 2)

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.

selection sort algorithm in pseudocode:


PROCEDURE SelectionSort(data)
FOR i = 1 TO length(data) - 1
minIndex := i
FOR j = i + 1 TO length(data)
IF data[j] < data[minIndex] THEN
minIndex := j
END IF
END FOR
SWAP(data[i], data[minIndex])
END FOR
END PROCEDURE

Explanation:

1. The SelectionSort procedure takes a list of data as input.


2. It iterates through the list using two nested loops. The outer loop (i) iterates from the
beginning of the list to the second-last element.

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:

1. Imagine the list has one sorted element at the beginning.


2. In each pass, we take an element from the unsorted part of the list.
3. We "insert" this element into its correct position within the already sorted part of the
list, by comparing it with elements and shifting them if needed.
4. We repeat steps 2 and 3, gradually building the sorted section from left to right until
the entire list is sorted.

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

data[j + 1] := temp // Insert the current element (temp) at its


correct position
END FOR
END PROCEDURE

Explanation:

1. The InsertionSort procedure takes a list of data as input.


2. It iterates through the list using a loop (i).
3. In each iteration, the element at the current position (i) is stored in a temporary
variable temp. This element will be inserted into its correct position.
4. Another variable j is initialized to one position before the current element (i - 1).
This variable is used to traverse the sorted part of the list.
5. A WHILE loop continues as long as j is greater than or equal to zero (not yet out of
bounds) and the element at j is greater than the temp value (we haven't found the
correct position yet).
6. Inside the loop, the element at j + 1 (one position ahead in the list) is overwritten
with the element at j. This essentially shifts the larger elements in the sorted part
one position to the right, creating a space for the temp element.
7. After shifting the elements, the j index is decremented by 1 to move the comparison
point one position to the left in the sorted part.
8. Once the WHILE loop exits (either j becomes negative or a smaller element is found),
the temp element (which holds the value to be inserted) is placed at the j +
1 position. This ensures it's inserted before any larger elements encountered during
the loop.
9. The outer loop (i) continues, repeating steps 3-8 for the next element in the list.

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.

Why use flowcharts?

Flowcharts offer several benefits:

 Improved Communication: They provide a clear and easy-to-understand way to


communicate complex processes to both technical and non-technical audiences.
 Planning and Design: They help visualize the logic of a program or system before
coding, allowing for better planning and identification of potential problems.
 Documentation: They serve as documentation for existing programs, making it
easier to understand and maintain the code.
 Problem-solving: By visually representing the steps and decisions, flowcharts can
aid in identifying inefficiencies or errors in a process.

Basic Flowchart Symbols:


Here are some of the most common flowchart symbols:

 Terminal: An oval shape representing the start or end of the flowchart.

 Process: A rectangle representing a specific step or action performed in the


process.

 Decision: A diamond shape representing a point where a decision needs to be


made based on a condition. Lines from the diamond represent the possible
outcomes (Yes/No or True/False).

 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.

 Direction of flow from one step or decision to another.

And more…

Creating a Flowchart for Programming Logic:


Define the Algorithm: Start by clearly understanding the algorithm you want to
represent with the flowchart. This involves identifying the problem the program is
solving and the steps it takes to reach the solution.

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.

Choose Programming Constructs: Identify the programming constructs used in


the algorithm, such as loops (FOR, WHILE), conditional statements (IF, ELSE IF,
SWITCH), and functions.

Map Constructs to Flowchart: Translate these programming constructs into


flowchart symbols. Loops will be represented by arrows circling back to a
decision point, conditional statements will have separate paths for true and false
conditions, and functions can be represented by separate sub-flowcharts within
the main 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.

Input/Output: Include parallelograms (input/output symbols) to represent any


user input or data output involved in the program.

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.

3. Understand the Symbols: Interpret the process steps (rectangles), decisions


(diamonds), and input/output (parallelograms) in the context of programming
logic.

4. Translate to Code: Based on the flowchart symbols and their connections,


mentally translate the logic into actual programming code using loops,
conditional statements, variables, etc.

Efficient Flowcharting Techniques:


Flowcharts are a great way to visualize the logic of your program, but creating
efficient and clear ones is an important skill. Here are some techniques to help you
achieve that:

 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)

Flowchart Symbols for Concurrency and Synchronization:


Flowcharts can also represent concurrent processes (processes happening
simultaneously) and synchronization points (where processes need to wait for each
other). While not as commonly used as basic flowchart symbols, here are some
options:

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:

Semaphores: Semaphores are a concurrency control mechanism. You can represent a


semaphore using a rectangle labeled "Semaphore" with an initial value (e.g., Semaphore =
1). Processes can then be shown acquiring or releasing the semaphore using separate
symbols (e.g., "P(Semaphore)" for acquire, "V(Semaphore)" for release).

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:

Remember: Using concurrency and synchronization symbols can add complexity to


your flowchart. Only use them if necessary to represent these specific concepts in
your program's logic.

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.)

 NOT: Represents negation, meaning it reverses the truth value of a single


expression. (Example: It is NOT raining, then I can go outside.)

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:

A B AND (A, B) OR (A, B) NOT (A)


TRUE TRUE TRUE TRUE FALSE
TRUE FALSE FALSE TRUE FALSE
FALSE TRUE FALSE TRUE TRUE
FALSE FALSE FALSE FALSE TRUE

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.

Components of a Decision Tree:

 Root Node: The starting point of the tree, representing the initial question or
decision.

 Internal Nodes: Represent subsequent questions or decisions based on


previous answers.

 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:

 Improve problem-solving by breaking it down into smaller, manageable steps.

 Visualize the logic and potential outcomes of different decisions.

 Easy to understand and communicate solutions to others.

Flowchart Symbols for Decision Making:


 Start/End Symbols: Ovals representing the beginning and end of the process.

 Process Symbols: Rectangles representing specific actions or steps.

 Decision Diamonds: Diamonds representing points where a decision needs to


be made based on a condition. Arrows leaving the diamond represent the "Yes"
and "No" (or True/False) paths.

 Connectors: Small circles used to connect flowchart elements across pages for
better readability.

Benefits of Flowcharts for Decision Making:

 Enhance clarity and communication of decision-making processes.

 Identify potential problems or inefficiencies in the logic.

 Document and plan decision-making steps before implementation.

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:

 Improved Code Organization: Modular code is easier to understand, maintain, and


modify.

 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.

 Promotes Teamwork: Modular design allows different programmers to work on


separate functions, improving collaboration in large projects.

Fundamentals of Function Design:


Here are some key aspects of designing good functions:

 Functionality: Each function should perform a well-defined, specific task.

 Parameters: Functions can accept input values (parameters) to customize their


behavior.

 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.

 Simplicity: Functions should be concise and focused on a single task.

Examples:

1. Simple Calculation Function:

FUNCTION calculate_sum(number1, number2)


DECLARE sum (numeric)
SET sum = number1 + number2
RETURN sum
END FUNCTION

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.

2. Function with Conditional Logic:

FUNCTION check_eligibility(age)
DECLARE is_eligible (boolean)

IF age >= 18 THEN


SET is_eligible = TRUE
ELSE
SET is_eligible = FALSE
END IF

RETURN is_eligible
END FUNCTION

// In the main program


DECLARE user_age (numeric)
Get user's age
SET eligible = check_eligibility(user_age)

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.

3. Function with String Manipulation:

FUNCTION greet_user(name)
DECLARE greeting (string)
SET greeting = "Hello, " + name + "!"
RETURN greeting
END FUNCTION

//In the main program


DECLARE user_name (string)
Get user's name
SET message = greet_user(user_name)
PRINT message

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

IF count > 0 THEN


DECLARE average (numeric)
SET average = total / count
RETURN average
ELSE
// Handle case of empty array (optional)
RETURN "Error: No elements in the array."
END IF
END FUNCTION

// In the main program


DECLARE marks[5] (numeric) ; Array to store marks
Get marks from user (or initialize with values)
SET average_score = calculate_average(marks)
PRINT "The average score is:", average_score

This example defines a function calculate_average that takes an array of numbers


as input and returns the average value. It uses a loop to iterate through the array,
calculate the total, and then calculates the average if there are elements in the array.

Modular Programming Concepts:


Modular programming goes beyond just creating functions. Here are some additional
concepts:

 Modules/Packages: Groups of related functions and variables that can be reused


across different parts of a program.

 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:

1. Functions as Building Blocks:

 Break down your program into smaller, well-defined functions that perform
specific tasks.

 Each function should have a clear purpose and responsibility.

 Functions can take input parameters (arguments) to customize their behavior.

 They can optionally return a value (output) based on their calculations.

2. Header Files for Interface Definition:

 Create header files (.h files) to define the interface for your functions.

 The header file should contain:

o Function prototypes: These declare the function name, parameter types,


and return type without implementation details.

o Constant declarations: Define any constants used by the functions in the


header file.

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:

calculate_area.h (header file):

C
#ifndef CALCULATE_AREA_H
#define CALCULATE_AREA_H

double calculate_area(double length, double width);

#endif

==============================================================

calculate_area.c (source file):

C
#include "calculate_area.h"

double calculate_area(double length, double width) {


return length * width;
}

===============================================================

main.c (source file):

C
#include "calculate_area.h"

int main() {
double length = 5.0;
double width = 3.0;

double area = calculate_area(length, width);


printf("The area is: %.2lf\n", area);

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:

 Use meaningful function names that reflect their purpose.


 Include necessary header files in your source code files.
 Maintain a clear separation between interface (header) and implementation (source).

35 | P a g e

You might also like