Hey guys, I need to make a program that lists out an average, highest and lowest stock price over a one month period. I'm focusing on the average first but it's already giving me problems.

http://omg.wthax.org/error_4.png

Here's what I have so far.

# include <iostream>

using namespace std;

int main()

{
        float stock[32];
          //Ask for the stock prices.
        cout << "List your stock prices during a one month period." << endl;
        int day = 0;
        int month = 31;
        while (day < month)
        {
          cout << "What was the stock price for day "<< ++day << "?" <<
               endl;
          cin >> stock[32];
        }
          //Calculate average stock price
        float average;
        average = (stock[0]+stock[1]+stock[2]+stock[3]+stock[4]+stock[5]+
                   stock[6]+stock[7]+stock[8]+stock[9]+stock[10]+stock[11]+
                   stock[12]+stock[13]+stock[14]+stock[15]+stock[16]+stock[17]+
                   stock[18]+stock[19]+stock[20]+stock[21]+stock[22]+stock[23]+
                   stock[24]+stock[25]+stock[26]+stock[27]+stock[28]+stock[29]+
                   stock[30]+stock[31]+stock[32])/31;
        cout << "Your average stock price over the month is " << average <<
             endl;
}

Yeah... really confused why this is happening. I would also like to know how to sort the numbers in array from highest to lowest and vice versa. I'm guessing I need to compare those values somehow in a while but I have no idea how to go about doing.

Recommended Answers

All 21 Replies

1) Why are you inputting all your stock prices into stock[32] , which is beyond your stock array? It stops at stock[31] .
2) Why are you adding all the stock prices by hand rather than
-- a) in a loop?
-- b) accumulating them during input?
3) What month do you know has 33 days? stock[0] to stock[32] is 33 values.

I see what I did wrong in questions one and three. And as for number two, my teacher didn't teach us how to loop things in an array. I only know how to use a while command at the moment. Got the average to work but can anyone show me an example of how to sort and compare the values in an array from highest to lowest? And as to why I set the array to stock[32] instead of stock[30], if I don't it gives me a segmentation fault.

I see what I did wrong in questions one and three. And as for number two, my teacher didn't teach us how to loop things in an array. I only know how to use a while command at the moment.

So what is this (after you fix the 32)?

while (day < month)
{
    cout << "What was the stock price for day "<< ++day << "?" << endl;
    cin >> stock[32];
}

And as to why I set the array to stock[32] instead of stock[30], if I don't it gives me a segmentation fault.

It wouldn't give you a seg fault if you'd use the proper values. In programming, you can't just arbitrarily change numbers just to make things work. You have to think about what values are necessary and choose the correct ones.

Using your definition, a month has 31 days. The array therefore goes from 0 to 30 (31 values). 32 is beyond the array bounds, therefore undefined -- a seg fault!

Here's what I changed in the code.

# include <iostream>

using namespace std;

int main()

{
        float stock[32];
          //Ask for the stock prices.
        cout << "List your stock prices during a one month period." << endl;
        int day = 0;
        int month = 31;
        float average = 0;
        while (day < month)
        {
          cout << "What was the stock price for day "<< ++day << "?" <<
               endl;
          cin >> stock[day];
          average = average + stock[day];
        }
          //Calculate average stock price
        average = average/31;
        cout << "Your average stock price over the month is " << average <<
             endl;
}

If I'm right, stock[0] is never used and it only uses stock[1]-stock[31] as it is using day as it's value. I still get a segmentation fault if I set the array to stock[31] though. Also:

Got the average to work but can anyone show me an example of how to sort and compare the values in an array from highest to lowest?

Anyone?

That's the problem. When day is 30, your cout statement increments it to 31, from where you try to read in the stock price for stock[31] which gives you a problem.
Rather than using ++day, use day + 1, since it doesn't increment day.

Also, if you're using floating point variables, initialize them as such. Good luck.

Edit: If you're looking for a sort and efficiency isn't what's important (as of now), then try bubble or insertion sort.

If I'm right, stock[0] is never used and it only uses stock[1]-stock[31] as it is using day as it's value.

You're right. And that's confusing. Increment day at the end of the loop. You will then use stock[0] thru stock[30], which is normal. C/C++ arrays are 0-based. It's easier to get used to that than fudging the code.

I still get a segmentation fault if I set the array to stock[31] though.

Remember, the last value usable in any array is one less than the definition. So stock[31] in this case is outside the array, since stock goes from 0 - 30 (31 values)

