BWINTER
BWINTER

Reputation: 1

Counting the number of times a number has appeared in C

I am attempting to write a code in c which can determine the number of times a particular number has appeared. This is what I have got so far.

#include<stdio.h>

int randomInt(int max)
{
    return (random(2) % max);
}

main()
{
    int i;
    int position = 1, r = 1; /*Position indicates the position of the particleand r represents where the particle will move next*/ 

    int L = 10,M = 20; /*L is the number of sites and M is the number of hops*/
    int seed, n;

    int frequency[position];

    //setup the random seed generator
    printf("\nEnter your value of seed\n");
    scanf("%d",&seed);
    srandom(seed);
    printf("\nThe value of the seed is %d\n",seed); 

    for(i = 0; i < M; i++) //This loops around the total number of loops.
    {
        printf("\nThe particle is at position %d\n",position);
        n = randomInt(2); /* This chooses either the numbers 0 or 1 randomly */

        frequency[position] = frequency[position] + 1;
        printf("This position has been visited %d times\n",frequency[position]);

        /*Below represents the conditions which will determine the movement of the particle*/

        if(n==0)
            r=1;

        if(n==1)
            r=-1;

        position = position + r;

        if(position == 0)
            position = L;

        if(position == L+1)
            position = 1; 
    }
}

As I stated above I need to be able to count the number of times a particular number has appeared. However, I am not sure how to do it. Any help would be greatly appreciated.

Upvotes: 0

Views: 66

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

You are using your own program in the wrong way, which makes me think that it's probably not your program, but that's an assumption that has no relation to the problem, the way you are using the code is the problem.

This

int frequency[position];

doesn't make sense, because you need to initialize the frequency array to the maximum number of numbers you are going to count, so it seems that it should be

int frequency[M];

instead, then you need to generate the random number between 0 and M, for which you should

position = randomInt(M);

then probably the code will work, but I can't spend more time checking if it will, try these fixes, if it doesn't work try to find out why by yourself, if you can't then may be ask a new question.

Upvotes: 1

Related Questions