For loops and arrays are a great way of simplifying your code. Consider the task of displaying which students did better on which test.
Name |
Test 1 |
Test 2 |
Bert |
8 |
3 |
Fiona |
5 |
7 |
Sally |
7 |
6 |
George |
7 |
7 |
Fred |
5 |
4 |
If we stored the values into an array we would end up with 3 arrays -
Array Position |
0 |
1 |
2 |
3 |
Names array 4 |
Value |
Bert |
Fiona |
Sally |
George |
Fred |
Array Position |
0 |
1 |
2 |
3 |
Test1 array 4 |
Value |
8 |
5 |
7 |
7 |
5 |
Array Position |
0 |
1 |
2 |
3 |
Test2 array 4 |
Value |
3 |
7 |
6 |
7 |
4 |
To display all of the values we could then write the code -
To work out the avearage for test 1 we could do -
Arrays and loops go together like peas in a pod. If you use an array you will most likely use loops. It just goes without saying.