The do-while loop

The do-while loop

Its format is:

do statement while (condition);

Its practicality is strictly identical with the while loop, except that condition within the do-while loop is evaluated when the execution of statement rather than before, granting a minimum of one execution of statement even though condition is never concluded. For instance, the subsequent example program prints any number you enter till you enter zero.

// number print

#include <iostream>

using namespace std;

int main ()


unsigned long numbers;

do {

cout << “Enter number (0 to end): “;

cin >> numbers;

cout << “You entered: ” << numbers <<std::endl;

} while (numbers != 0);

return 0;



Enter number (0 to end): 12345

You entered: 12345

Enter number (0 to end): 160277

You entered: 160277

Enter number (0 to end): 0

You entered: 0

The do-while loop is typically used once the condition that has got to confirm the terminating condition value of the loop is decided among the loop statement itself, like within the previous case, wherever the user input inside the block is what’s used to determine if the loop has got to finish. In reality if you ne’er enter the value zero within the previous example you’ll be prompted for a lot of numbers forever.

PDF is available here The do while loop

The while loop

The while loop

Loops have as purpose to repeat a message up to an explicit range of times or whereas a condition is achieved.

Its format is:

while (expression) statement

and its practicality is solely to repeat statement whereas the condition set in expression is true. For example, we will create a program to count backward employing a while-loop:

// custom countdown using while

#include <iostream>

using namespace std;

int main ()


int num;

cout << “Enter the starting number > “;

cin >> num;

