different_types_of_loop xdifferent_types_of_loop_1 x
Write a one page summary of different ways of writing a
loop. Also describe how to use a loop and display all the elements of an array.
Write a simple C program to show that .
In every programming language, thus also in the C programming language, there are circumstances were you want to do the same thing many times. For instance you want to print the same words ten times. You could type ten printf function, but it is easier to use a loop. The only thing you have to do is to setup a loop that execute the same printf function ten times.
There are three basic types of loops which are:
· “for loop”
· “while loop”
· “do while loop”
The for loop
The “for loop” loops from one number to another number and increases by a specified value each time.
The “for loop” uses the following structure:
for (Start value; end condition; increase value)
statement;
The while loop
The while loop can be used if you don’t know how many times a loop must run. Here is an example:
#include In every programming language, thus also in the C programming language, there are circumstances were you want to do the same thing many times. For instance you want to print the same words ten times. You could type ten printf function, but it is easier to use a loop. The only thing you have to do is to setup a loop that execute the same printf function ten times. · “for loop” · “while loop” · “do while loop”
The for loop
The “for loop” loops from one number to another number and increases by a specified value each time. for (Start value; end condition; increase value) statement; The while loop can be used if you don’t know how many times a loop must run. Here is an example: #include
int main()
{
int counter, howmuch;
scanf(“%d”, &howmuch);
counter = 0;
while ( counter < howmuch)
{
counter++;
printf("%d\n", counter);
}
return 0;
}
The do while loop
The “do while loop” is almost the same as the while loop. The “do while loop” has the following form:
do
{
do something;
}
while (expression);
Do something first and then test if we have to continue. The result is that the loop always runs once.
There are three basic types of loops which are:
The “for loop” uses the following structure:The while loop
int main()
{
int counter, howmuch;
scanf(“%d”, &howmuch);
counter = 0;
while ( counter < howmuch)
{
counter++;
printf("%d\n", counter);
}
return 0;
}
The do while loop
The “do while loop” is almost the same as the while loop. The “do while loop” has the following form:
do
{
do something;
}
while (expression);
Do something first and then test if we have to continue. The result is that the loop always runs once.
Example
#include
#include
void main()
{
int i,n,a[100];
clrscr();
printf(“enter the number”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
printf("the array is:\n");
for(i=1;i<=n;i++)
{
printf("%d\n",a[i]);
}
getch();
}