I have written the program below. I would like the user to input 4 unique integers. Whenever the user inputs a duplicate I want them to be prompted with an "error" message, and then the program should repeat asking the user to input non-duplicate integers until the user finishes inputting 4 unique integers(no repeats). Run from ubuntu lxde platform within code::blocks.
Code:
#include<stdio.h>
#include<stdlib.h>
#define MAX 4
int error;
int main()
{
//Declare Variables
int element, dup;
int arr[MAX];
//Initialize values
for(element=0;element<MAX;element++)
{
arr[element]==0;
}
error = 0;
//User Input
for(element=0;element<MAX;element++)
{
do
{
printf("Enter> ");
scanf("%d",&arr[element]);
//Search for duplicates
if(element !=0)
{
for(dup=element-1;dup>0;dup--) /*In order to search for repeats, start comparing element to the element just before element (dup=element-1), and repeat this search again until you get to arr[0] (dup-- >0;) */
{
if(arr[element]==arr[dup])
{
puts("Duplicate. ");
error=1;
}
//For Debugging Purposes Only
else if(arr[element] != arr[dup])
{
printf("Checked for element=%u dup=%u : No duplicate.\n",element,dup);
error=0;
}
} //ends for(dup=element-1;dup-->0;) loop
} //ends if(element !=0) loop
printf("error=%d\n",error);
}while(error); //if duplicate detected than go back and ask/scan all over, but without adding 1 to element.
} //ends for(element=0;element<MAX,element++)
return 0;
} //ends main
I don't know why but when I enter in duplicates, the program can't identify duplicates. I guess this narrows the problem down to "if(arr[element]==arr[dup])".
The following are my results, illustrating the program's failure to identify duplicates:
Code:
Enter> 1
error=0
Enter> 2
error=0
Enter> 3
Checked for element=2 dup=1 : No duplicate.
error=0
Enter> 3
Duplicate.
Checked for element=3 dup=1 : No duplicate. // *** 1)HERE IS THE MISTAKE!! 2) What happened to dup=2???***
error=0
Why do I get the above result "Duplicate" then "no duplicate". This totally defies the rules of if and else!
Code:
if(arr[element]==arr[dup])
{
puts("Duplicate. ");
error=1;
}
//For Debugging Purposes Only
else if(arr[element] != arr[dup])
{
printf("Checked for element=%u dup=%u : No duplicate.\n",element,dup);
error=0;
}
Another strange thing is how the program reports dup's value back one less than it should be:
Code:
Enter> 3
Duplicate.
Checked for element=3 dup=1 : No duplicate. // *** 1)HERE IS THE MISTAKE!! 2) What happened to dup=2???***
error=0