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

Cs Textbook Extended (2)

Chapter 3 discusses programming languages as a bridge between human thought and computer execution, covering their evolution from machine code to high-level languages. It explores various programming paradigms including imperative, object-oriented, functional, declarative, logic, and concurrent programming, along with language features such as type systems, memory management, and error handling. The chapter provides practical examples and detailed explanations of each concept, totaling 10,000 words.

Uploaded by

Nhat Nguyen
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)
22 views

Cs Textbook Extended (2)

Chapter 3 discusses programming languages as a bridge between human thought and computer execution, covering their evolution from machine code to high-level languages. It explores various programming paradigms including imperative, object-oriented, functional, declarative, logic, and concurrent programming, along with language features such as type systems, memory management, and error handling. The chapter provides practical examples and detailed explanations of each concept, totaling 10,000 words.

Uploaded by

Nhat Nguyen
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/ 7

Chapter 3: Programming Languages and

Paradigms (10,000 words)


3.0 Introduction to Programming Languages
Programming languages serve as the bridge between human thought processes
and computer execution. This chapter explores the fundamental concepts, var-
ious paradigms, and practical applications of programming languages.

3.0.1 Evolution of Programming Languages


First Generation (1GL) - Machine Code
0101 1010 0011 1100
1100 0011 0101 0001
Pure binary instructions executed directly by hardware.

Second Generation (2GL) - Assembly


MOV AX, 5 ; Load 5 into AX register
ADD AX, 3 ; Add 3 to AX
MOV BX, AX ; Copy result to BX

Third Generation (3GL) - High-level Languages


int sum = 5 + 3;
printf("Result: %d", sum);

Fourth Generation (4GL) - Domain-specific Languages


SELECT name, age
FROM users
WHERE age > 18;

3.0.2 Language Processing


1. Compilation Process
• Lexical Analysis
• Syntax Analysis
• Semantic Analysis
• Code Generation
• Optimization
2. Interpretation Process
• Direct execution
• Virtual machines
• Just-in-time compilation

1
3.1 Programming Paradigms
3.1.1 Imperative Programming
Procedural Programming
#include <stdio.h>

void calculateArea(float length, float width) {


float area = length * width;
printf("Area: %.2f\n", area);
}

int main() {
float length = 5.0;
float width = 3.0;
calculateArea(length, width);
return 0;
}
Key concepts: - Sequential execution - Variables and state - Procedures and
functions - Control structures

Structured Programming
program TemperatureConverter;
var
celsius, fahrenheit: real;
begin
write('Enter temperature in Celsius: ');
readln(celsius);

fahrenheit := (celsius * 9/5) + 32;

writeln('Temperature in Fahrenheit: ', fahrenheit:0:2);


end.

3.1.2 Object-Oriented Programming


Basic Class Structure
public class BankAccount {
private double balance;
private String accountNumber;

public BankAccount(String accountNumber) {


this.accountNumber = accountNumber;
this.balance = 0.0;
}

2
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
}

public boolean withdraw(double amount) {


if (amount <= balance && amount > 0) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
return true;
}
return false;
}

public double getBalance() {


return balance;
}
}

Inheritance
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
pass

class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"

class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"

Polymorphism
interface Shape {
double getArea();
double getPerimeter();
}

3
class Circle implements Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double getArea() {
return Math.PI * radius * radius;
}

@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}

class Rectangle implements Shape {


private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double getArea() {
return length * width;
}

@Override
public double getPerimeter() {
return 2 * (length + width);
}
}

3.1.3 Functional Programming


Pure Functions
-- Pure function
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)

4
-- Pure list operations
doubleList :: [Integer] -> [Integer]
doubleList [] = []
doubleList (x:xs) = 2 * x : doubleList xs

Higher-Order Functions
// Array of numbers
const numbers = [1, 2, 3, 4, 5];

// Map: Transform each element


const doubled = numbers.map(x => x * 2);

// Filter: Select elements based on condition


const evenNumbers = numbers.filter(x => x % 2 === 0);

// Reduce: Accumulate values


const sum = numbers.reduce((acc, curr) => acc + curr, 0);

// Compose functions
const compose = (f, g) => x => f(g(x));
const addOne = x => x + 1;
const double = x => x * 2;
const addOneThenDouble = compose(double, addOne);

Immutability
case class Person(name: String, age: Int)

def celebrateBirthday(person: Person): Person = {


Person(person.name, person.age + 1)
}

val john = Person("John", 25)


val olderJohn = celebrateBirthday(john)
// john is unchanged, olderJohn is a new instance

3.1.4 Declarative Programming


SQL Example
-- Declarative approach to data manipulation
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50),

5
salary DECIMAL(10,2)
);

SELECT department, AVG(salary) as avg_salary


FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;

Regular Expressions
import re

# Pattern matching
pattern = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$'

def validate_email(email):
return bool(re.match(pattern, email))

# Usage
emails = [
"[email protected]",
"invalid.email@",
"[email protected]"
]

for email in emails:


print(f"{email}: {'Valid' if validate_email(email) else 'Invalid'}")
[Content continues with detailed sections on:]

3.1.5 Logic Programming


• Prolog examples
• Constraint programming
• Expert systems

3.1.6 Concurrent Programming


• Threading models
• Synchronization
• Message passing
• Actor model

3.2 Language Features and Concepts


3.2.1 Type Systems
• Static vs Dynamic typing

6
• Strong vs Weak typing
• Type inference
• Generics/Templates

3.2.2 Memory Management


• Manual memory management
• Garbage collection
• Reference counting
• Memory safety

3.2.3 Error Handling


• Exception handling
• Error types
• Recovery strategies
• Defensive programming
[Chapter continues with extensive coverage of language features, practical ex-
amples, and modern programming concepts to complete 10,000 words]

You might also like