Here are some C++ code snippets that illustrate some of the most important concepts in C++. This introduction will cover basic syntax, data types, control structures, object-oriented programming, and more.
1. Basic Syntax and Output
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
This simple program prints “Hello, World!” to the console. It introduces the inclusion of headers (#include <iostream>
), the main function, basic output (std::cout
), and the return statement.
2. Variables and Data Types
#include <iostream>
int main() {
int age = 30;
double salary = 45000.50;
char grade = 'A';
bool isEmployed = true;
std::cout << "Age: " << age << ", Salary: " << salary;
std::cout << ", Grade: " << grade << ", Employed: " << isEmployed << std::endl;
return 0;
}
This snippet demonstrates declaring and initializing variables of different data types like int
, double
, char
, and bool
.
3. Control Structures (if-else)
#include <iostream>
int main() {
int score = 85;
if (score >= 90) {
std::cout << "Grade A" << std::endl;
} else if (score >= 80) {
std::cout << "Grade B" << std::endl;
} else {
std::cout << "Grade C" << std::endl;
}
return 0;
}
Here, we use if
, else if
, and else
statements to make decisions based on the value of score
.
4. Loops (for and while)
#include <iostream>
int main() {
// for loop
for (int i = 0; i < 5; i++) {
std::cout << "i = " << i << std::endl;
}
// while loop
int j = 0;
while (j < 5) {
std::cout << "j = " << j << std::endl;
j++;
}
return 0;
}
This code shows how to use for
and while
loops for iterating over a range of numbers.
5. Functions
#include <iostream>
int add(int x, int y) {
return x + y;
}
int main() {
int result = add(5, 3);
std::cout << "5 + 3 = " << result << std::endl;
return 0;
}
This demonstrates defining and calling a simple function that adds two numbers.
6. Classes and Object-Oriented Programming
#include <iostream>
class Car {
public:
std::string color;
int year;
void drive() {
std::cout << "Driving a " << color << " car from " << year << std::endl;
}
};
int main() {
Car myCar;
myCar.color = "red";
myCar.year = 2020;
myCar.drive();
return 0;
}
This snippet introduces a basic class with attributes and a method, showcasing the fundamental aspects of object-oriented programming in C++.
These snippets provide a quick tour through the essential elements of C++ programming and serve as a foundation for further exploration into more advanced topics in the language.