by Chris Hooper


introduction to programming in C

Assignment One

Loops

What's a Loop?

A loop is used in C to allow for a repeat of an action.
The loop starts the action, performs it then returns to the start, then unless there is a condition to tell the computer otherwise the loop will run infinitely.

Why have a Loop?

A loop replaces the need to type over and over again a operation that you require the program to perform more than once. It also allows the programmer to control how many times the operation occurs using conditions.

What Are the Different Types of Loop?

The first one is a do while loop. This means the program will perform the operation
as long as the condition(s) are true. The second one is a while loop. This checks
if the condition is true at the start of the operation. The loop will be performed
until this condition is found to be false.

Example of a Loop

  • You want to print out the numbers 1 to 50

  • You will need a integer called numbers

  • To perform this you need to have a conditional loop.

  • Once you have printed out The number 50 the loop needs to finish.

  • Therefore there must be a condition whereby If the number is greater than 50 the loop stops.


Program in C

#include <stdio.h> needed to get access to C's standard input output library
int main() start of execution of program
{ start of operations
int numbers; initialize the integer numbers
numbers = 1; declare numbers starts at 1 as you want the first number to be printed out to be 1
while (numbers<51) The condition Do only while the integer numbers is less than 50
{printf("%i \n", numbers); print out the integer numbers
numbers++; add one to numbers integer
}
return 0; end program return no error code
}

The For Loop

The for loop allows the program to condense the loop into one line of code.

Program in C

#include <stdio.h>
int main()
{
int index;
for (index=0; index<51; index) this is the loop section while the integer index is less than 50 - then carry on & do the loop below
{
printf("%i\n", index++); the operation the loop is to perform in this case print out the value of integer index then add 1 to it
}
return 0;
}

Advantages of a For Loop

one - the programmer has less to write

two - the computer has less code to read so its slightly faster

three - its easier to add more loops

Conclusion

The for loop saves the programmer time - if he/she wanted to create the above program without using the loop function they would have to type out the routine 50 times. It also allows the programmer a great degree of control over both how many times the operation is performed along with the ability to add many different types of conditions that effect the loop.

top of page