Sum of sales using break in for loop
Program to demonstrate an infinite for loop and the use of break in loop
Learning Objectives
- Use of infinite for loop
- Use of break within a for loop
Source Code
|
|
Alternate (?) : Related ( ? ) : |
Run Output
Code Understanding
float sale,sum=0.0; //variables for data collection and result storage.
for( ; true; )
This is an infinite for loop. The infinite for loop is like infinite while only with a small difference of empty first and third part of the 3 instruction for loop design.
{
cout<<“Enter Sale value :”;Β cin>>sale;
The sale figure is being collected inside the loop
sum+=sale;
The successive sale figure as the user keeps on entering the sale figure is being calculated here.
if(sale==0.0) break;
This is a way to come out of for loop, once the user enters a 0 value.
}
cout<<“Sum of total sales is “<<sum;
Final sales sum is being printed here.
Notes
- The above loop is also written as for( ; ; ) which is a completely EMPTY loop with just two instruction termination marks. When middle portion is not given in a loop then the true condition is assumed by the compiler. However sometimes correct implementation of empty loops may be compiler dependent.
- This code works like a do-while loop as it does execute at least once. and checks the exit condition at the end of the loop. In fact a language can do away with do-while loop and can use the while loop iteration process itself.
Common Errors
- Out of habit some students put the input collection outside and above the loop. In this case input has to be regularly collected so it has to be inside the loop.
Suggested Filename(s): tot-sales-for-break.cpp
Created: 1-Jan-2018 02:58 | Updated: 1-Jan-2018 03:05|
