Algorithms, and example with arrays
- a01337106
- 10 feb 2015
- 1 Min. de lectura
Imagine you want to store data of the same type, or that is going to be used for the same purpose. Or maybe even used in the same operation. You would use an array, let’s see how arrays are used in algorithms.
First, and array must be declared:
int a[];
The array will have a size of N
int N=10;
In this program we will sum all of the values inside de array a[]
First, a loop is needed for changing the index of the selected array.
Loop I from 0 to N-1
The loop is declared with the name I , the value of I is initialized in 0 and it will increase each time by one until it gets to the value of N-1. This is because when an array has a value of N, its indexes start from 0. So, we can now that an array with a size of 6 will have indexes from 0 to 5. For example:
N=5
A[0]
A[1]
A[2]
A[3]
A[4]
It contents five elements with indexes from 0 to N-1
With this been said we can continue, inside the loop we will declare the sum, for this an accumulator is needed. The value in the actual array (the value of I) will be summed each time.
int sum=sum+A[I];
Finally we end the loop
All together this program looks like this:
int A[];
int N=10;
loop I from 0 to N-1
int sum=sum+A[I];
end loop
Comments