Computer Programming Languages and Algorithmic Problem Solving
Course Overview and Computer Basics
- Computer systems consist of two primary components: hardware and software.
- A program is a defined set of instructions executed by a computer to carry out specific tasks.
- Software serves as the collective term for all the various programs used to instruct computer hardware.
- The Central Processing Unit (CPU), or processor, executes the instructions contained within a program.
- Computer memory stores data for processing and holds intermediate calculation results.
- Memory capacity is measured in bytes. For example, of RAM corresponds to approximately (1 billion bytes) of memory.
Memory Organization and Addressing
- Main memory is structured as a long, continuous list of numbered bytes.
- The unique number assigned to a specific byte is defined as its address.
- A byte is the smallest addressable unit of memory in a computer architecture.
- Data of all types (numbers, characters, and text strings) is binary-encoded as sequences of and and stored directly in memory.
- Memory locations can span multiple contiguous bytes depending on the data type (e.g., 1-byte, 2-byte, or 3-byte memory locations).

Programming Languages and Classification
- Software programs convert high-level human logic into low-level instructions that computer hardware can execute.
- Programming languages fall into three primary categories based on abstraction level:
- Machine Language: Low-level binary code consisting of and executed directly by the CPU (e.g.,
1101101010011010). - Assembly Language: Low-level language using symbolic mnemonics to represent machine operations (e.g.,
add 2, 3, result). - High-Level Language: High-abstraction language providing readable syntax close to human logic and math (e.g.,
result = 2 + 3).
- Machine Language: Low-level binary code consisting of and executed directly by the CPU (e.g.,
Overview of Major High-Level Programming Languages
- Ada: Named after Ada Lovelace, who worked on early mechanical general-purpose computing. Developed for the U.S. Department of Defense and used predominantly in defense projects.
- BASIC: Beginner's All-purpose Symbolic Instruction Code. Designed to be easy to learn and use for introductory programming.
- C: Developed at Bell Laboratories. Combines the speed and direct hardware control of assembly language with the portability and ease of use of high-level languages.
- C++: An object-oriented programming language built as an extension of C.
- C#: Pronounced "C Sharp". A hybrid language combining features of Java and C++, developed by Microsoft.
- COBOL: COmmon Business Oriented Language. Designed specifically for commercial business applications.
- FORTRAN: FORmula TRANslation. Highly popular for scientific, engineering, and mathematical calculations.
- Java: Developed by Sun Microsystems (now Oracle). Designed for creating platform-independent internet and enterprise applications.
- Pascal: Named after 17th-century calculating machine pioneer Blaise Pascal. A simple, structured, general-purpose language used primarily for teaching programming fundamentals.
- Python: A simple, general-purpose scripting language optimized for high readability and rapid development.
- Visual Basic: Developed by Microsoft to enable rapid development of graphical user interfaces (GUIs).
Programming Paradigms
- A paradigm is a system of concepts and practices reflecting the structural design and style of programming.
- A programming paradigm classifies languages based on how program execution and structure are organized.

Imperative vs. Declarative Programming
- Imperative Programming: The programmer explicitly gives sequential commands/instructions telling the machine how to change its state step-by-step. Examples include C, C++, Java, PHP, Python, and Ruby.
- Imperative snippet in C:
cpp void main() { int d; int a, b; a = 1; b = 1; d = a / b; cout << "division" << d; }
- Imperative snippet in C:
- Declarative Programming: The programmer specifies what result is required without defining the explicit control flow or step-by-step algorithm to achieve it. Examples include SQL and Prolog.
- Declarative snippet in SQL:
sql select upper(name) from people where length(name) > 5 order by name
- Declarative snippet in SQL:
Specific Programming Paradigms
Structured Programming
- A subcategory of imperative programming.
- Control flow is strictly defined using three core control structures:
- Sequence: Executing statements sequentially.
java x = 5; y = 11; z = x + y; System.out.println(z); - Selection: Conditional branching based on boolean evaluation.
java if (x % 2 == 0) { System.out.println("The number is even."); } - Repetition: Iterative looping constructs.
java while (x < 100) { System.out.println(x); x = x * x; }
- Sequence: Executing statements sequentially.
Procedural Programming
- Derived from structured programming and centered on procedural calls (functions, routines, or subroutines).
- Employs a top-down design approach where a program breaks down into smaller sub-functions.
- Programs begin execution from a central entry point function (e.g.,
main()). - Examples include COBOL, BASIC, Pascal, FORTRAN, and C.

- Example of Procedural C Program:
#include <stdio.h>
// Function to add two numbers
int add(int a, int b) {
return a + b;
}
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
int sum = add(num1, num2);
printf("Sum: %d\n", sum);
return 0;
}
```
### Object-Oriented Programming (OOP)
- Structured around **objects** containing both state (data fields) and behavior (methods).
- Core concepts include **Classes** (blueprints) and **Objects** (instances of classes).
- Examples include C++, C#, Java, and Python.
| Class | Object Instances |
| :--- | :--- |
| Fruit | Apple, Banana, Mango |
| Car | Volvo, Audi, Toyota |
| Student | Ali, Hamza, Ahmad |
- Example Object-Oriented Java Program:
java public class Car { String carReg; int carModel; String carClass;
public Car(String num) {
carReg = num;
}
public String getReg() {
return carReg;
}
public static void main(String[] args) {
Car Audi = new Car("AX-7865");
System.out.println(Audi.getReg());
}
} ```
Functional Programming (FP)
Programs are constructed entirely by composing short, pure mathematical functions.
Computation is driven by function applications rather than state changes and mutable variable assignments.
All code and variables are strictly scoped within functions.
Examples include Haskell, Lisp, JavaScript, Python, and C++.
Comparison: Summing integers to :
- Imperative approach (Java):
int total = 0; for (int i = 1; i <= 10; i++) total = total + i; ``` - Functional approach (Haskell):haskell sum [1..10] ```
Declarative/Functional vs. Imperative comparison in Java:
import java.util.Arrays;
import java.util.List;
public class Functional {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100);
final int factor = 2;
// Declarative / Functional Stream API
numbers.stream()
.filter(number -> number % 2 == 0)
.forEach(System.out::println);
// Imperative Loop Construct
for (int number : numbers) {
if (number % 2 == 0) {
System.out.println(number);
}
}
}
}
```
# Program Development Cycle
- Effective programming mandates planning algorithm design prior to writing source code.
- Large computational problems must be broken down into smaller sub-tasks.

## The Seven Steps of Program Development
1. **Step 1–4**: Devise Algorithm (identifies and resolves Algorithmic Problems).
2. **Step 5**: Translate to Code (identifies and resolves Implementation Problems).
3. **Step 6**: Test Program (verifies program execution correctness).
4. **Step 7**: Debug Program (routes algorithmic defects back to Steps 1–4 and syntax/implementation defects back to Step 5).
## Algorithmic Tools
### Algorithm
- A set of well-defined, ordered logical steps taken to perform a task.
- Example: Gross Pay Algorithm for an hourly employee:
1. Obtain hours worked.
2. Obtain hourly pay rate.
3. Multiply hours worked by pay rate.
4. Display the resulting gross pay calculation.
### Pseudocode
- An informal design language without strict syntax rules.
- Cannot be compiled or executed directly; serves as a language-agnostic blueprint for implementation.
- Example Pseudocode:
text Display "Enter the number of hours the employee worked." Input hours Display "Enter the employee's hourly pay rate." Input payRate Set grossPay = hours * payRate Display "The employee's gross pay is $", grossPay ```
Flowcharts
- Diagrams graphically depicting algorithm flow using standardized symbols:
- Ovals: Terminal symbols (Start / End).
- Parallelograms: Input and Output operations (e.g.,
GET,PUT). - Rectangles: Processing operations (computations and variable assignments).
- Arrows: Show execution flow path.

