To sort an array in C++, include <algorithm> and call std::sort(arr, arr + n), where n is the number of elements. It sorts in ascending order by default using introsort and runs in O(n log n) time. For descending order, pass greater<int>() as a third argument.
- Key Takeaway 1:
std::sort()is the fastest standard way to sort an array in C++, beating manual bubble sort in both speed and readability. - Key Takeaway 2: The
#include <iostream>andusing namespace std;lines unlock console I/O and save you from writingstd::before every function. - Key Takeaway 3: Converting a
charto anintin C++ is a one-liner: subtract'0'for digit chars, or cast directly with(int)ch. - Key Takeaway 4:
std::reverse()reverses a vector in place without any extra memory allocation. - Key Takeaway 5: C++ built-in functions like
min(),max(),to_string(), andstoi()eliminate the need to rewrite common logic from scratch.
What #include <iostream> and using namespace std Actually Do
Every beginner C++ program starts with two lines that most tutorials paste without explaining. #include <iostream> tells the preprocessor to load the input/output stream library, which contains cin, cout, and cerr. Without it, your program has no way to print anything to the screen.
using namespace std; tells the compiler that when you write cout, you mean std::cout. The std namespace is where the C++ standard library lives. Skipping this line is not an error, but you would then have to prefix every standard function with std::, which gets tedious fast in beginner programs.
A minimal working shell looks like this:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
That int main() is the entry point. The OS calls it when your program runs. return 0 signals successful execution. These are not conventions you can skip; they are part of the C++ standard itself.
According to the TIOBE Index (June 2025), C++ ranks 3rd among the most used programming languages globally, behind Python and C. For Indian students preparing for placements at companies like TCS, Infosys, or product firms, C++ is still a core language in coding rounds. If you are thinking about which skills to prioritise, our guide on top skills every college student must learn before graduation is worth reading before you map out your prep plan.
How to Sort an Array in C++, Print Fibonacci Series, and Reverse Vectors
How to Print a Fibonacci Series in C++
The Fibonacci series starts with 0 and 1, and every subsequent number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13. A clean iterative approach uses a loop and two integer variables.
#include <iostream>
using namespace std;
int main() {
int n = 10, a = 0, b = 1;
cout << a << " " << b << " ";
for (int i = 2; i < n; i++) {
int c = a + b;
cout << c << " ";
a = b;
b = c;
}
return 0;
}
Output: 0 1 1 2 3 5 8 13 21 34
The iterative version is preferred over recursion for beginners because it does not risk stack overflow on large inputs and runs in O(n) time. Recursive Fibonacci has O(2^n) complexity without memoisation, which is why interviewers specifically ask you to optimise it.
How to Sort an Array in C++ Using std::sort
The standard library’s std::sort() uses an introsort algorithm under the hood, which is a hybrid of quicksort, heapsort, and insertion sort. It is available in the <algorithm> header. The time complexity of std::sort in C++ is O(n log n) in the average and worst case.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = 5;
sort(arr, arr + n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Output: 11 12 22 25 64
To sort an array in C++ in descending order, pass a comparator: sort(arr, arr + n, greater<int>()). That is it. No manual swapping, no nested loops. You can also sort a vector in C++ the same way: sort(v.begin(), v.end()). To sort a string array in C++, the same std::sort call works because strings support the less-than operator by default. This is one reason C++ is still taught in engineering curricula across IITs, NITs, and state universities.
How to Sort a Vector in C++ in Descending Order
Sorting a vector in C++ in descending order follows the same pattern as sorting a raw array. Pass greater<int>() as the comparator argument to std::sort.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {5, 2, 8, 1, 9};
sort(v.begin(), v.end(), greater<int>());
for (int x : v)
cout << x << " ";
return 0;
}
Output: 9 8 5 2 1
How to Reverse a Vector in C++
Vectors are the go-to dynamic array in modern C++. Reversing one takes a single function call from <algorithm>.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
reverse(v.begin(), v.end());
for (int x : v)
cout << x << " ";
return 0;
}
Output: 5 4 3 2 1
std::reverse() works on any container that supports bidirectional iterators, including strings. It modifies the vector in place, so there is no return value to catch. The time complexity is O(n) and space complexity is O(1).
Type Conversions and the min/max Functions
Converting char to int in C++
In C++, characters are stored as their ASCII values. The char 'A' is stored as 65, '0' as 48. There are two common conversion patterns you will use in competitive programming.
char ch = '7';
int digit = ch - '0'; // digit = 7
int ascii = (int)ch; // ascii = 55
Subtracting '0' works only for digit characters (‘0’ through ‘9’). For any char, the C-style cast (int)ch gives the ASCII value directly. You can also use static_cast<int>(ch), which is the C++-preferred form because it is explicit about what you are doing.
Converting int to string and string to int
These two conversions come up constantly when you are building output strings or parsing user input.
- int to string:
string s = to_string(42);gives"42" - string to int:
int n = stoi("42");gives42 - char to string:
string s(1, ch);creates a single-character string
Both to_string() and stoi() are in the <string> header. stoi() throws a std::invalid_argument exception if the string is not a valid integer, so wrap it in a try-catch block when you are handling user input you do not control.
Using min() and max() in C++
The min() and max() functions are in <algorithm> and work on any comparable type.
cout << min(3, 7); // 3
cout << max(3.5, 2.1); // 3.5
For arrays or vectors, use *min_element(v.begin(), v.end()) and *max_element(v.begin(), v.end()). The asterisk dereferences the iterator that these functions return. It is a common beginner mistake to forget the dereference and end up printing a memory address instead of a value.
Comparing C++, C, and Java for Beginners
| Feature | C | C++ | Java |
|---|---|---|---|
| Object-Oriented | No | Yes (optional) | Yes (mandatory) |
| Standard sort function | qsort() (manual comparator) | std::sort() (O(n log n)) | Arrays.sort() (TimSort) |
| Memory management | Manual (malloc/free) | Manual + RAII | Automatic (GC) |
| Type conversion | Implicit / C-cast | static_cast, stoi, to_string | Integer.parseInt(), String.valueOf() |
| Dynamic arrays | Pointers only | std::vector | ArrayList |
| Typical use in India placements | Systems/embedded | Competitive programming, DSA | Backend, enterprise apps |
According to Stack Overflow’s Developer Survey 2024, C++ is used professionally by 23.0% of developers worldwide, while Java sits at 30.3% and Python at 51.0%. For Indian placement preparation, C++ remains the dominant language for Data Structures and Algorithms rounds because of its execution speed and STL library coverage.
If you are weighing which language to study first, check out our breakdown of top online courses for high-salary jobs in 2025. It puts language choices in the context of actual job market demand.
GeeksforGeeks reports that over 1.5 million Indian students use their platform monthly for coding prep, with C++ being the most-submitted language for DSA problems as of 2024 (GeeksforGeeks, 2024, geeksforgeeks.org). That is not a coincidence. The STL gives you sort, search, and data structure implementations out of the box, which cuts the time you spend on boilerplate during timed coding tests.
For students who want structured learning without spending money upfront, our list of best free online learning platforms for students in 2025 covers the best places to practice C++ problems with real-time feedback.
Once you have got these fundamentals down, the next step is thinking about where they take you professionally. Our guide on entry-level jobs for teens and fresh graduates covers roles where C++ knowledge gives you a real edge, especially in embedded systems, game development, and fintech.
Career planning matters as much as technical skill. If you are not sure which direction to move after mastering the basics, the 3.0 University guide on how to choose the right career path after graduation in 2026 walks through a decision framework that is practical and India-specific. And if you want a broader view of where the job market is heading, our best career options in 2026 for students and professionals article is a good companion read.
Mastering how to sort an array in C++ and related built-in functions puts you in a strong position for placement rounds, but the skills that pay the most in 2025-2026 sit at the intersection of programming and emerging tech. Cybersecurity, AI, and Blockchain roles all require strong fundamentals, and C++ knowledge transfers directly into those fields. Browse the full 3.0 University course catalogue to see what is available in those areas.
Frequently Asked Questions
How do you sort an array in C++?
Include <algorithm> and call std::sort(arr, arr + n), where n is the number of elements. It sorts in ascending order by default using introsort, which runs in O(n log n). For descending order, use sort(arr, arr + n, greater<int>()). This works on raw arrays, vectors, and any random-access container.
What is the time complexity of std::sort in C++?
std::sort in C++ runs in O(n log n) time in both the average and worst case. It uses introsort internally, which switches between quicksort, heapsort, and insertion sort depending on the input size and recursion depth. This makes it faster in practice than a pure quicksort implementation.
What is the difference between sort and stable_sort in C++?
std::sort does not guarantee that equal elements keep their original relative order. std::stable_sort does preserve that order, but it runs in O(n log^2 n) time without extra memory, or O(n log n) if additional memory is available. Use stable_sort when the original order of equal elements matters, such as when sorting records by one field while preserving a previous sort by another field.
How do you print a Fibonacci series in C++?
Use an iterative loop with two variables tracking the previous two values. Start with a = 0 and b = 1, print both, then loop from index 2 to n, computing c = a + b, printing c, then shifting: a = b; b = c;. This runs in O(n) time and avoids the exponential cost of naive recursion.
How do you reverse a vector in C++?
Call std::reverse(v.begin(), v.end()) after including <algorithm>. It reverses the vector in place in O(n) time with O(1) extra space. There is no return value; the original vector is modified directly. The same function works on strings and any other container that supports bidirectional iterators.
How do you convert a char to an int in C++?
For a digit character like '5', use int digit = ch - '0'; to get the numeric value 5. For the ASCII value of any character, use static_cast<int>(ch) or the C-style cast (int)ch. Subtracting '0' only works correctly for characters between '0' and '9'.
What does ‘using namespace std’ actually do?
It tells the compiler to look inside the std namespace when resolving names, so you can write cout instead of std::cout and sort instead of std::sort. It is convenient in beginner programs but avoided in large production codebases because it can cause name collisions when multiple libraries define functions with the same name.
These programs are your foundation. Run each one, break it intentionally, then fix it. That is how you actually learn what the compiler is doing rather than just memorising syntax. Once you are comfortable with sorting arrays in C++, reversing vectors, and type conversions, move on to linked lists, trees, and graph algorithms, because that is where placement-level DSA questions live.
If you are serious about building a career in tech, 3.0 University offers industry-recognised certification courses in Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, and Web3. These programmes are designed for students, working professionals, and career switchers who want practical, job-ready skills, not just theory. Explore the full course catalogue at 3.0 University and find the programme that fits where you want to go.
Last updated: June 2025. Reviewed by the 3University editorial team.