Tuesday, March 5, 2013

Matrices


Definition of Matrix

A matrix is a collection of numbers arranged into a fixed number of rows and columns. Usually the numbers are real numbers. In general, matrices can contain complex numbers but we won't see those
here. Here is an example of a matrix:
The upper left corner of the matrix is row 1 column 1. In the above matrix the element at row 1 col 1 is the value a1,1. The element at row 2 column 3 is the value a2,3.

Names for Matrices

If you sometimes forget whether rows or columns come first, just remember that matrices are build out of rowman columns. A matrix can be given a name. In printed text, the name for a matrix is usually a capital letter in bold face, like A or M. Sometimes as a reminder the dimensions are written to the right of the letter, as in B3x3.
The elements of a matrix also have names, usually a lowercase letter the same as the matrix name, with the position of the element written as a subscript. So, for example, the 3x3 matrix A might be written as:

Sometimes you write A = [aij] to say that the elements of matrix A are named aij.

 



Square Matrix :
     Any matrix that has equal number of rows and columns is called square matrix. E.g: 2x2, 3x3 matrix.


2x2 Square Matrix3x3 Square Matrix
a11a12
a21a22
2 rows & 2 columns
b11b12b13
b21b22b23
b31b32b33
3 rows & 3 columns



Diagonal Matrix :
     A Diagonal matrix is a square matrix with numbers on the leading diagonal and zeros in all other places.

Diagonal Matrix
200
030
008


Identity Matrix :
     An identity matrix is a square matrix denoted as I. It has ones (1) down the leading diagonal and zeros in all other places.

2x2 identity3x3 identity
10
01
100
010
001

Note: Any matrix multiplied by its identity matrix leaves the matrix unchanged.
It is similar to multiplying a number by 1.
i.e AI = A (where A is a matrix)

22
53
x
10
01
=
22
53
Zero (Null) Matrix :
      A zero or null matrix is a matrix with 0 as the element for all its cells (rows and columns).

Zero (null) Matrix
000
000
000


Symmetric Matrix :
      A symmetric matrix is a matrix where aij = aji. i.e an element at the ith row, jth columns should be equal to the element at the jth row, ith columns.

Symmetric Matrix
123
245
356


Equality Matrix :
     For any two matrices to be said as equal matrices they should be of same size and have same values.

Matrix Equality

For two matrices to be equal, they must have
  1. The same dimensions.
  2. Corresponding elements must be equal.
In other words, say that An x m = [aij] and that Bp x q = [bij].
Then A = B if and only if n=p, m=q, and aij=bij for all i and j in range.
Here are two matrices which are not equal even though they have the same elements.
 
 
   
Matrix Addition
If two matrices have the same number of rows and same number of columns, then the matrix sum can be computed:
If A is an MxN matrix, and B is also an MxN matrix, then their sum is an MxN matrix formed by adding corresponding elements of A and B
Here is an example of this:
 
 

Addition and Subtraction example

  Multiplication of a Matrix by a Scalar

A matrix can be multiplied by a scalar (by a real number) as follows:
To multiply a matrix by a scalar, multiply each element of the matrix by the scalar.
Here is an example of this. (In this example, the variable a is a scalar.)



Multiplying a Matrix by Another Matrix

But to multiply a matrix by another matrix you need to do the "dot product" of rows and columns ... what does that mean? Let me show you with an example:
To work out the answer for the 1st row and 1st column:
Matrix Multiply
The "Dot Product" is where you multiply matching members, then sum up:
(1, 2, 3) • (7, 9, 11) = 1×7 + 2×9 + 3×11 = 58
We match the 1st members (1 and 7), multiply them, likewise for the 2nd members (2 and 9) and the 3rd members (3 and 11), and finally sum them up.
Want to see another example? Here it is for the 1st row and 2nd column:
Matrix Multiply
(1, 2, 3) • (8, 10, 12) = 1×8 + 2×10 + 3×12 = 64
We can do the same thing for the 2nd row and 1st column:
(4, 5, 6) • (7, 9, 11) = 4×7 + 5×9 + 6×11 = 139
And for the 2nd row and 2nd column:
(4, 5, 6) • (8, 10, 12) = 4×8 + 5×10 + 6×12 = 154
And we get:
Matrix Multiply

