Help with a loop please :) - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Help with a loop please :)

UlnarianUlnarian Posts: 13Member
Hey all,

I'm trying a problem in this C book that I picked up and one of them has me stumped. I'm supposed to create a program that uses a loop to sum up monthly sales for the year.

Basically, I want something that asks you, "What were your sales in January", "What were your sales in February", etc., etc.

My thought is something like:

-----------------------------------------
#include

int main()
{
using namespace std;

string months[3]={"January", "February", "March"};
int i=0;
int monthly_sales;
int total_sales;

while (i <= 3)
{
cout << "How much did you make in " << months[i] << " : ";
cin >> monthly_sales;
total_sales+=monthly_sales;
++i;
};
cout << "Your total sales are: " << total_sales;

return 0;
}
-------------------------

However, this either crashes, or it returns a crazy value. For instance, I'll enter 1+1+3 for monthly sales and the total sales will be 233243243 or something like that.

Is it wrong to scroll through the elements of a string array the way I've done in this code? If so, what is the proper way to move down the elements of a string array with a loop. Thanks!

Comments

  • UlnarianUlnarian Posts: 13Member
    Actually, nevermind, I've located the problems :)



    : Hey all,
    :
    : I'm trying a problem in this C book that I picked up and one of them has me stumped. I'm supposed to create a program that uses a loop to sum up monthly sales for the year.
    :
    : Basically, I want something that asks you, "What were your sales in January", "What were your sales in February", etc., etc.
    :
    : My thought is something like:
    :
    : -----------------------------------------
    : #include
    :
    : int main()
    : {
    : using namespace std;
    :
    : string months[3]={"January", "February", "March"};
    : int i=0;
    : int monthly_sales;
    : int total_sales;
    :
    : while (i <= 3)
    : {
    : cout << "How much did you make in " << months[i] << " : ";
    : cin >> monthly_sales;
    : total_sales+=monthly_sales;
    : ++i;
    : };
    : cout << "Your total sales are: " << total_sales;
    :
    : return 0;
    : }
    : -------------------------
    :
    : However, this either crashes, or it returns a crazy value. For instance, I'll enter 1+1+3 for monthly sales and the total sales will be 233243243 or something like that.
    :
    : Is it wrong to scroll through the elements of a string array the way I've done in this code? If so, what is the proper way to move down the elements of a string array with a loop. Thanks!
    :

Sign In or Register to comment.