You are on page 1of 72

C++ BASICS

FOR EXIT EXAM


Presentation title

2 C++

Introduction

C++
Presentation title

3 INTRODUCTION

• C and C++ are both programming languages that share many similarities but also have
some key differences.
Here are some of the basic differences between C and C++:
1. Object-Oriented Programming (OOP) Support: C++ is an extension of C with added
support for object-oriented programming.
• C++ allows you to define classes and objects, encapsulate data and behavior within
objects, and use concepts such as inheritance, polymorphism, and encapsulation.
• C is a procedural programming language and does not have built-in support for OOP
concepts.
Presentation title

4 CONT..

2. Standard Template Library (STL): C++ includes the Standard


Template Library (STL), which provides a collection of reusable
data structures (such as vectors, lists, and maps) and algorithms
(such as sorting and searching) that can be used with minimal
effort.
• C does not have an equivalent standard library for data
structures and algorithms, although libraries such as the C
Standard Library provide basic functionality.
Presentation title

5 CONT…

3.Syntax and Features: C++ introduces additional syntax and features beyond
what is available in C.
• For example, C++ supports function overloading, allowing multiple functions
with the same name but different parameter lists.
• C++ also introduces references, exception handling, templates, and
namespaces, which are not present in C.
4.Compatibility: C++ is designed to be mostly backward-compatible with C.
• C code can generally be compiled and used in C++ programs without major
modifications.
• However, there are some differences in syntax and behavior that may require
slight adjustments or rewriting of code when migrating from C to C++.
Presentation title

6 CONT…

5.Memory Management: Both C and C++ allow manual memory


management through functions like malloc and free.
• However, C++ also provides additional memory management
options through features like constructors, destructors, and
the new and delete operators.
• C++ also introduces the concept of RAII (Resource Acquisition
Is Initialization), which allows for automatic resource
management using constructors and destructors of objects.
Presentation title

7
CONSTRUCTOR AND DESTRUCTOR
• In C++, a constructor is a special member function of a class that is automatically called when
an object of that class is created.
• The constructor is responsible for initializing the object's data members and preparing it for use.
• Constructors have the same name as the class and can be overloaded to provide different
initialization behaviors.
• In C++, a destructor is a special member function of a class that is automatically called when an
object of that class goes out of scope or is explicitly destroyed.
• The destructor is responsible for releasing any resources held by the object and performing
necessary cleanup operations.
Presentation title

8 C++ LIBRARIES

C++ provides a rich set of libraries, known as the Standard Library, which offers a wide range
of functionality for various purposes.
Some of the commonly used libraries in C++ include:
1. <iostream>: Provides input/output functionality, including cin and cout for console
input/output.
2. <vector>: Implements a dynamic array-like container called std::vector, which provides
dynamic size, efficient element access, and automatic memory management.
3. <string>: Provides various string manipulation functions and the std::string class to handle
strings efficiently.
4. <algorithm>: Offers a collection of algorithms such as sorting, searching, and manipulating
elements in containers.
Presentation title

9 CONT…

5. <sstream>: A stringstream associates a string object with a stream


allowing you to read from the string as if it were a stream (like cin).
To use stringstream, we need to include sstream header file.
The stringstream class is extremely useful in parsing input.
6. <cmath>: Contains mathematical functions like trigonometric,
logarithmic, and exponential functions.
7. <fstream>: Provides classes and functions for file input/output
operations, allowing reading from and writing to files.
Presentation title

10 CONT…

8. <chrono>: Offers facilities to measure time and perform time-related


operations, including high-resolution clocks and timers.
9. <thread> and <mutex>: Provide classes and functions for multithreading
and synchronization, allowing you to create and manage threads and protect
shared resources.
10. <random>: Provides facilities for generating pseudo-random numbers,
including various random number distributions.
11. <regex>: Implements regular expressions for pattern matching and
search operations on strings.
Presentation title

• Writing and compiling a simple C++ program


• Here's an example of a simple C++ program that you can write and compile:
• Simple program print hello, world
• #include <iostream>
• int main() {
• std:: cout << "Hello, World!" <<std::endl;
• return 0;
•}
Presentation title

