Customizable training materials to learn C++

Nano teach C++ found result for your search here:

C++ Tutorial

This tutorial series will help you to get started in C++ to develop system applications.

 














C++ Example:
/* 
* File: main.cpp
* Author: Nano
* Just click image to copy & paste
*/ 




#include <iostream>
int main() {
std::cout<<"This is my first c++ Program.";
std::cout<<std::endl<<"and its very easy"; 
}
Read More »

C++ Introduction

C++ is a multi-paradigm programming language that supports object oriented programming (OOP), created by BJarne Stroustrup in 1983 at Bell Labs, C++ is an extension (superset) of C programming and the programs written in C language can run in C++ compilers.
The development of C++ actually began four years before its release, in 1979. It did not start out with the name C++; its first name was C with Classes. In the late part of 1983, C with Classes was first used for AT&T’s internal programming needs. Its name was changed to C++ later in the same year. C++ was not released commercially until the late part of 1985.
C++ implements “data abstraction” using a concept called “classes“, along with other features to allow object-oriented programming and is considered a high level language. Classes help programmers with the organization of their code. They can also be beneficial in helping programmers to avoid mistakes.
The original C++ compiler, called Cfront, was written in the C++ programming language. C++ compilation is considered efficient and fast. Its speed can be attributed to its high-level features in conjunction with its low-level components. When compared to other computer programming languages, C++ can be viewed as quite short. This is due to the fact that C++ leans towards the use of special characters instead of keywords.


Uses of C++ language

C++ is used by programmers to create computer software. It is used to create general systems software, drivers for various computer devices, software for servers and software for specific applications and also widely used in the creation of video games.

Object-oriented Programming

C++ completely supports object-oriented programming, with four pillars of object-oriented development:
  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

Standard Libraries

Standard C++ consists of three important parts:
  1. All the building blocks including variables, data types and literals etc is provided by the core language.
  2. The C++ Standard Library is provides rich set of functions manipulating files and strings.
  3. The (STL) Standard Template Library provides a rich set of methods manipulating data structures.
Read More »

C++ Installation


To start learning C++ programming, you only need to install the C++ compiler in your System.

What is a Compiler?

A compiler is a computer program that transforms human readable (programming language) source code into another computer language (binary) code.
This tutorial is written for Windows, Unix / Linux and MAC users. All code has been tested and it works correctly on all three operating systems.

C++ Compiler Installation on Windows

To use C++ compiler in Windows, you can install any one software mentioned below.

C++ Compiler Installation on UNIX/Linux

If you are using UNIX / Linux, then most probably C++ compiler called GCC will already in your system. To check if you have it installed, you can type cc or gcc at command prompt.
$ gcc -v
If for some reason it is not Installed on your system, you can download it from gcc.gnu.org/install.

C++ Compiler Installation on MAC

You can install Xcode development environment from Apple’s website, to use GNU C/C++ compiler.
You can download Xcode from developer.apple.com/technologies/tools.
Read More »

C++ Program Structure

This tutorial will explain you about the C++ program structure.
Basically a C++ program involves the following section.
  • Documentations
  • Preprocessor Statements
  • Global Declarations
  • The main() function
    • Local Declarations
    • Program Statements & Expressions
  • User Defined Functions

Here is a simple program which outputs a line of text.

Example:


/* 
* File: main.cpp
* Author: Gautam
* Created on October 16, 2011, 4:09 PM
*/ 

    #include <iostream>

    int main() {
    
    std::cout<<"This is my first c++ Program.";
    std::cout<<std::endl<<"and its very easy"; 

    }
Program Output:
This is my first c++ Program.
and its very easy

Let’s look into various parts of the above C++ program.

/* Comments */ Comments are a way of explaining what makes a program. Comments are ignored by the compiler and used by others to understand the code.
#include<iostream> is a preprocessor directive. It tells the preprocessor to include the contents of iostream header file in the program before compilation. This file is required for input output statements.
int/void main() int/void is a return value, which will be explained in a while.
main() The main() is the main function where program execution begins. Every C++ program should contain only one main function.
Braces Two curly brackets “{…}” are used to group all statements together.

std::cout<<”This is my first c++ Program”;

