PRINCIPLES OF PROGRAMMING
MIU-SEN 101
BY
MR. ABUBAKAR NASIRU SALIHU
Anasiru858@[Link]
07065543277
Course Description
This course introduces the fundamental principles of procedural and object oriented programming
using a high level language like Java, Python, or C++. Students will learn to design, implement,
and debug programs by applying core concepts such as variables, control structures, data
abstraction, encapsulation, inheritance, and polymorphism. The course will places a strong
emphasis on code quality, reusability, and composition. Advanced topics including basic file I/O,
networking, concurrency, and GUI development are also explored. Learning is reinforced through
extensive hands on labs and projects.
Programming
Programming is the process of creating a set of instructions for a computer to execute, which
involves problem solving by breaking down complex issues into smaller, manageable steps,
designing step by step procedures known as algorithms to solve them, and finally translating these
algorithms into a specific programming language through coding. Every program works with data.
To manage data effectively, programming languages use variables (for storage) and data types (to
define the kind of data). Operators are then used to process and manipulate that data.
Components of a Programming Environment
Text Editor/IDE (Integrated Development Environment)
A Text Editor or Integrated Development Environment (IDE) is the primary workspace where
programmers write, edit, and manage their code. While a simple text editor can be used, a full
featured IDE like VS Code, IntelliJ, or PyCharm provides a powerful, all in one toolkit that
significantly boosts productivity. Key features include syntax highlighting, which color codes
different elements of the code (like keywords and variables) to improve readability auto
completion, which intelligently suggests and completes code as you type to speed up development
and reduce typos; and an integrated file explorer, version control support, and project management
tools. Essentially, an IDE is the programmer's command center, designed to make the complex
task of writing software more efficient and organized.
Compiler/Interpreter
The Compiler or Interpreter is the fundamental system component responsible for translating the
high level, human readable code written by a programmer into low level instructions that the
computer's hardware can understand and execute. The key difference lies in how they perform this
translation a compiler translates the entire source code into an executable file in one go before the
program is run, while an interpreter translates and executes the code line by line, in real time.
Without this crucial translation step, the computer would be unable to process the instructions
written in languages like C++, Python, or Java, making the compiler or interpreter an indispensable
bridge between human logic and machine operation.
Debugger
A Debugger is a specialized tool integrated into an IDE that allows programmers to find, analyze,
and fix errors (called "bugs") in their code in a controlled and systematic way. Instead of just
running the program and hoping for the correct output, a debugger lets you pause the program's
execution at specific points called breakpoints, and then step through the code line by line. As you
do this, you can inspect the current state of the program by watching the values of variables,
observing the flow of execution, and identifying the exact line where logic fails or a crash occurs.
This process transforms debugging from a frustrating guessing game into a precise investigation,
saving immense amounts of time and effort in the development cycle.
Variables
A variable is a named storage location in memory that holds data.
Declaration: Creating a variable and giving it a name.
Initialization: Assigning a value to a variable.
Examples (in Java):
int age = 20; // integer variable
double price = 15.75; // decimal number
string name = "Ali"; // text (string) variable
Data Types
A data type is a classification that tells a computer what kind of data a value represents, how much
memory to allocate for it, and what operations can be performed on it.
Classifications of Data Types
Primitive Data Types: Primitive data types are the most basic, fundamental data types built
directly into a programming language. They represent single values and are not composed of other
data types.
Characteristics of Primitive Types:
i. Store values directly (not references)
ii. Fixed size in memory
iii. Stored on the stack (fast access)
iv. Immutable (when "changed," a new value is created)
Common Primitive Data Types:
Type Description Examples Size
int Whole numbers 42, -7, 0 4 bytes
float/double Decimal numbers 3.14, -0.5 4/8 bytes
char Single character 'A', '$', '9' 2 bytes
boolean True/False values true, false 1 bit
byte Very small integers 127, -128 1 byte
long Large integers 123456789L 8 bytes
Reference Data Types: Reference data types store a reference (memory address) to the location
where the actual data is stored, rather than storing the data directly
Characteristics of Reference Types:
i. Store memory addresses (pointers to data)
ii. Stored on the heap (dynamic memory)
iii. Variable size (can grow/shrink)
iv. Multiple variables can reference the same object
Common Reference Data Types:
Type Description Examples
Objects Instances of classes Person person = new Person();
Arrays Collections of elements int[] numbers = {1, 2, 3};
Strings Sequences of characters String name = "John";
Constants
A constant is a variable whose value cannot change during program execution.
final int DAYS = 7;
double PI = 3.14159;
float TAX_RATE = 0.07f;
char NEWLINE = '\n';
Operators
Operators are special symbols that perform operations on variables and values.
a) Arithmetic Operators:
+ (addition), - (subtraction), * (multiplication), / (division), % (modulus).
Example:
int x = 10, y = 3;
[Link](x + y); // 13
[Link](x % y); // 1
b) Relational Operators:
==, !=, >, <, >=, <= → compare values, result is true or false.
c) Logical Operators:
&& (AND), || (OR), ! (NOT).
Example:
int a = 5, b = 10;
[Link](a < b && b > 0); // true
d) Assignment Operators:
=, +=, -=, *=, /=, %=.
Example:
int n = 5;
n += 3; // n = 8
Casting
Casting is the process of converting a variable from one data type to another.
Types of Castinhg:
1. Implicit Casting (Widening) Automatic conversion
i. Happens automatically by the compiler
ii. Converts from smaller to larger data types
iii. No data loss occurs
Example
char letter = 'A';
int asciiValue = letter;
2. Explicit Casting (Narrowing) - Manual conversion
i. Programmer explicitly specifies the conversion
ii. Converts from larger to smaller data types
iii. May cause data loss
Example
double price = 19.99;
int roundedPrice = (int)price; // Explicit casting: double → int
Basic Input and Output (I/O) in C++
Input Operations
Input operations in C++ are handled using the cin object with the stream extraction operator >>.
The cin object reads input from the standard input (usually the keyboard) and stores it in variables.
Unlike Python's input() which always returns a string, cin directly reads the appropriate data type
based on the variable type. However, you must be cautious with input validation and handling
different data types. For string input with spaces, you should use getline(cin, variable) instead of
cin >> variable to capture the entire line including spaces.
Output Operations
In C++, output operations are primarily handled using the cout object with the stream insertion
operator <<. To use these, you must include the <iostream> header and use the std namespace. For
simple text output, you can use cout << "text";, and to output multiple items, you can chain them
together with multiple << operators. C++ offers several formatting options: the std::endl
manipulator adds a newline and flushes the buffer, while \n provides a simple newline character.
Common Errors to Avoid
i. Syntax Errors: Missing colons, parentheses, or quotation marks
ii. Type Errors: Mixing incompatible data types
iii. Name Errors: Using variables before they're defined
iv. Logic Errors: Code runs but produces wrong results
Program syntax
#include <iostream>
using namespace std;
int main()
cout << "Hello world!" << endl;
return 0;
}
Program to print data
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName, lastName, fullName;
// Get first name
cout << "Enter your first name: ";
cin >> firstName;
// Get last name
cout << "Enter your last name: ";
cin >> lastName;
// Combine names
fullName = firstName + " " + lastName;
// Print results
cout << "\n=== Name Information ===" << endl;
cout << "First Name: " << firstName << endl;
cout << "Last Name: " << lastName << endl;
cout << "Full Name: " << fullName << endl;
cout << "Welcome, " << fullName << "!" << endl;
return 0;
Conditional Statements
Conditional statements allow your program to make decisions and execute different code blocks
based on certain conditions. They enable programs to respond dynamically to different situations
and inputs.
if Statement
The if statement executes a block of code only if a specified condition is true.
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
if (age >= 18) {
cout << "You are eligible to vote." << endl;
return 0;
If else Statement
The if-else statement provides an alternative code block to execute when the condition is false.
int score;
cout << "Enter your test score: ";
cin >> score;
if (score >= 60) {
cout << "You passed the exam!" << endl;
} else {
cout << "You failed the exam." << endl;
Nested if Statements
Place if statements inside other if statements for complex decision-making.
int age;
bool hasLicense;
cout << "Enter your age: ";
cin >> age;
cout << "Do you have a driver's license? (1 for yes, 0 for no): ";
cin >> hasLicense;
if (age >= 18) {
if (hasLicense) {
cout << "You can drive legally." << endl;
} else {
cout << "You need to get a driver's license." << endl;
} else {
cout << "You are too young to drive." << endl;
}
Switch Statement
The switch statement provides an efficient way to dispatch execution to different parts of code
based on the value of an expression.
int day;
cout << "Enter day number (1-7): ";
cin >> day;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day number!" << endl;
Looping Structures
Loops allow you to execute a block of code repeatedly until a specific condition is met. They are
essential for processing collections of data, performing calculations, and automating repetitive
tasks.
While Loop
The while loop repeats a block of code as long as a condition remains true.
#include <iostream>
using namespace std;
int main() {
int count = 1;
// Count from 1 to 5
while (count <= 5) {
cout << "Count: " << count << endl;
count++; // Increment count
char continueLoop = 'y';
while (continueLoop == 'y' || continueLoop == 'Y') {
cout << "Looping again!" << endl;
cout << "Continue? (y/n): ";
cin >> continueLoop;
return 0;
}
Do while Loop
The do while loop executes the code block first, then checks the condition. It always runs at least
once.
int number;
do {
cout << "Enter a positive number: ";
cin >> number;
} while (number <= 0);
cout << "You entered: " << number << endl;
for Loop
The for loop provides a compact way to iterate a specific number of times with built-in
initialization, condition checking, and increment/decrement.
int num;
cout << "Enter a number: ";
cin >> num;
for (int i = 1; i <= 10; i++) {
cout << num << " x " << i << " = " << (num * i) << endl;
}
Functions
Functions are reusable blocks of code that perform a specific task. They promote code
organization, reusability, and maintainability through procedural abstraction.
Components of Function
Function Declaration: Tells the compiler about the function's name, return type, and parameters
Function Definition: Implements the actual code of the function
Function Call: Executes the function
#include <iostream>
using namespace std;
// Function declaration (prototype)
int addNumbers(int a, int b);
// Function definition
int addNumbers(int a, int b) {
return a + b;
// Function without parameters and return value
void greet() {
cout << "Hello, welcome to the program!" << endl;
}
// Function with parameters but no return value
void displayMessage(string message, int times) {
for (int i = 0; i < times; i++) {
cout << message << endl;
int main() {
// Function calls
greet();
int result = addNumbers(5, 3);
cout << "5 + 3 = " << result << endl;
displayMessage("C++ is fun!", 3);
return 0;
Variable Scope
Variable scope determines where in your program a variable can be accessed. Understanding scope
is crucial for avoiding naming conflicts and managing memory efficiently.
Local Scope
Variables declared inside a function are local to that function.
void function1() {
int x = 10; // Local to function1
cout << "Function1 x: " << x << endl;
void function2() {
int x = 20; // Local to function2 (different variable)
cout << "Function2 x: " << x << endl;
Global Scope
Variables declared outside all functions are global and accessible throughout the program.
#include <iostream>
using namespace std;
int globalCounter = 0; // Global variable
void incrementCounter() {
globalCounter++;
cout << "Counter: " << globalCounter << endl;
int main() {
incrementCounter(); // Counter: 1
incrementCounter(); // Counter: 2
incrementCounter(); // Counter: 3
return 0;
Arrays
Arrays are collections of elements of the same data type stored in contiguous memory locations.
They allow you to store multiple values under a single variable name, accessed using an index.
#include <iostream>
using namespace std;
int main() {
// Array declaration and initialization
int numbers[5]; // Declaration without initialization
double prices[4] = {10.5, 20.0, 15.75, 8.99}; // Declaration with initialization
OOP (Object Oriented Programming)
Object Oriented Programming (OOP) is a programming paradigm that organizes software design
around objects and data rather than actions and logic. An object contains both data (attributes) and
behavior (methods), modeling real world entities in code.
Pillars of OOP
Encapsulation:
Bundling data and methods that operate on that data within a single unit (class)
Abstraction:
Hiding complex implementation details and showing only essential features
Inheritance:
Inheritance allows a new class (derived class) to inherit properties and behaviors from an existing
class (base class). This promotes code reuse and establishes relationships between classes.
Polymorphism: Allowing objects of different classes to be treated as objects of a common
superclass
Benefits of OOP
1. Modularity:
Code is organized into independent, reusable components Modularity in OOP means the entire
program is broken down into smaller, self contained units called classes and objects. Each class is
responsible for a specific task or functionality within the program. This makes the system easier
to understand because you can focus on one component at a time. It also helps in debugging if an
error occurs, you only need to check the part of the code related to that specific module instead of
the whole program.
2. Maintainability:
Easier to modify and extend existing code OOP provides a structured way of writing code, making
updates or improvements simpler. When you need to change a feature, you usually modify one
class without affecting the rest of the program. Inheritance also allows you to create new classes
based on existing ones, making it easy to extend functionality without rewriting large sections of
code. This ensures long-term support and easier upgrades.
3. Reusability:
Classes can be reused across different programs once you create a class for a specific functionality,
you can use it in other projects or programs without rewriting the logic. This saves development
time and ensures consistency across applications. For example, if you build a class that handles
user authentication, you can simply reuse the same class in another application that requires login
functionality.
4. Scalability:
Easier to manage complex software systems OOP makes it easier to build and manage large scale
applications. Because the program is divided into classes and objects, developers can work on
different parts of the system independently without conflicts. New features can be added smoothly,
and complexity becomes manageable since each component of the system has a clear role and
structure.
Class
Class: A blueprint or template that defines the properties and behaviors of objects
Objects
Object: An instance of a class that contains actual data and can perform operations
Class/object Declaration and Definition
#include <iostream>
using namespace std;
// CLASS DECLARATION
class Student {
private:
string name;
int age;
public:
// Constructor
Student(string n, int a) {
name = n;
age = a;
// Method to display student info
void display() {
cout << name << " is " << age << " years old." << endl;
}};
int main() {
// OBJECT CREATION
Student student1("Alice", 20);
Student student2("Bob", 22);
// USING OBJECTS
[Link]();
[Link]();
return 0;
}
Constructors and Destructors
Constructors
Special member functions that are automatically called when an object is created. They initialize
the object's data members.
Destructors
Special member functions that are automatically called when an object is destroyed. They perform
cleanup operations.
Exception Handling
Exceptions are runtime anomalies or unusual conditions that disrupt the normal flow of program
execution. Exception handling provides a structured way to detect and respond to errors.
Networking: Basic Client Server Model
Introduction to Networking
Networking refers to the process of connecting two or more computers so they can share
information and resources. In programming, networking allows different programs possibly
running on different devices to communicate with each other. This communication is made
possible through network protocols and sockets.
Sockets
A socket is an endpoint used for sending and receiving data across a network. You can think of it
as a virtual “plug” that allows programs to connect to each other, similar to how electrical plugs
connect to sockets to get electricity. Sockets allow programmers to Send data, receive data and
establish connections between computers
The Client Server Model
The client server model is one of the most widely used architectures in networking.
In this model:
i. Clients are programs that request services or data
ii. Servers are programs that provide services or respond to client requests
How It Works
1. Server starts and waits for requests the server runs continuously, listening on a specific
network port.
It waits for clients to connect.
2. Client connects to the server A client program initiates the communication by sending a
request to the server’s IP address and port.
3. Server processes the request once the server receives the request, it carries out whatever
task is required such as sending data, performing calculations, or storing information.
4. Server sends a response after processing, the server sends a result back to the client.
5. Connection closes or stays open Depending on the design, the connection may close, or
remain open for further communication.