Understanding the program in C++

In this article we will understand the program written in C++ programming language in step-by-step manner. Consider the below simple C++ program that performs multiplication of two integers and displays the result.

/*Program that performs multiplication of two 
integers and displays the result*/

//Include header files
#include <iostream>
#include "conio.h"
using namespace std;

//main program starts from here
void main() {
	//declare variables
	int result, variable1, variable2;

	//assign values to variable1 and variable2
	variable1 = 10;
	variable2 = 2;

	/*Perform multiplication of variable1 and variable2.
	Store the result in the variable named result*/

	result = variable1 * variable2;

	//Display the result in the output window
	cout << "The result is: " << result << endl;

}

Result of the above program:

The result is: 20

Let us understand the above program in detail:

  • Line 1 thru 2:
    This is a multiline comment. We have used it to describe the purpose of the program which is a very good programming practice
  • Line 4:
    This is a single line command.
    Note: Comments are ignored by the compilers
  • Line 5 thru 7:
    These are the header files that needs to be included in order to run the program successfully. These header files contains components/supporting components/functions needed by the inbuilt functions like cout, cin etc. for its execution.
    #include is known as pre-processor directives. It tell the compiler to include text from another file, stuffing it right into your source code. The whole statement #include tells the compiler to take text from the file iostream.h and stick it into your source code before the source code is compiled.
  • Line 10:
    This is the main function of the program. The program execution starts from this function. The statement that belongs to main() are enclosed within a pair of braces {}
  • Line 12:
    This line declares the integer variables to be used in the program. Any variable that we need to use must be declared before using it
  • Line 15 thru 16:
    These two lines of code have been used to assign a value to the variables declared in the line 12
  • Line 21
    Here, values stored in the variables named variable1 and variable2 are multiplied and the result is stored in the variable named result
  • Line 24:
    This line uses inbuilt function “cout” to display the result of the multiplication in a specified format. “endl” is an inbuilt function that ends the current line and takes the cursor to the next line.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *