cpp_basics
cpp_basics
2. Comments:
Comments help explain the code and are ignored by the compiler.
- Single-line comment: // This is a comment
- Multi-line comment: /* This is a multi-line comment */
3. Data Types:
C++ provides several basic data types to represent different types of data:
- int: Integer type (e.g., int x = 5;)
- float: Floating-point type (e.g., float y = 5.99;)
- double: Double precision floating-point type (e.g., double z = 19.99;)
- char: Character type (e.g., char letter = 'A';)
- bool: Boolean type (e.g., bool isCodingFun = true;)
6. Operators:
C++ provides various operators for performing operations on data:
- Arithmetic Operators: +, -, *, /, %
- Assignment Operator: =
- Comparison Operators: ==, !=, <, >, <=, >=
- Logical Operators: && (AND), || (OR), ! (NOT)
7. Control Structures:
- Conditional Statements:
- if, else if, else
if (x > 5) {
std::cout << "x is greater than 5";
} else {
std::cout << "x is not greater than 5";
}
- Switch Statements:
switch (x) {
case 1: std::cout << "x is 1"; break;
case 2: std::cout << "x is 2"; break;
default: std::cout << "x is not 1 or 2";
}
- Loops:
- for loop:
for (int i = 0; i < 5; i++) {
std::cout << i << " ";
}
- while loop:
int i = 0;
while (i < 5) {
std::cout << i << " ";
i++;
}
- do-while loop:
int i = 0;
do {
std::cout << i << " ";
i++;
} while (i < 5);
8. Functions:
Functions allow you to organize your code into reusable blocks.
int add(int a, int b) {
return a + b;
}
int main() {
int sum = add(5, 3);
std::cout << "Sum: " << sum;
return 0;
}
9. Arrays:
Arrays store multiple values of the same type in a single variable.
int numbers[5] = {1, 2, 3, 4, 5};
std::cout << numbers[0]; // Outputs the first element
10. Vectors:
Vectors are dynamic arrays provided by the C++ Standard Library.
#include <vector>
11. Pointers:
Pointers store the memory address of a variable.
int x = 10;
int* ptr = &x; // Store the address of x in ptr
std::cout << *ptr; // Outputs the value of x (dereferencing)
void display() {
std::cout << "Brand: " << brand << ", Year: " << year;
}
};
int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.display();
return 0;
}
int main() {
std::ofstream myfile("example.txt");
myfile << "Writing to file";
myfile.close();
std::ifstream readfile("example.txt");
std::string line;
while (getline(readfile, line)) {
std::cout << line;
}
readfile.close();
return 0;
}
15. Namespaces:
Namespaces prevent name conflicts in large programs. The standard library uses
the std namespace.
using namespace std;