4 - A C++Program
4 - A C++Program
1
The Basics of a C++ Program
A C++ program is a collection of functions, one of which is the function
main.
A function is a set of statements whose objective is to accomplish
something.
Some functions, called predefined or standard functions, are already
written and provided as part of the system.
But to accomplish most tasks, programmers must learn to write their own
functions.
if a C++ program has only one function, it must be the function main.
The function in C++ are 2 types:
1) pre-defined function in C++ compiler.
2)user-defined function by programmer.
2
Output console
Input
console
Programming language: A set of rules, symbols, and special words.
Many of the functions and symbols needed to run a C++ program are provided as a
collection of libraries.
Every library has a name and is referred to by a header file.
Preprocessor directives are processed by a program called a preprocessor .
All preprocessor commands begin with #.
3
Preprocessor Directives (cont’d.)
• For example:
#include <iostream>
– Causes the preprocessor to include the header file
iostream in the program
• Preprocessor commands are processed before the
program goes through the compiler
4
The tracing for any C++ program starts always from main function (starting
point of a C++ program).
cout: >>
it is an object used to print on monitor
console out .
>> : angular brackets is called the insertion operator.
cout is used together with the insertion operator.
endl causes the insertion point to move to the beginning of the next line.
7
A C++ Program
Example:
#include <iostream>
using namespace std;
int main()
{
cout << "My first C++ program." << endl;
cout << "The sum of 2 and 3 = " << 5 << endl;
cout << "7 + 8 = " << 7 + 8 << endl;
return 0;
}
Sample Run:
My first C++ program.
The sum of 2 and 3 = 5
7 + 8 = 15
8
Output (cont’d.)
9
Output (cont’d.)
10
Output (cont’d.)
11
How to get data from keyboard:
program performs three basic operations: it gets data, it
manipulates the data, and it outputs the results.
The syntax of an input statement using cin and the
extraction operator >> is:
for one variable: cin >> variable ;
12
The Basics of a C++ Program
Comments are for the user; they typically explain the purpose of the
programs, Single-line comments begin with // and can be placed anywhere
in the line. Everything encountered in that line after // is ignored by the
compiler
/* You can include comments that can occupy several lines */
13
EX.: #include <iostream>
using namespace std;
int main()
{ // cout<<"hello"<<endl;
return 0;
}
14