Matrix Subtraction

If A and B have the same number of rows and columns, then A - B is defined as A + (-B). Usually you think of this as:
To form A - B, from each element of A subtract the corresponding element of B.
Here is a partly finished example:
 
 

Transpose

The transpose of a matrix is a new matrix whose rows are the columns of the original (which makes its columns the rows of the original). Here is a matrix and its transpose:




The superscript "T" means "transpose". Another way to look at the transpose is that the element at row r column c in the original is placed at row c column r of the transpose. The element arc of the original matrix becomes element acr in the transposed matrix.
Usually we will work with square matrices, and it is usually square matrices that will be transposed. However, non-square matrices can be transposed, as well:

Rule for Transpose

If a transposed matrix is itself transposed, you get the original back:

This illustrates the rule (AT)T = A.

Determinant

The determinant of a matrix is a special number that can be calculated from the matrix. It tells us things about the matrix that are useful in system linear equations, in calculus and more.
The symbol for determinant is two vertical lines either side.
Example:
|A| means the determinant of the matrix A

Calculating the Determinant

First of all the matrix must be square (i.e. have the same number of rows as columns). Then it is just a matter of basic arithmetic. Here is how:

For  2×2 Matrix

For a 2×2 matrix (2 rows and 2 columns):
A Matrix
The determinant is:
|A| = ad - bc
"The determinant of A equals a times d minus b times c"
It is easy to remember when you think of a cross:
  • Blue means positive (+ad),
  • Red means negative (-bc)
A Matrix

Example:

A Matrix
|B| = 4×8 - 6×3
= 32-18
= 14

For  3×3 Matrix

For a 3×3 matrix (3 rows and 3 columns):
A Matrix
The determinant is:
|A| = a(ei - fh) - b(di - fg) + c(dh - eg)
"The determinant of A equals ... etc"
It may look complicated, but there is a pattern:
A Matrix
To work out the determinant of a 3×3 matrix:
  • Multiply a by the determinant of the 2×2 matrix that is not in a's row or column.
  • Likewise for b, and for c
  • Add them up, but remember that b has a negative sign!
As a formula (remember the vertical bars || mean "determinant of"):

"The determinant of A equals a times the determinant of ... etc"

Example:

A Matrix
|C| = 6×(-2×7 - 5×8) - 1×(4×7 - 5×2) + 1×(4×8 - -2×2)
= 6×(-54) - 1×(18) + 1×(36)
= -306

Inverse of a Matrix
using Minors, Cofactors and Adjoint

You can calculate the Inverse of a Matrix by 1) calculating the Matrix of Minors, 2) then turn that into the Matrix of Cofactors, 3) then the Adjoint, and 4) multiply that by 1/Determinant.
But it is best explained by working through an example!

Example: find the Inverse of A:

It needs 4 steps. It is all simple arithmetic but there is a lot of it, so try not to make a mistake!

Step 1: Matrix of Minors

The first step is to create a "Matrix of Minors":
For each element of the matrix:
Put those determinants into a matrix (the "Matrix of Minors")

Determinants

For a 2×2 matrix (2 rows and 2 columns) the determinant is easy: ad-bc
Think of a cross:
  • Blue means positive (+ad),
  • Red means negative (-bc)
A Matrix

The Calculations

Here are the first two, and last two, calculations of the "Matrix of Minors" (notice how I ignore the values in the current row and columns, and calculate the determinant using the remaining values):
And here is the calculation for the whole matrix:

Step 2: Matrix of Cofactors

This is easy! Just apply a "checkerboard" of minuses to the "Matrix of Minors". In other words, you need to change the sign of alternate cells, like this:

Step 3: Adjoint (also called Adjugate)

Now "Transpose" all elements of the previous matrix... in other words swap their positions over the diagonal (the diagonal stays the same):

