Thread: passing Array to function and for loop crashing

  1. #1
    Registered User
    Join Date
    Sep 2014
    Posts
    6

    passing Array to function and for loop crashing

    The first problem i'm having is in the following code.
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    // program ask for max value and always returns random numbers < max
    
    
    int main(void)
    {
        int max;
        long int num = 0;
        int ArrayElement;
        srand(time(NULL));
        
        puts("please enter a max number in array");
        scanf("%d", &max);
        system("cls");
        
        for(num = 0;num < 10; num++) // does not work if the number is large >10000 why? if i input 5 for max
        {
                
        ArrayElement = rand();
        
        while( ArrayElement > max)
        {
               ArrayElement = rand()%rand();   
        }
        printf("%d\n",ArrayElement);
        
       }
            
        system("pause");
        return 0;
    }
    what i'm trying to do is to have the user enter a max value say 20 and the program returns 10 random number from (0-20). This program works if the total numbers returned is small less than 100. but it starts to fall apart when the total numbers returned is large greater than (10^4). The ultimate goal is to return (10^6) total numbers ranging from 0 to the max value entered. The question is why is my program crashing for large numbers returned?


    The second question i have involves arrays and how to fill up a huge array. But first the code.

    Code:
    #include <stdio.h>
    #include<stdlib.h>
    #include<time.h>
     
    int main ()
    {
       srand(time(NULL));
       long int n[ 10 ]; //GOAL is to make this an array of 10^6 elements
       long int i;
       long int j;
             
       for ( i = 0; i < 10; i++ ) // again works for small numbers but not large (10^6)
       {
          n[ i ] = rand();
          /*this is where i want to initialize the array with the 
          random numbers generated in the first part. */
       }
       
       for (j = 0; j < 10; j++ ) // works for small numbers but not large (10^6)
       {
          printf("Element[%d] = %d\n", j, n[j] );
       }
       
       system("pause");
       return 0;
    }
    The ultimate goal of these two programs is to merge them and make one program that takes a max value from the user and fills up an array of (10^6) elements with values ranging from (0 to maxValue).
    Please be patient with me as i am new to programming in general.

    thank you.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by orion314
    what i'm trying to do is to have the user enter a max value say 20 and the program returns 10 random number from (0-20). This program works if the total numbers returned is small less than 100. but it starts to fall apart when the total numbers returned is large greater than (10^4). The ultimate goal is to return (10^6) total numbers ranging from 0 to the max value entered. The question is why is my program crashing for large numbers returned?
    Is your program "crashing" or is it "hanging" (as in it does not seem to respond)? The problem here is with this loop:
    Code:
    while( ArrayElement > max)
    {
        ArrayElement = rand() % rand();  
    }
    You keep looping until two consecutive pseudorandom integers are generated such that the remainder of dividing one by the other is not less than max. But this is rather unlikely, so your program ends up generating pairs after pairs of numbers until such a pair is found (and it may well be possible that no such consecutive pair exists for the particular max, PRNG and seed). When you want many of these numbers, it takes so long that you think that your program no longer works.

    Rather, focus on how you can get an integer in the range [0, max] from a pseudorandom number in the range [0, RAND_MAX]. A fairly simple way is to write:
    Code:
    ArrayElement = rand() % (max + 1);
    though it can introduce a small bias.

    By the way "ArrayElement" is a horrible name for a variable that is not an array element. It would be an okay name for a variable that is an array element, but something even more meaningful would be better.

    Quote Originally Posted by orion314
    The ultimate goal of these two programs is to merge them and make one program that takes a max value from the user and fills up an array of (10^6) elements with values ranging from (0 to maxValue).
    Once you are able to get an integer in the range [0, max] from a pseudorandom number in the range [0, RAND_MAX], this second part should be trivial since you already know how to loop over the elements of an array.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Tweaking master Aslaville's Avatar
    Join Date
    Sep 2012
    Location
    Rogueport
    Posts
    528
    You keep looping until two consecutive pseudorandom integers are generated such that the remainder of dividing one by the other is not less than max. But this is rather unlikely, so your program ends up generating pairs after pairs of numbers until such a pair is found (and it may well be possible that no such consecutive pair exists for the particular max, PRNG and seed). When you want many of these numbers, it takes so long that you think that your program no longer works
    This will crash from a floating point exception, because "rand()" can generate any number including zero so you will eventually be dividing by zero. Am pretty sure if he/she hackly added a +1 to the rand(), it will not crash/hang .

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Aslaville View Post
    This will crash from a floating point exception, because "rand()" can generate any number including zero so you will eventually be dividing by zero. Am pretty sure if he/she hackly added a +1 to the rand(), it will not crash/hang .
    While you are correct that rand() can return zero, it is pretty unlikely in practice. Even more unlikely that will occur on the second of two consecutive calls. So, I'd bet on laserlight's explanation over yours - and that your solution will still exhibit the same symptom - albeit while avoiding an attempt to compute a value modulo zero.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  5. #5
    Tweaking master Aslaville's Avatar
    Join Date
    Sep 2012
    Location
    Rogueport
    Posts
    528
    Quote Originally Posted by grumpy View Post
    While you are correct that rand() can return zero, it is pretty unlikely in practice. Even more unlikely that will occur on the second of two consecutive calls.
    Note the OP is experiencing a crash when using very values for the loop control, which makes it a pretty edgy case. Again am not implying it is more likely to occur on the second of the two consecutive calls but if it occurs on the first call it will go unnoticed -

    If you have a decent computer, am sure you will note the program taking some time to print the values(agreed)
    Last edited by Aslaville; 09-23-2014 at 04:49 AM.

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Aslaville View Post
    Note the OP is experiencing a crash when using very values for the loop control, which makes it a pretty edgy case.
    A lot of beginners use the word "crash" (as in, it appears to stop as if it ran into an obstacle) to describe a "hang".

    The jargon of computer programming can look a lot like English, despite being different.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  7. #7
    Registered User
    Join Date
    Sep 2014
    Posts
    6
    I got my program working but again i'm having trouble filling the array up with random numbers. the program works if the number of elements of the array does not exceed (10^5). I realize that the program is "hanging". I understand this to mean that it is taking a long time to fill the array. Is there a faster and more efficient way to fill the array with random integers? once the array is filled the rest of the program runs fast.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    // program ask for max value and always returns random numbers < max
    
    
    int main(void)
    {
        int max;
        long int n[1000];
        long int num = 0;
        int num2;
        int i;
        int j;
        int counter = 0;
        int target;
        int numberOfMatches;
        srand(time(NULL));
        
        puts("please enter a max number in array");
        scanf("%d", &max);
        system("cls");
        
        for(num = 0;num < 1000; num++) 
        {
        
    
    
          for ( i = 0; i < 1000; i++ ) 
          {         
                   num2 = rand();
                   while( num2 > max)
                   {
                   num2 = rand()%(max+1); // I suspect the problem is in this block
                   n[ i ] = num2; 
                   }
          }
       }
       
       printf("Enter a number you think is in the array from (0 to %d)\n",max);
       scanf("%d",&target);
       printf("Enter the amount of times you think (%d) is in the array\n",target);
       scanf("%d",&numberOfMatches);
       
       
       for ( i = 0; i < 1000; i++ )
       {
           if(target == n[i])
           {
              printf("Element[%d] = %d\n", i, n[i] ); 
              counter++;
           } 
       }
       
       printf("number of matches found  = %d\n", counter);
       printf("your guess = %d\n",numberOfMatches);
       printf("you were off by %d\n",counter-numberOfMatches);
       
            
        system("pause");
        return 0;
    }

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by orion314
    the program works if the number of elements of the array does not exceed (10^5).
    This is a different problem. You declared the array like this:
    Code:
    long int n[1000];
    Obviously, this cannot store more than 100000 elements; it cannot even store more than 1000 elements. So you change it to:
    Code:
    long int n[1000000];
    Now, this can certainly store 100000 elements and many more, except that there might not be enough space on the stack for an array of that size. One solution is to say that since you only need one such array in this program, you declare it static:
    Code:
    static long int n[1000000];
    This way, the storage would not be allocated on the stack, so your problem might be resolved. Alternatively, you can use malloc:
    Code:
    long int *n = malloc(1000000 * sizeof(*n));
    This way, the storage would be allocated on the heap, which is likely to be larger than the available stack space. The caveat would be that you would need to free(n) when you are done.

    By the way, with the rand()%(max+1) method, you do not need to check if num2 > max since it is guaranteed that num2 <= max. You might see a variation of this method that does involve a loop, but it will probably be meant to avoid the bias that I mentioned by rejecting numbers outside a range.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 09-25-2012, 01:31 AM
  2. Passing Array To Function & Display Array Contents
    By mcertini in forum C++ Programming
    Replies: 4
    Last Post: 12-10-2010, 01:32 PM
  3. Passing object to function outside of loop
    By HLMetroid in forum C++ Programming
    Replies: 6
    Last Post: 01-29-2008, 03:22 PM
  4. passing array to function
    By richdb in forum C Programming
    Replies: 12
    Last Post: 03-02-2006, 05:22 PM
  5. passing an array to a function
    By Dmitri in forum C Programming
    Replies: 9
    Last Post: 12-18-2005, 02:16 PM

Tags for this Thread