0% found this document useful (0 votes)
7 views67 pages

Isp Lesson 5 Share

The document covers fundamental programming concepts including variables, data types, operators, and program flow. It explains the importance of variables and data types in storing and manipulating data, as well as various types of operators used for calculations and comparisons. Additionally, it discusses control structures like sequential, conditional, and iterative flow, providing examples of how to implement these concepts in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views67 pages

Isp Lesson 5 Share

The document covers fundamental programming concepts including variables, data types, operators, and program flow. It explains the importance of variables and data types in storing and manipulating data, as well as various types of operators used for calculations and comparisons. Additionally, it discusses control structures like sequential, conditional, and iterative flow, providing examples of how to implement these concepts in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

PROGRAMMING

CONCEPTS
(WORKING WITH DATA -
VARIABLES, DATA TYPES AND
OPERATORS)
The concept of variables
• A variable in programming is a named storage location in memory
that holds a value. Variables are fundamental to programming because
they allow developers to store, manipulate, and retrieve data
dynamically during the execution of a program. The value stored in a
variable can change during the program's execution, hence the term
"variable."
Data Types
• Data types define the type of data that a variable can hold. Each
programming language supports a set of built-in data types, and they
determine the operations that can be performed on the data. Common
data types include:
Data Types
• Integer (int): Represents whole numbers (e.g., 5, -10, 100).
• Floating-Point (float, double): Represents decimal numbers (e.g., 3.14, -0.001).
• Character (char): Represents a single character (e.g., 'a', 'Z', '$').
• String (str): Represents a sequence of characters (e.g., "Hello, World!").
• Boolean (bool): Represents a true or false value (e.g., true, false).
• Array/List: Represents a collection of elements of the same data type.
• Object/Class: Represents complex data structures with properties and methods.
Data Types
• The choice of data type affects the amount of memory allocated to the
variable and the range of values it can hold.
Identifiers
An identifier is a name given to a variable, function, class, or other
programming elements. Identifiers must follow specific rules, which vary by
programming language, but generally include:
• Must start with a letter (a-z, A-Z) or an underscore (_).
• Can contain letters, digits (0-9), and underscores.
• Cannot be a reserved keyword (e.g., int, if, return).
• Are case-sensitive in most languages (e.g., myVar and myvar are
different).
Examples of valid identifiers: age, _count, totalAmount.
Declaration of variables
• Variable declaration is the process of defining a variable by specifying
its name and data type. In some languages, you can also initialize the
variable with a value at the time of declaration.
• int age; // Declaration
• age = 25; // Initialization
• Or combined:
• int age = 25; // Declaration and initialization
Declaration of variables
• In dynamically typed languages (e.g., Python), you don't need to
declare the data type explicitly:
• python
• age = 25 # Python automatically infers the type as int
Variable Scope
• Variable scope refers to the region of the program where a variable is
accessible. There are typically two types of scope:
Variable Scope
Local Scope: A variable declared inside a function or block is
accessible only within that function or block.
• void myFunction() {
• int localVar = 10; // Local variable
• printf("%d", localVar); // Accessible here
•}
• // printf("%d", localVar); // Error: localVar is not accessible here
Variable Scope
Global Scope: A variable declared outside all functions is accessible throughout the entire
program.
• int globalVar = 20; // Global variable

• void myFunction() {
• printf("%d", globalVar); // Accessible here
• }
Understanding scope is crucial for avoiding naming conflicts and managing memory
efficiently.
Operators (types and descriptions)
• Operators are symbols that perform operations on variables and
values. They are essential for performing calculations, comparisons, and
logical decisions in a program.
Types of Operators
Arithmetic Operators: Perform mathematical operations.
o + (Addition)
o - (Subtraction)
o * (Multiplication)
o / (Division)
o % (Modulus, remainder after division)
o ++ (Increment)
o -- (Decrement)
Example of Arithmetic Operation
• Example:
• int a = 10, b = 3;
• int sum = a + b; // 13
• int remainder = a % b; // 1
Types of Operators
Relational Operators: Compare two values.
o == (Equal to)
o != (Not equal to)
o > (Greater than)
o < (Less than)
o >= (Greater than or equal to)
o <= (Less than or equal to)
Example of Relational Operation
• Example:
• if (a > b) {
• printf("a is greater than b");
•}
Types of Operators

