C++ Program structure
A basic C++ program demonstrates the essential structure of the language, utilizing input/output streams and the primary execution function, main().
Basic C++ Program Example
The following program reads two numbers from the keyboard and calculates their average.
Program: Average of Two Numbers
#include <iostream>
using namespace std;
int main()
{
float numberl, number2, sum, average;
cout << "Enter two numbers: "; // prompt
cin >> numberl; // Reads numbers
cin >> number2; // from keyboard
sum = numberl + number2;
average = sum/2;
cout << "Sum = " << sum << "\n";
cout << "Average = " << average << "\n";
return 0;
}
Output of Program (Example Run):
Enter two numbers: 6.5 7.5
Sum = 14
Average = 7
Explanation of Program Features
This program illustrates several core components and structural elements of C++:
| Feature | Explanation |
| Header Inclusion | The line #include <iostream> is a pre-processor directive that inserts the contents of the iostream file into the program,. This file contains declarations for stream objects like cout and cin and is necessary for input/output operations,. |
| Namespace Directive | The statement using namespace std; must be included in all ANSI C++ programs,. It specifies that identifiers defined in the standard namespace (std), including cin and cout, are accessible in the program's global scope. |
main() Function | Execution of every C++ program begins at main(),. In C++, main() returns an integer value (implicitly or explicitly via int main()) to the operating system, with return 0; typically signaling successful execution,,. |
| Variable Declaration | The line float numberl, number2, sum, average; declares four variables of type float. In C++, variables generally must be declared before they are used in the program, though declarations can occur anywhere in the scope, even right before their first use. |
Output Operator (cout and <<) | The object cout represents the standard output stream (usually the screen). The operator << is the insertion or put to operator, which sends the contents of the right operand (e.g., a string literal or a variable value) to the stream object on its left. |
Input Operator (cin and >>) | The object cin corresponds to the standard input stream (usually the keyboard). The operator >> is the extraction or get from operator, which takes a value from the stream and assigns it to the variable on its right. |
| Cascading I/O | The multiple use of the << operator in one statement (e.g., cout << "Sum = " << sum << "\n";) is called cascading. This technique is used for inserting or extracting multiple items sequentially. |
The structure demonstrated here aligns with the overall C++ program structure, which typically includes pre-processor directives, class declarations (if used), function definitions, and the main() function,.