BREAK DOWN THE PROGRAM:


• The line #include <iostream> includes the iostream header, which provides input and
output functionality.
• The main() function is the entry point of the program. It's where the program starts
executing.
• std::cout is used to output data to the console. In this case, it outputs the string "Hello,
World!".
• std::endl is used to insert a newline character and flush the output stream.
• The return 0; statement indicates that the program has finished executing and returns 0
to the operating system, indicating successful execution.
Presentation title

13 STRUCTURE OF C++ PROGRAM

 Include files
 Class declaration
 Class functions, definition
 Main function program
# include<iostream.h> void display()
class person P.T.O 16 {
14 { cout<<”\n
char name[30];
name:”<<name;
int age;
public: cout<<”\n
void getdata(void); age:”<<age;
void display(void); }
}; int main( )
void person :: getdata {
( void )
person p;
{
cout<<”enter name”; p.getdata();
cin>>name; p.display();
cout<<”enter age”; return(0);
cin>>age; }
}
TO COMPILE AND RUN THE PROGRAM, FOLLOW THESE STEPS:
1. Save the program code in a file with a .cpp extension, for example, hello.cpp.
2. Open a command prompt or terminal and navigate to the directory where you saved the file.
3. Compile the program using a c++ compiler.
for example, if you have the gnu compiler collection (gcc) installed, you can use the command:
g++ hello.cpp -o hello
This command compiles the hello.cpp file and generates an executable named hello.
4. Run the program by executing the generated executable:
./hello
The output "hello, world!" should be displayed on the console.

Using Linux in gcc compiler


BASIC SYNTAX

• Variables:
• A variable is a named memory location that can hold a value of a specific data type.
• Example:
• int age = 25;
• float pi = 3.14;
• char grade = 'A';
• bool isPassed = true;

Presentation title
17
Declarations:

A declaration introduces a new variable by specifying its data type and name.
It can also include an optional initializer, which assigns an initial value to the
variable.
Multiple variables of the same data type can be declared in a single statement,
separated by commas.
Example:
int x = 10; // Declaration with initialization
int y, z; // Declaration of multiple variables
double pi = 3.14, radius; // Declaration with initialization and without initialization
char ch = 'Z';
Presentation title

19

Boolean
Presentation title

20
REFERENCE VARIABLES:
C++interfaces a new kind of variable known as the reference variable. A references
variable provides an alias.(alternative name) for a previously defined variable. For
example ,if we make the variable sum a reference to the variable total, then sum and
total can be used interchangeably to represent the variable.
A reference variable is created as follows:
Synatx: Datatype & reference –name=variable name;
Example:
float total=1500;
float &sum=total;
Presentation title

21
THE BASIC FUNDAMENTAL DATA TYPES IN C++, AS WELL AS THE RANGE OF
VALUES THAT CAN BE REPRESENTED WITH EACH ONE:
Presentation title

CONT..
C++ provides various built-in data types that determine the range and type of values
a variable can hold.
Some commonly used data types include:
Integers: int, short, long, long long
Floating-point numbers: float, double
Characters: char
Boolean: bool (can hold true or false)
int age = 25; // Integer variable
double salary = 50000.75; // Double variable
char grade = 'A'; // Character variable
Input and output streams:
In C++, input and output operations are performed using input and output streams.
The <iostream> library provides classes and functions for handling input and
output.
Here's an overview of input and output streams in C++:
Output Stream (std::cout):
std::cout is the standard output stream, used to display output to the console.
You can use the << operator to insert data into the output stream.
Example:
#include <iostream>
Using namespace std;
int main() {
int age = 25;
cout << "My age is: " << age << endl;
return 0;
String Stream (std::stringstream):
std::stringstream allows input and output operations on strings.
It provides a way to treat strings as input or output streams.
This can be useful when you want to convert between different data types or manipulate strings.
Example:
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string name;
int age;
std::stringstream ss;
ss << "John 25";
ss >> name >> age;
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
return 0;
}
Input Stream (std::cin):
std::cin is the standard input stream, used to read input from the user.
It is associated with the console or the standard input device.
You can use the >> operator to extract data from the input stream and store it in
variables.
Example:
#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You entered: " << age << std::endl;
return 0;
}
Presentation title

