Reputation: 141
I am writing a simple program wherein the user enters a few values in an integer array.The code I have written till now is this
#include<stdio.h>
#include<stdlib.h>
void main(){
int array[10],x,y;
for(x=0;x<10;x++)
{
scanf("%d",&array[x]);
//if the entered value is same as any of
//the previously entered values
//prompt the user to enter again till
//he enters a unique value.
} }
I want the integers in the array to be unique and in case the user enters a previously entered value, he should be prompted to enter again. How can I possibly do it?. Using a goto statement perhaps? But that is highly discouraged I guess. Using a while loop?. But I need to loop through the previously entered values to check for duplicates and I am not able to code this. Any help appreciated
Upvotes: 1
Views: 1424
Reputation: 10864
Untested:
#include<stdio.h>
#include<stdlib.h>
void main(){
int array[10],x,y;
x = 0;
while ( x < 10 ) {
int duplicated = 0;
scanf("%d",&array[x]);
//if the entered value is same as any of
//the previously entered values
//prompt the user to enter again till
//he enters a unique value.
for ( y = 0; y < x; y++ ) {
if ( array[x] == array[y] ) {
printf( "You already entered this! Try again.\n" );
duplicated = 1;
break;
}
}
if ( ! duplicated )
x++;
}
}
Upvotes: 4