while (num>0) {

cout << num << “, “;



cout << “FIRE!”;

return 0;



Enter the starting number > 8

8, 7, 6, 5, 4, 3, 2, 1, FIRE!

When the program starts the user is prompted to a number to start the counting back. Then the while loop begins, if the value entered by the user fulfills the condition num>0 (that num is bigger than zero) the block that follows the condition will run and keep on executing until the condition (num>0) remains being true.

The whole method of the previous program are often taken in keeping with the subsequent script (beginning in main):

  1. User assigns a value to num
  2. The while condition is checked (num>0). At this time there 2 posibilities:

* condition is true: statement is executed (to step 3)

* condition is false: ignore statement and continue  (to step 5)

  1. Execute statement:

cout << num << “, “;


(prints the value of num on the screen and reduces num by 1)

  1. finish of block. come back mechanically to step two
  2. Continue the program right when the block: print FIRE! and finish program.

Get PDF of Iteration structures—while loop

Pointers and Arrays

Pointers and Arrays

The idea of array is incredibly a lot of related to the one with pointer. In fact, the identifier of an array is corresponding the address of its initial component, as a pointer is associated with the address of the primary component that it points to, so in fact they are identical thought. As an example, supposing these 2 declarations:

int num [20];
int * p1;
The following assignment operation would be valid:
p1 = num;

After that, p1 and num would be equivalent and would have identical properties. The only distinction is that we tend to could modification the value of pointer p1 by another one, whereas num can continuously purpose to the primary of the twenty elements of kind integer with that it had been outlined. Therefore, unlike p1, that is a normal pointer, num is an array, and an array are often thought-about a constant pointer. Therefore, the subsequent allocation wouldn’t be valid:

num = p1;

Because num is an array, thus it operates as a constant pointer, and that we cannot assign values to constants.
Due to the characteristics of variables, all expressions that embrace pointers within the following example are absolutely valid:

// arrays and pointers
using namespace std;
int main ()
int num [5];
int * p1;
p1 = num; *p1 = 10;
p1++; *p1 = 20;
p1 = &num[2]; *p1 = 30;
p1 = num + 3; *p1 = 40;
p1 = num; *(p1+4) = 50;
for (int n=0; n<5; n++)
cout << num[n] << ", ";
return 0;

10, 20, 30, 40, 50,

In the chapter related to arrays we tend to used brackets ([]) many times so as to specify the index of part of the array to that we tend to needed to refer. Well, these bracket sign operators [] are a dereference operator referred to as offset operator. They dereference the variable they follow even as * will, however they additionally add the number between brackets to the address being dereferenced. For example:

array1[5] = zero; // array1 [offset of 5] = 0
*(array1+5) = zero; // pointed by (array1+5) = 0

These 2 expressions square measure equivalent and valid with each of array1 if array1could be array1 pointer or if array1 is an array.
You can download pdf of Pointers and arrays

Arrays as Parameters

Arrays as Parameters

At some moment we have a tendency to may have to pass associate degree array to a function as a parameter. In C++ it’s impracticable to pass a complete block of memory by worth as a parameter to a function, however we have a tendency to be allowed to pass its address. In practice this has nearly an equivalent result and it’s a far quicker and a lot of economical operation.

In order to just accept arrays as parameters the sole issue that we’ve got to try and do once declaring the function is to specify in its parameters the component variety of the array, associate degree symbol and a combine of void brackets []. as an example, the following function:

void passingarray (int arg[])

accepts a parameter of type “array of int” called arg. In order to pass to this function an array declared as:

int arraypram [40];

it would be enough to write a call like this:

passingarray (arraypram);

Here you have a complete example:

// arrays as parameters

#include <iostream>

using namespace std;

void showarray (int arg[], int length) {

for (int n=0; n<length; n++)

cout << arg[n] << ” “;

cout << “\n”;


int main ()


int array1 [] = {5, 10, 15};

int array2[] = {2, 4, 6, 8, 10};

showarray (array1,3);

showarray (array2,5);

return 0;



5 10 15

2 4 6 8 10

As you’ll be able to see, the primary parameter (int arg[]) accepts any array whose components square measure of type int, no matter its length. For that reason we’ve enclosed a second parameter that tells the function  the length of every array that we pass to that as its 1st parameter. This permits the for loop that prints out the array to understand the range to restate in the passed array while not going out of range.

In a function declaration it’s additionally potential to incorporate multi-dimensional arrays. The format for a tridimensional array parameter is:


for example, a function with a multi-dimensional array as argument may be:

void procedure (int myarray[][3][4])

Notice that the primary brackets [] square measure left blank whereas the subsequent ones aren’t. this can be therefore as a result of the compiler must be ready to confirm at intervals the function is that the depth of every further dimension.

Arrays, each simple or multi-dimensional, passed as function parameters square measure a quite common supply of errors for novice programmers. I would like to recommend the reading of the chapter regarding Pointers for a far better understanding on however arrays operate.

PDF tutorial Arrays as parameters

Multidimensional Arrays

Multidimensional Arrays

Multidimensional arrays may be represented as “arrays of arrays”. as an example, a bi-dimensional array may be imagined as a bi-dimensional table made of components, all of them of a same uniform type.

jimmy represents a bi-dimensional array of three per five components of type int. The method to declare this array in C++ would be:

int jimmy [3][5];

and, as an example, the method to reference the second part vertically and fourth horizontally in an expression
would be:


(remember that array indices continually begin by zero).
Multidimensional arrays don’t seem to be restricted to 2 indices (i.e., 2 dimensions). they will contain as several indices as needed. however be careful! the number of memory required for an array swiftly will increase with every dimension. For example:

char century [100][365][24][60][60];

declares associate array with a char part for every second during a century, that’s over three billion chars. So this declaration would consume over three gigabytes of memory!
Multidimensional arrays square measure simply associate abstraction for programmers, since we are able to acquire constant results with a simple array simply by just putting a factor between its indices:

int jimmy [3][5]; // is equivalent to

int jimmy [15]; // (3 * 5 = 15)

With the sole distinction that with multidimensional arrays the compiler remembers the depth of every unlikely dimension. Take as example these 2 items of code, with each precisely the same result. One uses a bi-dimensional array and therefore the alternative one uses a straightforward simple array:

None of the 2 supply codes on top of turn out any output on the screen, however each assign values to the memory block known as jimmy within the following way:

We have used “defined constants” (#define) to alter potential future modifications of the program. for instance,
in case that we tend to determined to enlarge the array to a height of four rather than three it might be done just by dynamical the line:


#define HEIGHT 3


#define HEIGHT 4

And there is no need to do any changes in the whole code other than this.

PDF articles and manuals

Initialization and accessing elements in arrays in c++


An array could be a series of components of a similar kind placed in contiguous memory locations that may be severally referenced by adding an index to a novel symbol.
That means that, as an example, we will store five values of kind integer in an array while not having to declare five totally different variables, each with a unique symbol. Rather than that, exploitation an array we will store five totally different values of the same type, integer as an example, with a novel symbol.
For example, an array to contain five whole number values of kind integer known as billy might be defined like this:

where every blank panel represents a part of the array, that during this case are number values of type int. These
elements are numbered from zero to four since in arrays the primary index is usually zero, respectively of its length.
Like a regular variable, associate degree array should be declared before it’s used. A typical declaration for associate degree array in C++ is:

type name [elements];



type could be a valid type (like int, float…), name could be a valid symbol and also the parts field (which is usually enclosed in sq. brackets []), specifies what percentage of those parts the array should contain.
Therefore, so as to declare associate degree array referred to as billy because the one shown within the on top of diagram it’s as easy as:

int billy [5];

NOTE: parts|the weather} field inside brackets [] that represents the amount of elements the array goes to carry,
must be a relentless worth, since arrays square measure blocks of non-dynamic memory whose size should be determined before execution. so as to form arrays with a variable length dynamic memory is required, that is explained later in this tutorials.

Initializing arrays.

When declaring an array of local scope (within a function, for example), if we tend to don’t specify otherwise, its
elements won’t be initialized to any value by default, thus their content are undetermined till we tend to store some value in them.  In each cases, local and global, once we declare an array, we’ve got the chance to assign initial values to every one of its components by enclosure the values in braces . For example:

int billy [5] = { 16, 2, 77, 40, 12071 };

This declaration would have created an array like this:

The amount of values between braces should not be larger than the quantity of components that we tend to declare for the array between sq. brackets [ ]. for instance, within the example of array billy we’ve declared that it’s five elements and within the list of initial values among braces we’ve nominal five values, one for every component.
When associate data formatting of values is provided for associate array, C++ permits the  chance of feat the sq. brackets empty [ ]. during this case, the compiler can assume a size for the array that matches the quantity of values enclosed between braces :

int billy [] = { 16, 2, 77, 40, 12071 };

After this declaration, array billy would be 5 ints long, since we have provided 5 initialization values.

Accessing the values of an array.

In array, we will access the value of any of its parts on an individual basis as if it had been a standard variable, so having the ability to each browse and modify its value. The format is as easy as:


Following the previous examples during which billy had five components and every of these components was of kind int, the name that we will use to talk over with every part is that the following:

For example, to store the value 75 in the third element of billy, we could write the following statement:

billy[2] = 75;

and, for example, to pass the value of the third element of billy to a variable called a, we could write:

a = billy[2];

Therefore, the expression billy[2] is for all functions sort of a variable of kind int. Notice that the third part of billy is such as billy[2], since the primary one is billy[0], the second is billy[1], and so, the third one is billy[2]. By this same reason, its last part is billy[4]. Therefore, if we write billy[5], we might be accessing the sixth part of billy and so exceptional the dimensions of the array.
In C++ it’s syntactically correct to exceed the valid vary of indices for Associate in Nursing array. this may produce issues, since accessing out-of-range parts don’t cause compilation errors however will cause runtime errors. the explanation why this is allowed are going to be seen more ahead once we begin to use pointers.
At now it’s vital to be able to clearly distinguish between the 2 uses that brackets [ ] have associated with
arrays. They perform 2 totally different tasks: one is to specify the dimensions of arrays once  they ar declared; and therefore the second one is to specify indices for concrete array parts. don’t confuse these 2 doable uses of brackets [ ] with arrays.

Some other valid operations with arrays:

billy[0] = a;

billy[a] = 75;

b = billy [a+2];

billy[billy[a]] = billy[2] + 5;

// arrays example

#include <iostream>

using namespace std;

int billy [] = {16, 2, 77, 40, 12071};

int n, result=0;

int main ()


for ( n=0 ; n<5 ; n++ )


result += billy[n];


cout << result;

return 0;





PDF tutorial is here

Identifiers in C++

A valid identifier may be a sequence of 1 or a lot of letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols may be a part of associate identifier. solely letters, digits and single underscore characters are valid. additionally, variable identifiers forever need to begin with a letter. they will additionally begin with associate underline character (_ ), however in some cases these is also reserved for compiler specific keywords or external identifiers, as well as identifiers containing 2 successive underscore characters anyplace. In no case they will begin with a digit.
Another rule that you just need to take into account once inventing your own identifiers is that they can’t match any keyword of the C++ language nor your compiler’s specific ones, that are  reserved keywords. The standard reserved keywords are:

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while

Additionally, various representations for a few operators can not be used as identifiers since they’re reserved words beneathsome circumstances:

and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

pdf articles here

C++ Basic Program structure

Program Structure

The best way to learn a programming  language is by writing a program. That s why, here is our first program:

// 1st  program in C++

#include <iostream>

using namespace std;

int main ()


cout << “This is my first program!”;

return 0;


The above section shows the source code of our first program. Output of this program after compilation and execution will be as given below:


This is my first program!

The way how to edit and compile a program depends on the compiler you are using. It depends on whether it has a Development Interface or not and on its version.

No doubt it is one of the simplest programs that can be written in C++, but it contains all the fundamental components that are essential by every C++ program.

Let’s explore this code line by line:

// 1st  program in C++

This is a comment line. Comments do not have any effect on the behaviour of the program. There are two types of comments.

  1. Single line comments
  2. Multi line comments

Single line Comments always starts with two slash signs (//). The programmer can add short explanations or descriptions within the source code itself. In this case, the line is a brief description of what our program is.

#include Lines starting with a hash sign (#) square measure preprocessor directives. These square measure indications for the compiler’s preprocessor during this 1st program example the directive #include tells the preprocessor to incorporate the iostream commonplace file. This specific file (iostream) contains the declarations of the essential commonplace input-output library in C++, and it’s enclosed as a result of its practicality goes to be used later within the program.

using namespace std; All the weather of the quality C++ library square measure declared at intervals what’s known as a namespace, the namespace with the name std. thus so as to access its practicality we have a tendency to declare with this expression.

int main () This line is that the starting of the definition of the main function. This can be the entry purpose of C++ programs to begin their execution, severally of its location at intervals the ASCII text file. The directions contained at intervals this function’s definition can forever be the primary ones to be dead in any C++ program. Therefore all C++ programs have a main function.

Main function is followed by a combine of parentheses (()). that’s as a result of it’s a function declaration: In C++, what differentiates a function declaration from alternative sorts of expressions square measure these parentheses that follow its name. Optionally, these parentheses might enclose an inventory of parameters inside them. Right once these parentheses we will realize the body of the most function penned in braces ().

cout << “This is my first program!”; This line

could be a C++ statement. In fact, this statement performs the sole action that generates an apparent result in our initial program. cout represents the quality output stream in C++, and also the that means of the complete statement is to insert a sequence of characters (in this case the This is my first program!! is the sequence of characters) into the quality output stream (which typically is that the screen). cout is asserted within the iostream customary file inside the std namespace, therefore that is why we wanted to incorporate that specific file and to declare that we tend to were attending to use this specific namespace earlier in our code. Notice that the statement ends with a punctuation character (;). This character is employed to mark the top of the statement and if truth be told it should be enclosed at the top of all expression statements altogether C++ programs (one of the foremost common syntax errors is so to forget to incorporate some punctuation once a statement).

return 0; The return statement causes the most perform to end. return could also be followed by a  return code (in our example is followed by the return code 0). A come back code of zero for the most perform is usually taken because the program worked of course with none errors throughout its execution. This is often the foremost usual thanks to finish a C++ console program.

The program has been structured in numerous lines so as to be additional legible, but in C++, we tend to don’t have strict rules on the way to separate directions in numerous lines. for instance, instead of

int main () { cout << ” Hello World!”; return 0; } We could have written: int main () { cout << ” This is my first program!”; return 0; }

PDF books and articles are here.