Page 1 of 1

Another C programming question?

PostPosted: Wed Oct 20, 2004 11:49 pm
by Just4Fun
I have a program that reads random numbers into an array. I am trying to get rid of the duplicates that are sometimes generated. Do I need to use a sort or another loop. Anyone...please. :?
(PS. Jazz. You gave me 4 functions for this quite a while ago, but being the slow poke that I am, I can't figure out how to use the code without functions here!) TIA

main()
{
int array[20];//create an array with 20 elements
int i; //index counter

srand(time(NULL)); //set random

for (i = 0; i < 20; i++) //fill the array
{
array[i] = 1+ rand() % 89; //fill each element of the array with a random number
}//end for


//output
for (i = 0; i < 20; i++)
{
printf("%2d\n", array[i]); //print the array element values
}//end for

}//end function main

PostPosted: Sun Oct 24, 2004 9:44 pm
by makslane
Quick and dirty:



Code: Select all
int array[20];//create an array with 20 elements

int found(int val, int n)
{
    int i;
    for(i = 0; i < n; i++)
    {
       if(array[i] == val) return 1; //found
    }

   return 0; //not found
}

main()
{
 
int i; //index counter
int val;

srand(time(NULL)); //set random

for (i = 0; i < 20;) //fill the array
{
  val = 1 + rand() % 89;
  if(!found(val))
  {
   array[i] = 1+ rand() % 89; //fill each element of the array with a random number

   i++;
  }
}//end for


//output
for (i = 0; i < 20; i++)
{
printf("%2d\n", array[i]); //print the array element values
}//end for

}//end function main

PostPosted: Sun Oct 24, 2004 11:20 pm
by Just4Fun
Thank you, Makslane. :lol:

Learning basic C programming is quite a challenge. I wonder if I will ever get it down?

I really appreciate your help. You make 'C' programming look so easy!!! :oops: