0% found this document useful (0 votes)
4 views46 pages

Introduction To Computer Programming Notes

This document provides a comprehensive introduction to computer programming using the C language, covering basic concepts such as program structure, variables, data types, control structures, functions, and memory management. It also includes practical examples of file handling, dynamic memory allocation, and best practices for coding in C. The content is designed for beginners to understand the fundamentals of C programming and set up a development environment.

Uploaded by

Philip Muema
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views46 pages

Introduction To Computer Programming Notes

This document provides a comprehensive introduction to computer programming using the C language, covering basic concepts such as program structure, variables, data types, control structures, functions, and memory management. It also includes practical examples of file handling, dynamic memory allocation, and best practices for coding in C. The content is designed for beginners to understand the fundamentals of C programming and set up a development environment.

Uploaded by

Philip Muema
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

INTRODUCTION TO COMPUTER PROGRAMMING

INTRODUCTION TO PROGRAMMING AND C

BASIC C PROGRAMMING CONCEPTS

1. Structure of a C Program

A C program generally has the following structure:

#include <stdio.h> // Preprocessor directive

int main() {

// Code goes here

return 0;

#include <stdio.h>: This is a preprocessor directive that includes the standard input-output
library.
int main(): This is the main function, where execution starts.
{ : start of program execution.
return 0;: It indicates that the program ran successfully.

} : end of program execution.

VARIABLES IN C

In C programming, variables are used to store data values. Each variable has a specific data type
that defines the type of data it can hold, such as integers, floating-point numbers, or characters.

A variable declaration specifies the type of data the variable will hold and its name. And the syntax is:

data_type variable_name

for example : int age, float amount, char grade


Variable can be initialized at the time of declaration: ie int age = 23; float amount = 34000; char grade =
‘A’;

Type of variable in c

Int – for storing integers (whole number) eg 0, 36, 213, 10000000004, etc example: int age =23;

Float – for storing single precision floating point number ie 3.14. example: float pi = 3.14;

Double – for storing double precision floating-point numbers ie 3.145628277. example:

double = 3.145628277

Char – For storing individual characters ie a, A etc. example char grade = ‘A’;

Rules of naming variables in C

Variable names must start with a letter or underscore (A-Z or a-z or _ )

No white spaces allowed while naming variables instead use an underscore.

Variable names are case sensitive ie name Name and NAME are different variable names.

Variable names cannot be key words ie int, float, char, double, switch, case, return etc.

Scope of variables

The scope of a variable determines where it can be accessed in a program. We have two types:

1. Local variables – these are declared inside a function and can only be accessed from within
that function.

Example:

void My_Function(){

int localVar = 23;

printf(“my local variable is %d ”, localVar);

}
2. Global Variables - are declared outside all functions and can be accessed by any function in
the program.

Example:

int globalVar = 23;

void My_Function(){

printf(“my global variable is %d ”, globalVar);

Data Types in C

C supports various data types, which can be categorized into

1. Primitive Data Types:

 int: Used to store integers (whole numbers).


o Example: int num = 5;
o Size: Typically 4 bytes
 float: Used to store single-precision floating-point numbers (numbers with decimals).
o Example: float num = 5.5;
o Size: Typically 4 bytes
 double: Used to store double-precision floating-point numbers (more precision and larger
range than float).
o Example: double num = 5.123456789;
o Size: Typically 8 bytes
 char: Used to store a single character or small integer values.
o Example: char letter = 'A';
o Size: 1 byte
 void: Represents the absence of type. Commonly used for functions that don’t return a
value.
o Example: void myFunction().
2. Derived Data Types:

 Arrays: Collection of elements of the same type.


o Example: int arr[10];
 Pointers: Variables that store memory addresses.
o Example: int *ptr;

 Structures: Used to store different types of data together.

Example:

struct Person {
char name[50];
int age;
};

 Unions: Similar to structures, but all members share the same memory location.
o Example:

union Data {

int i;
float f;
};

Control Structures in C

Control structures allow the flow of a program to change, based on conditions or loops. They can
be grouped into:

1. Conditional Statements:

 if: Executes a block of code if a condition is true.


o Example:

if (x > 0) {
printf("x is positive");
}

 if-else: Executes one block of code if a condition is true, otherwise executes another.
o Example:

if (x > 0) {
printf("x is positive");
} else {
printf("x is not positive");
}

 else if: Checks multiple conditions in sequence.


o Example:

if (x > 0) {
printf("x is positive");
} else if (x == 0) {
printf("x is zero");
} else {
printf("x is negative");
}

 switch: Chooses between multiple cases based on the value of a variable.


o Example:

switch (choice) {
case 1:
printf("Choice is 1");
break;
case 2:
printf("Choice is 2");
break;
default:
printf("Invalid choice");
}

2. Loops:

 for loop: Repeats a block of code a specified number of times.


o Example:
for (int i = 0; i < 10; i++) {
printf("%d ", i);
}

 while loop: Repeats a block of code while a condition is true.


o Example:

int i = 0;
while (i < 10) {
printf("%d ", i);
i++;
}

 do-while loop: Executes a block of code at least once, then continues if the condition is
true.
o Example:

int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 10);

3. Control Flow Statements:

 break: Exits the loop or switch statement.


o Example (in a loop)

for (int i = 0; i < 10; i++) {


if (i == 5) {
break;
}
printf("%d ", i);
}

 continue: Skips the current iteration of the loop and proceeds to the next iteration.
o Example:

for (int i = 0; i < 10; i++) {


if (i == 5) {
continue;
}
printf("%d ", i);
}

 return: Exits from a function, optionally returning a value.


o Example:

c
Copy code
int sum(int a, int b) {
return a + b;
}

Introduction to C Language Syntax

C is a general-purpose, procedural programming language developed in the 1970s by Dennis


Ritchie. It provides low-level access to memory and is widely used for system programming,
embedded systems, and applications requiring performance and control. The basic syntax of C is
simple, but it allows a powerful range of features.

Basic Structure of a C Program

Every C program follows a certain structure:

#include <stdio.h> // Preprocessor directive, includes standard input/output library

// Main function - Entry point of every C program


int main() {
printf("Hello, World!"); // Prints "Hello, World!" to the console
return 0; // Ends the program with a return value of 0 (success)
}

Setting Up a C Development Environment

1. Install a Compiler: To compile C code, you need a C compiler. Popular compilers


include:
o GCC (GNU Compiler Collection) for Linux/Windows (through MinGW or
Cygwin).
o Clang for macOS.
o Visual Studio or Visual Studio Code (with the C/C++ extension) for Windows.

2. Choose an IDE or Text Editor:


o Code::Blocks, Dev-C++, CLion: Full IDEs for C development.
o Visual Studio Code, Sublime Text, or Atom: Lightweight text editors with
support for C programming through extensions.

3. Compile and Run a Program:


o On Linux or macOS, you can compile with gcc from the command line:

bash
gcc hello.c -o hello
./hello

o On Windows, you can use MinGW or Visual Studio's compiler to compile and
run programs.

C Fundamentals

1. Arrays

An array is a collection of elements of the same type stored in contiguous memory locations.

int arr[5] = {1, 2, 3, 4, 5}; // Array of integers

printf("%d", arr[0]); // Accessing the first element of the array

Arrays in C are indexed from 0. Multidimensional arrays, like 2D arrays, are also supported.

int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

2. Pointers and Memory Management


Pointers store the address of a variable. They are powerful tools for memory management and
array manipulation.

int x = 10;
int *ptr = &x; // Pointer to an integer that holds the address of x
printf("%d", *ptr); // Dereferencing a pointer to get the value stored at the address

 Pointer Arithmetic: You can move pointers to traverse through arrays.


 Dynamic Memory Management: Use malloc(), calloc(), realloc(), and free() to
dynamically allocate and deallocate memory.

int *arr = (int*) malloc(5 * sizeof(int)); // Dynamically allocate memory for 5 integers
if (arr == NULL) {
printf("Memory allocation failed");
}
free(arr); // Deallocates the memory

3. Functions and Parameter Passing

Functions are reusable blocks of code that perform specific tasks. There are two ways to pass
arguments to functions:

 Pass by Value: Copies the actual value to the function.


 Pass by Reference: Passes the address, allowing the function to modify the original
variable.

// Function to add two numbers (pass by value)


int add(int a, int b) {
return a + b;
}

// Function to swap two numbers (pass by reference using pointers)


void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}