27
The cin.get(ch) function is used to read a single character from the
input stream (cin).
It reads the next available character from the input, including spaces,
tabs, and newline characters.
The getline() function is used to read a line of text from the input
stream.
It allows you to read a sequence of characters until a newline
character ('\n') is encountered or the specified delimiter is found.
The extracted characters are stored in a string object.
Here's an example of how to use getline():
Presentation title

28

In C++, the std::cout.put(ch) function is used to write a


single character to the output stream (std::cout). It writes the
specified character to the console or output device.
Presentation title

29 String Concatenation in c++


In C++, you can concatenate strings using the + operator or the +=
operator. Both operators allow you to combine multiple strings into a
single string.
Here's an example using the + operator:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = " World!";
std::string result = str1 + str2;
std::cout << result << std::endl;
return 0;
}
Your friend wrote a program called an adder.
The adder is supposed to take two numbers inputted by a user and then find the sum of
those numbers, but it’s behaving oddly. entering 1 and 1.
You expect the output to be 2 but you get 11 instead.
Similarly, if you enter 3 and 4, you expect the output to be 7 but you get 34.
Remember, string concatenation also uses the + operator.

1. int sum = stoi(num1) + stoi(num2);


cout << ( num1 + " + " + num2 + " = " + to_string(sum) ) << endl;
2. int sum = stoi(num1) + stoi(num2);
cout << ( num1 + " + " + num2 + " = " ) << sum << endl;
• Display the two string as one
string greeting1 = "Hello";
string greeting2 = "world";

cout << greeting1 << " " << greeting2 << endl;

string a = "Hello ";


string b = "world";

cout << (a + b) << endl;


Presentation title

32
In C++, the std::stod() function is used to convert a string to a double-
precision floating-point number. It stands for "string to double".
Here's an example of how to use std::stod():
#include <iostream>
#include <string>
int main() {
std::string str = "3.14159";
double number = std::stod(str);
std::cout << "The converted double is: " << number << std::endl;
return 0;
}
Presentation title

33
In C++, the std::stoi() function is used to convert a string to an
integer. It stands for "string to integer".
Here's an example of how to use std::stoi():
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
int number = std::stoi(str);
std::cout << "The converted integer is: " << number << std::endl;
return 0;
}
Presentation title

34 int a = 5;
string b = "3";
string c = "3.14";
bool d = true;
cout << a + stoi(b) << endl;

What happens if you:


Replace stoi(b) with stoi(c)?
Replace stoi(b) with stod(c)?
Replace stoi(b) with to_string(d)?
Replace a + stoi(b) with b + to_string(d)?
• #include <iostream>
• int main() {
• // Declare variables
• int num1, num2, sum;
• // Get input from the user
• std::cout << "Enter the first number: ";
• std::cin >> num1;
• std::cout << "Enter the second number: ";
• std::cin >> num2;
• // Perform the addition
• sum = num1 + num2;
• // Display the result
• std::cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << std::endl;
• return 0;
• }
Presentation title

36
Presentation title

37
Presentation title

38 Order of Operations

Evaluate all arithmetic operators according to PEMDAS


Evaluate all boolean operators according to this order -
Parentheses (()), Not (!), And (&&), then Or (||)
==Note== that arithmetic operators are performed before Boolean operators.
Presentation title

39 Modulo and PEMDAS


Use the text editor on the left to enter the following code:
cout << (5 * 8 / 3 + (18 - 8) % 2 - 25) << endl;
TRY IT
Below are the steps that C++ takes when evaluating the code
above.
5 * 8 / 3 + (18 - 8) % 2 - 25
5 * 8 / 3 + 10 % 2 - 25
40 / 3 + 10 % 2 - 25
13 + 10 % 2 - 25
13 + 0 - 25
13 - 25
-12
Presentation title