Step 4: Multiply by 1/Determinant

Now find the determinant of the original matrix. This isn't too hard, because we already calculated the determinants of the smaller parts when we did "Matrix of Minors".
A Matrix
So: multiply the top row elements by their matching "minor" determinants:
Determinant = 3×2 - 0×2 + 2×2 = 10


And now multiply the Adjugate by 1/Determinant:










 


Inverse of a Matrix
using Elementary Row Operations

Also called the Gauss-Jordan method.
This is a fun way to find the Inverse of a Matrix ...
... play around with the rows
(adding, multiplying and swapping them)
until you make your Matrix A
into the Identity Matrix I.
And by ALSO doing the changes to an
Identity Matrix it magically turns
into the Inverse!

The "Elementary Row Operations" are simple things like adding rows, multiplying and swapping ... but let me show you with an example!

Example: find the Inverse of "A":

We start with the matrix A, and write it down with an Identity Matrix I next to it:

(This is called the "Augmented Matrix")

Identity Matrix

The "Identity Matrix" is the matrix equivalent of the number "1":
Identity Matrix
A 3x3 Identity Matrix
  • It is "square" (has same number of rows as columns),
  • It has 1s on the diagonal and 0s everywhere else.
  • It's symbol is the capital letter I.

Now we do our best to turn "A" (the Matrix on the left) into an Identity Matrix. The goal is to make Matrix A have 1s on the diagonal and 0s elsewhere (an Identity Matrix) ... and the right hand side comes along for the ride, with every operation being done on it as well.
But we can only do these "Elementary Row Operations":
  • swap rows
  • multiply or divide each element in a a row by a constant
  • replace a row by adding or subtracting a multiple of another row to it
And we must do it to the whole row, like this:

Start with A next to I

In this example my first step was to add row 2 to row 1,

then divide row 1 by 5,

Then take 2 times the first row,
and subtract it from the second row,

Multiply second row by -1/2,

Now swap the second and third row,


Last, subtract the third row from the second row,

And we are done!
And matrix A has been made into an Identity Matrix ...
... and at the same time an Identity Matrix got made into A-1


Introduction to Sets


Introduction to Sets


What is a set? Well, simply put, it's a collection.

First you specify a common property among "things" (this word will be defined later) and then you gather up all the "things" that have this common property.

Notation

There is a fairly simple notation for sets. You simply list each element, separated by a comma, and then put some curly brackets around the whole thing.
Set

The curly brackets { } are sometimes called "set brackets" or "braces".


Numerical Sets

So what does this have to do with mathematics? When we define a set, all we have to specify is a common characteristic. Who says we can't do so with numbers?
Set of even numbers: {..., -4, -2, 0, 2, 4, ...}
Set of odd numbers: {..., -3, -1, 1, 3, ...}
Set of prime numbers: {2, 3, 5, 7, 11, 13, 17, ...}
Positive multiples of 3 that are less than 10: {3, 6, 9}

Universal Set


At the start we used the word "things" in quotes. We call this the universal set. It's a set that contains everything. Well, not exactly everything. Everything that is relevant to the problem you have.

Equality

Two sets are equal if they have precisely the same members. Now, at first glance they may not seem equal, you may have to examine them closely!
Example: Are A and B equal where:
  • A is the set whose members are the first four positive whole numbers
  • B = {4, 2, 1, 3}
Let's check. They both contain 1. They both contain 2. And 3, And 4. And we have checked every element of both sets, so: Yes, they are!
And the equals sign (=) is used to show equality, so you would write:
A = B

Subsets

When we define a set, if we take pieces of that set, we can form what is called a subset.
So for example, we have the set {1, 2, 3, 4, 5}. A subset of this is {1, 2, 3}. Another subset is {3, 4} or even another, {1}. However, {1, 6} is not a subset, since it contains an element (6) which is not in the parent set. In general:
A is a subset of B if and only if every element of A is in B.

Proper Subsets