You can return values from functions, and functions can also return pointers.

4. Basic Input/Output (I/O) Operations

In C, basic input/output is handled through the stdio.h library using:

 printf(): To output data.


 scanf(): To input data.

int num;

printf("Enter a number: ");


scanf("%d", &num); // Reads an integer from user input
printf("You entered: %d", num);

For character input/output, you can use getchar() and putchar():

char ch;
ch = getchar(); // Reads a single character from input
putchar(ch); // Outputs the character

Structures and Unions

Structures:

A structure (struct) is a user-defined data type that groups variables of different data types under
a single name. It allows you to create complex data types that represent real-world entities.
Example of a Structure:

#include <stdio.h>

struct Person {
char name[50];
int age;
float height;
};

int main() {
struct Person person1; // Declare a structure variable

// Assign values to structure members


strcpy([Link], "Alice");
[Link] = 30;
[Link] = 5.7;

// Access and print structure members


printf("Name: %s\n", [Link]);
printf("Age: %d\n", [Link]);
printf("Height: %.1f\n", [Link]);

return 0;
}

Unions:

A union is similar to a structure, but its members share the same memory location. At any given
time, only one member can hold a value. This is useful for memory optimization when you only
need one of the members at a time.
Example of a Union:
#include <stdio.h>

union Data {
int i;
float f;
char str[20];
};

