-
Arrays!!!
:confused: If we have this :
Code:
#include <iostream.h>
#include <stdlib.h>
int main()
{
const int size=7;
int a[size]={0};
for( int i=1; i<600; i++)
++a[1+ rand()%6];
cout<<a[i]<<endl;
for(int j=0; j<size; j++)
cout<<a[j]<<" ";
the out put would be like that:
Code:
0
9404 9063 14109 9306 18378 9454
why the value of the array remained 0 while i have already incremet it and also i have used rand()???
and wut are these numbers when the array is being printed in the second loop? why the each cell contains 4 or more numbers? why not one number? and why does it conttain 7, 8 and 9 if i used the rand() of range (0-6)?????????
anyone can tell me?:(
-
Code:
#include <iostream>
#include <stdlib.h>
using namespace std; //Remove .h from iostream and use this namespace instead.
int main(){
const int size=7;
int a[size]={0};
int i, j;
for(i=1; i < 600; i++) {
++a[(rand() % 6) + 1];
cout<<a[i]<<endl;
}
for(j=0; j < size; j++)
cout<<a[j]<<" " << endl;
}
I'm pritty sure your program was being confused from the lack of syntaxs. Remember to include the "{" "}" and "(" ")". I think that should fix the program.
Not sure if thats what you wanted it to do though :confused:.
-
Blackroot, in three attempted answers I've seen of you today you've been at least partially wrong three times. You might want to learn a bit more first.
That said, you are right that the formatting of the program leads to confusion - but only for the programmer, not the compiler. Confuse the compiler, and it give you an error.
You are also right about the old-style headers.
As for the program:
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); // Initialize pseudorandom number generator. Without this, you'll get the
// same result every run.
const int SIZE = 7; // Typical naming convention is to put constants in all upper case.
int a[SIZE] = {0};
for(int i = 1; i < 600; ++i) { // Good practice to use prefix ++ unless postfix is required.
int index = rand() % SIZE; // 1+rand()%6 would yield numbers from 1 to 6. Array indices
// start from 0, though.
++a[index];
cout<<a[index]<<endl; // Must use the same index here - i will be quickly out of bounds.
}
for(int i = 0; i < size; ++i) { // Unless you use a broken compiler, there's nothing wrong
// with reusing the variable name here. (VC++, enable "for-scope" in the language
// options.)
cout << a[j] << " ";
}
}