Home > Back-end >  Check if a number is already presented on an array with values introduced by the user
Check if a number is already presented on an array with values introduced by the user

Time:12-07

I am learning to program on C and I am trying to create a program that scan certain amount of numbers established by the user, and store them on an array that I will use later, but the numbers introduced by the user can't be repeated, so I am trying to implement this restriction with a comparation inside a for loop. I've tried with other kind of loops bu I cant make it work appropiately.

Thanks!

Here is my code so far:

#include<stdio.h>
int main ()
{
    int n;
    int i;
    int num;
    printf("Introduce the amount of numbers you will register \n");
    scanf("%d",&n);
    int N[n];
    printf("Introduce your numbers \n");
    for (i=0; i<n; i  )
    scanf ("%d",&num);
    {
        if (num == N[i])
        {
            printf("You already introduced this number, try again");
        }   

            N[i]=num;
            printf("____________ \n");  
    }
    getchar ();
    getchar ();
    return 0;   
} 

When I run this program the output is this one, and I have no idea why

Introduce the amount of numbers you will register
5
Introduce the first value
1
____________
____________
____________
____________
You already introduced this number, try again ____________

--------------------------------

CodePudding user response:

For starters you may not declare a variable length array with zero elements

int n=0;
//...
int N[n];

You need to declare the array after entering a positive value in the variable n.

int n;

//...

printf("Introduce the amount of numbers you will register");
scanf("%d",&n);

int N[n];

Also as the array was not initialized then this comparison

if (num == N[i])

invokes undefined behavior.

Also you have to enter values within the loop,

You need to write something like the following

for ( i=0; i<n;)
{
    scanf ("%d",&num);

    int j = 0;

    while ( j != i && num != N[i] )   j;

    if ( j != i )
    {
        printf("You already introduced this number, try again");
    }
    else
    {   
        N[i  ] = num;
        printf("____________ \n");  
    }
}
  • Related