cout << boolalpha << ((5 > 7) && (false || 1 < 9) || 4 != 5 && ! (2 >= 3)) << endl;
40 Below are the steps that C++ takes when evaluating the code above.
Evaluate all arithmetic operators according to PEMDAS
(5 > 7) && (false || 1 < 9) || 4 != 5 && ! (2 >= 3)
false && (false || 1 < 9) || 4 != 5 && ! (2 >= 3)
false && (false || true) || 4 != 5 && ! (2 >= 3)
false && (false || true) || true && ! (2 >= 3)
false && (false || true) || true && ! false
Evaluate all boolean operators according to this order - Parentheses (()), Not (!),
And (&&), then Or (||)
false && true || true && ! false
false && true || true && true
false || true && true
false || true
true
Presentation title

41 COMMA OPERATOR ( , )

• The comma operator (,) is used to separate two or more expressions that are
included where only one expression
• is expected. When the set of expressions has to be evaluated for a value, only
the rightmost expression is
• considered.
• For example, the following code:
• a = (b=3, b+2);
Presentation title

42 what output of the following code


#include <iostream>
Using namespace std;
int main() {
int x = 5;
int y = 10;
int z = (++x, ++y, x + y);
cout << "z = " << z << endl;
return 0;
}
The comma operator evaluates each expression separated by commas from left to right and returns the
result of the last expression.
Operators and Expressions:

C++ supports various operators like arithmetic, assignment, relational, logical, etc.
Expressions are formed using operators and operands.
Example:
int a = 5, b = 3;
int sum = a + b;
bool isGreater = (a > b);

using namespace std


 directive to simplify the usage of standard library elements like cout and cin
Presentation title

44 ASSIGNMENT OPERATOR

• A property that C++ has over other programming languages is that the assignment operation can
be used as the rvalue (or part of an rvalue) for another assignment operation.
• For example: a = 2 + (b = 5); is equivalent to: b = 5;
a = 2 + b;
• That means: first assign 5 to variable b and then assign to a the value 2 plus the result of the
previous assignment of b (i.e. 5), leaving a with a final value of 7.
• The following expression is also valid in C++:
• a = b = c = 5;
• It assigns 5 to the all the three variables: a, b and c.
45
Control Statements:
Control statements allow you to control the flow of program execution.
Common control statements include if-else, switch-case, and loops (for, while, do-while).
Example:
int num;
cout << "Enter a number: ";
cin >> num;
if (num > 0) {
cout << "The number is positive." << endl;
} else if (num < 0) {
cout << "The number is negative." << endl;
} else {
cout << "The number is zero." << endl;
}
In C++, functions play a crucial role in organizing and structuring code.
They allow you to encapsulate a block of code into a reusable unit, which
can be called from different parts of the program.
Functions also have their own scope, which defines the visibility and
lifetime of variables and other entities declared inside the function.
Here are some key aspects of functions and scope in C++:
1. Function Declaration and Definition:
A function is typically declared before it is used. The declaration includes
the function name, return type, and parameter list (if any).
The function definition provides the implementation of the function,
including the function body enclosed in curly braces.
Example:
// Function declaration
int add(int a, int b);
// Function definition
int add(int a, int b) {
return a + b;
}
2. Function Call:
To call a function, you simply use its name followed by parentheses that may
contain arguments (if the function expects any).
Example:
int result = add(5, 3); // Calling the add() function with arguments 5 and 3
Presentation title

3. Function Parameters:
Functions can have parameters, which are variables that receive values from
the calling code.
Parameters are declared in the function declaration and definition, and they
allow data to be passed into the function.
Example:
int multiply(int a, int b) {
return a * b;
}
Presentation title

