A simple C++ program
//************************************ // This program prints Hello World // Written by: George Bebis // Date: September 2, 1997 //************************************ #include <iostream.h> main() { cout << "Hello World" ; }
- Each line starting with // is a comment and is ignored by the compiler; its only use is to make the program more readable to humans and to record information (author, date, purpose)
- The line main() is where the C++ program begins execution and is required in every C++ program
- The braces { and } enclose the instructions to achieve the purpose of the program
- A sequence of instructions enclosed by a {} pair is called a block
- The cout statement along with the insertion operator (<<) instructs the computer to write the message enclosed within the double quotes on the screen (standard output device)
- The semicolon at the end of the cout statement delimits the end of the statement
- The line with the keyword include is for the C++ preprocessor (a program that acts as a filter during compilation) whose job is to provide some information to the compiler (in this case, information about cout)
A C++ program to add two numbers
Program revised - Getting input from the user
#include <iostream.h> main() { int x, y, sum; cout << "Give the first number "; cin >> x; // >> is called the extraction operator cout << "Give the second number "; cin >> y; sum=x+y; cout << "The sum is " << sum; }
Program revised - Using functions
- When compute_sum is called from main(), the values of x and y are copied to num1 and num2
- When compute_sum is done, the value of result is copied to sum
- This function is called a value-returning function because it returns a value to the main()
- There are functions which return more than one values and there are functions that return no values at all (i.e., they just execute a number of statements)