Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // collatzfile.cpp
- // Andrew Cummins
- // 21 Oct 2016
- // Program that will take users input of two integers and write collatz sequence between the two integers in a txt file
- #include <iostream>
- using std::cout;
- using std::endl;
- using std::cin;
- #include <string>
- using std::string;
- using std::getline;
- #include <sstream>
- using std::istringstream;
- #include <fstream>
- using std::ofstream;
- //function to handle the math and write to the file
- int collatz(int n)
- {
- // use ios_base::app to append the file instead of overwriting
- ofstream outfile("cseqs.txt", std::ios_base::app);
- if(!outfile)
- {
- // check if the file opened
- cout << "Could not open file" << endl;
- return 0;
- }
- outfile << n;
- while(n>1)
- {
- if(n%2==0)
- {
- n=n/2;
- outfile << ", " << n;
- }
- else
- {
- n=n*3+1;
- outfile << ", " << n;
- }
- }
- outfile << endl << endl;
- }
- int main()
- {
- // loop to keep asking user for input
- while(true)
- {
- // ask for first integer
- cout << "Enter the first integer to begin a Collatz sequence: ";
- int number1;
- cin >> number1;
- if(!cin){ // error check
- return 0;
- }
- if(number1<0){ // make sure it is not negative
- cout << "Must be a positive number" << endl;
- continue;
- }
- cout << endl << endl;
- // ask for last integer
- cout << "Enter the last integer to begin a Collatz sequence: ";
- int number2;
- cin >> number2;
- if(!cin){ // error checking
- return 0;
- }
- if(number2<0){// make sure it is not negative
- cout << "Must be a positive number" << endl;
- continue;
- }
- cout << endl << endl;
- // make sure last integer is larger than first
- if(number1>number2)
- {
- cout << "The second integer must be at least as large as the first: try again" << endl;
- continue;
- }
- else
- {
- cout << endl << endl;
- cout << "Sequence beginning at " << number1 << " ... " << number2 << " successfully written to file 'cseqs.txt'" << endl;
- cout << endl << endl;
- // send each integer in the range to the function
- for(int i=number1; i<=number2; ++i)
- {
- collatz(i);
- }
- return 0; // end program once file is written
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement