First C++ Program
Now that your system is set up, it is time to write and run your first C++ program.
In this lesson, you will learn the basic structure of a C++ program and understand what each part does.
Writing Your First Program
Every C++ program follows a specific structure. Even complex programs are built on the same basic foundation.
Let us start with a simple program that prints a message on the screen.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!" << endl;
return 0;
}
When you run this program, it displays:
Hello, C++!
Understanding Each Part of the Program
Let us break this program into smaller pieces and understand what each line means.
The #include <iostream> Line
This line tells the compiler to include the input-output stream library.
It allows the program to use features like printing text on the screen and reading input from the user.
The using namespace std; Line
This line allows us to use standard C++ features without writing the full namespace every time.
Without this line, we would need to write std::cout
instead of cout.
The main() Function
Every C++ program starts execution from the main() function.
It is the entry point where the operating system begins running your program.
Printing Output with cout
The cout statement is used to display output on the screen.
The symbols << are called insertion operators.
They send data to the output stream.
The return 0; Statement
This line tells the operating system that the program finished successfully.
Returning zero usually indicates that there were no errors.
Compiling and Running the Program
After writing the program, it must be compiled before it can run.
Open your terminal or command prompt, navigate to the file location, and use the following command:
g++ first.cpp -o first
This command creates an executable file from your C++ source code.
To run the program:
./first
Common Beginner Mistakes
When writing the first program, beginners often make small mistakes.
- Forgetting to include
<iostream> - Missing semicolons at the end of statements
- Spelling
mainincorrectly - Using
coutwithout the correct namespace
These errors are normal and will reduce with practice.
Mini Practice
Try the following small changes on your own:
- Change the message inside quotes
- Add another
coutstatement - Remove
endland observe the output
This will help you understand how output works in C++.
Key Takeaways
- Every C++ program starts with the
main()function coutis used to print output- Programs must be compiled before running
- Small syntax details are very important in C++
What’s Next
In the next lesson, we will learn how to take input from the user using cin.