Good Afternoon,

I'm having some difficulties on an assignment where I need to write a program which will generate a list of signed random numbers, find the average of all the numbers, the average of the positive and negative numbers and the largest e number. So far I have this code, but it doesn't runs.
Here is the main cpp file:

#include <iostream>
#include <fstream>
#include <time.h>
#include "hw5_head.h"

using namespace std;

int main()

{
            ofstream outFile;

            int list[1000]; //integer array for a list

            int n=0; //indicates array size

            srand((unsigned)time(0));
            int random_number;
            for(int i=0; i<1000; i++)
            {
                random_number = (rand()%0)+1;
                cout << random_number<<endl;
            }

            outFile.open("output.txt"); //output the data to file


            int avg=0,avgP=0,avgN=0,maximum;


            avgs(list,n,avg,avgP,avgN);

            maximum=max(list,n);

            printList(outFile,list,n,avg,avgP,avgN,maximum);



            cout<<"\nsearch using linear search"<<endl;

            cout<<"List contains 20: "<<linearSearch(list,n,20)<<endl;

            cout<<"List contains 999: "<<linearSearch(list,n,999)<<endl;



            int comparisions = 0;

            bubbleSort(list,n,comparisions);

            cout<<"\n\nNumber of comparisions in bubble sort: "<<comparisions;



            cout<<"\nAfter bubble sort list elements are: "<<endl;

            for(int i=0;i<n;i++)

            cout<<list[i]<<" ";



            cout<<"\n\nsearch using binary search"<<endl;

            cout<<"List contains 14: "<<(bool)binarySearch(list,n,14)<<endl;

            cout<<"List contains 99: "<<binarySearch(list,n,99)<<endl;

            //closing the opened files


            outFile.close();

            return 0;

} 

Header file:

#include <iostream>
#include <fstream>
#include <time.h>

using namespace std;

#ifndef     HW5_HEAD_H
#define     HW5_HEAD_H

//generates random numbers and fills the array with those random numbers

void randomList(int list[ ], const int n)

{

            srand(time(0));

            for(int i=0;i<n;i++)

                        list[i]= (rand() % 1000)+1;

}

//finds average of positive, negative and all numbers seperately.

void avgs (const int list[ ], const int n, int &avg, int &avgP, int &avgN)

{

            int posNums=0,negNums=0;

            int posSum=0,negSum=0;

            for(int i=0;i<n;i++)

            {

                        if(list[i]>0)

                        {

                                    posSum += list[i];

                                    posNums++;

                        }

                        else if(list[i]<0)

                        {

                                    negSum += list[i];

                                    negNums++;

                        }                     

            }



            avgP = posSum/posNums;

            avgN = negSum/negNums;

            avg=(avgP+avgN)/2;

}

//finds the maximum value in the list

int max (const int list[ ], const int n)

{

            int maximum =list[0];

            for(int i=1;i<n;i++)

            {

                        if(list[i] >maximum)

                                    maximum=list[i];

            }

            return maximum;

}

//prints the list values,averages and maximum into the file

void printList(ofstream & outfile, const int list[ ], const int n, const int avg, const int avgP, const int avgN, const int max)

{

            outfile<<"List eleemnts are: "<<endl;

            cout<<"List eleemnts are: "<<endl;

            for(int i=0;i<n;i++)

            {

            outfile<<list[i]<<" ";

            cout<<list[i]<<" ";

            }

            outfile<<"\n\nAverage of positive numbers: "<<avgP<<endl;

            cout<<"\n\nAverage of positive numbers: "<<avgP<<endl;

            outfile<<"Average of negitive numbers: "<<avgN<<endl;

            cout<<"Average of negitive numbers: "<<avgN<<endl;

            outfile<<"Average of all numbers: "<<avg<<endl;

            cout<<"Average of all numbers: "<<avg<<endl;

            outfile<<"Maximum is: "<<max<<endl;

            cout<<"Maximum is: "<<max<<endl<<endl;

}

//search for an element using linear search

bool linearSearch(const int list[ ], const int n, const int value)

{

            for(int i=0;i<n;i++)

            {

                        if(list[i] == value)

                                    return true;

            }

            return false;

}

//sorting the list using bubble sort

void bubbleSort(int list[ ], const int n, int & counts)

