golang loop through array
Here is an example of how to loop through an array in the C programming language:
#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int length = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < length; i++) {
printf("%d\n", numbers[i]);
}
return 0;
}
Explanation:
- The #include <stdio.h>
line includes the standard input/output library, which provides functions like printf
for printing output to the console.
- The int main()
function is the starting point of the program. It returns an integer value to indicate the status of the program.
- int numbers[] = {1, 2, 3, 4, 5};
declares an array called numbers
and initializes it with the given values.
- int length = sizeof(numbers) / sizeof(numbers[0]);
calculates the number of elements in the array by dividing the total size of the array by the size of an individual element.
- The for
loop is used to iterate through each element of the array. It starts with i = 0
and continues as long as i
is less than the length of the array. After each iteration, i
is incremented by 1.
- printf("%d\n", numbers[i]);
prints the value of the current element numbers[i]
to the console, followed by a newline character \n
.
- Finally, return 0;
ends the program and returns 0 to indicate successful execution.