If you haven’t set up a C++ compiler yet check this previous post.
https://niftynitin.medium.com/set-up-vs-code-for-c-1c961b12fd89

In our previous post, we wrote the following code

#include <iostream>
using namespace std;

int main()
{

// prints hello world
cout<<”Hello World!”<<endl;
return 0;
}

Let us now understand what each part of the program does.

  • The first line is #include<iostream> # is called the preprocessor directive. It tells the compiler to include the library iostream in the program. iostream contains the declaration of all the standard input/output functions.
  • using namespace std is used to import the entire std namespace. It contains functions like cin, cout. Namespaces are used to remove conflicts when using multiple libraries in a program as multiple libraries can contain the function with the same name. using namespace std is considered a bad practice. Instead, we should use std::cout where :: is the scope resolution operator.
  • int main() is a function in C++. It returns integer-type data. Every C++ program should contain the main function. A function must end with ( ). main() is the first line of code that gets executed by the compiler. The function follows with {…} which denotes a block of code. Everything in the main function will get executed by the compiler line by line.
  • // prints hello world is a comment. A comment is a line that is not executed by the compiler. It is written to improve the readability of the code which makes it easier for other programmers to understand it.
  • cout<<"Hello World!"<<endl tells the compiler to print Hello world! on the terminal. cout is a standard output function. It is followed by a “ ”. The quotes contain the text we want to print. endl is a manipulator function that adds a new line character to the output. Basically, it prints the output of the following lines of code from the next line.
    I suggest you try running the program without endl and see the output for yourself.
  • return 0 returns the main function the integer 0 which means that our program was executed successfully without any errors. return statements are used by functions to return the results of the operation performed by the function.

That’s all about the basic structure of a C++ program. I hope you understood the purpose of each part of the program.

I am a CS graduate and an ML enthusiast. My purpose here is to guide beginners in their programming and Machine learning journey.