C++ (ISO)
Sure! Here is an example that demonstrates the use of the C++ programming language:
#include <iostream>
int main() {
int num1, num2, sum;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
sum = num1 + num2;
std::cout << "The sum is: " << sum << std::endl;
return 0;
}
Explanation:
Step 1:
The first line #include <iostream>
is a preprocessor directive that tells the compiler to include the iostream
header file. This file contains the necessary functions for input and output operations.
Step 2:
The main()
function is the entry point of the program. It is where the execution of the program starts. In this example, the main()
function is defined with a return type of int
to indicate that it returns an integer value.
Step 3:
Inside the main()
function, three integer variables num1
, num2
, and sum
are declared. These variables will be used to store the user input and the sum of the two numbers.
Step 4:
The std::cout
statement is used to display the text "Enter two numbers: " on the console. std::cout
is an object of the std::ostream
class that represents the standard output stream. The <<
operator is used to insert the text into the output stream.
Step 5:
The std::cin
statement is used to read the user input from the console. std::cin
is an object of the std::istream
class that represents the standard input stream. The >>
operator is used to extract the input from the stream and store it in the variables num1
and num2
.
Step 6:
The next line calculates the sum of num1
and num2
and assigns it to the sum
variable.
Step 7:
The std::cout
statement is used to display the text "The sum is: " followed by the value of sum
on the console.
Step 8:
The std::endl
manipulator is used to insert a new line character into the output stream. This is done to ensure that the output is displayed on a new line.
Step 9:
The return 0;
statement is used to indicate the successful execution of the program. The value 0
is returned to the operating system to indicate that the program terminated successfully.
This is a simple example that demonstrates the basic structure and syntax of a C++ program. It takes two numbers as input from the user, calculates their sum, and displays the result on the console.