AIOC Banner

Addition

Let's write a program that solves Addition. Compared to some of the other problems on this training site, the solution isn't too complicated, so this will be a good opportunity to get some practice writing programs that handle the file I/O correctly. Many of the basic techniques used to solve this problem are universal to all informatics problems, so the sooner we get familiar with them, the better.

Before writing even a single line of code, we should make sure we know exactly what the program needs to do. (After all, if we don't plan ahead, there's a good chance we'll end up making mistakes or wasting time and effort.) Of course, all programs are different and there is no definitive solution, but all proper solutions to Addition will need to do the following things:

Each of these steps will be addressed one by one.

Skeleton Code

Open up a new file and write a few lines of code in the language of your choice. The program doesn't actually have to do anything right now: we're going to use it as a framework and insert all the really important code around it.

Below are a few examples in various languages supported by the training site. If your language of choice isn't there, don't panic - the instructions translate easily to most programming languages you'll encounter.

C C++
#include <stdio.h>

/*Declare variables*/

int main() {
	/*Read the input*/
	
	/*Calculate the answer*/
	
	/*Write the output*/
	
	/*Clean up!*/
	
	return 0;
}
#include <cstdio>

/*Declare variables*/

int main() {
	/*Read the input*/
	
	/*Calculate the answer*/
	
	/*Write the output*/
	
	/*Clean up!*/
	
	return 0;
}
Pascal
program Solution;

{Declare variables.}

begin
	{Read the input.}
	
	{Calculate the answer.}
	
	{Write the output.}
	
	{Clean up!}
end.

As you can see, there are a lot of comments in the sample code. Notice how they roughly correspond to the dot points in the previous section? Since we went to the trouble of planning out the program beforehand, this extra measure makes sure that we stick to the plan. (Sure, little reminders like 'declare variables' or 'calculate the answer' aren't going to make or break a solution, but they make the code more readable and easier to understand.)

Reading the input

Different languages have different ways of dealing with text files. Depending on your language and method of choice, you may wish to insert the following code right after the 'declare variables' comment:

C, C++
FILE* inputFile;
This declares a FILE* variable (used for working with text files) called inputFile.
Pascal
var
inputFile: text;
This declares a text variable (used for working with text files) called inputFile.

Next we tell the computer to open inputFile for reading. The following code goes in the "Input" section:

C, C++
inputFile = fopen("addin.txt", "r");

This line opens the file named addin.txt and associates it with inputFile. In practice, this means that anything we now do to inputFile in our code will now happen to addin.txt when we run the program. The "r" simply tells the computer that we plan on reading from the file.

Pascal
assign(inputFile,'addin.txt');
reset(inputFile);

The first line says to assign inputFile to the file named addin.txt. In practice, this means that anything we now do to inputFile in our code will now happen to addin.txt when we run the program.

The second line resets inputFile. This tells the computer that we will be reading from the file. If we didn't include this line, the computer would be unprepared when asked to read data from the file, and the program would probably crash when run.

Now that we are ready to read from the file, the next step is exactly that - we're after the two integers from the problem statement, a and b, which we will eventually add together. But before we can do this, we need somewhere to store these values during the calculation. Let's declare a couple of variables.

Let's backtrack and insert the following code at the bottom of the "Variables" section:

C, C++
int a, b, total;
Pascal
a, b, total: longint;

The above code declares three different integer-type variables to be used later on in the code. The first two, a and b, will be used to store the values in the input file. As for the third? That's for later. We'll use total to store the value of a + b.

You may not agree with the variable names in the example - there is no one correct way to name variables, so give them whatever names you want. "a, b, total" is just as legitimate as "firstNumber, secondNumber, answer" so long as the names of the variables remind you exactly what they're for.

Now that we have our variables ready, we just have two more lines of code before we're done with the input-reading part of our program. First, insert the following code at the bottom of the "Input" section:

C, C++
fscanf(inputFile, "%d %d", &a, &b);

This line tells the computer several things. "fscanf(inputFile...)" tells it to read data from inputFile. "%d %d" tells the computer to expect two integers separated by a space. The rest of the line tells it to store these integers in a and b (in that order).

Pascal
readln(inputFile,a,b);

This line tells the computer several things. "readln(inputFile...)" tells it to read an entire line from inputFile. The rest of the variable names between the parentheses tell it what to do with the data it reads - in this case, we're asking it to read in an integer and store it in a, and then to read in an integer and store it in b.

Finally, we need to do a bit of housekeeping. When a program opens a file for reading or writing, it's good practice to close the file before finishing. Otherwise we leave ourselves open to a variety of potentially undesirable side effects. Closing the file is achieved simply enough, since all we need to do is add the following line somewhere afterwards:

C, C++
fclose(inputFile);
Pascal
close(inputFile);

The above code would best be placed either at the end of the "Input" section or somewhere in the "Clean up!" section, just so that we can find it later if we need to.

By now our code should be beginning to resemble a full program. If you've been working in C++, it might look a bit like this:

#include <cstdio>

/*Declare variables*/
FILE* inputFile;
int a, b, total;

int main() {
	
	/*Read the input*/
	inputFile = fopen("addin.txt", "r");
	fscanf(inputFile, "%d %d", &a, &b);
	
	/*Calculate the answer*/
	
	/*Write the output*/
	
	/*Clean up!*/
	fclose(inputFile);
	
	return 0;
}

Before we go on you might want to give the code a quick test run. Compile it, make sure there's a file called addin.txt in the same directory (complete with two integers on the first line), and run it. If it compiles properly and doesn't crash, we're doing good.

Calculating the answer

As it turns out, the code to add the two numbers together is probably the simplest part of the program! Adding numbers is a fundamental computer operation, and most programming languages can tell the computer to add two numbers without any hassles. If you're still following the skeleton code structure, you'll want to put this in the "Calculation" section.

total = a + b;

It does exactly what it looks like - the value of total is set to the sum of the two other variables. Since these variables have just been loaded from the input file, the resulting number is the answer we're after!

Writing the output

Like before, we'll need to have a FILE* or text object to deal with the file manipulation. Let's go back to the "Variables" section and declare another variable specifically for writing output:

C, C++
FILE* outputFile;
Pascal
outputFile: text;

Now we jump forward to the "Output" section and prepare the file for writing:

C, C++
outputFile = fopen("addout.txt", "w");

We've seen fopen before. This time, the "w" tells the computer that we're about to write to the file. If there isn't already a file with that filename, the computer creates it for us; if there is, the existing file is deleted so that we are writing to an empty file. (Make sure you don't have anything important stored in addout.txt before you run the program!)

Pascal
assign(outputFile,'addout.txt');
rewrite(outputFile);

The assign directive is not new to us. The rewrite in the second line tells the computer that we're about to write to the file that outputFile was assigned to. If there isn't already a file with that filename, the computer creates it for us; if there is, the existing file is deleted so that we are writing to an empty file. (Make sure you don't have anything important stored in addout.txt before you run the program!)

Nearly done! The next line of code tells the computer to write the value of total into the file...

C, C++
fprintf(outputFile, "%d
", total);

The syntax is similar to fscanf from before. "%d" tells the computer that we are writing an integer; adds a linebreak.

Pascal
writeln(outputFile,total);

Everything after the first comma is translated into text and written to the file. Also, the computer adds a linebreak at the end. (If we didn't want a linebreak, we could use write instead of writeln.)

Finally, as before, we need to close outputFile so that the computer knows that we're done writing. Perhaps unsurprisingly, the code that we'll want to add to the "Clean up!" section looks something like this:

C, C++
fclose(outputFile);
Pascal
close(outputFile);

And with that, we've finished coding our solution!

Closing remarks

C C++
#include <stdio.h>

/*Declare variables*/
FILE* inputFile;
FILE* outputFile;
int a, b, total;

int main() {
	
	/*Read the input*/
	inputFile = fopen("addin.txt", "r");
	fscanf(inputFile, "%d %d", &a, &b);
	
	/*Calculate the answer*/
	total = a + b;
	
	/*Write the output*/
	outputFile = fopen("addout.txt", "w");
	fprintf(outputFile, "%d
", total);
	
	/*Clean up!*/
	fclose(inputFile);
	fclose(outputFile);
	
	return 0;
}
#include <cstdio>

/*Declare variables*/
FILE* inputFile;
FILE* outputFile;
int a, b, total;

int main() {
	
	/*Read the input*/
	inputFile = fopen("addin.txt", "r");
	fscanf(inputFile, "%d %d", &a, &b);
	
	/*Calculate the answer*/
	total = a + b;
	
	/*Write the output*/
	outputFile = fopen("addout.txt", "w");
	fprintf(outputFile, "%d
", total);
	
	/*Clean up!*/
	fclose(inputFile);
	fclose(outputFile);
	
	return 0;
}
Pascal
program Solution;

{Declare variables.}
var
inputFile: text;
a, b, total: longint;
outputFile: text;

begin
	{Read the input.}
	assign(inputFile,'addin.txt');
	reset(inputFile);
	readln(inputFile,a,b);
	
	{Calculate the answer.}
	total := a + b;
	
	{Write the output.}
	assign(outputFile,'addout.txt');
	rewrite(outputFile);
	writeln(outputFile,total);
	
	{Clean up!}
	close(inputFile);
	close(outputFile);
end.

The above code is (to the best of my knowledge) a working solution for Addition, and should score you 100% marks. A lot of the basic file-handling techniques used in the program will work for most other problems you find on the training site. Feel free to copy some of the file-handling code to use for other problems - file I/O gets repetitive after a while and you want to have as much time as possible to do the real problem-solving!

 


Privacy statement
© Australian Mathematics Trust 2001-2019

Contact: training@orac.amt.edu.au
Page generated: 24 May 2019, 11:21pm AEST