Logical Operators: Combine multiple conditions.


o && (Logical AND)
o || (Logical OR)
o ! (Logical NOT)
Example of Logical Operation
• Example:
• if (a > 0 && b > 0) {
• printf("Both a and b are positive");
•}
Types of Operators
Assignment and Compound Assignment Operators: Assign values to
variables.
o = (Simple assignment)
o += (Add and assign)
o -= (Subtract and assign)
o *= (Multiply and assign)
o /= (Divide and assign)
o %= (Modulus and assign)
Example of Assignment Operation
• Example:
• int x = 5;
• x += 3; // x is now 8
Types of Operators
Bitwise Operators: Perform operations on binary representations of data.
o & (Bitwise AND)
o | (Bitwise OR)
o ^ (Bitwise XOR)
o ~ (Bitwise NOT)
o << (Left shift)
o >> (Right shift)
Example of Bitwise Operation
• Example:
• int a = 5; // Binary: 0101
• int b = 3; // Binary: 0011
• int result = a & b; // Binary: 0001 (1 in decimal)
Operator Precedence
• Operator precedence determines the order in which operators are
evaluated in an expression. Operators with higher precedence are
evaluated first. For example:
• Parentheses () have the highest precedence.
• Multiplication * and division / have higher precedence than
addition + and subtraction -.
Operator Precedence
• int result = 5 + 3 * 2; // result is 11 (3*2 is evaluated first)
• int result2 = (5 + 3) * 2; // result2 is 16 (parentheses evaluated first)
Understanding operator precedence is crucial for writing correct and
efficient expressions.
PROGRAMMING
CONCEPTS
(PROGRAM FLOW)
Program Flow
• Program flow refers to the order in which instructions are executed in
a program. The flow of a program can be controlled using different
structures, such as sequential flow, conditional flow, and iterative flow.
Sequential Flow
• Sequential flow is the most basic and fundamental control structure in
programming. It refers to the execution of statements or instructions in
the order they are written, from top to bottom. Each statement is
executed one after the other, and the program moves to the next
statement only after the current one has been completed.
Sequential Flow
Key Characteristics of Sequential Flow:
1. Order of Execution: Statements are executed in the exact order they
appear in the code.
2. No Skipping or Jumping: The program does not skip or jump to
other parts of the code unless explicitly instructed (e.g., using control
structures like loops or conditionals).
3. Predictable Behavior: Since the flow is linear, the behavior of the
program is easy to predict and understand.
Sequential Flow - Example of Sequential Flow in
Pseudocode
• Let’s consider a simple example where we calculate the total cost of
purchasing items in a store.
• Pseudocode:
START
// Step 1: Initialize variables
SET price_of_item = 50
SET quantity = 3
SET tax_rate = 0.10
// Step 2: Calculate subtotal
SET subtotal = price_of_item * quantity
// Step 3: Calculate tax
SET tax = subtotal * tax_rate
// Step 4: Calculate total cost
SET total_cost = subtotal + tax

// Step 5: Display the result


PRINT "Subtotal: " + subtotal
PRINT "Tax: " + tax
PRINT "Total Cost: " + total_cost
END
Explanation of the Example
• Step 1: Initialize Variables

o The program starts by assigning values to variables: price_of_item, quantity, and tax_rate.

• Step 2: Calculate Subtotal

o The program calculates the subtotal by multiplying the price_of_item by the quantity.

• Step 3: Calculate Tax

o The program calculates the tax by multiplying the subtotal by the tax_rate.

• Step 4: Calculate Total Cost

o The program calculates the total cost by adding the subtotal and the tax.

• Step 5: Display the Result