The above line is a statement in C++. A statement must always terminate with a semicolon (;) otherwise it causes a syntax error. This statement introduces two new features of C++ language, cout and << operator.
You will also notice that the words are inside inverted commas because they are what is called a string. Each letter is called a character and a series of characters that is grouped together is called a string. Strings must always be put between inverted commas.
We used std:: before cout. This is required when we use #include <iostream> .
It specifies that we are using a name (cout) which belongs to namespace std. Namespace is a new concept introduced by ANSI C++ which defines the scope of identifiers which are used in the program. std is the namespace where C++ standard libraries are defined.
Operator << is the insertion stream operator. It sends contents of variable on its right to the object on its left. In our case, right operand is the string “This is my first c++ Program” and left operand is cout object. So it sends the string to the cout object and cout object then displays it on the output screen.

namespace

using namespace std;

If you specify using namespace std then you don’t have to put std:: throughout your code. The program will know to look in the std library to find the object. Namespace std contains all the classes, objects and functions of the standard C++ library.
Example:


/* 
* File: main.cpp
* Author: Gautam
* Created on October 16, 2011, 4:09 PM
*/   

    #include <iostream>
    using namespace std; 

    int main() {  
     
    cout<<"This is my first c++ Program.";
    cout<<endl<<"and its very easy";
    
    }

Return Statement

return 0 At the end of the main function returns value 0.
Read More »

C++ Manipulators

Manipulators are operators used in C++ for formatting output. The data is manipulated by the programmer’s choice of display.

Some of the more commonly used manipulators are provided here below:

endl Manipulator

endl is the line feed operator in C++. It acts as a stream manipulator whose purpose is to feed the whole line and then point the cursor to the beginning of the next line. We can use \n (\n is an escape sequence) instead of endl for the same purpose.

setw Manipulator

This manipulator sets the minimum field width on output.
Syntax:
setw(x)
Example:
/* 
* File: main.cpp
* Author: Gautam
* Created on October 16, 2011, 12:58 PM
*/
#include <iostream>
#include <iomanip>
using namespace std;

int main() {

 float basic, ta,da,gs;
 basic=10000; ta=800; da=5000;
  gs=basic+ta+da;
  cout<<setw(10)<<"Basic"<<setw(10)<<basic<<endl
   <<setw(10)<<"TA"<<setw(10)<<ta<<endl
   <<setw(10)<<"DA"<<setw(10)<<da<<endl
   <<setw(10)<<"GS"<<setw(10)<<gs<<endl;
  return 0;
}
Program Output:
Basic 10000
TA 800
DA 5000
GS 6800

setfill Manipulator

This is used after setw manipulator. If a value does not entirely fill a field, then the character specified in the setfill argument of the manipulator is used for filling the fields.
Example:
/* 
* File: main.cpp
* Author: Gautam
* Created on October 16, 2011, 12:58 PM
*/
#include <iostream>
#include <iomanip>
using namespace std;

int main() {

 cout << setw(20) << setfill('*') << "w3schools.in" << setw(20) << setfill('*')<<"Test"<< endl;
}
Program Output:
********w3schools.in******************Test
Read More »

C++ Data Types

Data types in any of the language means that what are the various type of data the variables can have in that particular language. Information is stored in a computer memory with different data types. Whenever a variable is declared it becomes necessary to define data type that what will be the type of data that variable can hold.

Data Types available in C++ are:

  1. Primary Data Type character, integer, floating point, boolean, double floating point, void, wide character
  2. Additional Data Types typedef, enumerated

Character Data Types

Data Type (Keywords) Description Size Typical Range
char Any single character. It may include a letter, a digit, a punctuation mark, or a space. 1 byte -128 to 127 or 0 to 255
signed char Signed character. 1 byte -128 to 127
unsigned char Unsigned character. 1 byte 0 to 255
wchar_t Wide character. 2 or 4 bytes 1 wide character

Integer Data Types

Data Type (Keywords) Description Size Typical Range
int Integer. 4 bytes -2147483648 to 2147483647
signed int Signed integer. Values may be negative, positive, or zero. 4 bytes -2147483648 to 2147483647
unsigned int Unsigned integer. Values are always positive or zero. Never negative. 4 bytes 0 to 4294967295
short Short integer. 2 bytes -32768 to 32767
signed short Signed short integer. Values may be negative, positive, or zero. 2 bytes -32768 to 32767
unsigned short Unsigned short integer. Values are always positive or zero. Never negative. 2 bytes 0 to 65535
long Long integer. 4 bytes -2147483648 to 2147483647
signed long Signed long integer. Values may be negative, positive, or zero. 4 bytes -2147483648 to 2147483647
unsigned long Unsigned long integer. Values are always positive or zero. Never negative. 4 bytes 0 to 4294967295

