C++ "Hello, World!" Program

Hello World!

A "Hello, World!" program is usually the first program written by people who are beginners in writing codes. It is a very simple program which displays the message "Hello, World!". It is probably the simplest program to illustrate a few basic syntaxes of a programming language. This article covers the C++ programs to print "Hello World!".






1. Algorithm for "Hello, World!"


1. Print "Hello, World!"





2. Pseudocode for "Hello, World!"


1. Procedure print():

2. Print "Hello, World!"

3. End Procedure





3. Time complexity for "Hello, World!"


Time Complexity: O(1)





4. C++ Program & output for "Hello, World!"

Code has been copied
// Header file
#include <iostream>

using namespace std;

int main() 
{
    // prints hello world
    cout << "Hello, World!";

    return 0;
}

Output


Hello, World!




5. Print "Hello, World!" without using semicolon

Generally in a C++ program a semicolon ( ; ) is required after the cout object. But there are a few tricks to print "Hello World!" without using a semicolon after this object. The ways are described below.


5.1. Use if in C++ Program to print "Hello, World!" without using semicolon

Code has been copied
#include <iostream>

using namespace std;

int main() {
    // prints hello world using 
    // if statement
    if (cout << "Hello, World!") {

    }

    return 0;
}

Output


Hello, World!




5.2. Use while loop in C++ Program to print "Hello, World!" without using semicolon

Code has been copied
#include <iostream>

using namespace std;

int main() {
    // prints hello world 
    // using while loop
    while (!(cout << "Hello, World!")) {

    }

    return 0;
}

Output


Hello, World!


  • cout << "Hello World!" returns true to the while loop in the above program. A while loop keeps getting executed repeatedly unless the condition becomes false.
  • Inside the while loop, a not ( ! ) operator is placed before the cout object to negate the true value to false so that we can avoid an infinite loop.



5.3. Use macro in C++ Program to print "Hello, World!" without using semicolon

Code has been copied
#include <iostream>
 // declare an macro
#define x cout << "Hello, World!"

using namespace std;

int main() {
    // prints hello world using macro
    if (x) {

    }

    return 0;
}

Output


Hello, World!


  • Here, x is the name of the macro, and it is replaced by the expression cout << "Hello World!" in the program at compile time.