• The program prints the subtotal, tax, and total cost to the screen.
Explanation of the Example
• Output of the Program
• Subtotal: 150
• Tax: 15
• Total Cost: 165
Why Sequential Flow is Important
1. Simplicity: Sequential flow is easy to understand and implement,
making it ideal for simple tasks.
2. Foundation for Complex Logic: It forms the basis for more complex
control structures like loops and conditionals.
3. Predictability: Since the program executes statements in order,
debugging and testing are straightforward.
When to Use Sequential Flow
• Use sequential flow when the task involves a series of steps
that must be executed in a specific order.
• Examples include:
o Performing calculations.
o Reading and processing input data.
o Displaying output to the user.
Limitations of Sequential Flow
• Lack of Flexibility: Sequential flow cannot handle decisions or
repetitions without additional control structures.
• Not Suitable for Complex Logic: For tasks requiring conditional
execution or looping, sequential flow alone is insufficient.
Limitations of Sequential Flow
• Sequential flow is the backbone of programming. It ensures that
instructions are executed in a logical and predictable order. While it is
simple and effective for basic tasks, more complex programs often
combine sequential flow with other control structures like conditionals
and loops to handle decision-making and repetition.
Conditional flow
• Conditional flow in programming allows a program to make decisions
based on certain conditions. It enables the execution of different blocks
of code depending on whether a condition is true or false. Common
conditional structures include if, if..else, nested if..else, and switch.
if Statement
• The if statement is the simplest form of conditional flow. It executes a
block of code only if a specified condition is true.
• Pseudocode:
• IF (condition) THEN
• // Code to execute if the condition is true
• END IF
• Example:
• IF (age >= 18) THEN
• PRINT("You are eligible to vote.")
• END IF
• If age is 18 or older, the message "You are eligible to vote." is printed.
Otherwise, nothing happens.
if..else Statement
• The if..else statement extends the if statement by providing an
alternative block of code to execute if the condition is false.
• Pseudocode:
• IF (condition) THEN
• // Code to execute if the condition is true
• ELSE
• // Code to execute if the condition is false
• END IF
• Example:
• IF (temperature > 30) THEN
• PRINT("It's a hot day.")
• ELSE
• PRINT("It's a cool day.")
• END IF • If temperature is greater than 30, "It's a hot day."
is printed. Otherwise, "It's a cool day." is printed.
Nested if..else Statement
• Nested if..else statements allow you to check multiple conditions in a
hierarchical manner. An if or else block can contain
another if..else statement.
• Pseudocode:
• IF (condition1) THEN

• // Code to execute if condition1 is true

• IF (condition2) THEN

• // Code to execute if condition2 is true

• ELSE

• // Code to execute if condition2 is false

• END IF

• ELSE

• // Code to execute if condition1 is false

• END IF
• Example:
• IF (marks >= 90) THEN
• PRINT("Grade: A")
• ELSE IF (marks >= 80) THEN
• PRINT("Grade: B")
• ELSE IF (marks >= 70) THEN
• PRINT("Grade: C")
• ELSE
• PRINT("Grade: D")
• END IF
• This checks multiple conditions to determine the grade based on the marks.
switch Statement
• The switch statement is used to select one of many code blocks to
execute based on the value of a variable or expression. It is an
alternative to multiple if..else statements.
• Pseudocode:
• SWITCH (expression) DO
• CASE value1:
• // Code to execute if expression == value1
• BREAK
• CASE value2:
• // Code to execute if expression == value2
• BREAK
• DEFAULT:
• // Code to execute if expression does not match any case
• END SWITCH
• Example:

• SWITCH (day) DO

• CASE 1:

• PRINT("Monday")

• BREAK

• CASE 2:

• PRINT("Tuesday")

• BREAK

• CASE 3:

• PRINT("Wednesday")

• BREAK

• DEFAULT:

• PRINT("Invalid day")
• If day is 1, "Monday" is printed. If day is 2,
"Tuesday" is printed, and so on. If day does not match
• END SWITCH
any case, "Invalid day" is printed.
Summary of Conditional Flow Structures:
1. if: Executes a block of code if a condition is true.
2. if..else: Executes one block of code if a condition is true and another if it is
false.
3. Nested if..else: Allows checking multiple conditions in a hierarchical
manner.
4. switch: Selects one of many code blocks to execute based on the value of
an expression.
These structures are fundamental to controlling the flow of a program and
making it dynamic and responsive to different inputs and conditions.
Iterative flow
• Iterative flow, also known as looping, is a fundamental concept in
programming that allows a set of instructions to be executed repeatedly
until a specific condition is met. Iteration is useful for performing
repetitive tasks, processing collections of data, or implementing
algorithms that require repeated steps. There are three common types of
loops in programming: for, while, and do-while. Each has its own use
case and syntax, but they all serve the purpose of repeating code
execution.
For Loop
• The for loop is used when the number of iterations is known in
advance. It typically consists of three parts:
• Initialization: Sets the starting value of the loop variable.
• Condition: Specifies the condition under which the loop continues to
execute.
• Update: Modifies the loop variable after each iteration.
For Loop
• Pseudocode Example:
• FOR i = 1 TO 5
• PRINT "Iteration: " + i
• END FOR
For Loop
• Explanation:
• The loop starts with i = 1.
• It checks if i <= 5. If true, the loop body executes.
• After each iteration, i is incremented by 1 (i++).
• The loop stops when i becomes greater than 5.
For Loop
• Output:

• Iteration: 1
• Iteration: 2
• Iteration: 3
• Iteration: 4
• Iteration: 5
While Loop
• The while loop is used when the number of iterations is not known in
advance, and the loop continues as long as a specified condition is true.
The condition is evaluated before each iteration.
While Loop
• Pseudocode Example:
• SET counter = 1
• WHILE counter <= 5
• PRINT "Iteration: " + counter
• counter = counter + 1
• END WHILE
While Loop
• Explanation:
• The loop checks if counter <= 5. If true, the loop body executes.
• After each iteration, counter is incremented by 1.
• The loop stops when counter becomes greater than 5.
While Loop
• Output:

• Iteration: 1
• Iteration: 2
• Iteration: 3
• Iteration: 4
• Iteration: 5
Do-While Loop
• The do-while loop is similar to the while loop, but it guarantees that
the loop body is executed at least once, even if the condition is false
initially. The condition is evaluated after each iteration.
Do-While Loop
• Pseudocode Example:
• SET counter = 1
• DO
• PRINT "Iteration: " + counter
• counter = counter + 1
• WHILE counter <= 5
Do-While Loop
• Explanation:
• The loop body executes first, regardless of the condition.
• After each iteration, the condition counter <= 5 is checked.
• If the condition is true, the loop repeats; otherwise, it stops.
• The loop stops when counter becomes greater than 5.
Do-While Loop
• Output:

• Iteration: 1
• Iteration: 2
• Iteration: 3
• Iteration: 4
• Iteration: 5
Key Differences Between the Loops
Loop Type When to Use Condition Guaranteed
Check Execution

For Known number of Before each No


iterations iteration

While Unknown number of Before each No


iterations iteration

Do-While Unknown number of After each Yes


iterations iteration
Practical Use Cases:
For Loop: Iterating over arrays, lists, or a fixed range of values.
• FOR each item IN list
• PRINT item
• END FOR
Practical Use Cases:
While Loop: Reading input until a valid value is entered.
• SET valid = FALSE
• WHILE NOT valid
• INPUT userInput
• IF userInput is valid THEN
• valid = TRUE
• END IF
• END WHILE
Practical Use Cases:
Do-While Loop: Menu-driven programs where the user must see the menu at
least once.
• DO
• PRINT "1. Option 1"
• PRINT "2. Option 2"
• PRINT "3. Exit"
• INPUT choice
• WHILE choice != 3
Practical Use Cases:
• By understanding and using these loops effectively, you can write
efficient and concise code to handle repetitive tasks in your programs.
PROGRAMMING
CONCEPTS
(THE CONCEPT OF FUNCTIONS (SUBPROGRAMS))

You might also like