#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Location
    Bristol
    Posts
    13
    Rep Power
    0

    Red face Completely new to programming: Having issues with arrays


    Hi guys, first things first, I am not looking for someone to write all this up for me I am jut really stuck and won't be able to get help from tutors until term starts again in October. I was in hospital in term time but have been allowed to keep studying as long as I do it over the summer. I figured you guys might be able to help me out. :)

    The first bit of the assignment is as follows:
    Write a program to calculate the distribution of numbers produced by the random number function
    rand().
    1) Calculate a random number between 0 and 1. To do this use rand() and divide by
    RAND_MAX. Remember to use a CAST for RAND_MAX

    2) Next write some code to ‘bin’ the data. Create an array where each element represents a bin
    (use, say, 10 bins to start but make this variable). Increment (increase by one) the array element
    where the number falls. You need to calculate which bin the random number will fall into. If x is
    the random number between 0 and 1 and there are 10 bins, then the bin number will be the integer
    part of x*10 (assuming your array starts at 0).

    Repeat this for a large number of times (use a for(){} loop).


    Okay, so this is my attempt so far:
    Code:
    #include <stdio.h> 
    #include <stdlib.h> 
    
    int main()
     { 
    
    double x; int i, imax=100, myarray[10][10]; 
    //Okay so here I figured that as we needed a cast on RAND_MAX x needed to be double and i, imax and myarray only needed to be int.
    
    for(i=0;i<9;i++) // How (I think) the number of random numbers is incremented. (Should produce 10 random numbers between 0 and 1)
    
    { 
    x = rand()/(double) RAND_MAX;
    printf("%f\n",x);
    } 
    
    if 0<x<0.1 
    {x=a;} 
    else if 0.1<x<0.2 
    {x=b;} 
    else if 0.2<x<0.3 
    {x=c;} 
    else if 0.3<x<0.4 
    {x=d;} 
    else if 0.4<x<0.5 
    {x=e;} 
    else if 0.5<x<0.6 
    {x=f;} 
    else if 0.6<x<0.7 
    {x=g;} 
    else if 0.7<x<0.8 
    {x=h;} 
    else if 0.8<x<0.9 
    {x=i;} 
    else 0.9<x<1.0 
    {x=j;} 
    // Right, this mess is me trying to sort out how to bin data. It's also where the errors and warning crop up. Do I need to declare the letters a-j at the top of the programme?
    
    {
    
     myarray[i][0]=a;
     myarray[i][1]=b;
     myarray[i][2]=c;
     myarray[i][3]=d;
     myarray[i][4]=e;
     myarray[i][5]=f;
     myarray[i][6]=g;
     myarray[i][7]=h;
     myarray[i][8]=i;
     myarray[i][9]=j;
     } 
    //I think this gives me (if I were to printf) an array which looks as follows a b c d e f g h i j with the random numbers as specified in the if loops beneath them.
    
    return 0; }
    Any suggestions or am I completely missing the point here.
    :o

    Thanks in advance to anyone who reads this. You are a star. :)
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    156
    Rep Power
    34
    Hmmm .... there's a couple of things worth of note here

    1) your ifs!

    The proper syntax for if is the keyword followed by the condition inside parenthesis followed by the statement (or group) optionally followed by the else part.

    You are missing the parenthesis for the condition

    [code=c]if (x < 0.1) { /* statements */ }[/code]

    Also, C is not like English: you cannot glue two conditions together in one. If you want to check if a number is between two other numbers you need to check if it's greater (or equal) to the lowest AND smaller than the second.

    [code=c]/* I like the inner parenthesis, though they are redundant */
    if ((0 <= x) && (x < 0.1)) { /* statements */ }[/code]

    After correcting the ifs your "if else" cascade is ok though :)

    2) you don't need the variables a through j; you need a variable bin. After you classify the number into the proper bin with the ifs, increase the count for the proper bin.
    You also need a count array, like this

    [code=c]int count[10] = {0}; /* initialize all counts to 0 */
    int bin;[/code]

    The ifs will set bin to the right value (replace the /* statements */ in my explanation above) and you increase the proper count with, for example

    [code=c]count[bin] = count[bin] + 1; // or count[bin] += 1; or count[bin]++;[/code]

    Hope this helps
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,996
    Rep Power
    481
    As bdb alluded, the c assignment statement

    a = b;

    changes the value of a.


    Invoke your compiler and start the process to learn how it's warnings and error messages relate to your program.
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    244
    Perhaps this can give you some hints without giving everything away:

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main(){
            const int MAXBINS = 5, MAXITERS = 1000;
            int bins[MAXBINS], i;
            srand(123); /* change '123' to 'time(NULL)' if you want different results each run */
            for (i=0; i<MAXBINS; ++i) bins[i] = 0; /* necessary because the array is occupied by 'stack garbage' */
            for (i=0; i<MAXITERS; ++i) bins[rand() % MAXBINS]++;
            for (i=0; i<MAXBINS; ++i) printf("bin %d has count %d\n", i, bins[i]);
            return 0;
    }

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Location
    Bristol
    Posts
    13
    Rep Power
    0

    Attempt 2


    OKay so the bottom suggestion looked really interested so I gave that a go. It's something that's only touched on in my course so far so it was more of me having a fiddle than anything else. I tried this one, just having a play but very quickly stumbled into an error. I am attempting to use an integer division on a floating point. Have I got the wrong end of the stick with this coding? (Goes of to try first method in the meantime. :))

    Code:
    #include <stdio.h> 
    #include <stdlib.h> 
    int main(){ 
    const int MAXBINS = 10, MAXITERS = 1000; //declares the number of bins and the number of of the numbers. 
    int bins[MAXBINS], i; 
    srand(time(NULL)); //ensures a different answer is given each time the program is run. 
    for (i=0; i<MAXBINS; ++i) bins[i] = 0; 
    for (i=0; i<MAXITERS; ++i) bins[(rand()/(double) RAND_MAX) % MAXBINS]++; //But the first term is a floating point so this will not work. 
    for (i=0; i<MAXBINS; ++i) printf("bin %d has count %d\n", i, bins[i]); 
    return 0; }
  10. #6
  11. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    244
    You need to read up on casting. Casting reassures the compiler you know what you are doing, though there are certain circumstances where what the compiler can do is ambiguous and so it needs direction.

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Location
    Bristol
    Posts
    13
    Rep Power
    0

    Attempt 3


    Okay so I understand the if cascade much better now but I don't understand the below:


    2) you don't need the variables a through j; you need a variable bin. After you classify the number into the proper bin with the ifs, increase the count for the proper bin.
    You also need a count array, like this

    Code:
    int count[10] = {0}; /* initialize all counts to 0 */ 
    int bin;

    The ifs will set bin to the right value (replace the /* statements */ in my explanation above) and you increase the proper count with, for example

    Code:
    count[bin] = count[bin] + 1; // or count[bin] += 1; or count[bin]++;


    In the statement section of the ifs I need to relate it to a bin? How do I do that? What is a count array used for?

    :o

    My coding in this format now looks like this:

    Code:
    #include <stdio.h> 
    #include <stdlib.h> 
    int main() 
    { 
    double x;
    int i;
    
    for(i=0;i<9;i++) 
    
    { 
    x = rand()/(double) RAND_MAX; 
    printf("%f\n",x); 
    } 
    
    if ((0 <= x) && (x < 0.1)) { /* statements */ } 
    else if ((0.1 <= x) && (x < 0.2)) { /* statements */ } 
    else if ((0.2 <= x) && (x < 0.3)) { /* statements */ } 
    else if ((0.3 <= x) && (x < 0.4)) { /* statements */ } 
    else if ((0.4 <= x) && (x < 0.5)) { /* statements */ } 
    else if ((0.5 <= x) && (x < 0.6)) { /* statements */ } 
    else if ((0.6 <= x) && (x < 0.7)) { /* statements */ } 
    else if ((0.7 <= x) && (x < 0.8)) { /* statements */ } 
    else if ((0.8 <= x) && (x < 0.9)) { /* statements */ }
    else ((0.9 <= x) && (x < 1.0)) { /* statements */ }
    
    return 0;
    }
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Location
    Bristol
    Posts
    13
    Rep Power
    0
    Originally Posted by mitakeet
    You need to read up on casting. Casting reassures the compiler you know what you are doing, though there are certain circumstances where what the compiler can do is ambiguous and so it needs direction.
    Okay so would that would mean telling the complier that the first number (rand()/(double) RAND_MAX) is an integer by sticking (int) before it? If I do that, the programme runs but gives the result:

    bin 0= 1000
    bin 1= 0
    bin 2= 0
    bin n = 0
  16. #9
  17. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    244
    You need to understand what happens when you divide an integer with a float.

    Really, what you need to do is take a break from programming and get a clean sheet of paper and draw out what your algorithm is intended to do and simulate the steps by hand. You are not really understanding what you are doing and are just grasping at straws, leastways that is how it looks to me. First you get a random number, then you convert it to something in the interval of 0-1 (which has to be a float since integers only represent 0 OR 1), then you need to make some sort of binning decision (which value goes in which bin), then you increment that bin and finally you report out your results. Draw that out on paper, simulate it a few times by hand, then start to convert each bit into pseudo code (doing test simulations to be sure you haven't messed something up), then repeat until you have compilable code, then test.

    This is the exact same process that professionals use (or should be if they are earning their pay), though for a problem of this scale they would probably do it all in their head. If you start coding before you actually know what you are trying to do you can easily wind up with crap code that you are too vested in to throw away. The ideal way of programming (seldom seen in the real world since managers, as a class, don't actually give a damn about good code) is to produce a prototype, validate it with the user community, then throw it away and do the design over again based on the knowledge gained during that process. However, the process always needs to start with requirements, then defining a design, breaking the design into codable-testable pieces and only then starting actual development.

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  18. #10
  19. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,996
    Rep Power
    481
    Try multiplying by MAXBINS before casting to int.

    In j, <. is the truncation verb.
    Code:
       <.  0.3 0.5 0.0001
    0 0 0
    
       <.  10 * 0.3 0.5 0.0001
    3 5 0
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo