Thursday, September 24, 2009

LOOPS

To execute a set of instructions repeatedly until a particular condition is being satisfied.


Three types of looping statements are there

1) For Loop

2) While Loop

3) Do while Loop

FOR LOOP:-

In for looping statement allows a number of lines represent until the condition is satisfied

Syntax:

for(initialize counter variable ; condition ; increment/decrement the counter variable)

{

Statement1;

...

Statement n;

}



Example program using for loop:


main()

{

int counter,a[10];

for(counter=0;counter<10;counter++)

{

printf(“Enter a[%d]=”,counter);

scanf(“%d\n”,a[counter]);

}

printf(“Array elements:”);

for(counter=0;counter<10;counter++)

printf(“%d”,a[counter]);

}

Explanation:

In above program array a length 10.It occupies 20bytes in memory.

Counter is normal integer variable. It is used to read and display the array values.

First FOR LOOP is used to read the array values.

Second FOR LOOP is used to display the array values. In this second FOR LOOP using one line. So, no need of brace brackets

WHILE LOOP:

In While looping statement allows a number of lines represent until the condition is satisfied

Syntax:

while( condition)

{

Statement1;

...

Statement n;

}




Example program using while loop:


main()

{

int counter,a[10];

counter=0;

while(counter<10)

{

printf(“Enter a[%d]=”,counter);

scanf(“%d\n”,a[counter]);

counter+=1;

}

printf(“Array elements:”);

counter=0;

while(counter<10)

{

printf(“%d”,a[counter]);

counter+=1;

}

}

Explanation:

In above program array a length 10.It occupies 20bytes in memory.

Counter is normal integer variable. It is used to read and display the array values.

Before using counter variable to initialize counter. Then use it in WHILE LOOP.

First WHILE LOOP is used to read the array values.

Second WHILE LOOP is used to display the array values.

DO WHILE LOOP:

In DO WHILE LOOP first execute the statements then it checks the condition.

Syntax:

do

{

Statement1;

...

Statement n;

}while(condition);



Example program using for loop:


main()
{

int counter;

counter=0;

do

{

printf(“%d”,counter);

}while(counter>0);

}

CONCLUTION:

In FOR LOOP:

No need to initialize variable before the LOOP

In WHILE LOOP:

To initialize the variable before the LOOP

Increment/decrement the variable within the LOOP

In DO WHILE LOOP:

Once it execute If the condition is TRUE/FALSE.

2 comments: