C++ tutorial, C++ programs, C++ Exercises, C++ Example Programs

Thursday, January 16, 2014

Insertion Sort Algorithm Trace Steps and C++ Program

Today, we will discuss Insertion Sort Algorithm Trace Steps on Sample Data and C++ Program implementation of Insertion Sort. First of all, we will:
  1. Define Insertion Sort
  2. Explain the working of Insertion Sort 
  3. Design an algorithm of Insertion Sort
  4. Show trace steps of Insertion sort algorithm for sample data on paper.
  5. Finally, write down the actual code of Insertion sort program in C++.

  What is Insertion Sort?

In Insertion sort, we have to insert elements in to correct position. First of all we find the correct position to insert for the key value under consideration. Secondly we will move other elements to make space for this new element (key value). Now we insert the new element at this space. Suppose there are the following elements in an array A to sort by insertion sort:

Working of Insertion Sort

1. Let first item be trivially sorted.
2. Now we consider first two items of list. Place second item on its correct location.
3. In Third pass we will consider first three items from list. Insert the 3rd item at its correct location among location1, location2 and location3.
4. In 4th pass, insert the 4th item at its correct location among location1, location2, location3 and location4.
5. And so on.

Algorithm of Insertion Sort

 Algorithm: INSERTION-SORT(array)
 This algorithm takes Array 'array' of size n numbers (array has index from 0 to n-1)as input. It sorts the given array in ascending order by INSERTION SORT method. i and j are integer variables used as index of array. temp is a temporary integer variable.
 1.   Repeat through step 6 for i ← 1 to n-1
 2.     temp  ← array[i]
 3.    Repeat through  step 5 while ( j > 0 && array[j-1] > temp)
 4.    array[j] ← array[j -1]
 5.    j ←   j - 1
 6.    array[j]← temp
 7.    End  

Insertion Algorithm Paper Tracing with data:a[0] ,a[1], a[2], a[3], a[4], a[5]
 5,       2,     4,      6,     1,     3
1. First of all we suppose that the first element 5 is its correct place or trivially sorted.

2. Now we consider second element 2. We have to insert 2 at its correct location from first two locations [0] and [1]. We will find its correct position from first two items 5 and 2.
3. Since 2 is less than 5, so the correct location of 2 is at array index[0].
4. We will move 5 from position [0] to [1].
5. Now we will place 2 at [0], so we have sorted first two items.

6. Now array = 2,5,4,6,1,3 Consider 3rd item which is 4. Now we find its correct location from first three locations. So 4 will be inserted at location [1] between 2 and 5.
7. We move 5 to position [2] and place 4 on position [1]
8. So first three items are sorted with array = 2,4,5,6,1,3

9. Now array = 2,4,5,6,1,3   consider 4th item 6 and place on its correct location among first four locations.
    We know that 6 is at its correct location which is 4th location and by index it is [3].

10. Now array is 2,4,5,6,1,3  consider 5th item which is 1. We know that its correct location between first
      five items is number one that is position [0] by index.
11. So we move 6 on [4]
           we move 5 on [3]
           we move 4 on [2]
           we move 2 on [1]
12. Now place 1 on position [0], so the array items a[0] to a[4] are sorted

13. Now array is 1,2,4,5,6,3   consider 6th item which is 3.
14. We know that 3 will be inserted at location [2] between item 2 and item 4.
15. We move 6 to location [5]
            move 5 to [4]
            move 4 to [3]
16. Now place 3 at location [2]
17. Hence the whole array has been sorted now     1,2,3,4,5,6
       
 You can check this all process in the following picture of insertion sort paper tracing.
   

Insertion Sort Algorithm Trace Steps and Program

Image: Trace steps : Insertion Sort Algorithm Trace Steps and Program

Easyway C++ : Insertion sort Algorithm trace steps and C++ Program
Easyway C++ : Insertion sort Algorithm trace steps and C++ Program

Program Insertion Sort in C++



/*
(c)EasyCppProgramming.Blogspot.Com
C++ is Simplified Here!
Target 1001 C++ Example Programs!
EasyCppProgramming.Blogspot.Com
*/

// Program To Input an array and sort
// the array by Insertion Sort Algorithm

