Starting with C++: The Classic 'Hello, World!' Guide
K Om Senapati
Posted on June 19, 2024
Hello fellas, I am an undergrad from Bhubaneswar, India. In the first semester, we had Programming with C and data structures. Now two semesters are over, so I thought why not try to learn and create a series on learning cpp
So let's dive into the world of C++
Wait one more thing, I will use Programiz for the coding for this blog series. So if you wanna test code or do online C++ coding you can try this compiler. I'M NOT PROMOTING IT. Its UI just looks nice to me.
First Program
Here is the first program we all do as a beginner
#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}
So here it prints "Hello, World!" to the console.
The entry point to any cpp program in the main() function. In some IDE's it may not return 0.
The input and output can be done via cout and cin defined in header file, so we include that in our program.
And then the line std::cout << "Hello, World!";
is responsible for printing Hello, World! to the console.
In this line, lots of things are used let's investigate 🔍
-
std
- This is the standard namespace where cout, cin and many functions are defined. -
::
- This is the scope resolution operator used to specify the namespace of class/object/function. -
cout
- This is an object of class ostream in header file which is included in header file which is included in our program -
<<
- This is a stream insertion operator used to send data to the output stream -
"Hello, World!"
- This is just a string - plain text inside "" -
;
- This isstupidsemicolon used to terminate every statement in cpp
I guess it's a lot to take in but relax, after some blogs you will be able to understand all of this.
Second Program
And let's do another program to take username from user and greet user.
#include <iostream>
#include <string>
int main() {
std::string username;
std::cout << "Enter your username > ";
std::cin >> username;
std::cout << "Hello, " << username << "!";
return 0;
}
Here we are
- declaring a string variable
username
- Asking the user to input his username via
cout
- Then storing the user input to our variable
username
- And then we are printing the username.
Note
- We have to include header file to use string data type. We will learn about this later but just note.
- We can print multiple expressions by appending
<<
operator followed by a string.
And if you find std::
is hard to include in everywhere and irritating to the eyes you can mention using namespace std;
under the include statements and skip that.
For example, std::cout
can be replaced by cout
.
So that's it for the introduction, see ya all in the next blog.
Bye! Bye!
Posted on June 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.