The files you create with your editor are called source files, and for C++ they typically are named with the extension .cpp, .cp, or .c.
We'll name all the source code files with the .CPP extension for these work, but check your compiler for what it needs.
NOTE: Most C++ compilers don't care what extension you give your source code, but if you don't specify otherwise, many will use .CPP by default.
My first program to display welcome to C++
// My first program in C++ with inline commenting.
/* My first program in C++ with block commenting */
#include <iostream>
using namespace std;
int main ()
{ cout <<"(1)Friends You Are Welcome To C++ Programming, Have Fun!!"<<endl;
cout <<"(2)Friends\nU Are Welcome To\nC++ Programming, Have Fun!!\n";
system("pause");
return 0;
}
BUILD AND RUN:
(1)Friends You Are Welcome To C++ Programming, Have Fun!!
(2)Friends
U Are Welcome To
C++ Programming,
Have Fun!!
Press any key to continue . . .
The above program is the source code for our first program. The below build and run shows the result of the program once compiled and executed using Microsoft visual studio C++ IDE. It is one of the simplest programs that can be written in C++ which contains the fundamental components for every C++ program. We shall discuss the line by line.
// My first program in C++ with inline commenting.
This is a comment line with inline. All lines beginning with two slash signs (//) are considered comments and do not have any effect on the behavior of the program. The programmer can use them to include short explanations or observations within the source code itself.
/* My first program
in C++ with block commenting */
This is the same comment as the first line but it is in a block format.
#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with expressions but indications for the compiler's preprocessor.
In this case the directive #include <iostream> is a collection precompiled C++ code that C++ programs (like ours) can use to tell the preprocessor to include the iostream standard file.
This specific file (iostream) includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is going to be used later in the program.
We include the file because the compiler needs to be aware of these iostream items so it can compile our program.
The #include directive specifies a file, called a header, that contains the specifications for the library code. The compiler checks how we use cout and endl within our code against the specifications in the <iostream> header to ensure that we are using the library code correctly.
Most of the programs we write use this #include <iostream> directive, and some programs we will write in the future will #include other headers as well.
using namespace std;
It is not mostly ethical to use namespace but for the sake of beginners it will be used. All the elements of the standard C++ library are declared within what is called a namespace, the namespace with the name std. So in order to access its functionality we declare with this expression that we will be using these entities. using namespace std;
The two items our program needs to display a message on the screen, cout and endl, have longer names: std::cout and std::endl. This using namespace std directive allows us to omit the std:: prefix and use their shorter names. This directive is optional, but if we omit it, we must use the longer names. The name std stands for “standard,” and the using namespace std line indicates that some of the names we use in our program are part of the so-called “standard namespace.”
int main ()
This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start and ends their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it. The instructions contained within this function's definition will always be the first ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function. The word main is followed in the code by a pair of parentheses (()). That is because it is a function declaration: In C++, what differentiates a function declaration from other types of expressions are these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within them. Right after these parentheses we can find the body of the main function enclosed in braces ({}). What is contained within these braces is what the function does when it is executed.
cout <<"(1) Friends You Are Welcome To C++ Programming, Have Fun!!"<<endl; This line is a C++ statement. cout represents the standard output stream in C++, and the meaning of the entire statement is to insert a sequence of characters (in this case the (1)Friends You Are Welcome To C++ Programming, Have Fun!! sequence of characters) into the standard output stream (which usually is the screen).
cout is declared in the iostream standard file within the std namespace, so that's why we needed to include that specific file and to declare that we were going to use this specific namespace earlier in our code. Notice that the statement ends with a semicolon character (;). This character is used to mark the end of every statements in C++ programs (one of the most common syntax errors is indeed to forget to include some semicolon after a statement).
Note: namepase std; can also be ignored by directly using std::ClassName for any family in the namespace standard. <<endl will direct the program to move to the next line which does the same thing in \n (meaning go to newline) in cout <<"(2)Friends\nU Are Welcome To\nC++ Programming, Have Fun!!\n". The division of code in different lines serves only to make it more legible and schematic for the humans that may read it.
NOTE: The compiler does not recognize spacing.
system("pause")
These will make my program to be steady during execution time, although is specifically for my compiler.
return 0
The return statement causes the main function to finish. It may be followed by a return code (in our example is followed by the return code 0). A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution. This is the most usual way to end a C++ console program.
//Example 1: A program to demonstrate assignment, increment and decrement for looping structures.
#include <iostream>
int main ()
int main ()
{
int x = 10;
// Original value of x.
std::cout <<"The original value of x is " <<x <<"\n\n";
int x1 =10;// Increament
std::cout <<"The value of x++ is now " << x1++ <<std::endl;
int x2 =10;
std::cout <<"The value of ++x is now " << ++x2 <<"\n\n";
int x3 = 10;//Decrement std::cout <<"The value of --x is now " << --x3 <<std::endl;
int x4 = 10;
std::cout <<"The value of x-- is now " << x4-- <<"\n\n";
system("pause");
return 0;
}
BUILD AND RUN:
The original value of x is 10
The value of x++ is now 10
The value of ++x is now 11
The value of --x is now 9
The value of x-- is now 10
Press any key to continue . . . //***************************************************************** ******************************************************************* ******************//
The solutions in computer programs reads code downwards from top and left to right hand side. This is applicable in the demonstration of the principles in decrement and increment of looping structures. The focus point is “terminate on encountering x”
In the initial output value, x value remain the same as 10. It was hence maintain 10 in the x++ because the value is 10 when read from left to right without continuation to the next looping level, it then automatically terminate to produce 10. Moreover, ++x will run once by adding 1 to the value of x when moving from left to right, on approaching x value will terminate.
However, --x will subtract 1 and terminate on x, while x-- will remain 10 when the program is to run once but on regular looping will then subtract 1 from x value before the next loop.
// A program to calculate the sum of two numbers entered from the keyboard.
#include <iostream>
using namespace std;
using namespace std;
int main(){
int num1, num2, sum;
cout <<"Enter the first number: \n";
cin>> num1;
cout <<"Enter the second number: \n";
cin>> num2;
sum = num1 + num2;
cout <<"The summation of " <<num1 <<" and " <<num2;
cout <<" = " <<sum <<endl;
return 0;
}
COMPILED AND RUN:
Enter the first number:
4
Enter the second number:
7
The summation of 4 and 7 = 11
Press any key to continue . . . //***************************************************************** *****************************************************************//
//Example 1: A program to calculate the factorial of number entered from the standard keyboard.
#include <iostream>
/*...... this is called inline commenting. When importing "Using namespace std;" will help the direct usage of cout/cin/endl */
int main()
{
int Number;// declaration
std::cout << "Enter a positive integer to compute factorial: " <<std::endl;
std::cin >> Number; //Reading number from Keyboard
if (Number == 0) {
// open of 1st If statement
std::cout << "The factorial = 1" <<std::endl;
} //close of 1st If statement
else // second option
{ int test = 0, factorialNum = 1;
while (Number > test)// while loop
{
factorialNum = (factorialNum * (Number-test));
test++;// dsame as test = test + 1;
}
std::cout << "The factorial = " <<factorialNum <<std::endl;
}// end else statement
system("pause");
return 0;
}// end main function/method
COMPILED AND RUN:
Enter a positive integer to compute factorial:
5
The factorial = 120
Press any key to continue . . .
Enter a positive integer to compute factorial:
0
The factorial = 1
Press any key to continue . . .
COMPILED AND RUN: //***************************************************************** *****************************************************************//
Example
A program to calculate the velocity and height of a body in Earth and Mars respectively*/
#include <iostream>
#include<String>
using namespace std;
int main ()
{
string type;
double velocity, time;
double g_earth = 9.81;
double g_mars = 3.63;
double velocity_t, height_t;
cout<<"Enter Mars or Earth to calculate velocity and height\n";
cout <<"of body in Mars or Earth respectively\n\n";
cin >> type;
cout <<"\nYou have selected:- " <<type<<endl;
cout <<"\nYou have selected:- " <<type<<endl;
cout<<"\nPlease enter initial velocity (m/s) and time (s) respectively:\n\n";
cin >> velocity; cin >> time;
if (type == "Earth")
{
velocity_t = velocity - (g_earth * time);
height_t = velocity - ((g_earth * time*time)/(2));
cout << "The final velocity of this body on Earth = "<< velocity_t <<"m/s\n";
cout << "The height of this body on Earth = "<< height_t <<"m\n\n";
}
else if (type == "Mars")
{
velocity_t = velocity - (g_mars * time);
height_t = velocity - ((g_mars * time*time)/(2));
cout << "The final velocity of this body on Mars = "<< velocity_t <<"m/s\n";
cout << "The height of this body on Mars = "<< height_t <<"m\n\n";
}
else
{
cout<<"There is no result for "<<type<<" selection ";
cout <<"please click F5 and try again \n\n";
}
system("pause");
return 0;
}
Example:
//A program to calculate the mean and standard deviation
//of the ages of student beneficiaries
#include <iostream>
#include <string>
using namespace std;
int main ()
{
float total = 0;
float deviation = 0;
float standard_deviation;
float Mean, studentAge;
int counter;
string studentName;
string title;
cout << "Enter the amount of student that qualify for the grant: ";
cin>> counter;
for (int j=1; j<= counter; j++)
{
cout <<"\nEnter the beneficiaries’ age: ";
cin >> studentAge;
total +=studentAge;
Mean = total/counter;
}
cout << "\nRe-enter the above "<<counter;
cout <<" Students Age to compute its STANDARD DEVIATION: ";
for (int i=1; i<= counter; i++)
{
cout <<"\nEnter the beneficiaries’ age: ";
cin >> studentAge;
deviation += pow((studentAge - Mean), 2);
standard_deviation = sqrt (deviation/(counter));
}
cout << "\nTotal Age entered = " << total << endl;
cout << "\nThe mean (X2) student Age = " << Mean << endl;
cout <<"\nThe Student Age standard deviation = "<<standard_deviation<<"\n\n";
system("pause");
return 0;
}// End main function
BUILD AND RUN:
Enter the amount of student that qualify for the grant: 5
Enter the beneficiaries’ age: 22
Enter the beneficiaries’ age: 23
Enter the beneficiaries’ age: 24
Enter the beneficiaries’ age: 25
Enter the beneficiaries’ age: 27
Re-enter the above 5 Students Age to compute its STANDARD DEVIATION:
Enter the beneficiaries’ age: 27
Enter the beneficiaries’ age: 22
Enter the beneficiaries’ age: 24
Enter the beneficiaries’ age: 23
Enter the beneficiaries’ age: 25
Total Age entered = 121
Total Age entered = 121
The mean (X2) student Age = 24.2
The Student Age standard deviation = 1.72046
Press any key to continue . . . //***************************************************************** *****************************************************************//
BUILD AND RUN: Value
//***************************************************************** *****************************************************************//BUILD AND RUN: Value
//***************************************************************** *****************************************************************//// A program to demonstrate constant value
#include <iostream>
using namespace std;
int main ()
{
const double PI = 3.1456987;
cout <<PI;
cout <<"\n\n";
int x = 4;
cout <<x ;
cout <<"\n\n";
x= 4444.5555;
cout <<x ; cout <<"\n\n";
system("pause"); return 0;
system("pause"); return 0;
}// End main function
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double d1 = 2000.5;
double d2 = 2000.0;
cout << setprecision(16) << (d1 - d2) << endl;
double d3 = 2000.58;
double d4 = 2000.0;
cout << setprecision(16) << (d3 - d4) << endl;
}
The cin input stream object can assign values to multiple variables in one
statement,
as shown here:
int num1, num2, num3;
cin >> num1 >> num2 >> num3;
A common beginner’s mistake is use commas to separate the variables, as in
int num1, num2, num3;
cin >> num1, num2, num3;
The compiler will not generate an error message, because it is legal C++ code. The statement, however, will not assign the three variables from user input as desired.
The comma operator in C++ has different meanings in different contexts, and here it is treated like a statement separator; thus, the variables num2 and num3 are not involved with the cin input stream object. We will have no need to use the comma operator in this way, but you should be aware of this potential pitfall.
cin is a object that can be used to read input from the user. The >> operator—as used here in the context of the cin object—is known as the extraction operator. Notice that it is “backwards” from
the << operator used with the cout object. The cin object represents the input stream—information
flowing into the program from user input from the keyboard. The >> operator extracts the data from
the input stream cin and assigns the pieces of the data, in order, to the various variables on its right.