Thursday, July 14, 2011

LOOP

LOOP
Loops can be created to execute a block of code for a fixed number of times. Alternatively, loops can be created to repetitively execute a block of code until a boolean condition changes state. For instance, the loop may continue until a condition changes from false to true, or from true to false. In this case, the block of code being executed must update the condition being tested in order for the loop to terminate at some point. If the test condition is not modified somehow within the loop, the loop will never terminate. This creates a programming bug known as an infinite loop.

While Loop:

Syntex:
while (condition)
{
    block of codes
}
Example: Here is a simple example of the use of while. This program counts from 1 to 100.
#include <stdio.h>

main()
{
    int count = 1;

    while (count <= 100)
    {
        printf("%d\n",count);
        count += 1; /* Shorthand for count = count + 1 */
    }
}

Do while Loop:

Syntax:
do {
    block of code
} while (condition is satisfied)
Example: Here is an example of the use of a do loop. The following program is a game that allows a user to guess a number between 1 and 100. A "do" loop is appropriate since we know that winning the game always requires at least one guess.
#include<stdio.h>
main()
{

    int number = 44;
    int guess;

    printf("Guess a number between 1 and 100\n");
    do {
        printf("Enter your guess: ");
        scanf("%d",&guess);

        if (guess > number) {
            printf("Too high\n");
        }
        if (guess < number) {
            printf("Too low\n");
        }
    } while(guess != number);

    printf("You win. The answer is %d", number);
}

For Loop:

Syntax:
for (initializations ;test conditions ;actions)
{
    block of code
}
Example 1: Displaying even numbers form 1 to 100
#include<stdio.h>
#include<conio.h>
 
main()
{
    int ctr;
 
    for (ctr = 1; ctr <= 10; ctr=ctr+2)
        printf("%d\n",ctr);
    getch();
}

Nested Loop:

Loop containing another loop with in it is what we call nested loop
Syntax:
for (initializations ;test conditions ;actions)
{
for (initializations ;test conditions ;actions)
{
block of codes;
}
    block of code
}
Example 1: Display the following output:
1
1      2
1      2        3
1      2        3        4
1      2        3        4      5
#include<stdio.h>
main()
{
    int i, j;
    for(i = 1; i <= 5; i++)
    {
           for(j=1; j<=i; j++)
              printf("%d ", j);
          printf("\n");
    }
     getch();
}

0 comments:

Post a Comment