Categories: C++

Syntax and Structure of a C++ Program

A specific template structure is used to write the C++ program. Let us see an example of “Hello World” program.

Example:
#include <iostream>
using namespace std;
int main() {
    // Write C++ code here
    cout << "Hello world!";

    return 0;
}
Output:
Hello world!
Header Files:

The C++ programming language defines several headers, each of which contains information that is either required or useful to your program. The header <iostream> is required for this program.

using namespace std:

Using namespace std; instructs the compiler to use the std namespace. Namespaces are a relatively new feature of C++.

int main:

The line int main() is the main function where program execution begins.

Comments:

// Write C++ code, here is the single-line comment in this program that is not executed by the compiler.

cout:

The following line cout “Hello World”; displays the message “Hello World” on the screen.

return 0:

The following line return 0; terminates the main() function and causes it to return 0 to the calling process.

Creating Classes in C++:

In C++, a class is defined by using the keyword class followed by the class name. The curly brackets define the body of the class, which is followed by a semicolon. Let us take an example:

#include <iostream>
using namespace std;
class Coderz
{
    int i;           //data variable
    void print()         //Member Function
    { 
        cout << "Inside Member Function of coderz";
    }
}; // Class ends here

int main()
{
    Coderz obj;  // Creatig Coderz class's object
    obj.print();  //Calling member function using class object
}

This is how a class is defined; after defining a class, its object is created and its member functions are used.

Variables can be declared anywhere in the program, but they must be declared before they can be used. As a result, we don’t need to declare variables at the beginning of the program.

Note: also read about the OOPs Concepts in C++

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

2 weeks ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 weeks ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

1 month ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

1 month ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

1 month ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

1 month ago