Topic01 / 11
Introduction to C++
What & Why
C++ is a compiled, statically-typed language that extends C with OOP, templates, and the Standard Template Library. It offers direct hardware control and near-zero overhead, making it the language of choice for competitive programming, game engines, and systems software.
Syntax
cpp
1#include <iostream>
2#include <string>
3using namespace std;
4
5int main() {
6 string name = "Priya";
7 int age = 22;
8 double gpa = 9.5;
9 bool isActive = true;
10
11 cout << "Name: " << name << ", Age: " << age << endl;
12 cout << "GPA: " << fixed << setprecision(1) << gpa << endl;
13
14 return 0; // 0 = success
15}Real-World Example
A simple student grade calculator:
example.ts
cpp
1#include <iostream>
2#include <vector>
3#include <numeric>
4#include <algorithm>
5using namespace std;
6
7int main() {
8 vector<int> marks = {85, 92, 78, 95, 88};
9
10 int total = accumulate(marks.begin(), marks.end(), 0);
11 double average = static_cast<double>(total) / marks.size();
12 int highest = *max_element(marks.begin(), marks.end());
13 int lowest = *min_element(marks.begin(), marks.end());
14
15 cout << "Total : " << total << endl;
16 cout << "Average : " << fixed << setprecision(2) << average << endl;
17 cout << "Highest : " << highest << endl;
18 cout << "Lowest : " << lowest << endl;
19 cout << "Grade : " << (average >= 90 ? "A" : average >= 75 ? "B" : "C") << endl;
20
21 return 0;
22}Pitfalls & Interview Tips
- ⚠️C++ doesn't initialize variables automatically — uninitialized variables contain garbage values, causing undefined behavior.
- ⚠️using namespace std; pollutes the global namespace. In large projects, prefer std:: prefix.
- 💡Interview tip: C++ is compiled directly to machine code — that's why it's faster than Java (JVM bytecode) or Python (interpreted).