Floating-point Data Types

Data Type (Keywords) Description Size Typical Range
float Floating point number. There is no fixed number of digits before or after the decimal point. 4 bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number. More accurate compared to float. 8 bytes +/- 1.7e +/- 308 (~15 digits)
long double Long double precision floating point number. 8 bytes +/- 1.7e +/- 308 (~15 digits)

Boolean Data Type

Data Type (Keywords) Description Size Typical Range
bool Boolean value. It can only take one of two values: true or false. 1 byte true or false
Note: Variables sizes might be different in your pc from those shown in the above table, depending on the compiler you are using.
Below example will produce correct size of various data type, on your computer.
Example:
#include <iostream>

    using namespace std;
    
    int main()
    {    
      cout << "Size of char is " << sizeof(char) << endl;
      cout << "Size of int is " << sizeof(int) << endl;
      cout << "Size of float is " << sizeof(float) << endl;
      cout << "Size of short int is " << sizeof(short int) << endl;
      cout << "Size of long int is " << sizeof(long int) << endl;
      cout << "Size of double is " << sizeof(double) << endl;
      cout << "Size of wchar_t is " << sizeof(wchar_t) << endl;
      return 0;
    }
Program Output:
Size of char is 1
Size of int is 4
Size of float is 4
Size of short int is 2
Size of long int is 4
Size of double is 8
Size of wchar_t is 4

Enum Data Type

This is an user defined data type having finite set of enumeration constants. The keyword ‘enum‘ is used to create enumerated data type.
Syntax:
enum enum-name {list of names}var-list;
enum mca(software, internet, seo);

Typedef

It is used to create new data type. But it is commonly used to change existing data type with another name.
Syntax:
typedef [data_type] synonym;
 or
typedef [data_type] new_data_type;
Example:
typedef int integer;
integer rollno;
Read More »

C++ Variables

In C++ Programming language variable is used to store data in memory location.

Rules of Declaring variables in C++

  • Variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and the underscore character.
  • The first character must be a letter or underscore.
  • Blank spaces cannot be used in variable names.
  • Special characters like #, $ are not allowed.
  • C++ keywords can not be used as variable names.
  • Variable names are case sensitive.
  • A variable name can be consist of 31 characters only if we declare a variable more than 1 characters compiler will ignore after 31 characters.

Variable Definition in C++

Syntax:
type variable_name;
type variable_name, variable_name, variable_name;
Example:
/* variable definition and initialization */
int    width, height=5;
char   letter='A';
float  age, area;
double d;

/* actual initialization */
width = 10;
age = 26.5;
Read More »

C++ Keywords

The C + + Keywords must be in your information because you can not use them as variable name.

C++ Keywords List

You can’t use below mentioned keyword as identifier in your C++ programs.
asm else new this
auto enum operator throw
bool explicit private true
break export protected try
case extern public typedef
catch false register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template

In addition, the following words are also reserved

And bitor not_eq xor
and_eq compl or xor_eq
bitand not or_eq
You should also try to avoid using names from the C++ library, e.g. swap, max.
Read More »

C++ Objects and Classes

In object-oriented programming languages like C++, the data and functions (procedures to manipulate the data) are bundled together as a self-contained unit called an object. A class is an extended concept similar to that of structure in C programming language; this class describes the data properties alone. In C++ programming language, class describes both the properties (data) and behaviors (functions) of objects. Classes are not objects, but they are used to instantiate objects.

What is a class ?

  • A class is an abstract data type similar to ‘C‘ structure.
  • Class representation of objects and the sets of operations that can be applied to such objects.
  • Class consists of Data members and methods.
Primary purpose of a class is to held data/information. This is achieved with
attributes which is also know as data members.
The member functions determine the behavior of the class i.e. provide
definition for supporting various operations on data held in form of an
object.

Definition of a class

Syntax:
Class class_name
{
    Data Members;
    Methods;
}
Example:
class A
{
    public:
    double length; // Length of a box
    double breadth; // Breadth of a box
    double height; // Height of a box 
}
  • Private, Protected, Public are called visibility labels.
  • The members that are declared private can be accessed only from within the class.
  • Public members can be accessed from outside the class also.
  • In C++, data can be hidden by making it private.
  • Encapsulation is thus achieved.

