Converting for loops to while with Arrays

Right now I have

1
2
3
4
5
6
7
8
max=myArr[0]; 

for(int i=1;i<10;i++){

if(max<myArr[i]){

max=myArr[i]; 


I'm trying to convert it to a while loop or a do while loop. It's really just the arrays that are throwing me off. I've tried finding online examples but to no avail.

I know i can do something like

1
2
3
4
for (int i = 1; i <= 10; i = i + 3)
{
cout<< "i is now :" <<i<<endl;
} 


to

1
2
3
4
5
6
7
int i = 1;

while (i <= 10)
{
cout << "i is now: " << i << endl;
i += 3;
} 
Last edited on
The way you access an array in a while loop is exactly the same as accessing it in a for loop. Unless your exit conditional can change every time you run the loop, I don't see why you'd want to use a while instead of a for loop.
I don't see why either but it's required.

So it would look something like

1
2
3
4
5
6
7
8
int i = 1;

while (i < 10)
{
i++;

if(max<myARR[i]){
max=myArr[i];
You probably don't want to increment i until after you do the array access.

Essentially, the equivalent while loop given a for loop is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
for (int i = 0; i < max; ++i)
{
    // Do something
    ....
}

// This will pretty much produce the same result as the for loop above.
int i = 0;
while (i < max)
{
    // Do something
    ...
    ++i;
}


A conditional statement for a do-while loop is evaluated at the end of the loop sequence, which is why a do-while loop is guaranteed to execute at least one time.
Topic archived. No new replies allowed.