Tried bubble sorting for the first time (if you can even call this that) and... well just take a look.

# include <iostream>

using namespace std;

int main()

{
        float stock[30];
          //Ask for the stock prices.
        cout << "List your stock prices during a one month period." << endl;
        int day = 0;
        int month = 31;
        int counter = 0;
        float average = 0;
        while (day < month)
        {
          cout << "What was the stock price for day "<< ++day << "?" <<
               endl;
          cin >> stock[counter];
          average = average + stock[counter];
          ++counter;
        }
          //Calculate average stock price
        average = average/31;
        cout << "Your average stock price over the month is " << average <<
                "." << endl;
          //Find the highest and lowest stock price
        int loop = 0;
        float temp;
        int count = 0;
        while (loop < 31)
        {
                if (stock[count] > stock[count+1])
                {
                  temp = stock[count+1];
                  stock[count] = stock[count+1];
                  stock[count+1]= temp;
                  ++loop;
                }
        }
        cout << "Your highest stock price over the month is " << stock[30] <<
                "." << endl;
        cout << "Your lowest stock price over the month is " << stock[0] <<
                "." << endl;
}

I don't see any bubble sort in that code. You need to do a little research. Try GOOGLE.

Nice job assuming I haven't. I've looked up multiple times on how to do a bubble sort but all of them include parts I haven't learned yet like "for" to "void". The code I above is actually what the teacher said we should try to do but obviously it's not working for some reason. I would also think that there would be some way to make a sorting algoritham using only what we learned or else why would he show us only this part.

Edit - I'll tell you what we have learned, while loops, if, array, inputs, outputs, and variables.

I think if you want to enter the values for 31 days then you need to declare the stock[] with 31 elements i.e stock[31] rather than float stock[30];

If you are taking stock[30] in that case you can only enter 30 elements in that array.

In an array say stock[n], your first element will be stock[0] and last element will be stock[n-1]

// To calculate the average of the monthly stock prices using while loop

#include <cstdlib>
#include<iostream>

using namespace std;

int main(int argc, char* argv[])
{
  float stock[31]; // assuming that you will enter for 31 days.
  float average = 0;
  float sum = 0;
  unsigned int index = 0;
  
  cout<<"List your stock prices during a one month period"<<endl;
  
  while(index < 31)
  {
    cout << "What was the stock price for day "<< index + 1 << " ?" <<endl;
    cin >> stock[index];
    sum = sum + stock[index]; 
    index++;          
  }
  average = sum/(index+1); 
  cout<< "Your average stock price over the month is: " << average <<endl;
  
  system("pause");
  return EXIT_SUCCESS;
}

Any for loop can be transformed into a while loop:

for(int i = 0;i<max;i++)
{
   //stuff
}

is equivalent to

int i = 0;
while(i<max)
{
   //stuff
   i++;
}

The wikipedia-page has a some nice pseudo-code in it which will allow you to think up your own implementation. It's strange however that you learn bubble-sort before you learn how functions work... :S

Dear C.Cen,

I hope this code will fulfill all your requirements.

#include <cstdlib>
#include<iostream>

using namespace std;

int main(int argc, char* argv[])
{
  unsigned int noOfDays = 31; // you can change it as per your requirement
  unsigned int index = 0;
  float stock[noOfDays]; // assuming that you will enter for 31 days.
  float average = 0;
  float sum = 0;
  bool flag = 1;
  cout<< " List your stock prices during a one month period "<<endl;
  
  while(index < noOfDays)
  {
    cout << "What was the stock price for day "<< index + 1 << " ?" <<endl;
    cin >> stock[index];
    sum = sum + stock[index]; 
    index++;          
  }
  average = sum/index; 
  cout<< "Your average stock price over the month is: " << average <<endl;
    
  for(int j = 1; (j < noOfDays && flag); j++)
  {
    for(int i = 0; i < noOfDays-1; i++)
    {
      float temp = 0;
      if(stock[i+1] < stock[i]) // Ascending order
      {
        temp = stock[i];
        stock[i] = stock[i+1];
        stock[i+1] = temp;
        flag = 1; // To confirm that swapping has been occured                 
      }
    }
  }
	
  cout << "Your highest stock price over the month is: " << stock[noOfDays-1] << endl;
  cout << "Your lowest stock price over the month is: " << stock[0] << endl;
    
  system("pause");
  return EXIT_SUCCESS;
}
commented: Don't do this. Also, he said he hasn't learned "for" so how is this useful to him? -1
// Using While loop
#include <cstdlib>
#include<iostream>