Class Members

Data and functions are members.
Data Members and methods must be declared within the class definition.
Example:
Class A
{
    int i; // i is a data member of class A
    int j; // j is a data member of class A
    int i; // Error redefinition of i 
}
  • A member cannot be redeclare within a class.
  • No member can be added elsewhere other than in the class definition.
Example:
Class A
{
    int i;
    int j;
    void f (int, int);
    int g(); 
}
f‘ and ‘g‘ are member function of class A. They determine the behavior of the objects of the class A.

Accessing the Data Members

The public data members of objects of a class can be accessed using the direct member access operator (.). Let us try following example to make the things clear:
Example:
#include <iostream> 
using namespace std;

class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
}

int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 4.0; 
Box1.length = 6.0; 
Box1.breadth = 3.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 12.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl; 

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
Program Output:
Volume of Box1 : 72
Volume of Box2 : 1440
It is important to note that private and protected members can not be accessed directly using direct member access operator (.). We will learn how private and protected members can be accessed.

Program to enter students details and display it

Example:
#include<iostream>
using namespace std;

class stud 
{
    public:
    char name[30],clas[10];
    int rol,age;
    float per;

void enter() 
{
    cout<<"\n Enter Student Name, Age, Roll number";     cin>>name>>age>>rol;
    cout<<"\n Enter Student Class and percentage in previous class";     cin>>clas>>per; 
}

void display() 
{
    cout<<"\n Age\tName\tR.No.\tClass\t%ge";
    cout<<"\n"<<age<<"\t"<<name<<"\t"<<rol<<"\t"<<clas<<"\t"<<per<<"%"; 
}
}

int main()
{
    class stud s;
    s.enter();
    s.display();
    cin.get(); //use this to wait for a keypress 
} 
Program Output:

Read More »

C++ Inheritance

One of the most important concepts in object-oriented programming is that of inheritance. Inheritance is a mechanism of reusing and extending existing classes without modifying them, thus producing hierarchical relationships between them and provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

Forms of Inheritance

  • Single Inheritance – If a class is derived from a single base class, it is called as single inheritance.
  • Multiple Inheritance – If a class is derived from more than one base class, it is known as multiple inheritance.
  • Multilevel Inheritance – The classes can also be derived from the classes that are already derived. This type of inheritance is called multilevel inheritance.
  • Hierarchical Inheritance – If a number of classes are derived from a single base class, it is called as hierarchical inheritance.
  • Hybrid Inheritance – This is a Mixture of two or More Inheritance and in this Inheritance a Code May Contains two or Three types of inheritance in Single Code.

Visibility Mode

It is the keyword that controls the visibility and availability of inherited base class members in the derived class. It can be either private or protected or public.
  • Private Inheritance – When deriving from a private base class, public and protected members of the base class become private members of the derived class.
  • Public Inheritance – When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class’s private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
  • Protected Inheritance – When deriving from a protected base class, public and protected members of the base class become protected members of the derived class.
Base class visibility Derived class visibility
Public derivation Private derivation Protected derivation
Private Not inherited Not inherited Not inherited
Protected Protected Private Protected
Public Public Private Protected
Read More »

C++ Friend Function

In C++ a function or an entire class may be declared to be a friend of another class or function. Friend function can also be used for function overloading.
Friend function declaration can appear anywhere in the class. But a good practice would be where the class ends. An ordinary function that is not the member function of a class has no privilege to access the private data members, but the friend function does have the capability to access any private data members. The declaration of the friend function is very simple. The keyword friend in the class prototype inside the class definition precedes it.

Example to Demonstrate working of friend Function

/* C++ program to demonstrate the working of friend function.*/
#include <iostream>
using namespace std; 

class Distance {
    private:
        int meter; 
    public:
        Distance(): meter(0){ }
        friend int func(Distance); //friend function 
};

int func(Distance d){
    //function definition
    d.meter=10; //accessing private data from non-member function
    return d.meter; 
}