If we look at the definition of subsets and let our mind wander a bit, we come to a weird conclusion.
Let A be a set. Is every element in A an element in A? (Yes, I wrote that correctly.)
Well, yes of course, right?
So wouldn't that mean that A is a subset of A?
This doesn't seem very proper, does it? We want our subsets to be proper. So we introduce (what else but) proper subsets.
A is a proper subset of B if and only if every element in A is also in B, and there exists at least one element in B that is not in A.
This little piece at the end is only there to make sure that A is not a proper subset of itself. Otherwise, a proper subset is exactly the same as a normal subset.

Example:

{1, 2, 3} is a subset of {1, 2, 3}, but is not a proper subset of {1, 2, 3}.

Example:

{1, 2, 3} is a proper subset of {1, 2, 3, 4} because the element 4 is not in the first set.
You should notice that if A is a proper subset of B, then it is also a subset of B.

Empty (or Null) Set

  It is a set with no elements.This is known as the Empty Set (or Null Set). There aren't any elements in it. Not one. Zero. It is represented by Or by {} (a set with no elements) Some other examples of the empty set are the set of countries south of the south pole. So what's so weird about the empty set?

Order

No, not the order of the elements. In sets it does not matter what order the elements are in.
Example: {1,2,3,4) is the same set as {3,1,4,2}
When we say "order" in sets we mean the size of the set.
Just as there are finite and infinite sets, each has finite and infinite order.
For finite sets, we represent the order by a number, the number of elements.
Example, {10, 20, 30, 40} has an order of 4.

Table of set theory symbols

Symbol Symbol Name Meaning / definition Example
{ } set a collection of elements A={3,7,9,14}, B={9,14,28}
A B intersection objects that belong to set A and set B A B = {9,14}
A B union objects that belong to set A or set B A B = {3,7,9,14,28}
A B subset subset has fewer elements or equal to the set {9,14,28} {9,14,28}
A B proper subset / strict subset subset has fewer elements than the set {9,14} {9,14,28}
A B not subset left set not a subset of right set {9,66} {9,14,28}
A B superset set A has more elements or equal to the set B {9,14,28}{9,14,28}
A B proper superset / strict superset set A has more elements than set B {9,14,28}{9,14}
A B not superset set A is not a superset of set B {9,14,28}{9,66}
2A power set all subsets of A
Ƥ (A) power set all subsets of A
A = B equality both sets have the same members A={3,9,14}, B={3,9,14}, A=B
Ac complement all the objects that do not belong to set A
A \ B relative complement objects that belong to A and not to B A={3,9,14},     B={1,2,3}, A-B={9,14}
A - B relative complement objects that belong to A and not to B A={3,9,14},     B={1,2,3}, A-B={9,14}
A ∆ B symmetric difference objects that belong to A or B but not to their intersection A={3,9,14},     B={1,2,3}, A ∆ B={1,2,9,14}
A B symmetric difference objects that belong to A or B but not to their intersection A={3,9,14},     B={1,2,3}, A B={1,2,9,14}
aA element of set membership A={3,9,14}, 3 A
xA not element of no set membership A={3,9,14}, 1 A
(a,b) ordered pair collection of 2 elements
A×B Cartesian product set of all ordered pairs from A and B
|A| cardinality the number of elements of set A A={3,9,14}, |A|=3
#A cardinality the number of elements of set A A={3,9,14}, #A=3
aleph-null infinite cardinality of natural numbers set
aleph-one cardinality of countable ordinal numbers set
Ø empty set Ø = { } C = {Ø}
U universal set set of all possible values
0 natural numbers / whole numbers  set (with zero) 0 = {0,1,2,3,4,...} 0 ∈ ℕ0
1 natural numbers / whole numbers  set (without zero) 1 = {1,2,3,4,5,...} 6 ∈ ℕ1
integer numbers set = {...-3,-2,-1,0,1,2,3,...} -6 ∈ ℤ
rational numbers set = {x | x=a/b, a,b∈ℕ} 2/6 ∈ ℚ
real numbers set = {x | -∞ < x <∞} 6.343434 ∈ ℝ
complex numbers set = {z | z=a+bi, -∞<a<∞,      -∞<b<∞} 6+2i ∈ ℂ
  
 Set-Builder Notation




