1

So I am working on some homework, in which I have to create a global array of 500 random integers between 0 and 99. Then, I have to count how many are greater than 75, and how many are less than 50.

Here is my code:

#include <stdlib.h>
#include <stdio.h>

static int ARRAY[500];
static char str[1];

void main() {
    int i = 0;
    for (i = 0; i < 500; i++) {
        int r = rand() % 99;
        ARRAY[i] = r;
        }
    int gt75 = count75();
    int lt50 = count50();
    printf("%d\n", str, gt75);
    printf("%d\n", str, lt50);
    }

int count75() {
    int i = 0, counter = 0;
    for (i = 0; i < 500; i++) {
        int n = ARRAY[i];
        if (n > 75) {
            counter += 1;
            }
        }
    return counter;
    }

int count50() {
    int i = 0, counter = 0;
    for (i = 0; i < 500; i ++) {
        int n = ARRAY[i];
        if (n < 50) {
            counter += 1;
            }
        }
    return counter;
    }

However, after compiling and running my program, I get the following output:

4225008
4225008

This can't be right, as the list should only have 500 elements in the first place. What am I doing wrong?

Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94

3 Answers3

5

You have two errors.

First, int r = rand() % 99; should be int r = rand() % 100; Otherwise you just get numbers between 0 and 98.

Second, your printf statements are odd. They should be:

printf("Greater than 75: %d\n", gt75);
printf("Less than 50: %d\n", lt50);

In the current printf statements, the str is cast to an int, which is interpreting the str pointer as an int, thus your strange output.

Steven Hansen
  • 3,189
  • 2
  • 16
  • 12
4

You're printing a char array with printf using "%d", which is for printing integers. Use "%s" for printing char arrays:

 printf("%s\n", str, gt75);

Or, if you're trying to print the value of gt75 as an integer:

printf("%d\n", gt75);

I do not know why you would pass str in this case, though.

When you use "%d", you are telling printf to interpret the input as an int. Since str is actually a char array, it does not output correctly. Instead, you're printing the memory location of str, which is the value of an array.

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
3

You are always printing the value of str, which is not an int.

rici
  • 234,347
  • 28
  • 237
  • 341