Random_values_checking

Please help:
tnis code has a logical error .
I am using rand function to generate random values from 1 to 5, funtion random generate random values and than this random values are checked by switch statement
that how many a numbers are repeatedly generated by that funtion,
logical error: when i try loop for 4 values (arraysize) result is correct when i try 5 to max values (arraysize) the result is not correct and when i a increment for loop to 14 values (arraysize) it prompt a message that program is stop working.
[/code]
#include <iostream>
#include<cstdlib>
#include<iomanip>
#include<ctime>
const int arrysize=8;
using namespace std;
int random(int rrandom[]){

srand(time(NULL));
for(int i=0;i<=arrysize;i++){
rrandom[i]= rand()%6;
}

}


int main()
{
int random_main[arrysize];

random(random_main);


cout<<endl;
for(int i=0;i<=arrysize;i++){
cout<<random_main[i]<<setw(3);
}

//cout<<random_main;


int zero=0,one=0,two=0, three=0, four=0, five=0 ,six=0;
for(int o=0; o<=arrysize;o++)
{
switch(random_main[o]){
//cout<<random();
case 0: {zero++; break;}
case 1: {one++;break;}
case 2: {two++; break;}
case 3:{three++; break;}
case 4:{four++; break;}
case 5:{five++; break;}
}

}
cout<<endl;
cout<<"zeros are : "<<zero<<endl;
cout<<"one : "<<one<<endl;
cout<<"two : "<<two<<endl;
cout<<"three : "<<three<<endl;
cout<<"four : "<<four<<endl;
cout<<"five : "<<five<<endl;


return 0;

}[/code]
Last edited on
Hey. Please edit your post and put your code in code tags - http://www.cplusplus.com/articles/jEywvCM9/


int random(int rrandom[]){ // If the function doesnt return anything. Change it to void.


If you create an array of size 5, int arr[5]; The indexes are 0-4. Meaning arr[0], arr[1], arr[2], arr[3], arr[4];

What you do is go out of range.

for(int i=0;i<=arrysize;i++){

If arraysize is 5. And we create an array of that size -int arr[arraysize];
Then the loop has to look like this -

for(int i=0;i < arrysize;i++){ // notice i < arraysize and not i <= arraysize

This way, it will loop with the values 0-4. If you use <= instead of <. It will use 0-5.
Topic archived. No new replies allowed.