Strictly identical arrays input

Hi there,

Any general tips to clean up this code?
just seems that I can accomplish the task w/o doing all the checks..

Thank you!

The txt book problem:
(strictly identical arrays) Two arrays list1[] and list2[] are strictly identical if they have the same length and list1[] is equal to list2[] for each[i].

write a function that returns true if list1 and list2 are strictly identical using the following header

1
2
      bool strictlyEqual(const int list1[], const int list2[], int size)
      

Write a test program that prompts the user to enter two lists of integers and dis­plays whether the two are strictly identical. The sample runs follow. Note that the first number in the input indicates the number of the elements in the list. This number is not part of the list. Assume the list size is maximum

My code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
       #include <iostream>
       using namespace std;
       
       bool strictlyEqual(int const list1[], int const list2[], int size);
       
       bool strictlyEqual (int x1[], int x2[], int n)
       {
        int int i;
        for (i =1; i<=n; i++)
        {
               if (x1[i] != x2[i])
               {
                  // breaks loop
                      return (false);
                      break;
                }
                else 
                return (true);

              }
  } 
 

    int main ()
    cout << "enter list1: " << endl;
    int list1[20], i;
    cin >> list1[0];
    for (i=1; i<= list1[0]; i++)
    cin>> list1[i];

    cout <<"enter the list2" << endl;
    int list2[20];
    cin >> list2[0];
    for (i=1; i<= list2[0]; i++)
    cin >> list2[i];

    if (list1[0] == list2[0]
    {
         int size = list2[0];
         bool v=strictlyEqual(list1, list2, size);
         if (v== true)
         cout << "identical" << endl;
         else 
         cout << "not identical " << endl;
     }

      return 0;
     }
Last edited on
Your code:
1
2
3
4
5
6
7
8
9
10
for ( i =1; i<=n; i++ )
{
  if ( x1[i] != x2[i] )
  {
    return (false);
    break; // will never be called
  }
  else 
    return (true);
}

Lets assume that the first elements are equal. The else-branch is executed and the function returns true without testing the remaining elements!
Topic archived. No new replies allowed.