{

   bool swap;

   int temp;

   counts=0;



   do

   {

      swap = false;

      for (int count = 0; count < (n - 1); count++)

      {

                          counts++;

         if (list[count] > list[count + 1])

         {

            temp = list[count];

            list[count] = list[count + 1];

            list[count + 1] = temp;

            swap = true;

         }

      }

   } while (swap);

}

//searching the array using binary serach

bool binarySearch(const int list[ ], const int n, const int value)

{

            int first = 0,             // First array element

       last = n - 1,       // Last array element

       middle,                // Mid point of search

       position = -1;         // Position of search value

   bool found = false;        // Flag



   while (!found && first <= last)

   {

      middle = (first + last) / 2;     // Calculate mid point

      if (list[middle] == value)      // If value is found at mid

      {

         found = true;

         position = middle;

      }

      else if (list[middle] > value)  // If value is in lower half

         last = middle - 1;

      else

         first = middle + 1;           // If value is in upper half

   }

   return found;

}

#endif

I appreciate any help that I can get.

Thank you

More details needed. Doesn't run how?

1) Won't compile?
2) Compiles but does not run to completion? If so, how far does it get? How often does it crash? Where does it crash?
3) Runs but gives bad results? If so, what are the correct results, what are the actual results, and ow do they differ?

compile but, hangs forever. Only a black screen shows up and nothing happens

random_number = (rand()%0)+1;

Why %0 ? That's a do-nothing statement.

line 31, main.cpp. The value of variable n is 0

Ancient Dragon,

I update %0 to random_number = (rand()%100)+1;
Now, the program is generating the numbers and then crash.

What about the value of n that I mentioned? Also, the array is not being initialized. The program gets a random number but does nothing with it except display it on the console screen.

Another problem -- rand() does not return negative values, so all you will get are a list of 1000 positive numbers.

Ancient Dragon,

Can you help me to figure out why the program crash when it show the list of the numbers it generated. Here is the updated code I have so far.
main .ccp

#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>
#include "hw5_head.h"

using namespace std;

int main()

{
        ofstream outFile;

        const int n = 1000; //indicates array size
        int list[n]; //integer array for a list
        int avg,avgP,avgN,maximum;
        int value, counts;

        randomList(list, n);

        showList(list, n);    


        avgs(list,n,avg,avgP,avgN);

        maximum=max(list,n);

        printList(outFile,list,n,avg,avgP,avgN,maximum);

        cout<<"\nsearch using linear search"<<endl;

        cout<<"List contains: "<<linearSearch(list,n,value)<<endl;

        bubbleSort(list,n,counts);

        cout<<"\nAfter bubble sort list elements are: "<<endl;

            for(int i=0;i<n;i++)

            cout<<list[i]<<" ";



            cout<<"\n\nsearch using binary search"<<endl;

            cout<<"List contains: "<<(bool)binarySearch(list,n,value)<<endl;


            //closing the opened files


            outFile.close();

            return 0;

} 

Header file:

#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>

using namespace std;

#ifndef     HW5_HEAD_H
#define     HW5_HEAD_H

//generates random numbers and fills the array with those random numbers

void randomList(int list[], const int n)

{
    signed seed;
    cout << "Enter a random seed ";
    cin>>seed;
    srand(seed);

    for (int i = 0; i < n; i++)
    {
        list[i] = rand()%1000;
    }
    return;
}

//finds average of positive, negative and all numbers seperately.

void avgs (const int list[ ], const int n, int &avg, int &avgP, int &avgN)
{
    int posNums=0,negNums=0;
    int posSum=0,negSum=0;

            for(int i=0;i<n;i++)

            {

                        if(list[i]>0)

                        {

                                    posSum += list[i];

                                    posNums++;

                        }

                        else if(list[i]<0)

                        {

                                    negSum += list[i];

                                    negNums++;

                        }                     

            }



            avgP = posSum/posNums;

            avgN = negSum/negNums;

            avg=(avgP+avgN)/2;

}

//finds the maximum value in the list

int max (const int list[], const int n)
{

            int maximum =list[0];

            for(int i=1;i<n;i++)

            {

                        if(list[i] >maximum)

                                    maximum=list[i];

            }

            return maximum;

}

//prints the list values,averages and maximum into the file

