Writing Your First C++ Program
Learn C++ through interactive, bite-sized lessons. Master memory management, OOP, and build powerful applications.
Start C++ Journey →Welcome to the world of C++ programming! In this guide, we'll walk you through creating your first C++ program. This fundamental step will introduce you to the basic structure and syntax of C++.
The "Hello, World!" Program
Traditionally, the first program in any programming language is the "Hello, World!" program. It's a simple program that outputs the text "Hello, World!" to the screen. Let's create this program in C++:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Breaking Down the Code
Let's examine each part of this program:
#include <iostream>: This line includes the input/output stream library, which allows us to usecoutfor output.int main(): This is the main function, where program execution begins.std::cout << "Hello, World!" << std::endl;: This line outputs the text "Hello, World!" to the console.return 0;: This indicates that the program has executed successfully.
Compiling and Running the Program
To run this program, you need to compile it first. Here's how:
- Save the code in a file with a
.cppextension, e.g.,hello_world.cpp. - Open a terminal or command prompt.
- Navigate to the directory containing your file.
- Compile the program using a C++ compiler. For example, with g++:
g++ hello_world.cpp -o hello_world
This creates an executable file named hello_world.
- Run the program:
./hello_world
You should see "Hello, World!" printed on your screen.
A More Interactive Example
Let's create a slightly more complex program that interacts with the user:
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "! Welcome to C++!" << std::endl;
return 0;
}
This program prompts the user for their name and then greets them personally.
Key Concepts to Remember
- Every C++ program must have a
main()function. - The
#includedirective is used to include necessary libraries. std::coutis used for output, whilestd::cinis used for input.- Semicolons (;) are used to end statements in C++.
Next Steps
Now that you've written your first C++ program, you're ready to explore more complex concepts. Consider learning about:
- C++ Variables to store and manipulate data
- C++ Data Types to understand different types of data in C++
- C++ Operators for performing operations on variables
- C++ If-Else Statements for decision-making in your programs
Remember, practice is key in programming. Try modifying the examples and experiment with your own ideas to solidify your understanding of C++ basics.