Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through an array in c++

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!

like image 644
user12074577 Avatar asked May 21 '13 00:05

user12074577


People also ask

How do I loop through an array in C?

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.

Can you loop through an array?

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.

How do you loop a loop through an array?

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.

Which statement is used to loop through 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.


1 Answers

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.

like image 59
shengy Avatar answered Sep 24 '22 09:09

shengy