venndiagrams





Venn Diagrams & Set Notation



Friday, February 1, 2013

Array in c++



What is an array?

C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

How to declare an array?

The general form of declaring a simple (one dimensional) array is
array_type variable_name[array_size];

in your C++ program you can declare an array like
int Age[10];


How to initialize an array?

Initialization of array is very simple in c++ programming. There are two ways you can initialize arrays.
  • Declare and initialize array in one statement.
  • Declare and initialize array separately.
Look at the following C++ code which demonstrates the declaration and initialization of an array.
  int Age [5] = {30, 22, 33, 44, 25};
   int Age [5];
   Age [0]=30;
   Age [1]=22;
   Age [2]=33;
   Age [3]=44;
   Age [4]=25;
Array can also be initialized in a ways that array size is omitted, in such case compiler automatically allocates memory to array.
  int Age [] = {30, 22, 33, 44, 25};
 
Array example
#include <iostream.h>
int main()
{
    //--- Declare array and number of elements in it.
    float a[100];
    int n;   // Number of values currenlty in array.
   
    //--- Read numbers into an array
    n = 0;
    while (cin >> a[n]) {
        n++;
    }
   
    //--- Print array in reverse order
    for (int i=n-1; i>=0; i--) {
        cout << a[i] << endl;
    }
   
    return 0;
}
 

How to declare and initialize multidimensional arrays?

Often there is need to manipulate tabular data or matrices. For example if employee salary is increased by 20% and you are required to store both the salaries in your program. Then you will need to store this information into a two dimensional arrays. C++ gives you the ability to have arrays of any dimension.
 
 

Multi dimension arrays

Consider the example above, you have to store, previous salary, present salary and amount of increment. In that case you will need to store this information in three dimensional arrays.
First I will show you how to declare a two dimensional array and initialize it. Then write a complete program to use multidimensional arrays.
  int Salary[10][2];
This defines an array containing 10 elements of type int. Each of these elements itself is an array of two integers. So to keep track of each element of this array is we have to use two indices. One is to keep track of row and other is to keep track of column.

Elements of multidimensional arrays

Here is a graphical view of multidimensional array that we use to store salary and increment on salary. First column stores the salary element of the array and second column stores increment on salary. We could add another column to store the new salary which adds the increment to the salary.



Initializing multidimensional arrays

Multidimensional arrays can also be initialized in two ways just like one dimensional array. Two braces are used to surround the row element of arrays.
If you are initializing more than one dimension then you will have to use as many braces as the dimensions of the array are.
int Salary [5][2] = 
{
        {2300, 460},
        {3400, 680},
        {3200, 640},
        {1200, 240},
        {3450, 690}
}; 
 
 
 
int Salary [5][2] ={0};  //This will  initialize all the array elements to 0 
 
int Salary [5][2];
Salary [0][0]=2300;
Salary [1][0]=3400;

Multi dimension Array example
 
#include <iostream.h>
int main()
{ 
  int t,i, nums[3][4];
 for(t=0; t < 3; ++t) {
    for(i=0; i < 4; ++i) { 
      nums[t][i] = (t*4)+i+1; 
      cout << nums[t][i] << ' '; 
    } 
    cout << '\n'; 
  }
 return 0;
}

Saturday, January 5, 2013

Operators ,WhileLoop,DoWhileLoop,ForLoop and Switch case in c++

Flow of Control

 Motivation

Normally, a program executes statements from first to last. The first statement is executed, then the second, then the third, and so on, until the program reaches its end and terminates. A computer program likely wouldn't be very useful if it ran the same sequence of statements every time it was run. It would be nice to be able to change which statements ran and when, depending on the circumstances. For example, if a program checks a file for the number of times a certain word appears, it should be able to give the correct count no matter what file and word are given to it. Or, a computer game should move the player's character around when the player wants. We need to be able to alter the order in which a program's statements are executed, the control flow.
Control Structures
Control structures are portions of program code that contain statements within them and, depending on the circumstances, execute these statements in a certain way. There are typically two kinds: conditionals and loops.
1. Conditionals
In order for a program to change its behavior depending on the input, there must a way to test that input. Conditionals allow the program to check the values of variables and to execute (or not execute) certain statements. C++ has if and switch-case conditional structures.
 1.Operators