using namespace std;

int main(int argc, char* argv[])
{
  unsigned int noOfDays = 31; // you can change it as per your requirement
  unsigned int index = 0;
  float stock[noOfDays]; // assuming that you will enter for 31 days.
  float average = 0;
  float sum = 0;
  bool flag = 1;
  cout<< " List your stock prices during a one month period "<<endl;
  
  while(index < noOfDays)
  {
    cout << "What was the stock price for day "<< index + 1 << " ?" <<endl;
    cin >> stock[index];
    sum = sum + stock[index]; 
    index++;          
  }
  average = sum/index; 
  cout<< "Your average stock price over the month is: " << average <<endl;
  
  int j = 1;  
  while(j < noOfDays && flag)
  {
    int i = 0;
    while(i < noOfDays-1)
    {
      float temp = 0;
      if(stock[i+1] < stock[i]) // Ascending order
      {
        temp = stock[i];
        stock[i] = stock[i+1];
        stock[i+1] = temp;
        flag = 1; // To confirm that swapping has been occured                 
      }
      i++;
    }
    j++;
  }
	
  cout << "Your highest stock price over the month is: " << stock[noOfDays-1]<<endl;
  cout << "Your lowest stock price over the month is: " << stock[0]<<endl;
    
  system("pause");
  return EXIT_SUCCESS;
}

@amit23.goyal: "Good job" on giving away free code man! Heavens forbid that the OP should actually learn something today. :icon_frown:

And if you're going to post code, be sure it compiles and works.

At Daniweb we try to help people by teaching them how to solve their problem their-selves rather than handing them a ready-to-go solution.

Dear Nick Evan,

Yes, that was my mistake and already got the -2 reputation for the same.

At least I learned a lesson today :)

My code is fully tested.


Cheers,
Amit Goyal


My code is fully tested.

What compiler are you using (and what wanring level) because this is no good:

unsigned int noOfDays = 31; // you can change it as per your requirement
  unsigned int index = 0;
  float stock[noOfDays]; // assuming that you will enter for 31 days.

If you want a dynamic array, you should've used new and delete . But in your case, you probably want const unsigned int noOfDays = 31

# include <iostream>

using namespace std;

int main()

{
        float stock[30];
          //Ask for the stock prices.
        cout << "List your stock prices during a one month period." << endl;
        int day = 0;
        int month = 31;
        int counter = 0;
        float average = 0;
        while (day < month)
        {
          cout << "What was the stock price for day "<< ++day << "?" <<
               endl;
          cin >> stock[counter];
          average = average + stock[counter];
          ++counter;
        }
          //Calculate average stock price
        average = average/31;
        cout << "Your average stock price over the month is " << average <<
                "." << endl;
          //Find the highest and lowest stock price
        int loop = 0;
        float temp;
        int count = 0;
        while (loop < 31)
        {
                if (stock[count] > stock[count+1])
                {
                  temp = stock[count+1];
                  stock[count] = stock[count+1];
                  stock[count+1]= temp;
                  ++loop;
                }
                else
                {
                  ++loop;
                }
        }
        cout << "Your highest stock price over the month is " << stock[30] <<
                "." << endl;
        cout << "Your lowest stock price over the month is " << stock[0] <<
                "." << endl;
}

I still don't see why this doesn't work (Nobody really told me what's wrong with it). I'm gonna throw a wild guess here and assume that it's because there aren't enough loops (it only runs 31 times)to make an entire swap of the array with randomly inputted numbers. I'm pretty certain I got the swap code right.

if (stock[count] > stock[count+1])
                {
                  temp = stock[count+1];
                  stock[count] = stock[count+1];
                  stock[count+1]= temp;
                  ++loop;
                }
                else
                {
                  ++loop;
                }

I think it's just that I need a way for it check if a swap is made or not...

Sigh, read http://learncpp.com

If you don't like learcpp, tale a look at http://www.cplusplus.com/doc/tutorial/

There is NO reason for you to be unable to do such a program on your own with enough learning. This sounds jackass-y, but it's NOT intended to. Just trust me, put the time in and you'll be rewarded big time.

commented: Not so jackassy! +7

Hi brother ! I thank you

commented: You are so welcome! Here's a present. -1
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.