To your 2nd aspect:
I'll explain it.
==========
THE INCLUDES
==========
I guess it's clear that you need
#include <iostream>
if you want to outputsomething on screen, e.g. text.
#include <stdio.h>
includes the implementation of
rand()
I guess..., so that you can use it as you want to. Because I used
srand((unsigned) time(0))
, I have had to include
#include <time.h>
. If I qould have not, the compiler would have complained about this.
==============
THE MAIN FUNCTION
==============
This is the heart of a program, programmed with C++. This
int main(int argc, char *argv[])
is used if you debug the project where your main.cpp is in and you use so-called parameters.
As Albatross said, you should call
srand((unsigned) time(0))
only once. So the source code of this file should look like at the end of this post. Using
NumArray[i]=1+(rand()%10)
, you generate a semi-random number and store it in
NumArray[i]
. The essential thing is that you want to have each number only once. The
1 2 3 4
|
for(int y=0;y<10;y++)
{
if(NumArray[i]==NumArray[y]) goto again;
}
|
in lines 17 to 20 attends this. The
goto again;
makes the program to get back to the label (a 'word' with a colon behind it) named
again:
. So, if the number is the same as anotherone already saved in the array, the program will get back to
again:
and re-starts doing this random stuff, until the number/s which is/are needed is/are addicted.
see EDIT, below
At last, the
for(int i=0;i<10;i++) cout<<"Random nuber "<<i<<": "<<NumArray[i]<<endl;
makes the program output for example this:
Random number 0: 5
Random number 1: 2
Random number 2: 7
Random number 3: 1
Random number 4: 4
Random number 5: 9
Random number 6: 6
Random number 7: 8
Random number 8: 3
Random number 9: 10 |
At the end of
main()
you need a
return
-statement because the return value of
main()
is
int
. If you would have a function
void function()
you do not need a
return
-statement.
The final code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include <stdio.h>
#include <time.h>
using namespace std;
int main(int argc, char *argv[])
{
int NumArray[10];
srand((unsigned) time(0));
for(int i=0;i<10;i++)
{
NumArray[i]=1+(rand()%10);
for(int y=0;y<10;y++)
{
if(NumArray[i]==NumArray[y])
{
i--;
break;
}
}
}
for(int i=0;i<10;i++) cout<<"Random Number "<<i<<": "<<NumArray[i]<<endl;
return 0;
}
|
EDIT: Sorry, please use instead of the
goto again;
a
. It makes the same as the
goto again;
but you can't choose which label to go, becuse the for-loop is 'finished' and the program goes back to line 16.
HINT: If you use
i++
/
y++
/
whatever++
, it's the same as if you would code
i=i+1
/
y=y+1
/
whatever=whatever+1
. If you want to substract instead, use
i--
or something equal. If you want to add/substract more than one, use
i+=summand
/
i-=subtrahend