#include<iostream>
#include<conio.h>

int main()
 {

   int n, array[100], i, j, t;

cout<<"\n/* Insertion sort Ascending order */\n";

  cout<<"Enter number of elements\n";
  cin>>n;

  cout<<"Enter "<<n<<" numbers\n";

  for (i = 0; i < n; i++)
    cin>>array[i];


for( i = 1;i < n; i++)
     {
     temp = array[i];
     for ( j = i; j > 0 && array[j-1] > temp; j--)
     array[j] = array[j-1];
     array[j] = temp;
     }

  cout<<"Sorted list in ascending order:\n";

  for (i = 0; i <= n - 1; i++)
    cout<<array[i]<<endl;

  getch();
  return 0;
}

Image: Sample Run of Program in Turbo C++ 3.0 - Insertion Sort Algorithm Trace Steps and Program

Easyway C++ : Insertion sort algorithm C++ Program Output Trace output
Easyway C++ : Insertion sort algorithm C++ Program Output Trace output

 Another Insertion Sorting Example for sorting data: 5,2,3,8,1

Figure: ample data trace steps: Insertion Sort Algorithm Trace Steps and Program
Another Insertion Sorting Example for sorting data - Insertion Sort Algorithm Trace Steps and Program
Insertion Sort Algorithm Trace Steps and Program - easyway C++ Program
So, we have completely discussed Insertion Sort Algorithm Trace Steps and Program, if you have any question please do not hesitate to ask question in comments section, thanks.

Further suggested Reading: Sorting Algorithms and Programs in C / C++

  1.  Bubble Sort Algorithm and Program Logic in C Plus Plus

Share:

Tuesday, January 14, 2014

Bubble Sort Algorithm Trace Steps on Sample Data and C++ Program

Today, we will discuss Bubble Sort Algorithm and Program Logic in CPP ( C++ ) programming language. We will study:
  1. Definition of Bubble Sort Algorithm
  2. Trace steps for sample data or working of Bubble sorting algorithm
  3. Algorithm of Bubble Sorting Method
  4. Actual code of Bubble sort program in C++ programming language

 What is Bubble Sort?

Bubble sort is a sorting algorithm, in which we repeatedly pass through the whole array and swap the adjacent elements if they are not sorted.

Note that: In Bubble sort there will be maximum (n-1) passes to sort the given array. For example, if array size n = 5 then there will be (n-1) that is 4 passes.
Note that: In first pass there will be 4 comparisons like 5>4. In second pass there will be 3 comparisons. In third pass there will be two comparisons. And in last that is 4th pass there will be only one comparison.

Method of Bubble Sorting

  • 1. Compare first two adjacent elements, if first is greater than second then swap them( if  sorting on ascending order)   
  • 2. Repeat this comparison for second and third adjacent elements, then third and fourth elements and so on to second last and last elements. And swap the values where needed. This makes ONE PASS of Bubble Sort Algorithm.
  • 3. Now again start with first and second element to compare and swap if first is greater than other. This time ignore last element. So you will compare adjacent elements from number 1 to second last element.
  • 4. Similarly in third pass, you will reduce another comparison from end, and so on.
  • 5. Keep repeating for one fewer element each time until there will be no pairs to compare. In Last Pass, there will be only one comparison of first and second element.

Bubble Sort Algorithm and Program Logic in CPP - on Sample Data

For example:

Let given un sorted array is:

5, 4, 3, 2, 1


In first pass:
5, 4, 3, 2, 1
Pass 1:

We will check if 5>4 then swap(5,4) so that array will become as follows
     4, 5, 3, 2, 1
    Next we will check if 5>3 then swap(5,3) so that array will become:
     4, 3, 5, 2, 1
    Next we will check if 5>2 then swap(5,2) so that array will become:
     4, 3, 2, 5, 1
    Next we will check that if 5>1 then swap(5,1) so that array will become:
    4, 3, 2, 1, 5
Note: You should note that in pass 1, the last element (5) is bubbled and placed to its correct location(sorted) in the given array.
Pass 2:

4, 3, 2, 1, 5
We will check if 4>3 then swap(4,3) which is true , so that array will become as follows:
     3, 4, 2, 1, 5
    Next we will check if 4>2 then swap(4,2) so that array will become:
     3, 2, 4, 1, 5
    Next we will check if 4>1 then swap(4,1) so that array will become:
     3, 2, 1, 4, 5
