I want to loop through an array that I have that has a max value of 1000. I am filling the array with values from a text file. I am trying to loop through that array but in my for loop, I do not know the length of the array, so I do not know what to put in the second part of the for loop statement. For example: I have an array called: int scores[1000];
and I am trying to iterate through this array and putting scores in a grade category. So A = 90-100, B = 80-89, C = 70-79, D = 60-69, F = 0-59.
So I dont know what my for loop would look like:
for(int i = 0; i < ...; i++){
if(scores[i] > = 90 || scores[i] <= 100){
//Do stuff...
}
I guess I am also confused as to how to get the total counts of each category at the end too. But for the most part its how to iterate through this array. I know sizeof(scores[]) wont work because that will give me the int size and not the length of the array itself. Thanks though in advance!
C – Iterate over Array using While Loop To iterate over Array using While Loop, start with index=0, and increment the index until the end of array, and during each iteration inside while loop, access the element using index.
You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.
For Loop to Traverse Arrays. We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.
Method 2: Using the for…of statement: The for…of statement can be used to loop through iterable objects and perform the required functions. Iterable objects include arrays, strings and other array-like objects.
Actually the sizeof()
should be done like this:
sizeof(scores) / sizeof(scores[0])
And this will give you the total element numbers of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With