First C++ Program
Writing and running a "Hello, World!" program is a simple and traditional way to get started with programming in any language, including C++.
Here are the steps using a few common tools: Visual Studio Code with the C/C++ extension and the GCC compiler.
1. Install Visual Studio Code (VSCode):
- Download and install Visual Studio Code from the VSCode website.
2. Install the C/C++ Extension:
- Open VSCode.
- Go to Extensions (you can use Ctrl+Shift+X or Cmd+Shift+X).
- Search for "C/C++" and install the extension provided by Microsoft.
3. Install GCC Compiler:
- On Windows, you can use MinGW. Follow the instructions mentioned earlier in the "Choose a Compiler" section.
- On Linux, you can install GCC using your package manager (e.g., sudo apt-get install g++ for Ubuntu).
- On macOS, you need to install Xcode Command Line Tools.
4. Open VSCode and Create a New C++ File:
- Open VSCode.
- Create a new file and save it with a .cpp extension, for example, first.cpp.
5. Write the "Hello, World!" Program:
- Inside hello.cpp, write code
Code:
#include<iostream> using namespace std; int main(){ cout<<"Hello Coders"; return 0; } |
Explanation:
- #include <iostream>: It tells the compiler to include the contents of the iostream header file before compiling the rest of the program. The iostream (input/output stream) header file provides functionality for handling input and output operations in C++. The #include directive is used to include external libraries or files in your C++ program.
- using namespace std;This line is declaring that you want to use the std namespace. The std (standard) namespace is a collection of classes and functions provided by the C++ Standard Library. By using using namespace std;, you can avoid typing std:: before standard C++ identifiers like cout and endl.
- int main(){...}: This is the main function. In C++, every program must have a main function, and the program starts executing from the beginning of this function. The int before main indicates that the function returns an integer. Conventionally, a return value of 0 indicates that the program executed successfully.
- cout<<"Hello Coders"; This line uses the cout object to print the text "Hello Coders" to the console. cout stands for "character output" and is part of the std namespace. The << operator is used to stream or output data, and "Hello Coders" is a string literal.
Execution Flow:
- The program starts executing from the main function.
- The cout statement outputs "Hello Coders" to the console.
- The program finishes executing, and the return 0; statement indicates a successful execution.
When you run this program, you should see "Hello Coders" displayed on the console.