int main() {
union Data data;

data.i = 10; // Store integer


printf("data.i: %d\n", data.i);

data.f = 220.5; // Now store float (overwrites data.i)


printf("data.f: %.1f\n", data.f);

strcpy([Link], "Hello"); // Now store string (overwrites data.f)


printf("[Link]: %s\n", [Link]);

return 0;
}

Key Differences:

 Structures: Each member has its own memory, and all members can store values
simultaneously.
 Unions: All members share the same memory space, and only one member can hold a
value at any given time.
2. Dynamic Memory Allocation and Deallocation

Dynamic memory allocation is the process of allocating memory during runtime using pointers.
The four key functions used for dynamic memory management in C are:

Memory Allocation Functions:

1. malloc(): Allocates a specified number of bytes and returns a pointer to the allocated
memory. The memory is not initialized.

int *ptr = (int*) malloc(sizeof(int) * 5); // Allocate memory for 5 integers

2. calloc(): Allocates memory for an array of elements, initializing all bytes to zero.

int *ptr = (int*) calloc(5, sizeof(int)); // Allocate and initialize memory for 5 integers

3. realloc(): Resizes the previously allocated memory block.

ptr = (int*) realloc(ptr, sizeof(int) * 10); // Resize the array to 10 integers

4. free(): Deallocates the previously allocated memory

free(ptr); // Free the memory allocated to ptr

Example of Dynamic Memory Allocation:


#include <stdio.h>
#include <stdlib.h>

