Introduction
3 min read ·
C++ is a general purpose programming language developed by Bjarne Stroustrup. It was created as an extension of the C language to include additional features such as classes and object oriented programming.
C++ is widely used because it is fast, efficient, and gives developers control over system resources. It is commonly used in applications where performance is important.
Note
C++ is a compiled language, which means the code is converted into machine language before execution.
Basic Syntax of C++
The syntax of C++ is simple and similar to C, but it introduces new elements like streams for input and output.
A C++ program consists of the following parts
Header files
Main function
Statements
Example Explained
Explanation
#include <iostream> is a header file library that allows us to work with input and output objects such as cout
using namespace std allows us to use names from the standard library without writing std:: before them
int main() is the main function where the program starts executing
cout is used to output data to the screen
return 0 ends the program
Pro Tip
Every C++ statement ends with a semicolon. Missing it will result in an error.
C++ Output
The cout object is used together with the insertion operator << to display output.
You can also print on separate lines.
C++ Input
The cin object is used to get user input.
Explanation
cin is used to take input from the user
The >> operator is used to extract input
cout is used to display output
Caution
Make sure the data type of the variable matches the input value, otherwise unexpected results may occur.
Comments in C++
Comments are used to explain code and make it more readable.
Single line comment
Multi line comment
Real World Scenario
In large projects, comments help developers understand the purpose of code written by others or even by themselves later.
How C++ Program Works
A C++ program is written in a text file and then compiled using a compiler.
The compiler converts the code into machine language, which the computer can understand and execute.
Goal Achieved
You now understand the basic syntax of C++, including input, output, and comments.
Exercise
Write a C++ program that takes your name as input and prints a greeting message.