Note: You should note that in pass 2, the second last element (4) is bubbled and placed to its correct location(sorted) in the given array.

Pass 3:

3, 2, 1, 4, 5
We will check if 3>2 then swap(3,2) which is true , so that array will become as follows:
     2, 3, 1, 4, 5
    Next we will check if 3>1 then swap(3,1) so that array will become:
     2, 1, 3, 4, 5
Note: You should note that in pass 3, the third last element (3) is bubbled and placed to its correct location(sorted) in the given array.

Pass 4:
2, 1, 3, 4, 5
We will check if 2>1 then swap(2,1) which is true so the array becomes:
1, 2, 3, 4, 5

Which is the required sorted array.

  Bubble Sort Algorithm and Program Logic in CPP

Bubble Sort Algorithm


This algorithm will input values in array A of n size. Then sort the array by Bubble sort method and display the display the array. Suppose A be a linear array of n numbers. Temp is a temporary variable for swapping (interchanging) the position of the numbers in array as required according to the sorting order.
1. Input n numbers of an array A
    Initialise i=0 and repeat through 1b if (i<n)
    1a) Display Message " Enter a number="
    1b) Input A[i]
2. Initialise i= 0 and repeat through step 4 if (i< n)
3. Initialize j= 0 and repeat through step 4 if (j< n – i– 1)
4. If (A[j] > A[j + 1])
(a) Temp = A[j]
(b) A[j] = A[j + 1]
(c) A[j+ 1] = Temp
5. Display the sorted numbers of array A
    Initialise i=0 and repeat through 5a if (i<n)
    5a) Display A[i]
6. Exit.

Picture: Bubble Sort Algorithm and Program Logic in CPP
Bubble Sort Algorithm, Trace Steps on Sample data with C++ Program
Bubble Sort Algorithm, Trace Steps on Sample data with C++ Program

Bubble Sort Program Code for Array of size s = 5 integer elements

Sample Run in Turbo C++ 3.0 IDE Bubble Sort Algorithm and Program Logic in CPP

Bubble Sort Algorithm and Program Logic in C++ Trace steps
Algorithm of Bubble Sort, Tracing Steps on Sample data with C++ Program
/*
(c)EasyCppProgramming.Blogspot.Com
C++ is Simplified Here!
Target 1001 C++ Example Programs!
EasyCppProgramming.Blogspot.Com
*/

// Program To Input an array and sort
// the array by Bubble Sort Algorithm

#include<iostream>
#include<conio.h>

int main()
 {

    int a[5], s=5, i, j, k, temp;
   clrscr();
   // input array
   cout<<"Enter 5 array elements to sort:\n";
   for(i=0;i<s;i++)
   cin>>a[i];
   // show un-sorted array
   cout<<"\n Un-Sorted array is =";
   for(i=0;i<s;i++)
   cout<<a[i]<<"    ";
   cout<<"\n------------------------------------";
   // sort array by bubble sort
    for(i=0;i<s-1;i++)
    {
    for(j=0;j<(s-1-i);j++)
            if(a[j]>a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
             }
cout<<"\nAfter Pass "<<(i+1)<<" elements are : ";
for (k = 0; k < s; k++)
cout<<a[k]<<"   ";
cout<<endl;
}/*End of outer for loop*/
    // show sorted array
   cout<<"\n ----------------------------------";
   cout<<"\nSorted Array is = ";

   for(i=0;i<s;i++)
   cout<<a[i]<<"    ";
   // wait for user to press any key
   getch();
   // end
   return 0;
 }

Now after studying Bubble Sort Algorithm and Program Logic in CPP, Read more on

Insertion Sort Algorithm Trace Steps and Program

Share:

Explain Different Types of Iterative Looping Structures

What is a Looping Structure in C++?


A looping structure is a statement used to repeatedly execute a block of  one or more statements for a specified number of times or as long as a given condition remains true.

In C++, looping statements are also called Repetitive statements or Iterative Statements.

Different Types of  Looping Structures in C++


