Here is a standard "Hello World" program, written in C++:
#include <iostream>
using std::cout;
using std::endl;
int main() {
cout << "Hello world!" << endl;
return 0;
}
When run, this program displays...you guessed it..."Hello World" to the standard output. (If you're running this program from the command line, standard output means the screen.)
main function is where your
program will start. Every executable program has to have a globally
defined main function in it somewhere. You cannot have
more than one main.Here's another little program that asks the user to enter two numbers and displays their sum:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
int number1 = 0;
int number2 = 0;
cout << "Enter a number: ";
cin >> number1;
cout << "Enter another number: ";
cin >> number2;
int result = number1 + number2;
cout << number1 << " + " << number2 << " = " << result << endl;
return 0;
}
cout and
cin are actually global instances (in the
std namespace) of the ostream
and istream
classes, respectively. These two objects, and their associated
classes, are part of the C++ Input and
Output Streams Library.
This next bit of code displays information about two numbers if their sum is even:
#include <iostream>
using std::cout;
using std::endl;
int main() {
for( int number1 = 0; number1 < 5; number1++ ) {
for( int number2 = 0; number2 < 5; number2++ ) {
// if the sum is even, print it out
if( (number1+number2) % 2 == 0 ) {
cout << number1 << " + " << number2 << " = "
<< (number1 + number2) << endl;
}
}
}
return 0;
}
To compile a program named myProg.cc with the GNU C++ compiler, type g++ -Wall
-Werror -o myProg myProg.cc. This command takes your C++ file,
named myProg.cc, compiles it, and creates an executable
named myProg. You should be able to run your
newly-created program by typing ./myProg on the command
line.
-Wall flag tells the compiler to
issue warnings about anything that it finds suspicious. The
-Werror flag tells the compiler to treat any warnings
that it encounters as errors, which means your code won't compile as
long as there are any warnings. Although they're not necessary, it's
generally considered good practice to use these two flags when
compiling code. Those compiler people are pretty smart; if they issue
warnings about your code, you should probably pay attention.