Convex Hull Algorithm in C++
Last Updated :
23 Jul, 2025
The Convex Hull problem is fundamental problem in computational geometry. In this, we need to find the smallest convex polygon, known as the convex hull, that can include a given set of points in a two-dimensional plane. This problem has various applications in areas such as computer graphics, geographic information systems, robotics, and more.
In this article, we will discuss several algorithms to solve the Convex Hull problem, with each algorithm's implementation in C++.
Example
Input:
Point points[] = {{0, 0}, {0, 4}, {-4, 0}, {5, 0}, {0, -6}, {1, 0}};
Output:
The points in the Convex Hull are:
(-4, 0)
(5, 0)
(0, -6)
(0, 4)
We can visualize a convex hull as the shape formed when a rubber band is stretched around a set of nails that represent points on a 2D plane. The convex hull is the smallest convex boundary that encloses all the points. Mathematically, it is the smallest convex polygon that contains all the given points.
Convex Hull using Divide and Conquer Algorithm in C++
In this approach, we follow the idea of recursively dividing the set of points into two halves, computing the convex hull for each half, and then merging these two convex hulls.
Approach:
- Start dividing the set of points into two halves based on their x-coordinates. The left half will contain all points with x-coordinates less than or equal to the median x-coordinate, and the right half will contain the remaining points.
- Recursively apply the divide and conquer approach to find the convex hull for the left half and the right half.
- After finding the convex hulls for the left and right halves, the next step is to merge these two convex hulls. To do this, find the upper and lower tangents that connect the two convex hulls.
- The upper tangent is the line that touches both convex hulls and lies above all the points in both hulls.
- The lower tangent is the line that touches both convex hulls and lies below all the points in both hulls.
- The points between these tangents form the final convex hull.
- Finally, Combine the points from the left convex hull and right convex hull that lie between the tangents to form the complete convex hull for the entire set of points.
Below is the implementation of above approach:
C++
// C++ program to to find convex
// hull of a given set of points using divide and conquer.
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
// stores the centre of polygon (It is made
// global because it is used in compare function)
pair<int, int> mid;
// determines the quadrant of a point
// (used in compare())
int quad(pair<int, int> p)
{
if (p.first >= 0 && p.second >= 0)
return 1;
if (p.first <= 0 && p.second >= 0)
return 2;
if (p.first <= 0 && p.second <= 0)
return 3;
return 4;
}
// Checks whether the line is crossing the polygon
int orientation(pair<int, int> a, pair<int, int> b, pair<int, int> c)
{
int res = (b.second - a.second) * (c.first - b.first) - (c.second - b.second) * (b.first - a.first);
if (res == 0)
return 0;
if (res > 0)
return 1;
return -1;
}
// compare function for sorting
bool compare(pair<int, int> p1, pair<int, int> q1)
{
pair<int, int> p = make_pair(p1.first - mid.first, p1.second - mid.second);
pair<int, int> q = make_pair(q1.first - mid.first, q1.second - mid.second);
int one = quad(p);
int two = quad(q);
if (one != two)
return (one < two);
return (p.second * q.first < q.second * p.first);
}
// Finds upper tangent of two polygons 'a' and 'b'
// represented as two vectors.
vector<pair<int, int>> merger(vector<pair<int, int>> a, vector<pair<int, int>> b)
{
// n1 -> number of points in polygon a
// n2 -> number of points in polygon b
int n1 = a.size(), n2 = b.size();
int ia = 0, ib = 0;
for (int i = 1; i < n1; i++)
if (a[i].first > a[ia].first)
ia = i;
// ib -> leftmost point of b
for (int i = 1; i < n2; i++)
if (b[i].first < b[ib].first)
ib = i;
// finding the upper tangent
int inda = ia, indb = ib;
bool done = 0;
while (!done)
{
done = 1;
while (orientation(b[indb], a[inda], a[(inda + 1) % n1]) >= 0)
inda = (inda + 1) % n1;
while (orientation(a[inda], b[indb], b[(n2 + indb - 1) % n2]) <= 0)
{
indb = (n2 + indb - 1) % n2;
done = 0;
}
}
int uppera = inda, upperb = indb;
inda = ia, indb = ib;
done = 0;
int g = 0;
while (!done) // finding the lower tangent
{
done = 1;
while (orientation(a[inda], b[indb], b[(indb + 1) % n2]) >= 0)
indb = (indb + 1) % n2;
while (orientation(b[indb], a[inda], a[(n1 + inda - 1) % n1]) <= 0)
{
inda = (n1 + inda - 1) % n1;
done = 0;
}
}
int lowera = inda, lowerb = indb;
vector<pair<int, int>> ret;
// ret contains the convex hull after merging the two convex hulls
// with the points sorted in anti-clockwise order
int ind = uppera;
ret.push_back(a[uppera]);
while (ind != lowera)
{
ind = (ind + 1) % n1;
ret.push_back(a[ind]);
}
ind = lowerb;
ret.push_back(b[lowerb]);
while (ind != upperb)
{
ind = (ind + 1) % n2;
ret.push_back(b[ind]);
}
return ret;
}
// Brute force algorithm to find convex hull for a set
// of less than 6 points
vector<pair<int, int>> bruteHull(vector<pair<int, int>> a)
{
// Take any pair of points from the set and check
// whether it is the edge of the convex hull or not.
// if all the remaining points are on the same side
// of the line then the line is the edge of convex
// hull otherwise not
set<pair<int, int>> s;
for (int i = 0; i < a.size(); i++)
{
for (int j = i + 1; j < a.size(); j++)
{
int x1 = a[i].first, x2 = a[j].first;
int y1 = a[i].second, y2 = a[j].second;
int a1 = y1 - y2;
int b1 = x2 - x1;
int c1 = x1 * y2 - y1 * x2;
int pos = 0, neg = 0;
for (int k = 0; k < a.size(); k++)
{
if (a1 * a[k].first + b1 * a[k].second + c1 <= 0)
neg++;
if (a1 * a[k].first + b1 * a[k].second + c1 >= 0)
pos++;
}
if (pos == a.size() || neg == a.size())
{
s.insert(a[i]);
s.insert(a[j]);
}
}
}
vector<pair<int, int>> ret;
for (auto e : s)
ret.push_back(e);
// Sorting the points in the anti-clockwise order
mid = {0, 0};
int n = ret.size();
for (int i = 0; i < n; i++)
{
mid.first += ret[i].first;
mid.second += ret[i].second;
ret[i].first *= n;
ret[i].second *= n;
}
sort(ret.begin(), ret.end(), compare);
for (int i = 0; i < n; i++)
ret[i] = make_pair(ret[i].first / n, ret[i].second / n);
return ret;
}
// Returns the convex hull for the given set of points
vector<pair<int, int>> divide(vector<pair<int, int>> a)
{
// If the number of points is less than 6 then the
// function uses the brute algorithm to find the
// convex hull
if (a.size() <= 5)
return bruteHull(a);
// left contains the left half points
// right contains the right half points
vector<pair<int, int>> left, right;
for (int i = 0; i < a.size() / 2; i++)
left.push_back(a[i]);
for (int i = a.size() / 2; i < a.size(); i++)
right.push_back(a[i]);
// convex hull for the left and right sets
vector<pair<int, int>> left_hull = divide(left);
vector<pair<int, int>> right_hull = divide(right);
// merging the convex hulls
return merger(left_hull, right_hull);
}
// Driver code
int main()
{
vector<pair<int, int>> a;
a.push_back(make_pair(0, 0));
a.push_back(make_pair(1, -4));
a.push_back(make_pair(-1, -5));
a.push_back(make_pair(-5, -3));
a.push_back(make_pair(-3, -1));
a.push_back(make_pair(-1, -3));
a.push_back(make_pair(-2, -2));
a.push_back(make_pair(-1, -1));
a.push_back(make_pair(-2, -1));
a.push_back(make_pair(-1, 1));
int n = a.size();
// sorting the set of points according
// to the x-coordinate
sort(a.begin(), a.end());
vector<pair<int, int>> ans = divide(a);
cout << "convex hull:\n";
for (auto e : ans)
cout << e.first << " " << e.second << endl;
return 0;
}
Outputconvex hull:
-5 -3
-1 -5
1 -4
0 0
-1 1
Time Complexity: The merging of the left and the right convex hulls take O(n) time and as we are dividing the points into two equal parts, so the time complexity of the above algorithm is O(n * log n).
Auxiliary Space: O(n)
Convex Hull using Jarvis March (Gift Wrapping) in C++
Jarvis March algorithm is also known as the Gift Wrapping algorithm. It is a brute-force approach that iteratively selects the points that form the convex hull. Starting from the leftmost point, the algorithm selects the point that is the most counterclockwise relative to the current point until it returns to the starting point.
Approach:
- Start identifying the leftmost point in the set of points.
- Starting from the leftmost point, select the next point in the convex hull by checking the orientation of the triplet formed by the current point, a candidate point, and any other point in the set.
- The candidate point that forms the most counterclockwise angle relative to the current point and the next point in the sequence is selected.
- Add the selected point to the convex hull and move on to it as the new “current” point.
- Continue this process until you return to the starting point.
- Stop when the convex hull is fully constructed, and all the points on the hull have been identified.
Below is the implementation of above approach:
C++
// C++ program to find the convex hull of a set of points using Jarvis's algorithm
#include <iostream>
#include <vector>
using namespace std;
// Structure to represent a point in 2D space
struct Point
{
int x, y;
};
// Function to find the orientation of the ordered triplet (p, q, r)
// Returns 0 if p, q, r are collinear
// Returns 1 if clockwise
// Returns 2 if counterclockwise
int orientation(Point p, Point q, Point r)
{
int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (val == 0)
return 0; // Collinear
return (val > 0) ? 1 : 2; // Clockwise or Counterclockwise
}
// Function to print the convex hull of a set of points
void convexHull(Point points[], int n)
{
// There must be at least 3 points to form a convex hull
if (n < 3)
return;
// Initialize the result vector to store the convex hull points
vector<Point> hull;
// Find the leftmost point
int l = 0;
for (int i = 1; i < n; i++)
if (points[i].x < points[l].x)
l = i;
// Start from the leftmost point and keep moving counterclockwise
// until we reach the start point again
int p = l, q;
do
{
// Add the current point to the result (convex hull)
hull.push_back(points[p]);
// Search for a point 'q' such that the orientation of (p, q, x)
// is counterclockwise for all points 'x'
q = (p + 1) % n;
for (int i = 0; i < n; i++)
{
// If i is more counterclockwise than the current q, then update q
if (orientation(points[p], points[i], points[q]) == 2)
q = i;
}
// Set p as q for the next iteration
p = q;
}
// Repeat until we reach the first point
while (p != l);
// Print the result (convex hull)
for (int i = 0; i < hull.size(); i++)
cout << "(" << hull[i].x << ", " << hull[i].y << ")\n";
}
// Driver program to test the above functions
int main()
{
// Define an array of points
Point points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}};
int n = sizeof(points) / sizeof(points[0]);
// Calculate and print the convex hull
convexHull(points, n);
return 0;
}
Output(0, 3)
(0, 0)
(3, 0)
(3, 3)
Time Complexity: O(m * n), where n is number of input points and m is number of output or hull points (m <= n). For every point on the hull we examine all the other points to determine the next point.
Worst case, Time complexity: O(n2). The worst case occurs when all the points are on the hull (m = n).
Auxiliary Space: O(n), since n extra space has been taken.
Convex Hull using Graham's Scan in C++
Graham's Scan is a more efficient algorithm for finding the convex hull of a set of points. It begins by sorting the points based on their polar angle relative to a reference point, typically the point with the lowest y-coordinate. The algorithm then processes the sorted points and constructs the convex hull by maintaining a stack of candidate points.
Approach:
- Find the point with the lowest y-coordinate. This point will serve as the reference point for sorting the other points based on their polar angles.
- Sort all the points based on the polar angle they make with the reference point. If two points have the same angle, the one closer to the reference point is considered first.
- Start constructing the convex hull by considering the first three sorted points. These points are always part of the convex hull.
- Traverse the sorted points one by one. For each point, check the orientation formed by the last two points on the convex hull and the current point.
- If the orientation is counterclockwise, the current point is part of the convex hull. If not, remove the last point from the hull (since it would create a concave shape) and continue checking with the previous points until a counterclockwise orientation is achieved.
- Continue adding points until all points have been processed. Finally, the result is the convex hull that encloses all the given points.
Below is the implementation of above approach:
C++
// C++ program to find convex hull of a set of points using Graham Scan
#include <iostream>
#include <stack>
#include <stdlib.h>
using namespace std;
struct Point
{
int x, y;
};
// A global point needed for sorting points with reference
// to the first point Used in compare function of qsort()
Point p0;
// A utility function to find next to top in a stack
Point nextToTop(stack<Point> &S)
{
Point p = S.top();
S.pop();
Point res = S.top();
S.push(p);
return res;
}
// A utility function to swap two points
void swap(Point &p1, Point &p2)
{
Point temp = p1;
p1 = p2;
p2 = temp;
}
// A utility function to return square of distance
// between p1 and p2
int distSq(Point p1, Point p2)
{
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
}
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are collinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (val == 0)
return 0; // collinear
return (val > 0) ? 1 : 2; // clock or counterclock wise
}
// A function used by library function qsort() to sort an array of
// points with respect to the first point
int compare(const void *vp1, const void *vp2)
{
Point *p1 = (Point *)vp1;
Point *p2 = (Point *)vp2;
// Find orientation
int o = orientation(p0, *p1, *p2);
if (o == 0)
return (distSq(p0, *p2) >= distSq(p0, *p1)) ? -1 : 1;
return (o == 2) ? -1 : 1;
}
// Prints convex hull of a set of n points.
void convexHull(Point points[], int n)
{
// Find the bottommost point
int ymin = points[0].y, min = 0;
for (int i = 1; i < n; i++)
{
int y = points[i].y;
// Pick the bottom-most or choose the left
// most point in case of tie
if ((y < ymin) || (ymin == y && points[i].x < points[min].x))
ymin = points[i].y, min = i;
}
// Place the bottom-most point at first position
swap(points[0], points[min]);
// Sort n-1 points with respect to the first point.
// A point p1 comes before p2 in sorted output if p2
// has larger polar angle (in counterclockwise
// direction) than p1
p0 = points[0];
qsort(&points[1], n - 1, sizeof(Point), compare);
// If two or more points make same angle with p0,
// Remove all but the one that is farthest from p0
// Remember that, in above sorting, our criteria was
// to keep the farthest point at the end when more than
// one points have same angle.
int m = 1; // Initialize size of modified array
for (int i = 1; i < n; i++)
{
// Keep removing i while angle of i and i+1 is same
// with respect to p0
while (i < n - 1 && orientation(p0, points[i], points[i + 1]) == 0)
i++;
points[m] = points[i];
m++; // Update size of modified array
}
// If modified array of points has less than 3 points,
// convex hull is not possible
if (m < 3)
return;
// Create an empty stack and push first three points
// to it.
stack<Point> S;
S.push(points[0]);
S.push(points[1]);
S.push(points[2]);
// Process remaining n-3 points
for (int i = 3; i < m; i++)
{
// Keep removing top while the angle formed by
// points next-to-top, top, and points[i] makes
// a non-left turn
while (S.size() > 1 && orientation(nextToTop(S), S.top(), points[i]) != 2)
S.pop();
S.push(points[i]);
}
// Now stack has the output points, print contents of stack
while (!S.empty())
{
Point p = S.top();
cout << "(" << p.x << ", " << p.y << ")" << endl;
S.pop();
}
}
// Driver program to test above functions
int main()
{
Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};
int n = sizeof(points) / sizeof(points[0]);
convexHull(points, n);
return 0;
}
Output(0, 3)
(4, 4)
(3, 1)
(0, 0)
Time Complexity: O(nLogn), where n be the number of input points.
The first step (finding the bottom-most point) takes O(n) time. The second step (sorting points) takes O(nLogn) time. The third step takes O(n) time. In the third step, every element is pushed and popped at most one time. So the sixth step to process points one by one takes O(n) time, assuming that the stack operations take O(1) time. Overall complexity is O(n) + O(nLogn) + O(n) + O(n) which is O(nLogn).
Auxiliary Space: O(n), as explicit stack is used, since no extra space has been taken.
Convex Hull using Monotone Chain Algorithm in C++
The Monotone Chain algorithm is another efficient approach for constructing the convex hull, sometimes referred to as Andrew's algorithm. This method builds the convex hull by first sorting the points and then constructing the upper and lower hulls separately.
Approach:
- Start by sorting the points based on their x-coordinates. If two points have the same x-coordinate, sort them by their y-coordinates.
- Construct the Lower Hull:
- Begin with the leftmost point and proceed to the rightmost point. For each point, check if the last two points in the current hull and the current point form a clockwise turn. If they do, remove the second-to-last point from the hull.
- Add the current point to the lower hull.
- Construct the Upper Hull:
- After constructing the lower hull, repeat the process for the upper hull but traverse the points from right to left.
- Combine the upper and lower hulls. The points where the upper and lower hulls meet are only included once.
C++
// C++ program to find the convex hull of a set of points using the Monotone chain algorithm
#include <algorithm>
#include <iostream>
#include <vector>
#define llu long long int
using namespace std;
// Structure to represent a point in 2D space
struct Point
{
llu x, y;
// Operator overloading to compare two points lexicographically
bool operator<(Point p)
{
return x < p.x || (x == p.x && y < p.y);
}
};
// Function to calculate the cross product of vectors OA and OB
// Returns positive for a counterclockwise turn and negative for a clockwise turn
llu cross_product(Point O, Point A, Point B)
{
return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
}
// Function to return a list of points on the convex hull in counterclockwise order
vector<Point> convex_hull(vector<Point> A)
{
int n = A.size(), k = 0;
// If there are 3 or fewer points, return them as the convex hull
if (n <= 3)
return A;
// Initialize a vector to store the convex hull points
vector<Point> ans(2 * n);
// Sort the points lexicographically
sort(A.begin(), A.end());
// Build the lower hull
for (int i = 0; i < n; ++i)
{
// Remove the last point if it is not part of the convex hull
// Check if the cross product indicates a clockwise turn
while (k >= 2 && cross_product(ans[k - 2], ans[k - 1], A[i]) <= 0)
k--;
ans[k++] = A[i];
}
// Build the upper hull
for (size_t i = n - 1, t = k + 1; i > 0; --i)
{
// Remove the last point if it is not part of the convex hull
// Check if the cross product indicates a clockwise turn
while (k >= t && cross_product(ans[k - 2], ans[k - 1], A[i - 1]) <= 0)
k--;
ans[k++] = A[i - 1];
}
// Resize the vector to remove any extra elements
ans.resize(k - 1);
return ans;
}
// Driver program to test the above functions
int main()
{
// Define a vector to store the points
vector<Point> points;
// Add points to the vector
points.push_back({0, 3});
points.push_back({2, 2});
points.push_back({1, 1});
points.push_back({2, 1});
points.push_back({3, 0});
points.push_back({0, 0});
points.push_back({3, 3});
// Find the convex hull
vector<Point> ans = convex_hull(points);
// Print the points in the convex hull
for (int i = 0; i < ans.size(); i++)
cout << "(" << ans[i].x << ", " << ans[i].y << ")" << endl;
return 0;
}
Output(0, 0)
(3, 0)
(3, 3)
(0, 3)
Time Complexity: O(n*log(n))
Auxiliary Space: O(n)
Convex Hull using QuickHull Algorithm in C++
The QuickHull algorithm is a divide-and-conquer method in which we recursively finds the convex hull by identifying points that lie outside the current hull and then refining the hull with these points.
C++
// C++ program to implement the Quick Hull algorithm to find the convex hull
#include <cmath>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
// iPair is used to represent integer pairs (x, y coordinates)
#define iPair pair<int, int>
// Set to store the result (points of the convex hull)
set<iPair> hull;
// Function to find the side of point p with respect to the line
// joining points p1 and p2
int findSide(iPair p1, iPair p2, iPair p)
{
int val = (p.second - p1.second) * (p2.first - p1.first) - (p2.second - p1.second) * (p.first - p1.first);
if (val > 0)
return 1;
if (val < 0)
return -1;
return 0;
}
// Function to return a value proportional to the distance
// between the point p and the line joining points p1 and p2
int lineDist(iPair p1, iPair p2, iPair p)
{
return abs((p.second - p1.second) * (p2.first - p1.first) -
(p2.second - p1.second) * (p.first - p1.first));
}
// Recursive function to find the convex hull using Quick Hull algorithm
// Endpoints of line L are p1 and p2, side can have value 1 or -1
void quickHull(iPair a[], int n, iPair p1, iPair p2, int side)
{
int ind = -1;
int max_dist = 0;
// Find the point with maximum distance from the line L
// and on the specified side of L
for (int i = 0; i < n; i++)
{
int temp = lineDist(p1, p2, a[i]);
if (findSide(p1, p2, a[i]) == side && temp > max_dist)
{
ind = i;
max_dist = temp;
}
}
// If no point is found, add the endpoints of L to the convex hull
if (ind == -1)
{
hull.insert(p1);
hull.insert(p2);
return;
}
// Recur for the two parts divided by the point a[ind]
quickHull(a, n, a[ind], p1, -findSide(a[ind], p1, p2));
quickHull(a, n, a[ind], p2, -findSide(a[ind], p2, p1));
}
// Function to print the convex hull of a set of points
void printHull(iPair a[], int n)
{
// If there are fewer than 3 points, convex hull is not possible
if (n < 3)
{
cout << "Convex hull not possible\n";
return;
}
// Find the points with minimum and maximum x-coordinates
int min_x = 0, max_x = 0;
for (int i = 1; i < n; i++)
{
if (a[i].first < a[min_x].first)
min_x = i;
if (a[i].first > a[max_x].first)
max_x = i;
}
// Recursively find convex hull points on one side of the line
// joining a[min_x] and a[max_x]
quickHull(a, n, a[min_x], a[max_x], 1);
// Recursively find convex hull points on the other side of the line
quickHull(a, n, a[min_x], a[max_x], -1);
// Print the points in the convex hull
cout << "The points in Convex Hull are:\n";
while (!hull.empty())
{
cout << "(" << (*hull.begin()).first << ", " << (*hull.begin()).second << ") ";
hull.erase(hull.begin());
}
}
// Driver code to test the Quick Hull algorithm
int main()
{
// Define an array of points
iPair a[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};
// Calculate the number of points
int n = sizeof(a) / sizeof(a[0]);
// Find and print the convex hull
printHull(a, n);
return 0;
}
OutputThe points in Convex Hull are:
(0, 0) (0, 3) (3, 1) (4, 4)
Time Complexity: The analysis is similar to Quick Sort. On average, we get time complexity as O(n Log n), but in worst case, it can become O(n2)
Auxiliary Space: O(n)
Complexity Analysis
Convex Hull Algorithm | Time Complexity | Description |
---|
Divide and Conquer Algorithm | O(N log N) | Recursively divides the points and merges convex hulls. |
Jarvis’ March (Wrapping) | O(N^2) | Simple but less efficient, wraps points in counterclockwise direction. |
Graham Scan | O(N log N) | Sorts points and constructs the convex hull using stack. |
Monotone Chain Algorithm | O(N log N) | Sorts points and constructs upper and lower hulls separately. |
QuickHull Algorithm | O(N log N) | Similar to QuickSort, divides points using extreme points and recursively finds convex hulls. |
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
C++ Overview
Introduction to C++ Programming LanguageC++ is a general-purpose programming language that was developed by Bjarne Stroustrup as an enhancement of the C language to add object-oriented paradigm. It is considered as a middle-level language as it combines features of both high-level and low-level languages. It has high level language featur
3 min read
Features of C++C++ is a general-purpose programming language that was developed as an enhancement of the C language to include an object-oriented paradigm. It is an imperative and compiled language. C++ has a number of features, including:Object-Oriented ProgrammingMachine IndependentSimpleHigh-Level LanguagePopul
5 min read
History of C++The C++ language is an object-oriented programming language & is a combination of both low-level & high-level language - a Middle-Level Language. The programming language was created, designed & developed by a Danish Computer Scientist - Bjarne Stroustrup at Bell Telephone Laboratories (
7 min read
Interesting Facts about C++C++ is a general-purpose, object-oriented programming language. It supports generic programming and low-level memory manipulation. Bjarne Stroustrup (Bell Labs) in 1979, introduced the C-With-Classes, and in 1983 with the C++. Here are some awesome facts about C++ that may interest you: The name of
2 min read
Setting up C++ Development EnvironmentC++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. If you do not want to set up a local environment you can also use online IDEs for compiling your program.Using Online IDEIDE stands for an integrated development environment. IDE is a software application that provides facilities to
8 min read
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
C++ Basics
Understanding First C++ ProgramThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
C++ Basic SyntaxSyntax refers to the rules and regulations for writing statements in a programming language. They can also be viewed as the grammatical rules defining the structure of a programming language.The C++ language also has its syntax for the functionalities it provides. Different statements have different
4 min read
C++ CommentsComments in C++ are meant to explain the code as well as to make it more readable. Their purpose is to provide information about code lines. When testing alternative code, they can also be used to prevent execution of some part of the code. Programmers commonly use comments to document their work.Ex
3 min read
Tokens in CIn C programming, tokens are the smallest units in a program that have meaningful representations. Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid expressions and statements. Tokens can be classified into various categories, each with specific r
4 min read
C++ KeywordsKeywords are the reserved words that have special meanings in the C++ language. They are the words that have special meaning in the language. C++ uses keywords for a specifying the components of the language, such as void, int, public, etc. They can't be used for a variable name, function name or an
2 min read
Difference between Keyword and Identifier in CIn C, keywords and identifiers are basically the fundamental parts of the language used. Identifiers are the names that can be given to a variable, function or other entity while keywords are the reserved words that have predefined meaning in the language.The below table illustrates the primary diff
3 min read
C++ Variables and Constants
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Constants in CIn C programming, const is a keyword used to declare a variable as constant, meaning its value cannot be changed after it is initialized. It is mainly used to protect variables from being accidentally modified, making the program safer and easier to understand. These constants can be of various type
4 min read
Scope of Variables in C++In C++, the scope of a variable is the extent in the code upto which the variable can be accessed or worked with. It is the region of the program where the variable is accessible using the name it was declared with.Let's take a look at an example:C++#include <iostream> using namespace std; //
7 min read
Storage Classes in C++ with ExamplesC++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specif
6 min read
Static Keyword in C++The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses.In C++, a static keyword can be used in the following context:Table of ContentStatic Variables in a FunctionStatic Member Variab
5 min read
C++ Data Types and Literals
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
Literals in CIn C, Literals are the constant values that are assigned to the variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, âconst int =
4 min read
Derived Data Types in C++The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. They are generally the data types that are created from the primitive data types and provide some additional functionality.In C++, there are four different derived data types:Table of Cont
4 min read
User Defined Data Types in C++User defined data types are those data types that are defined by the user himself. In C++, these data types allow programmers to extend the basic data types provided and create new types that are more suited to their specific needs. C++ supports 5 user-defined data types:Table of ContentClassStructu
4 min read
Data Type Ranges and Their Macros in C++Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold but remembering such a large and precise number comes out to be a difficult job. Therefore, C++ has certain macros to represent these numbers, so that these can
3 min read
C++ Type ModifiersIn C++, type modifiers are the keywords used to change or give extra meaning to already existing data types. It is added to primitive data types as a prefix to modify their size or range of data they can store.C++ have 4 type modifiers which are as follows:Table of Contentsigned Modifierunsigned Mod
4 min read
Type Conversion in C++Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { // Two variables of different t
4 min read
Casting Operators in C++The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer).Let's take a look at an example:C++#
5 min read
C++ Operators
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
C++ Arithmetic OperatorsArithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands (generally numeric values). An operand can be a variable or a value. For example, â+â is used for addition, '-' is used for subtraction, '*' is used for multiplication, etc. Let's take a look at an
4 min read
Unary Operators in CIn C programming, unary operators are operators that operate on a single operand. These operators are used to perform operations such as negation, incrementing or decrementing a variable, or checking the size of a variable. They provide a way to modify or manipulate the value of a single variable in
5 min read
Bitwise Operators in CIn C, bitwise operators are used to perform operations directly on the binary representations of numbers. These operators work by manipulating individual bits (0s and 1s) in a number.The following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are
6 min read
Assignment Operators in CIn C, assignment operators are used to assign values to variables. The left operand is the variable and the right operand is the value being assigned. The value on the right must match the data type of the variable otherwise, the compiler will raise an error.Let's take a look at an example:C#include
4 min read
C++ sizeof OperatorThe sizeof operator is a unary compile-time operator used to determine the size of variables, data types, and constants in bytes at compile time. It can also determine the size of classes, structures, and unions.Let's take a look at an example:C++#include <iostream> using namespace std; int ma
3 min read
Scope Resolution Operator in C++In C++, the scope resolution operator (::) is used to access the identifiers such as variable names and function names defined inside some other scope in the current scope. Let's take a look at an example:C++#include <iostream> int main() { // Accessing cout from std namespace using scope // r
4 min read
C++ Input/Output
C++ Control Statements
Decision Making in C (if , if..else, Nested if, if-else-if )In C, programs can choose which part of the code to execute based on some condition. This ability is called decision making and the statements used for it are called conditional statements. These statements evaluate one or more conditions and make the decision whether to execute a block of code or n
7 min read
C++ if StatementThe C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { int
3 min read
C++ if else StatementThe if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it wonât. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
3 min read
C++ if else if LadderIn C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. I
3 min read
Switch Statement in C++In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is a simpler alternative to the long if-else-if ladder.SyntaxC++switch (expression) { case value_1: // code to be executed. break; case v
5 min read
Jump statements in C++Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function.In C++, there is four jump statement:Table of Contentcontinue Statementbreak Statementreturn Statementgoto S
4 min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
for Loop in C++In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand.Let's take a look at an example:C++#include <bits/stdc++.h
6 min read
Range-Based for Loop in C++In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops.Let's take
3 min read
C++ While LoopIn C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
3 min read
C++ do while LoopIn C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
4 min read
C++ Functions
Functions in C++A Function is a reusable block of code designed to perform a specific task. It helps break large programs into smaller, logical parts. Functions make code cleaner, easier to understand, and more maintainable.Just like in other languages, C++ functions can take inputs (called parameters), execute a b
8 min read
return Statement in C++In C++, the return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and returns the control from where it was calle
4 min read
Parameter Passing Techniques in CIn C, passing values to a function means providing data to the function when it is called so that the function can use or manipulate that data. Here:Formal Parameters: Variables used in parameter list in a function declaration/definition as placeholders. Also called only parameters.Actual Parameters
3 min read
Difference Between Call by Value and Call by Reference in CFunctions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.The following table lists the differences between the call-by-value and call-by-reference methods of parameter passing.Call By Valu
4 min read
Default Arguments in C++A default argument is a value provided for a parameter in a function declaration that is automatically assigned by the compiler if no value is provided for those parameters in function call. If the value is passed for it, the default value is overwritten by the passed value.Example:C++#include <i
5 min read
Inline Functions in C++In C++, inline functions provide a way to optimize the performance of the program by reducing the overhead related to a function call. When a function is specified as inline the whole code of the inline function is inserted or substituted at the point of its call during the compilation instead of us
6 min read
Lambda Expression in C++C++ 11 introduced lambda expressions to allow inline functions which can be used for short snippets of code that are not going to be reused. Therefore, they do not require a name. They are mostly used in STL algorithms as callback functions.Example:C++#include <iostream> using namespace std; i
4 min read
C++ Pointers and References
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
C++ PointersA pointer is a special variable that holds the memory address of another variable, rather than storing a direct value itself. Pointers allow programs to access and manipulate data in memory efficiently, making them a key feature for system-level programming and dynamic memory management. When we acc
8 min read
Dangling, Void , Null and Wild Pointers in CIn C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall
6 min read
Applications of Pointers in CPointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C. Prerequisite: Pointers in C. C Pointers Appl
4 min read
Understanding nullptr in C++Consider the following C++ program that shows problem with NULL (need of nullptr) CPP // C++ program to demonstrate problem with NULL #include <bits/stdc++.h> using namespace std; // function with integer argument void fun(int N) { cout << "fun(int)"; return;} // Overloaded fun
3 min read
References in C++In C++, a reference works as an alias for an existing variable, providing an alternative name for it and allowing you to work with the original data directly.Example:C++#include <iostream> using namespace std; int main() { int x = 10; // ref is a reference to x. int& ref = x; // printing v
5 min read
Can References Refer to Invalid Location in C++?Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the
2 min read
Pointers vs References in C++Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and
5 min read
Passing By Pointer vs Passing By Reference in C++In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++?Let's first understand what Passing by Pointer and Passing by Reference in C++ mean:Passing by
5 min read
When do we pass arguments by pointer?In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program. In C, variables are passed by pointer in the following ca
5 min read