(you are here)

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 (input/output) 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:

• Read in the integers a and b from addin.txt.
• Calculate the value of a + b.
• Write the value of a + b to addout.txt.
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.

# Declare variables

# Write the output

# Clean up!
#include <cstdio>

/*Declare variables*/

int main() {

/*Write the output*/

/*Clean up!*/

return 0;
}

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.)

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:

# Python doesn't need you to declare variables like most other languages do, but we'll do it anyway.
# "None" is a special value which means "this has no value" (at the moment)
inputFile = None
/* This declares a FILE* variable (used for working with text files) called inputFile */
FILE* inputFile;

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

# 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 "r"eading from the file.
inputFile = open("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 "r"eading from the file.
*/
inputFile = fopen("addin.txt", "r");

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:

# The below code declares three different 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".
#
# We'll set them to "0" now to remind us these variables are supposed to store integers.
# We could also have set them to "None" like we did for inputFile.
a = 0
b = 0
total = 0
/*
The below 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".
*/
int a, b, total;

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:

# This line tells the computer several things:
#     - "inputFile.readline()" tells it to read an entire line from inputFile
#     - ".split()" tells it to take that line and split it into parts, using
#           spaces as separators.
#     - "a, b = map(int, ...)" tells it to take each part of the line, turn it
#           into an integer, and store them in "a" and "b" (in that order)
a, b = map(int, inputFile.readline().split())
/*
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 ("&a, &b") tells it to store these integers
in "a" and "b" (in that order).
*/
fscanf(inputFile, "%d %d", &a, &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:

inputFile.close()
fclose(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. It might look a bit like this:

# Declare variables
inputFile = None
a = 0
b = 0
total = 0

# Write the output

# Clean up!
inputFile.close()
#include <cstdio>

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

int main() {

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

/*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 (if applicable), 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.

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
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:

outputFile = None
FILE* outputFile;

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

# We've seen open 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!)
outputFile = open("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!)
*/
outputFile = fopen("addout.txt", "w");

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

# This line tells the computer to write out the sum we calculated
# earlier ("str(total)"), followed by a linebreak ("\n").
# "write" only accepts strings (text), not integers. That's why we have
# to convert it into a string first, using "str".
outputFile.write(str(total) + "\n")
/*
The syntax is similar to fscanf from before. "%d" tells the computer that
we are writing an integer; "\n" adds a linebreak.
*/
fprintf(outputFile, "%d", total);

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:

outputFile.close()
fclose(outputFile);

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

## Closing remarks

The code below 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!

# Declare variables
inputFile = None
outputFile = None
a = 0
b = 0
total = 0

total = a + b

# Write the output
outputFile.write(str(total) + "\n")

# Clean up!
inputFile.close()
outputFile.close()
#include <cstdio>

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

int main() {

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

total = a + b;

/*Write the output*/
}