Please Help !! 1D Array

Hi guys i had problem with my code =="

i want my program to input 1D array and check if there is 2 Elements of the array has the same Value , if there is then stop the program or return entering the array if there is not any Then Print The Array =D

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
#include <iostream>
using namespace std;
// input Function
 int ca(int x[])
 {
	int i;
	for(i=0;i<5;i++)
	 cin>>x[i];
 }
// Check Function 
int OP(int a[])
  {
	int i,n,j;
	      for(i=0;i<5;i++)
	        {
			  for(j=0;j<5;j++)
	            if(a[i]==a[j])
				{
			      return 0;
	               cout<<"Wrong Answer";
				}
else
   for(i=0;i<5;i++)
     cout<<a[i];
		  
		}
  }
//====================== The Main Code ==========================
	int main()
{
	
 int a[5];
 ca(a);
 OP(a);
}


it must done with functions =\

my main problem is when the program checking the array it will check from the Begin so the if i entered the first value is 1 and then the program will check first value 1 again so the condition always is True


I Hope u understand me
and sorry for my bad English =D
Last edited on
You're doing this checking after all the values in the array are entered? Do you need to find all duplicate numbers, or do you stop after the first duplicate entry is found?

To avoid comparing the same element in the outer and inner for loops, the values of i and j should be offset.

The outer loop is holding the value of the first element of the array, a[0], so the inner loop should start comparing it to the next element, a[1], and continue through the rest of the array values.

Next time through the loops, the outer loop will hold the value of the second element in the array, a[1], and the inner loop will start looking at the next element, a[2], and continue through the rest of the array values.

The outer loop would stop at the next to last value in the array, so the inner loop's last comparison is the next to last and the last values in the array.


On line 19, you have a return statement that will terminate the function, so line 20 won't get executed.
Wild Blue Thank You very much it Worked =D

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
#include <iostream>
using namespace std;
// input Function
 int ca(int x[])
 {
	int i;
	for(i=0;i<5;i++)
	 cin>>x[i];
 }
// Check Function 
int OP(int a[])
  {
	int i,n,j;
	      for(i=0;i<5;i++)
			  for(j=(i+1);j<5;j++)
			  {
	            if(a[j]==a[i])
				{
	               cout<<"Wrong Insert";
				   return 0;
			  }}
if (a[j]=!a[i])
   for(i=0;i<5;i++)
     cout<<a[i];
			  
  }
//====================== The Main Code ==========================
	int main()
{
	
 int a[5];
 ca(a);
 OP(a);
}
Topic archived. No new replies allowed.