int main() {
int *arr;
int n = 5;

// Dynamically allocate memory using malloc


arr = (int*) malloc(n * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Initialize and print array elements


for (int i = 0; i < n; i++) {
arr[i] = i + 1;
printf("%d ", arr[i]);
}

// Deallocate memory
free(arr);

return 0;
}

Best Practices:

 Always check if malloc() or calloc() returns NULL (memory allocation failure).


 Don’t forget to free() dynamically allocated memory to avoid memory leaks.

File Handling and I/O Operations

File handling in C allows you to read from and write to files on disk. C provides a set of
functions for performing input/output (I/O) operations on files, which are included in the stdio.h
library.
Opening and Closing Files:

 fopen(): Opens a file.


o Syntax: FILE *fopen(const char *filename, const char *mode);
o Modes:
 "r": Open a file for reading.
 "w": Create a file for writing (overwrites if the file exists).
 "a": Open a file for appending (data is added to the end).
 "rb", "wb", "ab": Same as above, but for binary mode.

FILE *fp = fopen("[Link]", "w"); // Open file for writing


if (fp == NULL) {
printf("Error opening file\n");
return 1;
}

 fclose(): Closes a file.

fclose(fp); // Close the file after use

Writing to a File:

 fprintf(): Writes formatted data to a file (similar to printf()).

fprintf(fp, "Name: %s, Age: %d\n", "Alice", 30); // Write to file

 fputs() and fputc(): Write strings and characters to a file.

fputs("This is a test.\n", fp); // Write a string to the file


fputc('A', fp); // Write a single character to the file

Reading from a File:


 fscanf(): Reads formatted data from a file (similar to scanf()).
 fscanf(fp, "%s %d", name, &age); // Read a name and age from the file
 fgets() and fgetc(): Read strings and characters from a file.

char buffer[100];
fgets(buffer, 100, fp); // Read up to 100 characters from a file

char ch = fgetc(fp); // Read a single character

Example of File Handling:


#include <stdio.h>

int main() {
FILE *fp;

// Open file for writing


fp = fopen("[Link]", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}

// Write data to file


fprintf(fp, "Hello, File Handling in C!\n");
fclose(fp); // Close the file

// Open file for reading


fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read data from file
char buffer[100];
fgets(buffer, 100, fp);
printf("Data from file: %s", buffer);

fclose(fp); // Close the file


return 0;
}

ADVANCED C PROGRAMMING TECHNIQUES

In this section, we'll dive into some more advanced C programming techniques, such as
preprocessor directives, bitwise manipulation, function pointers, and the use of popular C
libraries.

1. Preprocessor Directives and Macros

Preprocessor Directives:

Preprocessor directives are commands given to the C preprocessor, which runs before the actual
compilation of code begins. Common preprocessor directives include:

 #include: Includes the contents of a file.

#include <stdio.h> // Includes the standard I/O library

 #define: Defines macros, which are constants or functions replaced by the preprocessor.

#define PI 3.14159 // Define a constant

 #if, #ifdef, #ifndef, #else, #endif: Conditional compilation, allowing certain parts of code
to be compiled based on conditions.
#ifdef DEBUG
printf("Debug mode is on.\n");
#endif

Macros:

Macros are typically used to define constants and inline functions. They help in avoiding
repetitive code.

 Constant Macro:

#define MAX 100


int arr[MAX]; // Creates an array of size 100

 Function-like Macros: You can define a macro that behaves like a function, which
avoids the overhead of a function call.

#define SQUARE(x) ((x) * (x))


printf("Square of 5: %d\n", SQUARE(5)); // Output: 25

Caution: Use parentheses carefully in macros to avoid unexpected behavior.

2. Bitwise Operators and Bitwise Manipulation

Bitwise operators perform operations at the bit level, which is useful for tasks such as low-level
hardware programming, optimizing memory usage, and encryption.

Bitwise Operators:
 & (AND): Sets each bit to 1 if both bits are 1.

int a = 5 & 3; // 5 = 101, 3 = 011, result = 001 (1 in decimal)

 | (OR): Sets each bit to 1 if at least one of the bits is 1.

int a = 5 | 3; // 5 = 101, 3 = 011, result = 111 (7 in decimal)

 ^ (XOR): Sets each bit to 1 if only one of the bits is 1.

int a = 5 ^ 3; // 5 = 101, 3 = 011, result = 110 (6 in decimal)

 ~ (NOT): Inverts all the bits.

int a = ~5; // 5 = 00000000 00000000 00000000 00000101, result = 11111111 11111111


11111111 11111010

 << (Left Shift): Shifts bits to the left, adding 0s on the right.

int a = 5 << 1; // 5 = 00000101, result = 00001010 (10 in decimal)

 >> (Right Shift): Shifts bits to the right, adding 0s on the left for unsigned integers.

int a = 5 >> 1; // 5 = 00000101, result = 00000010 (2 in decimal)

Bitwise Manipulation Examples:

 Set a bit: Use OR to set a particular bit.

x = x | (1 << n); // Sets the nth bit of x

 Clear a bit: Use AND with the complement to clear a bit.

x = x & ~(1 << n); // Clears the nth bit of x

 Toggle a bit: Use XOR to flip a bit.


x = x ^ (1 << n); // Toggles the nth bit of x

 Check if a bit is set: Use AND to check a bit.

bool isSet = x & (1 << n); // Checks if the nth bit is set

3. Pointers to Functions and Function Pointers

A function pointer is a pointer that points to a function. You can use it to call a function or pass it
as an argument to another function. This is useful for implementing callbacks, function dispatch
tables, and more.

Declaring a Function Pointer:

// Function to be pointed to
int add(int a, int b) {
return a + b;
}

// Declaration of a function pointer


int (*funcPtr)(int, int);

// Assign the function to the pointer


funcPtr = &add;

// Calling the function through the pointer


int result = funcPtr(10, 20); // Output: 30

Passing Function Pointers to Functions:

Function pointers can be passed as arguments to other functions, enabling more flexible and
reusable code.
void execute(int (*func)(int, int), int x, int y) {
printf("Result: %d\n", func(x, y));
}

int subtract(int a, int b) {


return a - b;
}

int main() {
execute(add, 10, 5); // Output: 15
execute(subtract, 10, 5); // Output: 5
return 0;
}

4. Libraries in C

The C Standard Library provides a collection of built-in functions and header files that simplify
common programming tasks.

Standard Library Functions:

Some of the most commonly used functions include:

 printf() and scanf() for I/O.


 malloc(), calloc(), realloc(), free() for memory management.
 strcmp(), strlen(), strcpy() for string manipulation.

Math Library (math.h):

The math library contains functions for performing mathematical operations like square roots,
power, and trigonometric functions.
#include <math.h>

double result = sqrt(16.0); // Square root of 16


double power = pow(2.0, 3.0); // 2 raised to the power of 3
double sineValue = sin(45.0); // Sine of 45 degrees

Other useful functions include:

 fabs(): Returns the absolute value of a floating-point number.


 ceil(): Rounds a floating-point number up to the nearest integer.
 floor(): Rounds a floating-point number down to the nearest integer.

String Library (string.h):

The string library provides functions for handling and manipulating C-style strings.

#include <string.h>

char str1[20] = "Hello";


char str2[20];

// Copy a string
strcpy(str2, str1);

// Concatenate strings
strcat(str1, " World!");

// Compare two strings


int result = strcmp(str1, str2); // Returns 0 if equal

// Get the length of a string


int len = strlen(str1);
Other useful string functions include:

 strchr(): Finds the first occurrence of a character in a string.


 strstr(): Finds the first occurrence of a substring in a string.
 strtok(): Splits a string into tokens based on a delimiter.

Other Common Libraries:

 time.h: Functions for working with time (e.g., time(), clock()).


 stdlib.h: General utilities like random number generation (rand()), dynamic memory
management, and process control (exit()).
 ctype.h: Functions for character classification (e.g., isdigit(), isalpha()).

1. Basic C++ Programming Concepts

Variables and Data Types:

Variables are containers that store data, and C++ supports various data types to store different
kinds of information. A data type defines the type of data a variable can hold, such as integers,
floating-point numbers, characters, etc.

Common data types in C++:

 int: Used to store integer values.


 float: Used to store floating-point numbers (decimal numbers).
 double: Used for more precise floating-point numbers.
 char: Used to store single characters.
 bool: Used to store Boolean values (true or false).
 string: Used to store sequences of characters (requires including <string>).

Example:

#include <iostream>
#include <string>
int main() {
int age = 25;
float height = 5.9;
char grade = 'A';
bool isStudent = true;
std::string name = "Alice";

std::cout << "Name: " << name << std::endl;


std::cout << "Age: " << age << std::endl;
std::cout << "Height: " << height << std::endl;
std::cout << "Grade: " << grade << std::endl;
std::cout << "Is student: " << (isStudent ? "Yes" : "No") << std::endl;

return 0;
}

Control Structures:

Control structures direct the flow of a program. In C++, control structures include:

 If-else statement:

int x = 10;

if (x > 5) {
std::cout << "x is greater than 5" << std::endl;
} else {
std::cout << "x is less than or equal to 5" << std::endl;
}

 Loops:

o For loop:

for (int i = 0; i < 5; i++) {


std::cout << "i: " << i << std::endl;
}

o While loop:

int j = 0;
while (j < 5) {
std::cout << "j: " << j << std::endl;
j++;
}

o Do-while loop:

int k = 0;
do {
std::cout << "k: " << k << std::endl;
k++;
} while (k < 5);

2. Introduction to C++ Language Syntax

C++ has a syntax similar to C but with added features for object-oriented programming (OOP)
and other advanced concepts.
Basic Syntax:

 Every C++ program must have a main() function, which is the entry point of the program.
 Code is written inside functions and blocks are defined by {} brackets.
 Statements must end with a semicolon (;).
 Input/output operations are done using cin and cout.

Example of a simple C++ program:

#include <iostream> // Include the input-output stream library

int main() {
std::cout << "Hello, World!" << std::endl; // Output a string
return 0; // Return 0 to indicate successful execution
}

3. Setting Up a Development Environment

To write and run C++ programs, you'll need the following:

1. Text Editor or IDE:

You can use any text editor like VS Code, Sublime Text, or a full-fledged Integrated
Development Environment (IDE) like Code::Blocks, CLion, or Visual Studio.

2. Compiler:

You need a compiler that converts your C++ code into machine code. Popular C++ compilers
include:

 g++ (part of the GNU Compiler Collection, or GCC) on Linux or macOS.


 MinGW on Windows.
 Microsoft Visual C++ (MSVC) with Visual Studio.
3. Running Your First Program:

After installing an IDE or text editor and compiler, write a simple "Hello, World!" program to
ensure everything is set up correctly.

To compile and run the program (assuming you're using g++):

g++ [Link] -o myProgram // Compile the program


./myProgram // Run the compiled program

4. C++ Fundamentals

Arrays:

An array is a collection of elements of the same type stored in contiguous memory locations.
Arrays are zero-indexed in C++.

Example:

#include <iostream>
int main() {
int arr[5] = {1, 2, 3, 4, 5}; // Declare and initialize an array

// Access elements using a loop


for (int i = 0; i < 5; i++) {
std::cout << "Element at index " << i << ": " << arr[i] << std::endl;
}

return 0;
}
Pointers:

Pointers store the memory address of another variable. They are a powerful feature in C++ for
dynamic memory allocation and managing memory more efficiently.

Example:

#include <iostream>

int main() {
int x = 10;
int *ptr = &x; // Pointer to x

std::cout << "Value of x: " << x << std::endl;


std::cout << "Address of x: " << ptr << std::endl;
std::cout << "Value pointed to by ptr: " << *ptr << std::endl; // Dereference the pointer

return 0;
}

Memory Management:

In C++, dynamic memory can be allocated and deallocated using new and delete.

 Dynamic Memory Allocation:

int *arr = new int[5]; // Dynamically allocate an array of 5 integers

 Memory Deallocation:

delete[] arr; // Free the dynamically allocated memory


Functions and Parameter Passing:

Functions in C++ allow you to encapsulate reusable code. Functions can pass parameters by
value, by reference, or by pointer.

 Passing by Value: The function gets a copy of the value.

void myFunction(int x) {
x = 10; // This change won't affect the original variable
}

 Passing by Reference: The function can modify the original variable.

void myFunction(int &x) {


x = 10; // This change affects the original variable
}

 Passing by Pointer: The function receives the address of the variable.

void myFunction(int *x) {


*x = 10; // Modifies the value at the memory address
}

Basic Input/Output (I/O) Operations:

C++ uses cin for input and cout for output, both of which are part of the iostream library.

 Output using cout:

std::cout << "Enter your age: ";


 Input using cin:

int age;
std::cin >> age;
std::cout << "You entered: " << age << std::endl;

Example:

#include <iostream>

int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You are " << age << " years old!" << std::endl;
return 0;
}

1. Introduction to Object-Oriented Programming (OOP) Concepts

OOP revolves around the following key concepts:

 Objects: Real-world entities that have attributes (data) and behaviors (methods). Objects
are instances of classes.
 Classes: Templates or blueprints used to create objects. They define the attributes and
behaviors that objects of that class will have.

OOP Principles:

 Encapsulation: Bundling data (attributes) and methods (functions) that operate on the
data into a single unit (class), and restricting access to some of the object's components.
 Inheritance: Creating new classes (derived classes) based on existing ones (base
classes), allowing reuse of code and extension of functionalities.
 Polymorphism: The ability of different classes to be treated as instances of the same
class through interfaces or inheritance, typically through method overloading and
overriding.

2. Classes, Objects, and Member Functions

Classes:

A class is a user-defined type that describes what attributes (data members) and methods
(member functions) its objects will have. The syntax for creating a class involves specifying the
class name and the body of the class.

#include <iostream>

class Person {
public:
// Data members (attributes)
std::string name;
int age;

// Member function (behavior)


void introduce() {
std::cout << "Hello, my name is " << name << " and I am " << age << " years old." <<
std::endl;
}
};

int main() {
// Create an object (instance) of class Person
Person person1;

// Access data members and member functions


[Link] = "John";
[Link] = 30;
[Link](); // Calls the member function introduce()

return 0;
}
Objects:

Objects are instances of a class. You can create objects using the class name and then use the dot
operator (.) to access the class members (data and functions).

Person person1; // Create an object of the class Person


Member Functions:

Member functions are functions defined inside a class that operate on objects of that class. They
have access to the data members of the class.

3. Encapsulation

Encapsulation refers to the bundling of data and functions that manipulate the data within a
single unit or class. It also involves controlling the access to the data by making it private and
exposing it through public methods.

In C++, access specifiers control the accessibility of class members:

 public: Accessible from outside the class.


 private: Accessible only from within the class.
 protected: Accessible within the class and derived classes.
Example:

#include <iostream>

class Car {
private:
int speed; // Private member

public:
// Public setter method to set the value of speed
void setSpeed(int s) {
if (s > 0) {
speed = s;
}
}

// Public getter method to retrieve the value of speed


int getSpeed() {
return speed;
}
};

int main() {
Car car1;
[Link](120); // Access through public methods
std::cout << "Car speed: " << [Link]() << std::endl;

return 0;
}

In this example, speed is encapsulated as a private member, and it can only be accessed or
modified through the public methods setSpeed() and getSpeed().
4. Inheritance

Inheritance allows one class (child or derived class) to inherit properties and behaviors from
another class (parent or base class). It enables code reuse and the creation of a class hierarchy.

Example:

#include <iostream>

// Base class (parent)


class Animal {
public:
void eat() {
std::cout << "This animal is eating." << std::endl;
}
};

// Derived class (child) inheriting from Animal


class Dog : public Animal {
public:
void bark() {
std::cout << "The dog is barking." << std::endl;
}
};

int main() {
Dog dog1;
[Link](); // Inherited from the Animal class
[Link](); // Defined in the Dog class
return 0;
}

Types of Inheritance:

 Single Inheritance: A class inherits from one base class.


 Multiple Inheritance: A class inherits from more than one base class.
 Multilevel Inheritance: A class inherits from a derived class, which in turn inherits from
another class.
 Hierarchical Inheritance: Multiple derived classes inherit from a single base class.

5. Polymorphism

Polymorphism means "many forms" and allows objects of different classes to be treated as
objects of a common base class. It is achieved through:

 Function Overloading: Defining multiple functions with the same name but different
parameters.
 Function Overriding: Redefining a function in a derived class that was already defined
in the base class.

Function Overloading:

#include <iostream>

class Calculator {
public:
// Overloading the add function to handle different parameter types
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
};

int main() {
Calculator calc;
std::cout << "Sum of integers: " << [Link](3, 5) << std::endl;
std::cout << "Sum of doubles: " << [Link](2.5, 4.1) << std::endl;

return 0;
}

Function Overriding and Virtual Functions:

Overriding allows a derived class to provide its own implementation of a function that is defined
in its base class. To achieve runtime polymorphism, C++ uses virtual functions.

Example:

#include <iostream>
// Base class
class Animal {
public:
virtual void sound() {
std::cout << "Some animal sound." << std::endl;
}
};

// Derived class
class Dog : public Animal {
public:
void sound() override { // Function overriding
std::cout << "The dog barks." << std::endl;
}
};

int main() {
Animal* animalPtr;
Dog dog1;

animalPtr = &dog1; // Base class pointer pointing to derived class object


animalPtr->sound(); // Calls the overridden version in Dog

return 0;
}

In this example, the base class Animal has a virtual function sound(), and the derived class Dog
overrides this function. When using a base class pointer to refer to a derived class object, the
overridden method in the derived class is called, achieving runtime polymorphism.

6. Abstraction

Hiding the complex details of a system from the user and only exposing the essential features.

How Abstraction is Achieved in C++:

Abstraction can be implemented in C++ using abstract classes and interfaces:

1. Abstract Classes: An abstract class is a class that cannot be instantiated on its own and
typically contains at least one pure virtual function. This allows you to define a common
interface for derived classes while enforcing that certain methods must be implemented.

class Shape {
public:
// Pure virtual function
virtual void draw() = 0; // No implementation in the base class
};

class Circle : public Shape {


public:
void draw() override { // Implementing the pure virtual function
std::cout << "Drawing a circle." << std::endl;
}
};

class Rectangle : public Shape {


public:
void draw() override { // Implementing the pure virtual function
std::cout << "Drawing a rectangle." << std::endl;
}
};

In this example, Shape is an abstract class with a pure virtual function draw(). The
derived classes Circle and Rectangle provide specific implementations for the draw()
function.

2. Interfaces: In C++, an interface is essentially a class with only pure virtual functions. It
defines a contract that derived classes must fulfill.

class Drawable {
public:
virtual void draw() = 0; // Interface method
};
Any class that implements this interface must provide an implementation for the draw()
method.

Advantages of Abstraction:

 Reduced Complexity: Abstraction helps manage complexity by allowing programmers


to work at a higher level of understanding.
 Code Reusability: Abstract classes and interfaces promote code reuse, as multiple
classes can implement the same interface or inherit from the same abstract class.
 Improved Maintainability: By separating the interface from implementation, changes to
the internal workings of a class do not affect the code that uses it, making it easier to
maintain and update.
 Encourages Design Patterns: Abstraction enables the use of design patterns, facilitating
more organized and flexible code structures.

Intermediate C++ Concepts

Intermediate C++ programming encompasses several advanced topics that enhance code
reusability, error management, and data manipulation. Here’s a detailed overview of templates
and generic programming, exceptions and error handling, and the Standard Template
Library (STL).

1. Templates and Generic Programming

Templates are a powerful feature in C++ that allows you to write generic and reusable code.
With templates, you can create functions and classes that operate on any data type.

Function Templates

Function templates enable you to define a function without specifying the exact type of the
parameters. The type is determined when the function is called.

Example:

#include <iostream>

// Function template
template <typename T>
T add(T a, T b) {
return a + b;
}

int main() {
std::cout << "Integer sum: " << add(3, 4) << std::endl; // Calls
add<int>
std::cout << "Double sum: " << add(2.5, 3.5) << std::endl; // Calls
add<double>

return 0;
}

In this example, the add function is defined as a template that can take any type T. When called
with specific types, the compiler generates the appropriate function.

Class Templates

Class templates allow you to create a class that can operate on any data type.

Example:

#include <iostream>

// Class template
template <typename T>
class Pair {
private:
T first, second;

public:
Pair(T a, T b) : first(a), second(b) {}

T getFirst() const { return first; }


T getSecond() const { return second; }
};

int main() {
Pair<int> intPair(1, 2);
Pair<double> doublePair(1.5, 2.5);

std::cout << "First integer: " << [Link]() << std::endl; // 1


std::cout << "First double: " << [Link]() << std::endl; //
1.5

return 0;
}

Here, Pair is a class template that can hold two values of the same type T.

2. Exceptions and Error Handling


C++ provides a mechanism for handling errors through exceptions. Exceptions allow you to
separate error-handling code from regular code, making it cleaner and more robust.

Throwing Exceptions

You can throw exceptions using the throw keyword.

Example:

#include <iostream>
#include <stdexcept> // For std::runtime_error

void divide(int a, int b) {


if (b == 0) {
throw std::runtime_error("Division by zero error!"); // Throwing an
exception
}
std::cout << "Result: " << a / b << std::endl;
}

int main() {
try {
divide(10, 0); // This will throw an exception
} catch (const std::runtime_error& e) {
std::cerr << "Error: " << [Link]() << std::endl; // Catching and
handling the exception
}

return 0;
}

In this example, if b is zero, an exception is thrown, which is then caught and handled in the
catch block.

Catch Blocks

You can have multiple catch blocks to handle different types of exceptions:

try {
// Code that might throw exceptions
} catch (const std::invalid_argument& e) {
// Handle invalid argument exception
} catch (const std::runtime_error& e) {
// Handle runtime error exception
}

You can also catch exceptions by reference to avoid unnecessary copying.


3. Standard Template Library (STL)

The Standard Template Library (STL) is a powerful library in C++ that provides a collection
of template classes and functions, including various containers and algorithms.

STL Containers

STL containers are data structures that store collections of objects. Common containers include:

 Vector: A dynamic array that can grow and shrink in size.

#include <vector>
std::vector<int> numbers = {1, 2, 3, 4, 5};

 List: A doubly linked list that allows efficient insertion and deletion.

#include <list>
std::list<int> myList = {1, 2, 3};

 Map: A collection of key-value pairs, allowing efficient retrieval by key.

#include <map>
std::map<std::string, int> ageMap = {{"Alice", 30}, {"Bob", 25}};

STL Algorithms

The STL provides a variety of algorithms that operate on containers, including sorting,
searching, and manipulating data.

Example:

#include <iostream>
#include <vector>
#include <algorithm> // For std::sort

int main() {
std::vector<int> numbers = {4, 2, 5, 1, 3};

// Sort the vector


std::sort([Link](), [Link]());

// Display sorted numbers


for (int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;

return 0;
}
1. Advanced Language Features

Operator Overloading

Operator overloading allows you to define custom behavior for operators (like +, -, *, etc.) for
user-defined types (classes). This enables intuitive syntax for operations on objects.

Example:

#include <iostream>

class Complex {
private:
double real, imag;

public:
Complex(double r, double i) : real(r), imag(i) {}

// Overloading the + operator


Complex operator+(const Complex& other) {
return Complex(real + [Link], imag + [Link]);
}

void display() const {


std::cout << real << " + " << imag << "i" << std::endl;
}
};

int main() {
Complex c1(3.0, 4.0);
Complex c2(1.0, 2.0);
Complex c3 = c1 + c2; // Using overloaded + operator
[Link](); // Output: 4.0 + 6.0i

return 0;
}

In this example, the + operator is overloaded to add two Complex numbers.

Type Conversions

Type conversions in C++ can be implicit or explicit. Implicit conversions happen automatically,
while explicit conversions require a cast.

 Implicit Conversion: When a smaller data type is converted to a larger one.

int a = 5;
double b = a; // Implicit conversion from int to double

 Explicit Conversion (Casting): Use static_cast, dynamic_cast, const_cast, or


reinterpret_cast for explicit type conversions.

double d = 9.7;
int i = static_cast<int>(d); // Explicit conversion from double to int

2. Multithreading and Concurrency

Multithreading allows a program to execute multiple threads simultaneously, improving


performance, especially on multi-core processors.

Creating Threads

In C++, you can create threads using the <thread> library.

Example:

#include <iostream>

#include <thread>

void printHello() {
std::cout << "Hello from thread!" << std::endl;
}

int main() {
std::thread t(printHello); // Create a thread
[Link](); // Wait for the thread to finish
return 0;
}

In this example, a new thread is created to execute the printHello function.

Mutexes and Locks

To manage access to shared resources, C++ provides std::mutex for synchronization.

Example:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx; // Mutex for synchronization


int sharedCounter = 0;

void increment() {
for (int i = 0; i < 1000; ++i) {
std::lock_guard<std::mutex> lock(mtx); // Lock the mutex
++sharedCounter; // Increment shared counter
}
}

int main() {
std::thread t1(increment);
std::thread t2(increment);

[Link]();
[Link]();

std::cout << "Final counter: " << sharedCounter << std::endl; // Output: 2000
return 0;
}

Here, std::lock_guard automatically locks the mutex when it is created and releases it when it
goes out of scope, ensuring safe access to the shared resource.

3. C++11, C++14, and C++17 Features

The C++ standards introduced several important features that enhance the language's
capabilities:

C++11 Features

 Auto Keyword: Automatically deduces the type of a variable.


auto x = 5; // x is int

 Range-based For Loops: Simplifies iterating through containers.

std::vector<int> vec = {1, 2, 3};


for (auto& v : vec) {
std::cout << v << " ";
}

 Lambda Expressions: Allow you to define anonymous functions.

auto add = [](int a, int b) { return a + b; };


std::cout << add(2, 3); // Output: 5

C++14 Features

 Generic Lambdas: Lambda expressions can now use auto in their parameter lists.

auto lambda = [](auto a, auto b) { return a + b; };


std::cout << lambda(2, 3) << std::endl; // Output: 5

 Return Type Deduction: Functions can deduce their return type automatically.

auto func() { return 42; } // Return type deduced as int

C++17 Features

 Structured Bindings: Simplifies unpacking tuples and pair-like structures.

std::tuple<int, double> myTuple(1, 2.5);


auto [a, b] = myTuple; // a is int, b is double

 Optional and Variant: Provides types that represent optional values or values that can
take on several types.

std::optional<int> optInt = std::nullopt; // Optional integer

 Inline Variables: Allows the definition of variables that can be initialized in header files
without violating the one-definition rule.

inline int myVar = 10; // Can be defined in header files

You might also like