-
December 7th, 2014, 08:50 AM
#1
Fill Array with even numbers only
Hey guys i'm having a little issue here
i need to fill two 2D arrays, the first one with even numbers from 1 to 50, the second one with odd numbers from 1 to 50. Heres what i have
Code:
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int main()
{
srand(time(NULL));
int TA1[8][6];
int TA2[8][6];
int x;
for ( int row=0;row<8;row++)
{ for ( int col=0;col<6;col++)
{
x = rand()%50 + 1;
if ( x%2 != 0 )
TA1[row][col] = x;
}
}
for ( int row=0;row<8;row++)
{
for(int col=0;col<6;col++)
cout<<right<<setw(5)<< TA1[row][col] << " ";
cout<<endl;
}
for( int row=0; row<8;row++)
{
x=0;
for ( int col=0;col<6;col++)
{ x=rand()%50 +1;
if( x%2 ==0)
TA2[row][col] =x;
else continue;
}
}
for ( int row=0;row<8;row++)
{
for(int col=0;col<6;col++)
cout<<right<<setw(5)<< TA2[row][col] << " ";
cout<<endl;
}
}
-
December 7th, 2014, 09:12 AM
#2
Re: Fill Array with even numbers only
So... what exactly is the "little issue"?
-
December 7th, 2014, 09:18 AM
#3
Re: Fill Array with even numbers only
Ohh sorry i forgot to mention it
when i compile the program i get trash numbers in the array
however if i just fill the array with normal random number( not specifying if odd or even) the program works
any ideas on how to fix this?
-
December 7th, 2014, 09:37 AM
#4
Re: Fill Array with even numbers only
Ah, look carefully:
Code:
x = rand()%50 + 1;
if ( x%2 != 0 )
TA1[row][col] = x;
You're saying: generate a number in the range [1, 50]. If the number is odd, assign it to TA1[row][col]. Otherwise, move on. As such, if it so happens that you get a long enough sequence of odd numbers, none of the elements of your array would have been assigned a value.
Instead of checking if the number is odd, a better approach would be to generate an odd number. For example, notice that for an integer n, 2n+1 would be an odd number. Perhaps you could figure out a range for n such that you could apply this formula to obtain odd numbers, and hence generate pseudorandom numbers within that range.
-
December 8th, 2014, 10:03 AM
#5
Re: Fill Array with even numbers only
You can add internal loop and call rand until it generates desired number - odd or even.
-
December 9th, 2014, 03:48 AM
#6
Re: Fill Array with even numbers only
Originally Posted by AhmadMough
when i compile the program i get trash numbers in the array
When you "compile" the program you get one or more object modules (if there is no errors in code).
Then the linker links the executable module from all these "object modules" and usually some additional "object or library modules".
And when you run the program you may get "trash numbers in the array" (if your code is not logically correct!)
Victor Nijegorodov
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|