void printList(ofstream & outFile, const int list[], const int n, const int avg, const int avgP, const int avgN, const int max)
{

            outFile<<"List elements are: "<<endl;

            cout<<"List elements are: "<<endl;

            for(int i=0;i<n;i++)

            {

            outFile<<list[i]<<" ";

            cout<<list[i]<<" ";

            }

            outFile<<"\n\nAverage of positive numbers: "<<avgP<<endl;

            cout<<"\n\nAverage of positive numbers: "<<avgP<<endl;

            outFile<<"Average of negitive numbers: "<<avgN<<endl;

            cout<<"Average of negitive numbers: "<<avgN<<endl;

            outFile<<"Average of all numbers: "<<avg<<endl;

            cout<<"Average of all numbers: "<<avg<<endl;

            outFile<<"Maximum is: "<<max<<endl;

            cout<<"Maximum is: "<<max<<endl<<endl;

}

//search for an element using linear search

bool linearSearch(const int list[ ], const int n, const int value)
{

            for(int i=0;i<n;i++)

            {

                        if(list[i] == value)
                        {
                            return true;
                        }

            }

            return false;

}

//sorting the list using bubble sort

void bubbleSort(int list[ ], const int n, int & counts)

{

   bool swap;
   int temp;
   int i,j;

   counts=0;

   for (i = 0; i<n; i++)
   {
       swap = false;
       for (j = 0; j < n - i - 1; j++)
       {
           if (list[j] > list [j+1])
           {
               swap = true;

               temp = list[j];
               list[j] = list[j+1];
               list[j+1] = temp;

               counts++;
           }
       }
           if(!swap)
               break;
    }
       return;
}



//searching the array using binary serach

bool binarySearch(const int list[ ], const int n, const int value)

{

       int first = 0,             // First array element

       last = n - 1,       // Last array element

       middle,                // Mid point of search

       position = -1;         // Position of search value

   bool found = false;        // Flag



   while (!found && first <= last)

   {

      middle = (first + last) / 2;     // Calculate mid point

      if (list[middle] == value)      // If value is found at mid

      {

         found = true;

         position = middle;

      }

      else if (list[middle] > value)  // If value is in lower half

         last = middle - 1;

      else

         first = middle + 1;           // If value is in upper half

   }

   return found;

}
void showList(const int list[], const int n)
{
    cout<<"The list is ..... " <<endl;
    for (int i=0; i<n; i++)
    {
        cout<<setw(8)<<right<<list[i];
        if ((i+1)%1000==0)
            cout<<endl;
    }
    cout<<endl;
}
#endif

Problem #1:
Never ever put code or variable definitions in a header file. Header files are used to declare functions and variables, not define them.

Problem #2:

void showList(const int list[], const int n)
{
    cout<<"The list is ..... " <<endl;
    for (int i=0; i<n; i++)
    {
        cout<<setw(8)<<right<<list[i];
        if ((i+1)%1000==0)        // What are these 2 
        cout<<endl;               // lines supposed to do?
    }
    cout<<endl;
}

Problem #3:
In all your functions, why are there so many blank lines? It makes the code very hard to follow.

I've looked through the program through the call to printList() and don't see any problems with crashing. You might need to be more specific.

The immediate problem actually lies in avgs(); what is happening is that, since you aren't generating any negative numbers, negNums is zero, which means that when you go to get the average of the negative numbers, you cause a divide-by-zero error.

Since this is a possibility even when correctly generating the random numbers (it might by sheer chance only have positive or negative values), you will want to test for this eventuality:

    if (posNums > 0)
        avgP = posSum / posNums;
    if (negNums > 0)
        avgN = negSum / negNums;

Of course, the root problem lies with how you are generating the numbers. To get a range [-1000, 1000], you want a range (that is, a modulo) of 2000 and an offset of -1000.

//generates random numbers and fills the array with those random numbers
void randomList(int list[], const int n)
{
    signed seed;
    cout << "Enter a random seed ";
    cin>>seed;
    srand(seed);
    for (int i = 0; i < n; i++)
    {
        list[i] = (rand() % 2000) - 1000;
    }
    return;
}

While this isn't a very good way to generate random numbers, it will at least give you the desired range.

Thank you everyone for your help, I really appreciated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.