Click here to Skip to main content
15,885,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using arrays, prompt the user to input how many random number to generate in the range of -10 to 10. Valid input is from 1-50. Display all the negative numbers entered and compute and output the sum of all the negative numbers entered. Also, display all the positive numbers entered and compute and output the product of all the positive numbers entered.

What I have tried:

C++
        do{
            cout<<"No. of random numbers (-10-10): "<<endl;
            cin>>howmany;
                if(howmany<1 || howmany >50)
                cout<<"INVALID INPUT"<<endl;
        }while (howmany<1 || howmany>50);

    cout<<endl<<endl
    <<"The "<<howmany<<" random numbers from 1-50 are :"<<endl;

srand(time(0));

    for (ctr=0,negativectr=0,positivectr=0; ctr<howmany;>     {
        randnum[ctr]= rand() % 50-1;
        cout<<randnum[ctr]<<"\t";

        if (randnum[ctr] % 2 ==0)
            {
                positive[positivectr]=randnum [ctr];
                positivectr++;
            }

        else
            {
                negative[negativectr]=randnum [ctr];
                negativectr--;
            }

{
    cout<<endl<<endl<<"There are "<<positivectr<<" positive numbers generated"<<endl;
for(ctr=0;ctr<positivectr;ctr++);>
}
    cout<<positive[ctr]<<"\t";
}

cout<<endl;

cout<<"There are "<<negativectr<<" negative numbers generated"<<endl;
for(ctr=0;ctr<negativectr;ctr++)>
{
    cout<<negative[ctr]<<"\t";
}
Posted
Updated 10-Aug-16 22:31pm
v2
Comments
Patrice T 11-Aug-16 4:08am    
And what is the problem in this code ?

1 solution

Start by looking at your random number generation code: does it generate numbers in the required range?
Simply put: no.
Your code generates numbers between 0 and 48 inclusive, not values between -10 and 10 inclusive. Rememebr, "%" is the modulus operator: it returns the remainder of a division, so x % 10 will always return values below 10, i.e. "0" to "9" inclusive.

Try changing it to something like:
C++
eachRandomNumber = (rand() % 21) - 10;

The "21" is there so it generates values between 0 and 20 inclusive, then it subtracts 10 to offset the values into your range -10 to 10.

And then use the debugger to work out what else is going on.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900