Why need this line before go into loop?

Hi, the following code from C++ book, but I don't know why need this line of code at line 11 and 12
1
2
cout<<"Enter price of item: ";
cin>>price;


and also why need int itemCnt=0;, I tried to use only int itemCnt; without declare to 0, it would run well too...thanks...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <conio>

int main ()
{

	int itemCnt=0;
	double price, totalPrice=0, averagePrice;
   cout<<"Program To Calculate The Average and Total Price Of Items \n\n";

   cout<<"Enter price of item: ";
   cin>>price;

   while(price>0)
   {
   	totalPrice += price;
      itemCnt++;

      cout<<"Enter price of item: ";
      cin>>price;
   }

   cout<<"\nThe Average Price Of The Items Is "<<totalPrice/itemCnt;
   cout<<"\nThe Total Price of the Items Is "<<totalPrice;
   cout<<"\nEnd of Program";

getch ();
return 0;
}
This line:
 
 cin>>price;

Gets input from user, and stores in the price variable.

And, if you don't initialize your variables, their values may be anything until you set them to something spesific. Therefore, it is better to just initialize them with some value. This allows you to be sure that what is that variable's value.
Thanks, I mean why I need both line 11 and 12? Can I just delete them? Coz I don't know the reason why they are not inside the while loop which already have that 2 lines?
Ohh, I see your question now I guess. You could also do something like this:
1
2
3
4
5
6
do {
      cout<<"Enter price of item: ";
      cin>>price;
      totalPrice += price;
      itemCnt++;
} while (price > 0);


This does the same thing as your code. Difference is, while loop first checks the condition and than executes the block, on the other hand, do-while loop, executes the block first, then checks for the condition to exeute the block again. Thus, code block in do-while loop gets executed at least once. Thus, making your "Enter price of the item: " prompt to be shown at least one time.
Last edited on
I mean why I need both line 11 and 12? Can I just delete them? Coz I don't know the reason why they are not inside the while loop which already have that 2 lines?


because it's related with your while. if price uninitialized, you'll get error message, that price is uninitialized. as far as i know, even though that price is initialized by default, it will contain the default value (zero). your while will not work at all (and so the rest of the code)...
Last edited on

Thanks, I mean why I need both line 11 and 12? Can I just delete them? Coz I don't know the reason why they are not inside the while loop which already have that 2 lines?


You cannot delete any of them because of the form of loop used and the way it's structured. If you wish to use one and only one input statement, yasar's advise would be best.
Thanks everyone for the explaination~~

For Yasar~I understand ur explanation that "while" will check the condition before doing the content inside that while loop and do-while loop will just execute the content at very 1st time, then only excute the condition in while loop right(same as my code, where Enter price at very 1st, then only go inside while loop)?

So, I guess u mean delete this
1
2
3
4
5
6
7
8
9
10
11
   cout<<"Enter price of item: ";
   cin>>price;

   while(price>0)
   {
   	totalPrice += price;
      itemCnt++;

      cout<<"Enter price of item: ";
      cin>>price;
   }


and replace with
1
2
3
4
5
6
do {
      cout<<"Enter price of item: ";
      cin>>price;
      totalPrice += price;
      itemCnt++;
} while (price > 0);

right?

but now i testing with the input 2 and 2
it should give average=2 by calcualting in this way ((2+2)/2), right? But the answer give 1.3333 which mean ((2+2)/3), may i know why? Thanks...^^
Your itemCnt variable will always be one big than actual number of items, since it will get incremented even when you enter a price that is zero or negative, Also, if you enter something negative as a price, your total price variable will be wrong too. Consider this:

You have entered 10:
totalPrice = 10, itemCnt = 1;

You have entered 20:
totalPrice = 30 itemCnt = 2;

Now you have wanted to quit, and entered -3, since it is not bigger than zero, and now your variables looks like:

totalPrice 27, itemCnt = 3;
at this points, you are out of do-while loop. And that is not what you want, you could define price to be unsigned, and remove 1 from itemCnt to get over this issue:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <conio>

int main ()
{

	int itemCnt=0;
	unsigned double price, totalPrice=0, averagePrice;
   cout<<"Program To Calculate The Average and Total Price Of Items \n\n";
   do {
      cout<<"Enter price of item: ";
      cin>>price;
      totalPrice += price;
      itemCnt++;
   } while (price > 0);
   --itemCnt; // decrement itemCnt by one
   cout<<"\nThe Average Price Of The Items Is "<<totalPrice/itemCnt;
   cout<<"\nThe Total Price of the Items Is "<<totalPrice;
   cout<<"\nEnd of Program";

getch ();
return 0;
}


Since there is no chance that price will be a negative number, you don't have decremented total price problem. And by decremening itemCnt, you will get actual number of items.
Last edited on
That gets a little ugly, and you can't have an unsigned double

I prefer while( cin>>price and price>0 ) but as you want to show a message use a function
Like
1
2
3
4
istream& get_input( istream &in, double &value, const char *message, ostream &out=std::cout ){
  out << message;
  return in>>value;
}
which can be easily templatized.

And used as while( get_input(cin, price, "Enter price of item: ") and price>0 )
Thanks yasar, but like what ne555 said, we can't have unsigned double, I got this error "too many type in declaration"...so far ur --itemCnt got help to reduce itemCnt by 1...but I still not sure how to solve the negative number from ur code~

Thanks ne555 for ur code too...
I don't really understand ur code, is it run in Visual Studio 2010 C++, I'm a new learner, don't know the meaning of, "&" in &value and &out, "*" in *message as well as istream and ostream(i saw ifstream and ofstream before only which I used in Borland C++)...

also what is "out" in out << message;, is that same as cout?
return in>>value; means return 0?

get_input in while( get_input(cin, price, "Enter price of item: ") and price>0 ) means cin?

Thanks and hope u can explain a little bit^^
Take a look at the tutorial http://cplusplus.com/doc/tutorial/functions2/
then when it does in>>value; it is actually changing the 'price' variable.

For sake of simplicity take const char* as the type to use when passing strings as arguments. (like "hello world"). It is const because we will not modify its content.
If you know about std::string use it instead.

cin is a istream
cout, cerr, clog are ostreams.
ofstream are ostreams, ifstreams are istreams (take it like an especial type)
So the idea was to make it general, the function works with cin/cout but also with files.
If you want just change it to
1
2
3
4
bool get_input( double &value, std::string message ){
  std::cout << message;
  return std::cin >> value;
}


while( cin>>input ) will keep reading till an error occur. By instance, the input ends or you try to do something like putting a character in an integer variable.
So return cin>>value; is telling you if the input was successful.
Thanks for the explanation, I will try to look in details at the link given...
By the way, may I know what compiler u use for the above function? and can it suit Borland C++ and Ms Visual Studio 2010 C++? Thanks...
Topic archived. No new replies allowed.