Docstoc

loops _ switch statement

Document Sample
loops _ switch statement Powered By Docstoc
					                                         loops
A loop is a programming language construction that allows the programmer to instruct
the computer to perform a certain instruction, or set of instructions over and over again.

For statements
By far, the most utilized looping statement in C++ is the for statement. The for statement
is ideal when we know exactly how many times we need to iterate, because it lets us
easily declare, initialize, and change the value of loop variables after each iteration.

the for statement has the form:

for(initial_value, test_condition, step)
{
  // code to execute inside loop
};

      initial_value Typically, the init-statement consists of variable declarations and
       assignments. This statement is only evaluated once, when the loop is first
       executed.
      test_condition this is the condition that is tested to see if the loop is executed
       again. If test_condition is false, the loop terminates immediately. If it is true, the
       statement is executed.
      step this describes how the counter is changed on each execution of the loop.
       Typically, this step consists of incremented/decrementing the variables declared
       in init-value. After step has been evaluated, the loop returns to test_condition.

Let’s take a look at an example of a for loop:

1. for (int i=0; i < 10; i++)
2. cout << i << " ";


First, a loop variable named i is declare, and assign it the value 0.

Second, the i < 10 is evaluated, and since i is 0, 0 < 10 evaluates to true. Consequently,
the statement executes, which prints 0.

Third, After the statement executes, i++ is evaluated, which increments i to 1. Then the
loop goes back to the second step.
1 < 10 is evaluates to true, so the loop iterates again. The statement prints 1, and i is
incremented to 2. 2 < 10 evaluates to true, the statement prints 2, and i is incremented to
3. And so on.

Eventually i is incremented to 10, 10 < 10 evaluates to false, and the loop exits.

Consequently, this program prints the result:

0123456789

Multiple declarations
Although for loops typically iterate over only one variable, sometimes for loops need to
work with multiple variables. When this happens, the programmer can make use of the
comma operator in order to initialize or change the value of multiple variables:

1. for (int i=0, j=9; i < 10; i++, j--)
2. cout << i << " " << j << endl;


This loop initializes two variable: iii to 0, and jjj to 9. It iterates iii over the range 0 to 9,
and each iteration iii is incremented and jjj is decremented.

This program produces the result:

09
18
27
36
45
54
63
72
81
90
Sample Program 1

// program to print first 10 numbers using a for loop
#include <iostream.h>

int main ()
{
  for (int i=0; i<=10; i++)
  {
    cout << i<< ", ";
  }
  return 0;
}

Sample Program 2

// countdown using a for loop
#include <iostream.h>

int main ()
{
  for (int n=10; n>0; n--)
  {
    cout << n << ", ";
  }
  cout << "FIRE!\n";
  return 0;
}

The while loop
Its format is:
while (test_condition)
  {
    statement;
    expression;
  }
and its functionality is simply to repeat statement while the condition set in
expression is true.

Sample Program 1
// Program to print first 10 numbers using while

#include <iostream.h>

int main ()
{
  int n=0;
  while (n<=10)
{
    cout << n << ", ";
    n++;
  }
   return 0;
}


Sample Program 2
// custom countdown using while

#include <iostream.h>

int main ()
{
  int n;
  cout << "Enter the starting number > ";
  cin >> n;

    while (n>0)
{
     cout << n << ", ";
     --n;
  }
cout << "FIRE!\n";
  return 0;
}
When the program starts the user is prompted to insert a starting number for the
countdown. Then the while loop begins, if the value entered by the user fulfills the
condition n>0 (that n is greater than zero) the block that follows the condition will be
executed and repeated while the condition (n>0) remains being true.

The do-while loop
Its format is:

do{
      Statement;

   }while (condition);
Its functionality is exactly the same as the while loop, except that condition in the do-
while loop is evaluated after the execution of statement instead of before, granting at least
one execution of statement even if condition is never fulfilled.

Sample Program 1
// Program to print first 10 numbers using do-while loop

