Sum of sales using break in while loop
Program to demonstrate an infinite while loop and the use of break in loop
Learning Objectives
- Use of infinite while loop
- Use of break within a loop
Source Code
|
|
Alternate (?) : Related ( ? ) : |
Run Output
Code Understanding
float sale,sum=0.0; //variables for data collection and result storage.
while(true)
This is an infinite loop. This loop can only be broken by break, return or goto statements. Here we will learn to come out using break.
{
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 loop, once the user enters a 0 value.
}
cout<<“Sum of total sales is “<<sum;
Final sales sum is being printed here.
Notes
- The while(true) is often written as while(1) to depict the infinite while loop. This simply means that the condition inside the while loop remains true.
- 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 while loop. In this case input has to be regularly collected so it has to be inside the loop.
Suggested Filename(s): tot-sales-break.cpp
Created: 1-Jan-2018 02:49 | Updated: 15-Sep-2018 12:32|
