Lesson 6: Revision to while

Revise lesson 5 and attempt Challenge 2 and 3 once more.

Intermediate while

while is powerful because it allows a program to run until a certain condition is reach. Remember that you wrote a program to find the first 10 Fibonacci numbers in Lesson 4?

Challenge 1

Now, rewrite you program to find the number of Fibonacci numbers that are less than 1000. You will need to use the while keyword. Hint: you need to use if to check whether the Fibonacci number is greater than 1000. If it is, stop the while loop.

Reading/writing from a file

The programs that you are able to write till now read values from keyboard and output to the console. Sometimes, you might want to read large amount of data and the data is usually presented in a file. In this section, you will learn how to read and write to files on the computer.

filestream

You include the iostream to read from keyboard and print to console. If you are going to read and write to file, then you need to include the filestream library.

#include <iostream>
#include <fstream>

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

Go to this web page and read until you reach Text files.

Challenge 2

print