Arrays:
An array is a collection of elements of the same data type, stored in contiguous
memory locations.
Elements in an array can be accessed using their indices.
The index of the first element is 0, and the index of the last element is (size - 1),
where size is the number of elements in the array.
Example:
int numbers[5]; // Array declaration
numbers[0] = 10; // Assigning a value to the first element
int x = numbers[2]; // Accessing the third element
Pointers:
A pointer is a variable that holds the memory address of another variable.
Pointers are declared using the * symbol.
The data type before the * specifies the type of data the pointer points to.
Pointers allow direct access to a memory location and facilitate dynamic
memory allocation.
Example:
int number = 42; // Variable declaration
int* ptr = &number; // Pointer declaration and initialization
*ptr = 99; // Modifying the value using the pointer
Relationship between Arrays and Pointers:
The name of an array is a constant pointer to its first element.
When an array is passed to a function or assigned to a pointer, the pointer holds
the memory address of the first element of the array.
Pointer arithmetic can be used to traverse and manipulate array elements.
Example:
int numbers[5] = {1, 2, 3, 4, 5};
int* ptr = numbers; // Pointer initialized to the first element of the array
// Accessing array elements using pointer arithmetic
int thirdElement = *(ptr + 2); // Equivalent to numbers[2]
Dynamic Memory Allocation:
C++ provides the new and delete operators for dynamic memory allocation using
pointers.
The new operator allocates memory for a single object or an array dynamically
at runtime and returns the pointer to the allocated memory.
The delete operator deallocates the memory previously allocated using new.
Example:
int* dynamicInt = new int; // Dynamic memory allocation for a single integer
*dynamicInt = 42;
delete dynamicInt; // Release the allocated memory
int* dynamicArray = new int[5]; // Dynamic memory allocation for an array of
integers
dynamicArray[0] = 10;
delete[] dynamicArray; // Release the allocated memory for the array
Classes and Objects:

A class is a user-defined type that serves as a blueprint for creating objects.


It encapsulates data (member variables) and functions (member functions) that
operate on that data.
An object is an instance of a class.
It represents a specific occurrence of the class and can hold its own unique data.
Example:
class Circle {
private:
double;
public:
void setRadius(double r) {
radius = r;
}

double calculateArea() {
return 3.14 * radius * radius;
}
};
int main() {
Circle myCircle; // Creating an object of class Circle
myCircle.setRadius(5.0);
double area = myCircle.calculateArea();
return 0;
}
Encapsulation:
C++ supports access specifiers (public, private, protected) to control the visibility of class members.
By default, members are private, which means they are inaccessible outside the class.
Public members are accessible from anywhere.
Encapsulation allows you to hide the internal implementation details of a class and provide a public
interface for interacting with objects.
Example:
class Rectangle {
private:
double length;
double width;
public:
void setDimensions(double len, double wid) {
length = len;
width = wid;
}
double calculateArea() {
return length * width;
}};
Inheritance:
Inheritance allows you to create new classes (derived classes) based on existing classes (base classes).
The derived class inherits the properties and behaviors of the base class and can add its own additional
members.
In C++, inheritance can be achieved using the public, private, or protected access specifiers.
Example:
class Vehicle {
protected:
int speed;
public:
void setSpeed(int s) {
speed = s;
}};
class Car : public Vehicle {
public:
void start() {
cout << "Car started. Speed: " << speed << " km/h" << endl;
} };
Polymorphism:
Polymorphism means having multiple forms. It allows objects of different classes to be treated as objects of a
common base class.
C++ supports polymorphism through function overriding and function overloading.
Function overriding allows a derived class to provide its own implementation of a function defined in the
base class.
Example:
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape." << endl;
}};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle." << endl;
} };
Abstraction:
Abstraction focuses on representing essential features and hiding unnecessary details.
C++ supports abstract classes, which cannot be instantiated and serve as base classes for other
classes.
Abstract classes can contain pure virtual functions, which are virtual functions without an
implementation.
Example:
class Animal {
public:
virtual void makeSound() = 0; // Pure virtual function
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "Woof!" << endl;
}
};
Write a program that divides 7 by 2 and prints out the result (3.5) without using the printf() command. Your
program must do the following things:

1.Declare two variables and assign them to the appropriate values, and use them to calculate your quotient of 3.5.
2.Include just one division (/) operator in your code.
3.Use just one cout << statement.

Below are a few sample solutions.


You can either declare one or both of the variables as doubles:
double seven = 7.0;
double two = 2.0;
cout << ( seven / two ) << endl;
Or you can type cast one or both of the variables:
int seven = 7;
int two = 2;
cout << ( (double) seven / (double) two ) << endl;
Alternatively, you can convert string variables to doubles:
string seven = "7";
string two = "2";
cout << ( stod(seven) / stod(two) );
Presentation title

