Speed Challenge, my solution:
Today in class my teacher proposed a simple (for me) challenge and wanted the fastest possible solution, while still being well done, etc. I was the first one done, and mine was imo the best (some ppl had a variable for each input, no loops, etc).
The problem was this:
Take in 5 integers from user, write to a file.
Read values in, and display the sum and average of them.
My solution. I am posting this too see if there was a faster way to do it, or what your opinion is. I wrote it in 3 1/2 minutes.
Code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
int value,
sum = 0,
avg;
ofstream outfile;
ifstream infile;
outfile.open("c:\\myfile");
for (int i = 1; i <= 5; i++)
{
cout << "Enter an integer value: ";
cin >> value;
outfile << value << endl;
}
outfile.close();
infile.open("c:\\myfile");
while (! infile.fail())
{
if (infile >> value)
{
sum += value;
}
}
avg = sum / 5;
cout << "Sum: " << sum << endl;
cout << "Avg: " << avg << endl;
return 0;
}
Re: Speed Challenge, my solution:
>>the fastest possible solution
>>Take in 5 integers from user
These two sentences don't go together very well. What's the point of a program that works like lightning, but has to wait for the user to input data, which in CPU terms, is like waiting for eternity. And don't tell me the point is "its an exercise", because their are better speed style lesson.
3.5 minuits sounds pretty fast to me!
I think there is some value to this type of exercise. When you are a beginner, you have to 1- Figure out how you're going to do it. 2- Look in books to find the functions and how to use them. 3- Debug all of your errors.... Well... even experienced programmers have to take all these steps, but they don't have to look-up as much, and they don't have to do nearly as much debugging! So, an exercise lile this can let you know how much you "know" and how much you're haviing to look-up and re-do!
A friend of mine, who is an experienced-professional programmer, described a process similar to Hammer. By the time they start writing the code, almost every line has been documented! The actual writing of the code is the easiest part.
Personally, I don't spend that much time "up-front". I seem to spend more time improving the program as I do "making it work". It seems like most of the "improvements" are tweeking the user interface to make it user-proof and making the output display more "meaningful". Of course, this should be planned-out in advance.
P.S.
At least your teacher is still interested in keeping you challenged, and is letting you show your stuff!