Cs Textbook Extended (2)
Cs Textbook Extended (2)
1
3.1 Programming Paradigms
3.1.1 Imperative Programming
Procedural Programming
#include <stdio.h>
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);
2
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
}
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;
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
@Override
public double getArea() {
return length * width;
}
@Override
public double getPerimeter() {
return 2 * (length + width);
}
}
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];
// 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)
5
salary DECIMAL(10,2)
);
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]"
]
6
• Strong vs Weak typing
• Type inference
• Generics/Templates