Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

arrays...cant find the error in my program 1

Status
Not open for further replies.

watshamacalit

Programmer
Dec 10, 2002
1
US
Write a program that rolls a six-sided die 6000 times and displays the
number of times each face was rolled.

so far i have...

#include <stdio.h>

void main ( void )
{
int index, count, roll ;
int face[ 6 ] ;

for ( index = 1 ; index <= 5 ; index++ )
face[ index ] = 0 ;

printf( &quot;Face\tFrequency\n&quot; ) ;
printf( &quot;----\t---------\n&quot; ) ;

for ( roll = 0 ; roll <= 10 ; roll++ )
++face[ roll ] ;

for ( count = 1 ; count <= 6 ; count++ )
printf( &quot;%4i\t%9i\n&quot;, count, face[ index ] ) ;

}

this doesnt work... the compiler says it has created a fatal error... whats wrong with the program?
 
Try this.

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

#define MAX 6000

int *intArray();
int dieRoll(void);
void frequencyCheck(int *,int);


int main(void) {
int *array = NULL;
int y = 0;

if ( (array = intArray()) != NULL) {
while (y++ < MAX) {
array[y] = dieRoll();
}

for (y=1 ; y <= 6 ; y++) {
frequencyCheck(array,y);
}
free(array);
return 0;
}
return 1;
}

int *intArray() {
int *arr = malloc(MAX * sizeof(int));

if (arr) {
return arr;
}
return NULL;
}

int dieRoll() {
return (1 + rand() % 6);
}

void frequencyCheck(int *arr, int n) {
int y,x = 0;
for (y=0 ; y <= MAX ; y++) {
if (arr[y] == n) {
x++;
}
}
printf(&quot;%d occurred %d times\n&quot;, n, x);
}
 
Hi

There are a few errors in your pgm

1) You have defined the array int face[ 6 ]

But you start intialising it from index 1 to 5.
The indexing to arrays start from 0 to size -1 so in your case 0 - 5.
This could case a runtime error as your face[0] is not initialised.

2) In the second loop you are writing beyond the array boundary when you index 6,7,... in it. You should keep the upper limit as 5 only.

3) Third loop again you have indexed 6 which is beyond your array bounds.

4) The program that you have written does not achive what your objective was it would merely increment each array location to 1 and print it.
Follow the marsd example.




 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top