File Input/Output (I/O) in C++ allows you to read data from files and
write data to files. It provides a way to interact with external files and
store or retrieve information. Here's an overview of file I/O in C++:

1. Opening a File:

To work with a file, you need to open it using the ifstream (for reading)
or ofstream (for writing) classes from the <fstream> library.
The file must be opened before you can read from or write to it.
Presentation title

Example:
#include <fstream>
using namespace std;
int main() {
ifstream inputFile("input.txt"); // Open a file
for reading
ofstream outputFile("output.txt"); // Open a
file for writing
// Perform file operations
inputFile.close(); // Close the input file
outputFile.close(); // Close the output file
return 0;
}
2. Reading from a File:
To read data from a file, you can use the >> operator or the getline() function to
extract data from the file stream.
Example using >> operator:
#include <fstream>
using namespace std;
int main() {
ifstream inputFile("input.txt");
int num;
inputFile >> num; // Read an integer from the file
string name;
inputFile >> name; // Read a string from the file
inputFile.close();
return 0;
}
3. Writing to a File:
To write data to a file, you can use the << operator to insert data into the file stream.
Example:
#include <fstream>
using namespace std;
int main() {
ofstream outputFile("output.txt");
int num = 10;
outputFile << num << endl; // Write an integer to the file
string name = "John";
outputFile << name << endl; // Write a string to the file
outputFile.close();
return 0;
}
4. Checking for File Open/Close Status:
You can check if a file was successfully opened or closed by using the is_open()
and close() functions respectively.
Example:
#include <fstream>
using namespace std;
int main() {
ifstream inputFile("input.txt");
if (inputFile.is_open()) {
// Perform file operations
inputFile.close();
}
return 0;
}
Exception handling in C++ allows you to handle and manage runtime errors and
exceptional situations that may occur during program execution.
It provides a structured way to handle errors and recover from them. Here's an
overview of exception handling in C++:
Try-Catch Blocks:
Exception handling is done using try-catch blocks.
The code that may throw an exception is enclosed in a try block.
The catch block catches and handles the thrown exception.
Example:
try {
// Code that may throw an exception
} catch (ExceptionType exception) {
// Code to handle the exception
}
Throwing Exceptions:
Exceptions are thrown using the throw keyword.
You can throw an object of any type, which will be caught by an
appropriate catch block.
Example:
if (condition) {
throw ExceptionType(); // Throw an exception
}
Catching Specific Exceptions:
You can catch specific exceptions by specifying the exception type in the catch
block.
This allows you to handle different types of exceptions differently.
Example:
try {
// Code that may throw an exception
} catch (ExceptionType1 exception1) {
// Code to handle ExceptionType1
} catch (ExceptionType2 exception2) {
// Code to handle ExceptionType2
}
Presentation title

Catch-All Block:
You can use a catch-all block to catch any exception that is not caught by the
specific catch blocks.
The catch-all block should be placed at the end.
Example:
try {
// Code that may throw an exception
} catch (ExceptionType exception) {
// Code to handle ExceptionType
} catch (...) {
// Code to handle any other exception
}
def divide_numbers(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero.")
else:
return a / b

try:
numerator = 10
denominator = 0
result = divide_numbers(numerator, denominator)
print("Result:", result)
except ZeroDivisionError as e:
print("Error:", str(e))
Output:Error: Cannot divide by zero.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std
int main() {
vector<int> numbers = {5, 2, 8, 1, 9, 3, 7};
// Search for an element in the vector
int searchElement = 9;
auto it = find(numbers.begin(), numbers.end(), searchElement);
if (it != numbers.end()) {
cout << "Element " << searchElement << " found at position: " << distance(numbers.begin(), it) << endl;
} else {
cout << "Element " << searchElement << " not found." << endl; }
// Sort the vector
sort(numbers.begin(), numbers.end());
// Print the sorted vector
cout << "Sorted vector: ";
for (const auto& num : numbers) {
cout << num << " "; }
cout << endl;
return 0;}
THANK YOU

You might also like