int main(){ Distance D;
    cout<<"Distace: "<<func(D);
    system("pause"); 
    return 0;
}
Program Output:
Distance: 10
Here, friend function func() is declared inside Distance class. So, the private data can be accessed from this function. Though this example gives you what idea about the concept of friend function.
In C++, friend means to give permission to a class or function. The non-member function has to grant an access to update or access the class.
The advantage of encapsulation and data hiding is that a non-member function of the class cannot access a member data of that class. Care must be taken using friend function because it breaks the natural encapsulation, which is one of the advantages of object oriented programming. It is best used in the operator overloading.
Read More »

C++ Loops, Creating a Pyramid

C++ program to create a pyramid using for loop and if condition.
Example:
#include<iostream>
using namespace std;

int main()
{
   int i,j,k,space=10; // to print the pyramid in center, you can also increase the # of spaces
   
for (int i=0;i<=5;i++)
{
   for (int k=0;k<space;k++)
{
   cout<<" ";
}
for (int j=0;j<2*i-1;j++)
{
   cout<<"*";
}
   space--;
   cout<<endl;
}
cin.get(); /*use this to wait for a keypress*/

} 
 















Program Output:
         *
        ***
       *****
      *******
     *********
Read More »

C++ Program to find Perfect Number

Perfect number is a positive number which sum of all positive divisors excluding that number.
For example: 6 is Perfect Number since divisor of 6 are 1, 2 and 3. Sum of its divisor is
1 + 2+ 3 =6
and 28 is also a Perfect Number
since 1+ 2 + 4 + 7 + 14= 28
Other perfect numbers: 496, 8128
Example:
#include<iostream> 
#include<cctype>
using namespace std; 

int main(){
    int n,i=1,sum=0;
    cout << "Enter a number: ";
    cin >> n;
       while(i<n){
       if(n%i==0)
       sum=sum+i;
       i++; 
}
 
if(sum==n)
    cout << i << " is a perfect number\n"; 
else
    cout << i << " is not a perfect number\n";
    system("pause"); 

return 0;

}
Program Output:
6 is a perfect number
15 is not a perfect number
28 is a perfect number
496 is a perfect number
Read More »

C++ Compute the Sum and Average of Two Numbers

This program takes in two integers x and y as a screen input from the user.
The sum and average of these two integers are calculated and outputted using the ‘cout’ command.
Example:
#include<iostream>
using namespace std; 

int main(){ 

    int x,y,sum;
    float average;
    cout << "Enter 2 integers : " << endl;
    cin>>x>>y;
    sum=x+y;
    average=sum/2;
    cout << "The sum of " << x << " and " << y << " is " << sum << "." << endl;
    cout << "The average of " << x << " and " << y << " is " << average << "." << endl;
    system("pause");

}
Program Output:
Enter 2 integers :
12
15
The sum of 12 and 15 is 27.
The average of 12 and 15 is 13.
Read More »

C++ Program to find Prime Number

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Example:
#include<iostream>
#include<math.h> //sqrt function used

using namespace std;

int main(){
// Variable Declaration 
int n;

// Get Input Value
 cout<<"Enter the Number : ";
 cin>>n;

cout <<"List Of Prime Numbers Below "<<n<<endl;

//for Loop Block For Find Prime Number 

for (int i=2; i<n; i++)
 for (int j=2; j*j<=i; j++)
 {
    if (i % j == 0)
    break;
    else if (j+1 > sqrt(i)) {
    cout << i << endl;
 }
} 

// Wait For Output Screen
 system("pause");
 return 0;
}
Program Output:
Enter the Number : 50
List Of Prime Numbers Below 50
5
7
11
13
17
19
23
29
31
37
41
43
47
Read More »

C++ Program to demonstrate the use of Ternary Operator

The conditional operator can often be used instead of the if else statement. Since it is the only operator that requires three operands in c++, It is also called the ternary operator.
X = Y > 5 ? 4 : 8;
If Y is greater than 5 then 4 will be assigned to variable X or else the value 8 will be assigned to X.
Example:
#include<iostream>
#include<iomanip> 
using namespace std;

int main (){

    int first, second;

    cout << "Please enter two integers." << endl;

    cout << "First" << setw (3) << ": ";
    cin >> first;

    cout << "Second" << setw (2) << ": ";
    cin >> second;

    string message = first > second ? "first is greater than second" : "first is less than or equal to second";

    cout << message << endl;
    system("pause");
    return 0; 

}
or
string message = first > second ? "first is greater than second" :
first < second ? "first is less than second" : "first and second are equal";
Read More »