While Loop
#include <iostream> using namespace std; int main() { int cnt = 0, // Count of numbers read. tot = 0; // Total of numbers read. int num; // Input number. // Read all the numbers (until a read fails and the stream // turns bad.) cin >> num; while(cin.good()) { tot += num; ++cnt; cin >> num; } /* Print the average. */ if(cnt > 0) cout << "Average is " << (double)tot / (double)cnt << endl; else cout << "No numbers." << endl; }

This program reads integers and adds them together as long as there are numbers to read, then prints the average. Most of what is shown here is familiar from Java, though we also see some features of C++ iostreams which are not Java-like at all.