C++ is a powerful and widely used programming language that can be found in everything from web browsers and operating systems to game development and machine learning tools. It's an extension of the C language and shares much of its syntax.
Here's a breakdown of fundamental C++ concepts and examples to get you started:
A "Hello World!" program is the traditional first step in learning any new programming language. It simply prints "Hello World!" to the screen.
#include <iostream> // This line includes the iostream library, which allows us to use input/output functionalities.
int main() { // The main() function is where the program execution begins.
std::cout << "Hello World!"; // std::cout is used to print output to the console.
return 0; // return 0; indicates that the program finished successfully.
}
Explanation:
* #include <iostream>: This is a preprocessor directive that includes the iostream library. This library provides functionalities for input and output operations, like printing to the console.
* int main() { ... }: Every C++ program must have a main() function. This is the entry point of your program, where execution begins.
* std::cout << "Hello World!";:
* std::cout is an object used to send data to the standard output device (usually your screen).
* << is the insertion operator, used to send the string "Hello World!" to std::cout.
* Strings in C++ are enclosed in double quotes.
* return 0;: This statement indicates that the program has finished executing successfully.
Variables are used to store data. In C++, you must declare the type of data a variable will hold.
#include <iostream>
int main() {
// Declaring and initializing variables
int age = 30; // 'int' for integer numbers
double price = 19.99; // 'double' for floating-point numbers (numbers with decimals)
char initial = 'J'; // 'char' for single characters
std::string name = "John Doe"; // 'std::string' for sequences of characters (text)
bool isStudent = true; // 'bool' for boolean values (true or false)
// Printing variable values
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "Price: " << price << std::endl;
std::cout << "Initial: " << initial << std::endl;
std::cout << "Is student: " << isStudent << std::endl;
return 0;
}
Explanation:
* int age = 30;: Declares an integer variable named age and assigns it the value 30.
* double price = 19.99;: Declares a double-precision floating-point variable named price and assigns it 19.99.
* char initial = 'J';: Declares a character variable named initial and assigns it the character 'J'. Single characters are enclosed in single quotes.
* std::string name = "John Doe";: Declares a string variable named name and assigns it the text "John Doe". To use std::string, you often need to include the <string> header, though iostream might implicitly include it in some compilers.
* bool isStudent = true;: Declares a boolean variable named isStudent and assigns it true. Boolean values are either true or false.
* std::endl: Inserts a new line character and flushes the output buffer.
You can get input from the user using std::cin.
#include <iostream>
#include <string> // Required for std::string
int main() {
std::string userName;
int userAge;
std::cout << "Enter your name: ";
std::cin >> userName; // Reads a single word from the input
std::cout << "Enter your age: ";
std::cin >> userAge;
std::cout << "Hello, " << userName << "! You are " << userAge << " years old." << std::endl;
return 0;
}
Explanation:
* std::cin >> userName;: The >> operator (extraction operator) is used to read input from the keyboard and store it in the userName variable.
Conditional statements allow your program to make decisions based on certain conditions.
#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 if (score >= 70) {
std::cout << "Grade: C" << std::endl;
} else {
std::cout << "Grade: D or F" << std::endl;
}
return 0;
}
Explanation:
* The if statement checks if score is greater than or equal to 90. If true, it executes the code block.
* else if provides alternative conditions to check if the previous if or else if conditions were false.
* else provides a default block of code to execute if none of the preceding if or else if conditions are true.
Loops are used to execute a block of code repeatedly.
for loop#include <iostream>
int main() {
for (int i = 0; i < 5; ++i) { // Initializes i to 0, continues as long as i < 5, increments i by 1 after each iteration
std::cout << "Iteration: " << i << std::endl;
}
return 0;
}
Explanation:
* The for loop has three parts separated by semicolons:
1. Initialization (int i = 0;): Executed once at the beginning to set up the loop counter.
2. Condition (i < 5;): Checked before each iteration. If true, the loop continues; otherwise, it terminates.
3. Increment/Decrement (++i;): Executed after each iteration.
while loop#include <iostream>
int main() {
int count = 0;
while (count < 3) { // Continues as long as count is less than 3
std::cout << "Count: " << count << std::endl;
count++; // Increments count by 1
}
return 0;
}
Explanation:
* The while loop continues to execute its code block as long as the specified condition (count < 3) remains true.
Functions are blocks of code designed to perform a specific task. They make your code more organized, reusable, and easier to understand.
#include <iostream>
// Function declaration (prototype)
int add(int a, int b);
int main() {
int result = add(5, 3); // Calling the add function
std::cout << "Sum: " << result << std::endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Explanation:
* int add(int a, int b);: This is the function declaration (or prototype). It tells the compiler about the function's name, return type (int), and the types of its parameters (int a, int b).
* int add(int a, int b) { return a + b; }: This is the function definition, which contains the actual code that the function executes. It takes two integer arguments (a and b) and returns their sum.
Arrays are used to store collections of elements of the same data type.
#include <iostream>
int main() {
int numbers[5] = {10, 20, 30, 40, 50}; // Declares an array named 'numbers' of size 5
// Accessing array elements (indexing starts from 0)
std::cout << "First element: " << numbers[0] << std::endl; // Output: 10
std::cout << "Third element: " << numbers[2] << std::endl; // Output: 30
// Modifying an array element
numbers[1] = 25;
std::cout << "Modified second element: " << numbers[1] << std::endl; // Output: 25
// Iterating through an array using a for loop
std::cout << "All elements: ";
for (int i = 0; i < 5; ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
* int numbers[5] = {10, 20, 30, 40, 50};: Declares an array named numbers that can hold 5 integer values. The values are initialized within the curly braces.
* Array elements are accessed using square brackets [] and their index. The first element is at index 0, the second at index 1, and so on.
C++ is an object-oriented programming language. Classes are blueprints for creating objects, which are instances of those classes.
#include <iostream>
#include <string>
class Car { // Declaring a class named Car
public: // Access specifier: members declared public are accessible from outside the class
std::string brand;
std::string model;
int year;
// A member function
void displayInfo() {
std::cout << "Brand: " << brand << ", Model: " << model << ", Year: " << year << std::endl;
}
}; // Don't forget the semicolon after the class definition
int main() {
Car car1; // Creating an object (instance) of the Car class
// Accessing and setting object's attributes
car1.brand = "Toyota";
car1.model = "Camry";
car1.year = 2022;
car1.displayInfo(); // Calling a member function of the object
Car car2;
car2.brand = "Honda";
car2.model = "Civic";
car2.year = 2023;
car2.displayInfo();
return 0;
}
Explanation:
* class Car { ... };: This defines a class named Car.
* public:: This is an access specifier. public members (attributes and functions) can be accessed from outside the class.
* std::string brand;, std::string model;, int year;: These are member variables (attributes) of the Car class.
* void displayInfo() { ... }: This is a member function of the Car class.
* Car car1;: This creates an object named car1 of the Car class.
* car1.brand = "Toyota";: This accesses the brand attribute of car1 and assigns it a value.
* car1.displayInfo();: This calls the displayInfo() function for the car1 object.
Pointers are variables that store memory addresses. They are a fundamental concept in C++ and allow for powerful memory management.
#include <iostream>
int main() {
int myVariable = 10; // An integer variable
int* myPointer = &myVariable; // Declares a pointer 'myPointer' and stores the memory address of 'myVariable'
std::cout << "Value of myVariable: " << myVariable << std::endl; // Output: 10
std::cout << "Memory address of myVariable: " << &myVariable << std::endl; // Output: (memory address)
std::cout << "Value stored in myPointer (memory address of myVariable): " << myPointer << std::endl; // Output: (memory address)
std::cout << "Value pointed to by myPointer: " << *myPointer << std::endl; // Output: 10 (dereferencing the pointer)
*myPointer = 20; // Changing the value at the memory address pointed to by myPointer
std::cout << "New value of myVariable: " << myVariable << std::endl; // Output: 20
return 0;
}
Explanation:
* int* myPointer;: Declares a pointer variable named myPointer that can hold the address of an int type variable. The * indicates it's a pointer.
* &myVariable;: The & operator (address-of operator) gives you the memory address of a variable.
* *myPointer;: The * operator (dereference operator) when used with a pointer, gives you the value stored at the memory address the pointer is holding.
To continue learning C++, consider exploring these resources:
As you learn, remember to practice regularly. Writing and experimenting with code is crucial for understanding.