#include <iostream.h>

int main ()
{
  int n=0;
do{
    cout << n << ", ";
    n++;
   } while (n<=10);

 return 0;
}
Sample Program 2
// Program to print any number you enter until 0 using do-while loop

#include <iostream.h>

int main ()
{
  unsigned long n;
  do {
   cout << "Enter number (0 to end): ";
   cin >> n;
   cout << "You entered: " << n << "\n";
  } while (n != 0);
  return 0;
}


The break statement
Using break we can leave a loop even if the condition for its end is not fulfilled. It can be
used to end an infinite loop, or to force it to end before its natural end. For example, we
are going to stop the count down before its natural end.

// break loop example

#include <iostream.h>

int main ()
{
  int n;
  for (n=10; n>0; n--)
  {
    cout << n << ", ";
    if (n==3)
    {
      cout << "countdown aborted!";
      break;
    }
  }
  return 0;}
The selective structure: switch.
The switch statement chooses statements to execute depending on a certain value. The
same effect can be achieved with a series of cascading if statements, but in some cases
the switch statement is easier to read, and some compilers will produce more efficient
code. The break statement exits from the switch statement. If there is no break at the end
of a case, execution continues in the next case, which is usually an error.


The general form of a switch statement is

  switch (expr) {
      case c1:
          statements 1 // do these if expr == c1
          break;
      case c2:
          statements 2 // do these if expr == c2
          break;
      case c3:
          statements 3// do these if expr == any of c2, c3, or c4
          break;
      default:
          statements // do these if expr != any above
  }


It works in the following way: switch evaluates expression and checks if it is equivalent
to C1, if it is, it executes statements 1 until it finds the break statement. When it finds this
break statement the program jumps to the end of the switch selective structure.

If expression was not equal to c1 it will be checked against C2. If it is equal to this, it will
execute statements 2 until a break keyword is found, and then will jump to the end of the
switch selective structure.

Finally, if the value of expression did not match any of the previously specified constants,
the program will execute the statements included after the default: label, if it exists (since
it is optional).
Both of the following code fragments have the same behavior:

switch example                                 if-else equivalent
                                               if (x == 1)
switch (x) {                                   {
 case 1:                                         cout << "x is 1";
   cout << "x is 1";                             }
   break;                                      else if (x == 2)
 case 2:                                       {
   cout << "x is 2";                             cout << "x is 2";
   break;                                        }
 default:                                      else
   cout << "value of x unknown";               {
 }                                               cout << "value of x unknown";
                                                 }

Sample Program 1

// Demonstrates switch statement
  #include <iostream.h>


  int main()
  {
    int marks;
    cout << "Enter no between 0 to 5: ";
    cin >> number;
    switch (number)
    {
       case 0:
             {   cout << "Too small, sorry!";
                        break;
                }
          case 5:
               {
                        cout << "Good job!\n";             // fall through
                         break;
                  }
        case 4:
              {
                       cout << "Nice Pick!\n"; // fall through
                       break;
              }
        case 3:
               {
                         cout << "Excellent!\n"; // fall through
                          break;
               }
        case 2:
              {
                         cout << "Masterful!\n"; // fall through
                         break;
               }



        case 1:
             {
                      cout << "Incredible!\n";
                      break;
              }
        default:
                {
                      cout << "Too large!\n";
                      break;
                  }
    }
    cout << "\n\n";
     return 0;
}
Two cases, one action

#include <iostream.h>

int main(void)
{
  char answer = 0;

    cout<<"Enter Y or N: ";
    cin>>answer;

    switch (answer)
    {
      case 'y': case 'Y':
       printf("\nYou responded in the affirmative.");
       break;

     case 'n': case 'N':
      printf("\nYou responded in the negative.");
      break;

     default:
      printf("\nYou did not respond correctly...");
      break;
    }
    return 0;
}

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:1
posted:1/17/2012
language:
pages:10