Conditionals use two kinds of special operators: relational and logical. These are used to determine whether some condition is true or false.
The relational operators are used to test a relation between two expressions:

They work the same as the arithmetic operators (e.g., a > b) but return a Boolean value of either true or false, indicating whether the relation tested for holds. (An expression that returns this kind of value is called a Boolean expression.) For example, if the variables x and y have been set to 6 and 2, respectively, then x > y returns true. Similarly, x < 5 returns false.
The logical operators are often used to combine relational expressions into more complicated Boolean expressions:
The operators return true or false, according to the rules of logic:
The ! operator is a unary operator, taking only one argument and negating its value:

Examples using logical operators (assume x = 6 and y = 2):
!(x > 2) → false
(x > y) && (y > 0) → true
(x < y) && (y > 0) → false
(x < y) || (y > 0) → true
Of course, Boolean variables can be used directly in these expressions, since they hold true and false values. In fact, any kind of value can be used in a Boolean expression due to a quirk C++ has: false is represented by a value of 0 and anything that is not 0 is true. So, “Hello, world!” is true, 2 is true, and any int variable holding a non-zero value is true. This means !x returns false and x && y returns true!
2.if, if-else and else if
The if conditional has the form:
if(condition)
{
           statement1
           statement2
}

The condition is some expression whose value is being tested. If the condition resolves to a value of true, then the statements are executed before the program continues on. Otherwise, the statements are ignored. If there is only one statement, the curly braces may be omitted, giving the form:

if(condition)
statement
The if-else form is used to decide between two sequences of statements referred to as blocks:
if(condition)
{
statementA1
statementA2
}
else
{
statementB1
statementB2
}

If the condition is met, the block corresponding to the if is executed. Otherwise, the block corresponding to the else is executed. Because the condition is either satisfied or not, one of the blocks in an if-else must execute. If there is only one statement for any of the blocks, the curly braces for that block may be omitted:

if(condition)
statementA1
else
statementB1

The else if is used to decide between two or more blocks based on multiple conditions:
if(condition1)
{
statementA1
statementA2
}
else if(condition2)
{
statementB1
statementB2
}

If condition1 is met, the block corresponding to the if is executed. If not, then only if condition2 is met is the block corresponding to the else if executed. There may be more than one else if, each with its own condition. Once a block whose condition was met is executed, any else ifs after it are ignored. Therefore, in an if-else-if structure, either one or no block is executed.
An else may be added to the end of an if-else-if. If none of the previous conditions are met, the else block is executed. In this structure, one of the blocks must execute, as in a normal if-else.
Here is an example using these control structures:
 #include <iostream.h>
 int main()
 {
 int x = 6;
 int y = 2;
 if(x > y)
 cout<<"\nx is greater than y";
 else if(y > x)
 cout <<"\ny is greater than x";
 else
 cout <<"\nx and y are equal";
 return 0;
 }
The output of this program is x is greater than y. If we replace lines 5 and 6 with
int x = 2;
int y = 6;
then the output is y is greater than x. If we replace the lines with
int x = 2;
int y = 2;
then the output is x and y are equal.
3 switch-case

The switch-case is another conditional structure that may or may not execute certain statements. However, the switch-case has peculiar syntax and behavior:
switch(expression)
{
case constant1:
statementA1
statementA2
...
break;
case constant2:
statementB1
statementB2
...
break;
...
default:
statementZ1
statementZ2
...
}
The switch evaluates expression and, if expression is equal to constant1, then the statements beneath case constant 1: are executed until a break is encountered. If expression is not equal to constant1, then it is compared to constant2. If these are equal, then the statements beneath case constant 2: are executed until a break is encountered. If not, then the same process repeats for each of the constants, in turn. If none of the constants match, then the statements beneath default: are executed.