The 4-Step Algorithm Design Framework

- Step 1: Work an Instance Yourself.
- Step 2: Write Down Exactly What You Just Did.
- Step 3: Generalize Your Steps.
- Step 4: Test Your Algorithm.
Worked Example 1: Exponentiation ()
- Problem statement: Calculate raised to the power ().
Step 1: Work an Instance
- Choose concrete values and . The mathematical target is .
Step 2: Write Down Steps
- Multiply by yields .
- Multiply by yields .
- Multiply by yields .
- is the final answer.
Step 3: Generalize
- Replace static base with variable :
- Multiply by yields .
- Multiply by yields .
- Multiply by yields .
- Identify repetitive loop behavior:
- Start with running result variable
- Loop count from to (inclusive):
- Update
- Output
Step 4: Test and Refine Algorithm
- Handle edge case :
If y is 0 then
1 is your answer
Otherwise:
Start with n = x
Count up from 1 to y - 1 (inclusive), for each number you count:
n = Multiply x by n
n is your answer.
```
- Simplified unified form (initializing ):
text Start with n = 1 Count up from 1 to y (inclusive), for each number you count: n = Multiply x by n n is your answer. ```
Worked Example 2: Nearest Point Search Problem
- Problem statement: Given a target point and a set of candidate points , find the point in closest to .
Step 1: Work an Instance
- Input target point .
- Input candidate set .
- Domain formula (Euclidean Distance):
- Step-by-step evaluations:
- Point : . Set current minimum distance = .
- Point : . Compare to ( is smaller; retain ).
- Point : . Compare to ( is smaller; update best candidate to ).
- Point : . Compare to ( is smaller; retain ).
- Point : . Compare to ( is smaller; update best candidate to ).
- Point : . Compare to ( is smaller; retain ).
- Point : . Compare to ( is smaller; retain ).
- Final Result: Closest point is .
Step 2: Write Down Log of Actions
- Document distance calculations and compare each result against the ongoing minimal distance, recording best candidate updates whenever a smaller distance is encountered.
Step 3: Generalize
- Define calculation for point in set :
- Define state tracking variables:
bestChoice: Point coordinates yielding the minimum distance.bestDistance: Numerical value of the minimum distance found.
- Establish initialization:
- Set
bestChoice= - Set
bestDistance=
- Set
- Iterative step rule:
- Loop index from to length of (exclusive of total point count):
- Calculate
currentDistancefor point . - If
currentDistance<bestDistance, setbestChoice= andbestDistance=currentDistance.
Step 4: Final Generalized Pseudocode
Compute sqrt((S[0].x - P.x)^2 + (S[0].y - P.y)^2), call it bestDistance
Start with bestChoice of S[0]
Count from 1 to the number of points in S exclusive, call each number i:
Compute sqrt((S[i].x - P.x)^2 + (S[i].y - P.y)^2), call it currentDistance
If currentDistance is smaller than bestDistance:
Update bestChoice to S[i] and bestDistance to currentDistance
Return bestChoice