Unit 1_System programming
Unit 1_System programming
Programming
Course Credit : 4
Theory : 9 Hours
What is Systems Programming
Systems programming is the process of developing software that makes a computer
system work. It involves writing programs that control the computer's operations, such
as the operating system, firmware, and network software.
C++ is one of the most popular and widely used languages for systems programming,
The programming language need to follow some strategy when they are
implemented and this methodology/strategy is referred as paradigms.
Introduction to Programming Paradigms
❖ Imperative Programming ❖ Functional Programming
❖ Imperative programming consists of sets of ❖ Here we subdivide the program execution into
detailed instructions that are given to the functions, as a way of improving modularity and
organization and code maintainability.
computer to execute in a given order. Step by
step instructions are given. ❖ Functions are treated as first-class citizens, meaning
that they can be assigned to variables, passed as
❖ C : developed by Dennis Ritchie and Ken Thompson arguments, and returned from other functions.
Fortran : developed by John Backus for IBM
Basic : developed by John G Kemeny and Thomas E ❖ They are pure functions, no side effects and strict
Kurtz control flow.
❖ JavaScript : developed by Brendan Eich
Example: Python: developed by __________, Haskell :
define squared_sum (x,y): developed by Lennart Augustsson, Dave Barton Scala :
developed by Martin Odersky
sum = x+y Example:
squared= sum^2 define squared_sum (x,y):
return squared return (x+y)^2
// squared_sum(2,3) = 25 Square_sum(2,3) = 25
Introduction to Programming Paradigms
❖ Object-Oriented Programming ❖ Generic programming
❖ Object-oriented programming allows to organize code into
classes, objects, inheritance, and polymorphism, making it ❖ Allows to write code that works with different
easier to model complex systems and reuse code.
types of data, using templates, containers, and
❖ Example
algorithms, making it more efficient and
#include <iostream> expressive.
using namespace std;
class person { ❖ Multi paradigm
char name[20]; ❖ supports more than one programming paradigm
int id;
public:
void getdetails() {}
};
int main()
{
person p1; // p1 is a object
return 0;
}
Why C++ for Systems Programming
C++ is not only a low-level language, but also a multi-paradigm language that
supports object-oriented and generic programming.
C++ comes with a rich and powerful standard library that provides a wide range
of functionality, such as input/output, strings, containers, algorithms,
exceptions, threads, and smart pointers.
C++ is known for its high performance and efficiency, which are crucial for
systems programming.
C++ is a compiled language, which means it translates code into machine code
that runs directly on the hardware, without any intermediate layer or overhead.
C++ is a dynamic language adding new features like lambda expressions, auto
type deduction, range-based for loops that make it more user friendly
C Vs C++
C++ was developed by Bjarne Stroustrup at Bell labs in 1979, as an extension to the C language.
C++ is a combination of procedural programming as well as object oriented programming. Objects
consists of Data in form of it's characteristics and are coded in the form of methods.
In object oriented programming computer programs are designed using the concept of objects that
interact with the real world.
C++ Syntax
#include <iostream>: . It tells the compiler to include the standard
iostream file which contains declarations of all the standard input/output #include <iostream>
library functions. # is the directive. It allows us to include objects such as
cin and cout, cerr etc using namespace std;
using namespace std: This is used to import the entirety of the std int main()
namespace into the current namespace of the program. Means that {
names for objects and variables can be used from the standard library. It
is also used as additional information to differentiate similar functions. cout <<"Hello World.";
int main(): The function main is called just as in C. Any code inside its return 0;
curly brackets {} will be executed. Execution of every C++ program
}
begins with the main() function, no matter where the function is located in
the program. S Better alternative
cout: is an object used to print a particular text after << in quotes. In our #include <iostream>
example it will output "Hello World". (for personal reference we can say it
int main()
is similar to printf in c)
return 0: Terminates the function main. This statement is used to return a {
value from a function and indicates the finishing of a function. std::cout <<"Hello World";
Note: return 0;
1) Every C++ statement ends with a semicolon ';' }
2) Compiler ignores white spaces. Multiple line spaces are used to make
C++ Syntax
cout object, together with the << operator, is used to output
values/print text.
In order to insert a new line after each object declaration \n or #include <iostream>
end1 is used. using namespace std;
cin is used to get user input. This is paired along with the int main() {
extraction operator (>>) // Comment
Comments are used by the programmer to make the code cout << "Demo Code.\n";
understandable so that is can be improvised later and to make it cout << "I am learning C++" <<end1;
more readable. It can also be used to prevent execution when
cout << "print text";
testing alternative code.
return 0;
Single line comments: Single-line comments are initiated with
two forward slashes (//). This comments the entire line after the }
two slashes.
Multi Line comments: Multi-line comments start with /* and ends
with */ .
The text in between both of these will not be executed by the
compiler. Hence comments can we written in multiple lines
In class assignment
int i = 3;
// A pointer to variable i or "stores the address of i"
int *ptr = &i;
// A reference (or alias) for i.
int &ref = i;
References Vs Pointers
Functions
The purpose of creating a function is so that a block of
code can be executed multiple times when a function is #include <iostream>
called. using namespace std;
Data known as parameters is passed into the function. void myFunction()
The function main() is predefined and is mandatory in {
program. However there are other functions which are cout << "We are learning functions";
user defined. }
Function Calling int main()
To call a function we are to write the function's name {
followed by brackets () and a semicolon; myFunction();
Note: The function can be called multiple times and that's return 0;
what makes it useful. }
Output:
How to create a function? We are learning functions
Syntax:
void nameFunction() { Note: If a user-defined function as in the above example is
//code block declared after the main() function the code will throw an error.
It is because C++ works from top to bottom in a sequential
} flow.
Note: Void means the function doesn't have a return
value.
Function Parameters
Data can be passed to a function as a parameter. These
are variables inside of functions. These are specified #include <iostream>
withing the brackets with their datatypes. #include <string>
using namespace std;
Syntax:
void myFunction(string name)
void function( datatype variable; datatype variable;)
{
{ cout << name << " \n";
//code block }
} int main()
{
myFunction("Honey");
myFunction("sam");
myFunction("Anja");
return 0;
How to create a function? }
Syntax:
Output:
void nameFunction() { Honey
//code block sam
} Anja
Note: Void means the function doesn't have a return
value. Note: Honey is an argument , however name is a parameter
#include <iostream>
Function Parameters using namespace std;
Return Values void swapNums(int &x, int &y) {
In the following example the keyword return is used. int z = x;
Using int instead of void helps us to derive a return x = y;
value. However as discussed earlier void doesn't return a y = z;
value.
}
Call by Reference
int main() {
You can also pass a reference to the function by using
int firstNum = 10;
pointers
int secondNum = 20;
#include <iostream> cout << "Before swap: " << "\n";
using namespace std;
cout << " "<<firstNum <<“ " <<secondNum << "\n";
int myFunction(int x, int y)
swapNums(firstNum, secondNum);
{
return x + y; cout << "After swap: " << "\n";
} cout << " "<<firstNum << " "<<secondNum << "\n";
int main() return 0;
{ }
int z = myFunction(2, 3);
Before swap:
cout << z; Output:
10 20
return 0; 5
After swap:
}
20 10
Call by value and call by reference in C++
Call by reference
There are two ways to pass value or data to function In call by reference, original value is modified because we pass reference
Call by value : original value is not modified. (address).
⚫Here, address of the value is passed in the function, so actual and formal
In call by value, value being passed to the function is locally stored by arguments share the same address space. Hence, value changed inside
the function parameter in stack memory location. If you change the the function, is reflected inside as well as outside the function.
value of function parameter, it is changed for the current function only.
It will not change the value of variable inside the caller method such
as main().
// Swap function to demonstrate call by
// C++ Program to implement Swapping using Call by function Reference method
#include <iostream> #include<iostream>
using namespace std;
// Swap function to demonstrate call by value method using namespace std;
void swap(int x, int y) void swap(int *x, int *y)
{ {
int t = x;
x = y; int swap;
y = t; swap=*x;
cout << "After Swapping in function x: " << x *x=*y;
<< ", y: " << y << endl;
} *y=swap;
// Driver Code }
int main() int main()
{
int x = 1, y = 2; {
cout << "Before Swapping: "; int x=500, y=100;
cout << "x: " << x << ", y: " << y << endl; swap(&x, &y); // passing value to function
swap(x, y); Output
cout << "After Swapping in driver code: "; cout<<"Value of x is: "<<x<<endl;
Before Swapping: x: 1, y: 2
cout << "x: " << x << ", y: " << y << endl; cout<<"Value of y is: "<<y<<endl;
return 0;
After Swapping in function x: 2, y: 1
return 0;
} After Swapping in driver code: x: 1, y: 2
}
Functions contd..
Function Overloading
This property is special to C++. Using Function overloading #include <iostream>
multiple functions can have the same name with different using namespace std;
parameters. void add(int a, int b){
Note: It is better to over load one function instead of defining two cout << "sum = " << (a + b);
functions to do the same thing.
}
Remember multiple functions can have the same name until their
void add(int a, int b, int c){
datatype or parameters differ.
cout << endl << "sum = " << (a + b + c);
Function overloading can be considered as an example of a
polymorphism feature in C++. }
// Driver code
#include <iostream> int main(){
using namespace std; add(10, 2);
void add(int a, int b){
add(5, 6, 4);
cout << "sum = " << (a + b);
}
return 0;
} Output:
void add(double a, double b){
cout << endl << "sum = " << (a + b);
sum = 12
} sum = 15
// Driver code
int main(){
add(10, 2);
add(5.3, 6.2);
Output:
return 0;
sum = 12
}
sum = 11.5
Function Overloading
Advantages of function overloading:
⚫ Improves code readability and allows code reusability.
⚫ It saves memory space, consistency, and readability.
⚫ It speeds up the execution of the program
⚫ Code maintenance also becomes easy.
⚫ Function overloading brings flexibility to code.
Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common
properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc.
So here, the Car is the class, and wheels, speed limits, and mileage are their properties.
Object
An Object is an identifiable entity with some characteristics and behavior.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.
Objects take up space in memory and have an associated address.
When a program is executed the objects interact by sending messages to one another.
Each object contains data and code to manipulate the data.
Objects can interact without having to know details of each other’s data or code, it is sufficient to know the type of message accepted
and the type of response returned by the objects.
Class in C++
// C++ Program to show the syntax/working of Objects as a
// part of Object Oriented Programming
#include <iostream>
using namespace std;
class person {
char name[20]; //data member or attributes
int id;
public: //access specifiers
void getdetails() {} //member method
};
int main()
{
person p1; // p1 is a object
return 0; Attributes and Methods are accessed by creating an object of the class and
} using the dot syntax (.)
Example to illustrate simple Class and object in C++
// C++ program to illustrate how create a simple int main()
//class and object
{
// Create an object of the Person class
#include <iostream>
#include <string> Person person1;
using namespace std; // accessing data members
// Define a class named 'Person' person1.name = "Alice";
class Person { person1.age = 30;
public: // Call the introduce member method
// Data members
person1.introduce();
string name;
return 0;
int age;
} Output
// Member function to introduce the person Hi, my name is Alice and I am 30 years old.
void introduce()
{
cout << "Hi, my name is " << name << "
and I am "
<< age << " years old." << endl;
Attributes and Methods are accessed by creating an object of the class and
}
using the dot syntax (.)
};
Example to illustrate simple Class and object in C++
#include<iostream>
#include<string>
using namespace std;
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
class MyClass {
public: // Public access specifier class MyClass {
int x; // Public attribute
int x; // Private attribute
private: // Private access specifier
int y; // Private attribute int y; // Private attribute
}; };
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
C++ Encapsulation
Encapsulation: to make sure that "sensitive" data is hidden from users. T
Declare class variables/attributes as private (cannot be accessed from outside the class).
To read or modify the value of a private member, provide public get and set methods.
class Employee {
private:
// Private attribute The salary attribute is private, which have restricted access.
int salary;
The public setSalary() method takes a parameter (s) and assigns it to the
public:
salary attribute (salary = s).
// Setter
void setSalary(int s) {
salary = s; The public getSalary() method returns the value of the private salary
} attribute.
// Getter
int getSalary() { Inside main(), we create an object of the Employee class.
return salary;
Now we can use the setSalary() method to set the value of the private
}
attribute to 50000.
};
Then we call the getSalary() method on the object to return the value.
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
C++ Inheritance
In C++, it is possible to inherit attributes and methods from one class to another.
⚫ derived class (child) - the class that inherits from another class
⚫ base class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
//Multilevel Inheritance
// Base class // Base class (parent)
class Vehicle { class MyClass {
public: public:
string brand = "Ford"; void myFunction() {
void honk() { cout << "Some content in parent class." ;
cout << "Tuut, tuut! \n" ; }
} };
}; The Car class
(child) inherits the
attributes and // Derived class (child)
// Derived class class MyChild: public MyClass {
class Car: public Vehicle { methods from the
Vehicle class };
public:
string model = "Mustang"; (parent)
// Derived class (grandchild)
}; class MyGrandChild: public MyChild {
};
int main() {
Car myCar; int main() {
myCar.honk(); MyGrandChild myObj;
cout << myCar.brand + " " + myCar.model; myObj.myFunction();
return 0; return 0;
} }
C++ Inheritance Access // Base class
class Employee {
In C++, there are three access specifiers: protected: // Protected access specifier
⚫ public - members are accessible from outside int salary;
the class };
⚫ private - members cannot be accessed (or // Derived class
viewed) from outside the class. By default, all class Programmer: public Employee {
members of a class are private if you don't public:
specify an access specifier: int bonus;
⚫ protected - members cannot be accessed void setSalary(int s) {
from outside the class, however, they can salary = s;
be accessed in inherited classes. }
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary()
<< "\n";
cout << "Bonus: " << myObj.bonus <<
"\n";
return 0;
}
C++ Polymorphism // Base class
class Animal {
⚫ Polymorphism means "many public:
forms", and it occurs when we void animalSound() {
have many classes that are related cout << "The animal makes a sound
to each other by inheritance. \n";
⚫ Inheritance lets us inherit }
attributes and methods from };
another class.
⚫ Polymorphism uses those methods // Derived class
to perform different tasks. This class Pig : public Animal {
allows us to perform a single action public:
in different ways. void animalSound() {
cout << "The pig says: wee wee \n";
}
};
base class :Animal
method : animalSound(). // Derived class
Derived classes of Animals: Pigs, class Dog : public Animal { int main() {
public: Animal myAnimal;
Cats, Dogs, Birds - And they also
void animalSound() { Pig myPig;
have their own implementation of Dog myDog;
cout << "The dog says: bow wow \n";
an animal sound (the pig oinks, }
and the cat meows, etc.): }; myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
To read a file
C++ Files #include <iostream>
#include <fstream>
Using fstream library we can work with files. That library using namespace std;
function can be included by using <fstream>
int main () {
There are 3 objects included in this library. // Create a text file
ofstream: Creates and writes in files ofstream MyFileWrite ("filename.txt");
ifstream: Reads from file // Write to the file
fstream: Capable of creating, reading and writing in files. MyFileWrite << "Hello File!";
// Close the file
Create and write in file
MyFileWrite.close ();
#include <iostream> // Create a text string, which is used to output the text file
#include <fstream> string RandomText;
using namespace std; // Read from the text file
int main () { ifstream MyFileRead ("filename.txt");
//create and open a text file // Use a while loop together with the getline() function to
read the file line by line
ofstream MyFile ("filename.txt");
while (getline (MyFileRead, RandomText)) {
//Write to the file // Output the text from the file
MyFile << "Hello File"; cout << RandomText;
//close the file }
MyFile.close(); // Close the file
return 0; MyFileRead.close ();
return 0;
}
Exception handling in C++ consist of three keywords:
C++ Exceptions try, throw and catch:
The try statement allows you to define a block of code to
When executing C++ code, different errors can occur: be tested for errors while it is being executed.
coding errors made by the programmer, errors due to The throw keyword throws an exception when a problem is
wrong input, or other unforeseeable things. detected, which lets us create a custom error.
When an error occurs, C++ will normally stop and The catch statement allows you to define a block of code
generate an error message. The technical term for this to be executed, if an error occurs in the try block.
is: C++ will throw an exception (throw an error). The try and catch keywords come in pairs:
//C++ Exceptions
try {
int age = 15;
if (age >= 18) {
We use the try block to test some code: If the age variable is less than
cout << "Access granted - you are old enough.";
18, we will throw an exception, and handle it in our catch block.
} else {
throw (age); In the catch block, we catch the error and do something about it. The
} catch statement takes a parameter: in our example we use an int
variable (myNum) (because we are throwing an exception of int type in
} the try block (age)), to output the value of age.
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n"; If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be
cout << "Age is: " << myNum; greater than 18), the catch block is skipped:
}
#include <iostream>
C++ Date and Time #include <ctime> // Import the ctime library
using namespace std;
The <ctime> library allows us to work with dates and times.
To use it, you must import the <ctime> header file: int main () {
The time() function gives us a timestamp representing the struct tm datetime;
current date and time. We can use the ctime() function to time_t timestamp;
show the date and time that a timestamp represents:
datetime.tm_year = 2023 - 1900; // Number of years since 1900
datetime.tm_mon = 12 - 1; // Number of months since January
datetime.tm_mday = 17;
Hours are represented in 24-hour format. 11pm would be represented as 23. datetime.tm_hour = 12;
The months go from 0 to 11. For example, December would be represented datetime.tm_min = 30;
as 11 rather than 12. datetime.tm_sec = 1;
Years are represented relative to the year 1900. The year 2024 would be // Daylight Savings must be specified
represented as 124 because 124 years have passed since 1900.
// -1 uses the computer's timezone setting
datetime.tm_isdst = -1;
The time() function can only create a timestamp for the current timestamp = mktime(&datetime);
date, but we can create a timestamp for any date by using the
cout << ctime(×tamp);
mktime() function.
return 0; Output
The mktime() function converts a datetime structure into a } Sun Dec 17 12:30:01 2023
timestamp.
// thread example
#include <iostream> // std::cout
C++ Threads #include <thread>
void foo()
// std::thread
Thread {
Class to represent individual threads of execution. // do stuff...
}
void bar(int x)
A thread of execution is a sequence of instructions that can be
{
executed concurrently with other such sequences in
// do stuff...
multithreading environments, while sharing a same address
}
space.
int main()
Threads allow multiple functions to execute concurrently.
{
std::thread first (foo); // spawn new thread that calls foo()
An initialized thread object represents an active thread of std::thread second (bar,0); // spawn new thread that calls bar(0)
execution; Such a thread object is joinable, and has a unique
thread id. std::cout << "main, foo and bar now execute concurrently...\n";
// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
std::cout << "foo and bar completed.\n";
return 0;
} Output
main, foo and bar now execute concurrently...
foo and bar completed.
// function template
#include <iostream>
C++ Templates using namespace std;
Function templates are special functions that can
template <class T>
operate with generic types. T GetMax (T a, T b) {
This allows us to create a function template whose T result;
functionality can be adapted to more than one type or result = (a>b)? a : b;
class without repeating the entire code for each type.
In C++ this can be achieved using template parameters.
return (result);
A template parameter is a special kind of parameter that }
can be used to pass a type as argument: just like regular int main () {
function parameters can be used to pass values to a
function, template parameters allow to pass also types to int i=5, j=6, k;
a function. long l=10, m=5, n;
function template GetMax() twice. The first time with k=GetMax<int>(i,j);
arguments of type int and the second one with n=GetMax<long>(l,m);
arguments of type long.
cout << k << endl;
The compiler has instantiated and then called each time
the appropriate version of the function. cout << n << endl; Output
As you can see, the type T is used within the GetMax() return 0; 6
template function even to declare new objects of that } 10
type:
T result;
// function template II
#include <iostream>
int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax(i,j);
n=GetMax(l,m);
The use of function templates and template parameters
cout << k << endl;
is a great C++ resource to produce cleaner code, as it
prevents function duplication. cout << n << endl;
return 0;
} Output
6
10