Due to the peculiar behavior of switch-cases, curly braces are not necessary for cases where
there is more than one statement (but they are necessary to enclose the entire switch-case). switch-cases generally have if-else equivalents but can often be a cleaner way of expressing the same behavior

Here is an example using switch-case:
#include <iostream.h>
int main()
{
int x = 6;
switch(x)
{case 1:cout << "x is 1\n";
break;
case 2:
case 3:cout << "x is 2 or 3"; break;
default:cout << "x is not 1, 2, or 3";
 }
return 0;
}
This program will print x is not 1, 2, or 3. If we replace line 5 with int x = 2; then the program will print x is 2 or 3.

2.Loops

Conditionals execute certain statements if certain conditions are met; loops execute certain statements while certain conditions are met. C++ has three kinds of loops: while, do-while, and for.

1.while and do-while
while(condition)
{
statement1
statement2
}

As long as condition holds, the block of statements will be repeatedly executed. If there is only one statement, the curly braces may be omitted. Here is an example:
#include <iostream.h>
int main()
{
int x = 0;
while(x < 10)
x = x + 1;
cout << "x is " << x << "\n";
return 0;
}


This program will print x is 10.

The do-while loop is a variation that guarantees the block of statements will be executed at least once:

do
{
statement1
statement2
}
while(condition);

The block of statements is executed and then, if the condition holds, the program returns to the top of the block. Curly braces are always required. Also note the semicolon after the while condition.

2. for

The for loop works like the while loop but with some change in syntax:

for(initialization; condition; incrementation)
{
statement1
statement2

}



The for loop is designed to allow a counter variable that is initialized at the beginning of the loop and incremented (or decremented) on each iteration of the loop. Curly braces may be omitted if there is only one statement. Here is an example:

#include <iostream.h>
 int main()
 {
for(int x = 0; x < 10; x++)
 cout << x << "\n";
 return 0;
 }
This program will print out the values 0 through 9, each on its own line.
If the counter variable is already defined, there is no need to define a new one in the initialization portion of the for loop. Therefore, it is valid to have the following:

#include <iostream.h>
int main() {
int x = 0;
 for(;x < 10; x = x + 1)
 cout << x << "\n";
 return 0;
 }

Note that the first semicolon inside the for loop's parentheses is still required.
A for loop can be expressed as a while loop and vice-versa. Recalling that a for loop has the form

for(initialization; condition; incrementation)
{
statement1
statement2
}

we can write an equivalent while loop as

initialization
while(condition)
{
statement1
statement2
incrementation
}

Using our example above,

#include <iostream.h>
int main()
{
 for(int x = 0; x < 10; x++)
 cout << x << "\n";
 return 0;
 }

is converted to

#include <iostream.h>
int main()
{
int x = 0;
while(x < 10)
{
cout << x << "\n";
x++;
}
return 0;
 }
The incrementation step can technically be anywhere inside the statement block, but it is good practice to place it as the last step, particularly if the previous statements use the current value of the counter variable.

 3.Nested Control Structures

It is possible to place ifs inside of ifs and loops inside of loops by simply placing these structures inside the statement blocks. This allows for more complicated program behavior.Here is an example using nesting if conditionals:

#include <iostream.h>
int main()
{
 int x = 6;
 int y = 0;
 if(x > y)
 {
 cout << "x is greater than y\n";
 if(x == 6)
 cout << "x is equal to 6\n";
 else
 cout << "x is not equalt to 6\n";
 } else
 cout << "x is not greater than y\n";
 return 0;
 }

This program will print x is greater than y on one line and then x is equal to 6 on the next line.
Here is an example using nested loops:

#include <iostream.h>
 int main()
 {
 for(int x = 0; x < 4; x = x + 1)
 {
 for(int y = 0; y < 4; y = y + 1)
 cout << y;
 cout << "\n";
}
 return 0;
 }

This program will print four lines of 0123.