Another C programming question?

Non-platform specific questions.

Another C programming question?

Postby Just4Fun » Wed Oct 20, 2004 11:49 pm

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
I've learned that I still have a lot to learn.

** Makslane == Genious **
Just4Fun
 
Posts: 524
Joined: Tue Jul 01, 2003 5:19 am
Location: USA: Washington State; West Coast
Score: 6 Give a positive score

Postby makslane » Sun Oct 24, 2004 9:44 pm

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
makslane
Site Admin
 
Posts: 3947
Joined: Sat Apr 05, 2003 6:47 pm
Score: 182 Give a positive score

Postby Just4Fun » Sun Oct 24, 2004 11:20 pm

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:
I've learned that I still have a lot to learn.

** Makslane == Genious **
Just4Fun
 
Posts: 524
Joined: Tue Jul 01, 2003 5:19 am
Location: USA: Washington State; West Coast
Score: 6 Give a positive score


Return to General

Who is online

Users browsing this forum: No registered users and 1 guest