comparing arrays with a for loop

I know how to compare them with a while/if loop but how can i compare these arrays with a for loop?

#include <iostream>
#include <string>
using namespace std;

int main()
{
int days[3]={24,6,18};
int days2[3]={24,9,18};
bool status =true;
int i=0;

while(status && i<3)
{
if(days[i]!=days2[i])
status=false;
i++;
}
if(status)
cout<<"equal"<<endl;
else
cout<<"not"<<endl;

cout<<status;
cin.get();
cin.get();
}
Last edited on
Just like that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream> 
using namespace std;
int main()
{
    int days[3]={24,6,18};
    int days2[3]={24,9,18};
    bool status =true;

    for(int i = 0; status && i < 3; ++i)
    {
        if(days[i]!=days2[i])
            status=false;
    }
    if(status)
            cout << "equal\n";
    else
            cout << "not\n";
    cout << status;
    cin.get();
    cin.get();
}


bonus: you could also use C++ functions to compare arrays:


1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int days[3]={24,6,18};
    int days2[3]={24,9,18};

    if(equal(days, days+3, days2))
            cout << "equal\n";
    else
            cout << "not\n";
}
thanks.
I have one doubt ,

when value of i was 0, status was true ,
when value of i was 1, status was false ,
when value of i was 2, status was true ,

now loop reaches to end and value of status is true, which says array is equal , which is not correct.
Actually, Cubbi was showing the the individual values in each array, not if one array was the same as the other. So, yes, the program is correct. days[0] and days[2], are the same as days2[0] and days2[2], 24 and 18, respectively, while days[1] and days2[1], are not. 6 and 9, in this case.
Topic archived. No new replies allowed.