There are three types of looping structures in C and C++ programming languages, as follows:

  1. for loop
  2. while loop
  3. do while loop
Explain Different Types of Iterative Looping Structures
 Let us study these iterative statements deeply with syntax and purpose with the help of sample codes and outputs.

1. for Loop statement


A for loop statement is used to execute a block of one or more statements repeatedly for a specified number of times.

Syntax of for loop


for(initialization;condition;increment/decrement-expression)
{
    statement1;
    statement 2;
    .
    .
    .
   statement N;
}

Example of for loop


int d;
for(d=5; d>=1; d--)
   cout<<d<<endl;

Output:

5
4
3
2
1

2. while Loop Statement in C / C++


while loop is used to execute a block of one or more statements repeatedly as long as the given condition remains true.

Syntax of while loop


while(condition)
{
    statement1;
    statement 2;
    .
    .
    .
   statement N;
}

Example of while loop


int f=5;
while(f>=1)
{
    cout<<f<<endl;
    f--;
}

Output:

5
4
3
2
1

3. do while Loop statement in C / C++


A do while loop is used to execute a block of one or more statements as long as the given condition remains true but condition is placed after loop body.

Syntax of do while loop


do
{
    statement1;
    statement 2;
    .
    .
    .
   statement N;
}
while(condition);

Example of do while loop


int h=5;
do
{
    cout<<h<<endl;
    h--;
}
while(h>=1);

Output:


5
4
3
2
1http://easycppprogramming.blogspot.com/2014/01/working-of-for-loop-statement-with.html

After studying a brief description of Different Types of Iterative Looping Structures in C++
For further reading:


Purpose and Example of do while Loop in CPP Language
Working of for loop statement with examples

Working of While Loop With Examples
Share:

Monday, January 13, 2014

Purpose and Example of do while Loop in CPP Language

What is a do while Loop?

The do while loop is another iterative statement in C++ language. It is used to repeat a set of one or more statements while the given condition remains true. It is similar to while loop in C++ except that the condition is written after the body of loop.
Purpose and Example of do while Loop in CPP Language
Purpose and Example of do while Loop in C++ Language

Syntax of do while loop


