C++ is a powerful, high-performance programming language that is used to create all sorts of applications, from games to operating systems.
You have a few options for getting started with C++. You can use a desktop IDE like VS Code or an online compiler like Replit.
Visual Studio Code is a free, open-source code editor developed by Microsoft. It supports C++ development through extensions.
Replit is an online IDE that allows you to write and run code in your browser. It's a great option if you don't want to install anything on your computer.
Let's write a simple "Hello, World!" program. This is a classic first program for any new language.
This code will print "Hello, World!" to the console.
#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}
#include <iostream>: Includes the input/output stream library.int main(): The main function where your program starts.std::cout: The standard output stream, used to print text.return 0;: Indicates that the program has executed successfully.#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}
Variables are containers for storing data values. In C++, you must declare the type of a variable.
int: for integers (whole numbers)double: for floating-point numbers (numbers with decimals)char: for single charactersstd::string: for textbool: for true/false valuesHere's how you declare and initialize a variable.
#include <iostream>
#include <string>
int main() {
int myAge = 25;
std::cout << "I am " << myAge << " years old.";
return 0;
}
You can get user input using std::cin.
std::cin ExampleThis program asks the user for their age.
#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You are " << age << " years old.";
return 0;
}
The main function is the entry point of every C++ program. It's where the execution of your code begins.
Here is the basic structure of a C++ program with the main function.
int main() {
// Your code goes here
return 0;
}
We use #include to bring in pre-written code from libraries. For example, <iostream> is used for input and output.
This is how you include the iostream library.
#include <iostream>
std::cout is used to print text to the console. The << operator is used to send data to the output stream.
Here's an example of how to print a line of text.
#include <iostream>
int main() {
std::cout << "This is a line of text.";
return 0;
}
Comments are used to explain code. They are ignored by the compiler. Single-line comments start with // and multi-line comments start with /* and end with */.
Here is an example of how to use comments in your code.
// This is a single-line comment
/*
This is a
multi-line
comment
*/
Try to write your own "Hello, World!" program and experiment with `std::cout`.
Modify the "Hello, World!" program to do the following:
std::endl or a second std::cout statement to create a new line.Here is one way to solve it. Your name and fact will be different!
#include <iostream>
int main() {
std::cout << "Hello, my name is Alex!" << std::endl;
std::cout << "I enjoy hiking on weekends.";
return 0;
}
A variable is a named storage location in memory that holds a value. In C++, variables must be declared with a specific data type.
To declare a variable, you specify its type, followed by its name, and optionally an initial value.
type variableName = value;
Integers are whole numbers. The int data type is used to store them.
int myNumber = 42;
int anotherNumber;
anotherNumber = 100;
Floating-point numbers have a decimal point. The double and float data types are used to store them.
double price = 19.99;
float temperature = 98.6f;
Characters are single letters, symbols, or numbers. The char data type is used to store them. They are enclosed in single quotes.
char grade = 'A';
char initial = 'J';
Strings are sequences of characters. The std::string data type is used to store them. They are enclosed in double quotes.
#include <string>
std::string greeting = "Hello, world!";
Booleans can have one of two values: true or false. The bool data type is used to store them.
bool isRaining = false;
bool isSunny = true;
Constants are variables whose values cannot be changed after they are initialized. The const keyword is used to declare a constant.
Here's how you declare a constant.
const double PI = 3.14159;
C++ supports the following arithmetic operators:
+ (addition)- (subtraction)* (multiplication)/ (division)% (modulus)Here's an example of using arithmetic operators.
int x = 10;
int y = 3;
int sum = x + y;
int difference = x - y;
int product = x * y;
int quotient = x / y;
int remainder = x % y;
We can get input from the user and store it in variables using std::cin.
This program asks the user for two numbers and then prints their sum.
#include <iostream>
int main() {
int num1, num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
int sum = num1 + num2;
std::cout << "The sum is: " << sum;
return 0;
}
Control flow refers to the order in which the statements in your program are executed. By default, code is executed sequentially. Control flow statements allow you to alter this sequence.
The if statement allows you to execute a block of code only if a certain condition is true.
This code checks if a number is positive.
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (number > 0) {
std::cout << "The number is positive.";
}
return 0;
}
The if-else statement allows you to execute one block of code if a condition is true, and another block of code if it is false.
This code checks if a number is even or odd.
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (number % 2 == 0) {
std::cout << "The number is even.";
} else {
std::cout << "The number is odd.";
}
return 0;
}
You can chain multiple conditions together using else if.
This code checks if a number is positive, negative, or zero.
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (number > 0) {
std::cout << "The number is positive.";
} else if (number < 0) {
std::cout << "The number is negative.";
} else {
std::cout << "The number is zero.";
}
return 0;
}
The switch statement is a good alternative to long if-else if-else chains when you are checking the value of a single variable.
This code prints the name of a day of the week based on a number.
#include <iostream>
int main() {
int day = 4;
switch (day) {
case 1:
std::cout << "Monday";
break;
case 2:
std::cout << "Tuesday";
break;
// ... and so on
default:
std::cout << "Invalid day";
}
return 0;
}
Loops are used to execute a block of code repeatedly. C++ has three main types of loops: for, while, and do-while.
The for loop is used when you know how many times you want to execute a block of code.
This code prints the numbers from 1 to 5.
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
std::cout << i << " ";
}
return 0;
}
The while loop is used to execute a block of code as long as a condition is true.
This code prints the numbers from 1 to 5.
#include <iostream>
int main() {
int i = 1;
while (i <= 5) {
std::cout << i << " ";
i++;
}
return 0;
}
The do-while loop is similar to the while loop, but it will always execute the block of code at least once, because the condition is checked at the end of the loop.
This code will ask the user to enter a number until they enter a positive one.
#include <iostream>
int main() {
int number;
do {
std::cout << "Enter a positive number: ";
std::cin >> number;
} while (number <= 0);
return 0;
}
Functions are blocks of code that perform a specific task. They are reusable and help to organize your code.
To define a function, you specify its return type, name, and parameters.
returnType functionName(parameters) { ... }
This function takes two integers as input and returns their sum.
int add(int a, int b) {
return a + b;
}
To use a function, you "call" it by its name and provide the required arguments.
This code calls the add function and prints the result.
#include <iostream>
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3);
std::cout << "The result is: " << result;
return 0;
}
If you define a function after you call it, you need to provide a function prototype at the beginning of your file. A prototype tells the compiler about the function's name, return type, and parameters.
Here's how you would write a prototype for the add function.
#include <iostream>
int add(int a, int b); // Function prototype
int main() {
int result = add(5, 3);
std::cout << "The result is: " << result;
return 0;
}
int add(int a, int b) {
return a + b;
}
Scope refers to the region of your code where a variable is accessible. Variables declared inside a function are only accessible within that function (local scope).
Variables declared outside of any function have global scope and can be accessed from anywhere in your program.
#include
int globalVar = 100; // Global variable
void function1() {
int localVar = 50; // Local variable
std::cout << "Global: " << globalVar << std::endl; // Accessible
std::cout << "Local: " << localVar << std::endl; // Accessible
}
void function2() {
std::cout << "Global: " << globalVar << std::endl; // Accessible
// std::cout << localVar << std::endl; // ERROR! Not accessible
}
int main() {
function1();
function2();
return 0;
}