do
{
   statement 1;
   statement 2;
   .
   .
   .
   statement N;

while (condition);

Where:
do is a reserved word or keyword.
{
   statement 1;
   statement 2;
   .
   .
   .
   statement N;

is body of loop (a set of one or more statements enclosed in curly brackets)
while is a reserved word or keyword
condition is normally given as a relational expression like (n>=1) etc

Example of do while loop

int n = 1;
do
{
    cout<<n<<endl;
    n++;
 } 
 while (n<=5); 

Output of the above written C++ code segment is list of 1 to 5 numbers as follows:

1
2
3
4
5

How this output comes?

1. First of all an integer variable n is intialized to 1.
2. Body of loop is executed for first time. 1 is printed and control goes to next line due to endl.
3. The valuse of n is incremented by one so that n is equal to 2 now.
4. Condition is checked for first time n<=5, that is, 2<=5 which is true.
5. Body of loop is executed for second time.
6. 2 is printed and control goes to next line due to endl.
7. The value of n is incremented by one so that n is equal to 3 now.
8. Condition is checked  n<=5, that is, 3<=5 which is true.
9. Body of loop is executed for third time.
6. 3 is printed and control goes to next line due to endl.
7. The value of n is incremented by one so that n is equal to 4 now.
8. Condition is checked  n<=5, that is, 4<=5 which is true.
9. Body of loop is executed for fourth time.
10. 4 is printed and control goes to next line due to endl.
11. The value of n is incremented by one so that n is equal to 5 now.
12. Condition is checked  n<=5, that is, 5<=5 which is true.
13. Body of loop is executed for fourth time.
14. 5 is printed and control goes to next line due to endl.
15. The value of n is incremented by one so that n is equal to 6 now.
16. Condition is checked  n<=5, that is, 6<=5 which is false. So the do while loop ends here.

Example 2 of do while loop


int n=100;
do
{
   cout<<n<<endl;
   n++;
}
while (n>=1000);

Output is as follows:


100

Explanation of working of above sample do while code:

1. First of all the value of n is set to 100.
2. Body of loop is executed for the first time.
3. 100 is printed on screen and control goes to next line due to endl. The value of variable n is incremented by one so that now n = 101
4. The given condition (n>=1000) is checked. Since the condition (101>=1000) is false so the loop will will end.
Share:

Friday, January 10, 2014

Explanation of Fibonacci Series n Terms Program

Q:Write a C++ program to input a number N and display N fibonacci Terms.

Program Planning: Printing n Terms of Fibonacci Series

We start the logic building about the above mentioned Fibonacci series program. First of all we try to understand what the Fibonacci Series is:

What is a Fibonacci Series?

Fibonacci Series is a series of numbers where every next number is obtained by adding the two previous numbers. Note that first two numbers are 0 and 1 by definition. So the Fibonacci Series will be as under:

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 and so on.

Term No 1 2 3 4 5 6 7 8 9 10
Term 0 1 1 2 3 5 8 13 21 34
For example, if we wish to write Nth term of the series, then we will get nth term by adding (n-1)th and (n-2)th term.

Nth Term = (n-1)th Term + (n-2)th Term

For example, if we wish to find 5th term

5th Term  = (5-1)th + (5-2)th Term

                 = 2          +           1

                 = 3

Easyway how to write C++ Program Logic: N Terms of Fibonacci Series in C++

Easyway how to write C++ Program Logic: N Terms of Fibonacci Series in C++

 

Program Logic: N Terms of Fibonacci Series in C++

1. We know that First Two Terms are 0 and 1, so initialize First=0 and Second=1
2. Print the value of first and second term by cout<<
3. If we find n terms then we know that we have already displayed two terms. Therefore, we will use a while loop to display remaining n-2 terms. In loop body we will add first and second to get third term.
4. Now we will place the value of second term in first. We will also place value of  third term in second.


Program Coding: N Terms of Fibonacci Series in C++

/*
(c)EasyCppProgramming.Blogspot.Com
C++ is Simplified Here!
Target 1001 C++ Example Programs!
EasyCppProgramming.Blogspot.Com
*/

// Program To Input a Number n and
// display n terms of Fibonacci Series
// by while loop
#include<iostream>
#include<conio.h>
#include<stdlib.h>


 int main()                 
 {
   int first=0, second=1, third, count=2, n;
   clrscr();
   cout<<"How Many Terms of Fibonacci Series? ";
   cin>>n;
   if (n<1)
      {
       cout<<"\n Invalid Input, Enter a Positive number";
       getch();
       exit(0);
      }

   if (n==1)
       cout<<first;
   else if (n==2)
       cout<<first<<"\t"<<second;
   else
   {
      cout<<first<<"\t"<<second;
    while(count<n)
      {
        third = first + second;
        cout<<"\t"<<third;
        first = second;
        second = third;
        count++;
      }
   }
   getch();
   return 0;
 }

Further reading suggestions:

Basic Structure of a C++ Program

C++ Program Development Cycle

How To Write, Compile and Run Your First C++ Program

How To Start Turbo C++ IDE

How To Install Turbo C++ 3.0 - IDE

Features of C++ Programming Language

Brief History of C++

Flowcharts in Computer Programming

The Role of Algorithms in Programming

How To Start Computer Programming
What is a Computer Program
- See more at: http://easycppprogramming.blogspot.com
Share:

Program Factorial by While Loop Logic

Q: Write a program in C++ to input a number and display its factorial. Use while Loop.

Easyway How to Write a program in C++ to input a number and display its factorial

Easyway How to Write a program in C++ to input a number and display its factorial


Program factorial : How to understand mathematical  Logic behind factorial?

We know that factorial of a number is equal to the product of all numbers from one to the given number. For example
Factorial of  3 = 1 x 2 x 3   hence 6
Factorial of  4 = 1 x 2 x 3 x 4 , hence 24
Similarly Factorial of  N = 1 x 2 x 3 .......... x n
If  N = 5 then
Factorial = 1 x 2 x 3 x 4 x 5 , hence 125
Which Statements we Need For Factorial Program?
1. We need cout<< for displaying messages and results to the user.
2. We need cin>> for inputting a number.
3. We need assignment statement, for example fact = 1;
4. We need a while loop statement to multiply all numbers from 1 to N.
And above all we need some variable declarations as well.

Coding : Find Factorial of a Number by while Loop


/*
(c)EasyCppProgramming.Blogspot.Com
C++ is Simplified Here!
Target 1001 C++ Example Programs!
EasyCppProgramming.Blogspot.Com
*/

// Program To Input a Number and Find
// its Factorial by while Loop
#include<iostream>
#include<conio.h>


 int main()                  
 {
   int num;
   clrscr();
   cout<<"Enter a Number to Display\nits Factorial=";
   cin>>num;

   long i=1, fact=1;
   while(i<=num)
   {
   fact = fact * i;
   i++;
   }
   cout<<"Factorial of "<<num<<" = "<<fact<<endl;
   getch();
   return 0;  
 }

 A Sample Run on Paper of Program Factorial

1.  Let we input 3.
2. Now num = 3, we also initialize i and fact variables to 1.So that now i = 1 and fact =1
3. Condition of While loop is tested (i<=num) putting the values 1<=3 which is true.
4. So while loop starts

     First Iteration

      fact = fact * i
      before execution
      1   =  1    *   1
      fact =1 and i = 1
      after execution
      fact =1  and i =1
     The value of i is incremented by 1 so i=2

     

Second Iteration

Since i<=num that is 2<=3 is true so loop takes second iteration    
      fact = fact * i
      before execution
      1   =  1    *   2
      fact =1 and i = 2
      after execution
     fact =2  and i =2
     Note: First of all, Right hand side expression (1 * 2) is evaluated and the result is assigned to the variable fact on left hand side of  =.
The value of i is incremented by 1 so i=3


Third Iteration

Since i<=num that is 3<=3 is true so loop takes third iteration    
      fact = fact * i
      before execution
      2   =  2    *   3
      fact =2 and i = 3
      after execution
      fact =6  and i =3
     The value of i is incremented by 1 so i=4

 Since i<=num that is 4<=3 is false so loop ends now.

The control goes to next statement which is
  cout<<"Factorial of "<<num<<" = "<<fact<<endl;
So it will print Factorial of 3 = 6
Share:

Thursday, January 9, 2014

Program Multiplication Table by While Loop

Q. Write a C++ Program to input a number and then display its multiplication table.
Write a C++ Program to input a number and then display its multiplication table -Easyway C++
Easyway C++ -
Write a C++ Program to input a number and then display its multiplication table -Easyway C++
#include<iostream>
#include<conio.h>


 int main()                  
 {
   int num;
   clrscr();
   cout<<"Enter a Number to Display\nits Multiplication Table=";
   cin>>num;
   cout<<"Table of "<<num<<endl<<"................."<<endl;
   int i=1;
   while(i<=10)
   {
   cout<<num<<" x "<<i<<" = "<<num*i<<endl;
   i++;
   }
   getch();
   return 0;  
 }

Logic of the Multiplication Table Program in C++

1.  First of all, we input a number to display its table in a variable num.
2.  Initialize a loop control variable i to 1.
3. Set a while loop with the condition i<=10 because we wish to repeat loop body for 10 times from i=1 to i=10
4. cout<<num<<" x "<<i<<" = "<<num*i<<endl;  
    The above statement will display one line of multiplication table as follows
    Let the entered number is 7 and i = 1
    7 x 1 = 7
5. The statement i++; will cause increment of 1 to i, so that i has the value 2 now.
6.
   
int i=1;
   while(i<=10)
   {
   cout<<num<<" x "<<i<<" = "<<num*i<<endl;
   i++;
   }

This while loop will repeat loop body as long as the condition remains true for the value of i = 1 to 10.
When i becomes 11 then the condition i<=10  takes the form 11<=10 which gives false. Hence loop will stop.
Share:

Working of While Loop With Examples

What is a while Loop in C++?

A while Loop in C++ and C Language is used to execute a block of one or more statements repeatedly as long as the given condition remains TRUE.

When To Use a while Loop in C++?

A while Loop is suitable in a condition where the number of iteratios is not known in advance.

Syntax of while Loop in C++


while(condition) 
       statement;

Where:

  • while is the reserved word.
  • condition is a valid C++ relational expression. For example i>=1   or k<=5
  • statement is a C++ instruction. This instruction will be executed repeatedly as long as the given condition remains true.

or

 while(condition)
{
    statement 1;
    statement 2;
   .
   .
   .
     statement N;
 }

Where:

  • while is the reserved word.
  • condition is a valid C++ relational expression. For example i>=1   or k<=5
  • {
        statement 1;
        statement 2;
       .
       .
       .
         statement N;
     }
    Statement BLOCK or a compound statement   A set of one or more statements enclosed in BRACES { } is called a statement block or a Compound Statement. This block will be executed repeatedly as long as the given condition remains true. This statement block is also called body of loop or Loop Body.
    working-of-while-loop-examples-easycppprogramming

    Working of a while loop

    We will explain the working of a while loop in C++ with the help of an example loop statement as follows:

    int counter = 1;

    while ( counter <=3 )
    {
           cout<<"while LOOP"<<endl;
           counter ++;
    }

    Explanation:
    First of all, a loop control variable called "counter" is initialized to 1.

    FIRST ITERATION

    Working of while loop starts by checking the condition ( counter<=3 ). Now the value of counter is 1. So that the condition becomes 1<=3 which produces true result. Therefore, loop body that is
    {
           cout<<"while LOOP"<<endl;
           counter ++;
    }
    will be executed. while LOOP will be printed on screen and cursor will move to next line because of endl. counter variable will be incremented by 1 so that it has the new value 2.


    SECOND ITERATION

    The control will move to start of while loop. Condition is checked ( counter<=3 ). Now the value of counter is 2. So that the condition becomes 2<=3 which produces true result. Therefore, loop body that is
    {
           cout<<"while LOOP"<<endl;
           counter ++;
    }
    will be executed. while LOOP will be printed on screen for second time and cursor will move to next line because of endl. counter variable will be incremented by 1 so that it has the new value 3.


    THIRD ITERATION

    The control will move to start of while loop. Condition is checked ( counter<=3 ). Now the value of counter is 3. So that the condition becomes 3<=3 which produces true result. Therefore, loop body that is
    {
           cout<<"while LOOP"<<endl;
           counter ++;
    }
    will be executed. while LOOP will be printed on screen for third time and cursor will move to next line because of endl. counter variable will be incremented by 1 so that it has the new value 4.

    Now the control will move to the start of while loop. The condition ( counter <=3 ) is tested. Since the value of counter variable is 4 now. Hence the condition becomes  4<=3 which will give false now. This will cause the while loop to end.

    Example Code 2: Display the numbers 5 down to 1 with the help of while loop.

     

    int k=5;
    while( k >=1)
    {
        cout<<k<<endl;
        k--;
    }
     

    Explanation:
    First of all, a loop control variable called "k" is initialized to 5.

    FIRST ITERATION

    Working of while loop starts by checking the condition ( k>=1 ). Now the value of counter is 5. So that the condition becomes  5>=1 which produces true result. Therefore, loop body that is
    {
        cout<<k<<endl;
        k--;
    }
    will be executed. The value of k that is 5 will be printed on screen and cursor will move to next line because of endl. counter variable k will be decremented by 1 so that it has the new value 4.


    SECOND ITERATION

    The control will move to start of while loop. Condition is checked (  k>=1 ). Now the value of counter is 4. So that the condition becomes  4>=1 which produces true result. Therefore, loop body that is
    {
        cout<<k<<endl;
        k--;
    }
    will be executed. The value of k that is 4 will be printed on screen and cursor will move to next line because of endl. counter variable k will be decremented by 1 so that it has the new value 3.


    THIRD ITERATION

    The control will move to start of while loop. Condition is checked (  k>=1 ). Now the value of counter is 3. So that the condition becomes  3>=1 which produces true result. Therefore, loop body that is
    {
        cout<<k<<endl;
        k--;
    }
    will be executed. The value of k that is 3 will be printed on screen and cursor will move to next line because of endl. counter variable will be decremented by 1 so that it has the new value 2.

    FOURTH ITERATION

    The control will move to start of while loop. Condition is checked (  k>=1 ). Now the value of counter is 2. So that the condition becomes  2>=1 which produces true result. Therefore, loop body that is
    {
        cout<<k<<endl;
        k--;
    }
    will be executed. The value of k that is 2 will be printed on screen and cursor will move to next line because of endl. counter variable will be decremented by 1 so that it has the new value 1.


    FIFTH ITERATION

    The control will move to start of while loop. Condition is checked (  k>=1 ). Now the value of counter is 3. So that the condition becomes  1>=1 which produces true result. Therefore, loop body that is
    {
        cout<<k<<endl;
        k--;
    }
    will be executed. The value of k that is 1 will be printed on screen and cursor will move to next line because of endl. counter variable will be decremented by 1 so that it has the new value 0.

    Now the control will move to the start of while loop. The condition (  k>=1 ) is tested. Since the value of counter variable is 4 now. Hence the condition becomes   0>=1 which will give false now. This will cause the while loop to end.

Share:

Tuesday, January 7, 2014

Working of for loop statement with examples

What is a For Loop Statement?


for Loop is a looping or iteration statement. It is used to execute a set of one or more statements for a specified number of times. It is a  counter-controlled loop.

Syntax of for Loop

for(initialization; condition; increment_decrement_expression)

{

   statement number 1;

   statement number 2;

   statement number 3;

   .

   .

   .

  statement number N;

}

Explanation of syntax of for loop

1. Initialization: 
It is used to assign a starting value to loop control variable also called a loop counter variable. Here we can initialize more than one variables separated by commas.
Example:  i = 1;
Example: int counter = 1;
Example: int i = 1, j = 10, k = 20;
2. condition
This condition is normally a relational expression. This expression will either produce a TRUE or FALSE. The statements in loop body will be executed only if the given condition is TRUE. If condition is FALSE then the loop body will not be executed.
Example: i < 11;
Example: counter <=10;
Example: j > 0;

3. Increment_Decrement_expression
It is used to increase or decrease the value of the counter variable. It is used to change the value of counter value in such a way that at some time it will make the given condition FALSE, so that the loop may be terminated. If this expression fails to produce a value that makes the given condition false, then for loop will never stop. Such for loop is called an infinite for loop the will never stop. It will continue executing loop body infinitely.
Example: i ++;
Example: counter --;
Example: j += 2;
Example: i = i + 1;
Example: k = k - 1;
4. Loop Body ( Statements 1 to N)
The statements in braces (curly brackets) are also called loop body. These are the statements to be executed again and again as long as the given condition remains TRUE. Note that if there is a single statement then the the use of curly brackets is optional. However, more than one statements make a block that must be placed within curly brackets.

How for loop works

 We will use the following example to explain the working of for loop in C++:
Example:
for( int i = 1; i <= 3; i ++)
     cout<<i<<"\t";
will produce the following output:

1        2        3  

working-of-for-loop-with-examples
Explanation
1. First of all counter variable i is initialized to 1.
2. Now condition i <= 3; is checked for the value of i = 1. So that 1 <= 3 is TRUE.
3. Since condition is TRUE, so loop body   cout<<i<<"\t"; will be executed and will print 1
4. Now increment expression  i ++  is executed. So that the value of i becomes 2.
5. Now condition i <= 3; is checked for the value of i = 2. So that 2 <= 3 is TRUE.
6. Since condition is TRUE, so loop body   cout<<i<<"\t"; will be executed and will print 2
7. Now increment expression  i ++  is executed. So that the value of i becomes 3.
8. Now condition i <= 3; is checked for the value of i = 3. So that 3 <= 3 is TRUE.
9. Since condition is TRUE, so loop body   cout<<i<<"\t"; will be executed and will print 3
10. Now increment expression  i ++  is executed. So that the value of i becomes 4.
11. Now condition i <= 3; is checked for the value of i = 4. So that 4 <= 3 is FALSE.
12. Since condition is False, so loop body   cout<<i<<"\t"; will not be executed and the for loop is terminated.

Example:

 for(int i = 1; i <=3; i ++)
     cout<<"Good ";
     cout<<"Luck";


will produce the following output:

Good Good Good Luck 


Example:
 for(int i = 1; i <=3; i ++)
{    

cout<<" Good ";
cout<<"Luck";

}
will produce the following output:
  Good Luck Good Luck Good Luck
Share:

EasyCPPprogramming.blogspotcom

Labels