# Using command to compute sum?

I must admit this sounds like an easy question.

I'm creating a grading model for a homework assignment, and I'm adding the maximum amount of points to each question. Is there a way to have LaTeX print out the sum of these (integer) points automatically?

\points{3} Solve equation [...]
\points{5} Give proof of [...]

Max points: \totalpoints{}


That would then print out "Max points: 8" at the end of the document.

This is actually very simple using a normal LaTeX counter:

\documentclass{article}

\newcounter{points}
\newcommand*{\totalpoints}{\thepoints}% Or simply use \thepoints directly.

\begin{document}

\points{3} Solve equation [...]
\points{5} Give proof of [...]

Max points: \totalpoints{}

\end{document}


I'm not sure if this is interesting at all, and it's complete overkill. It is just a very simple example of using Lua code in a LaTeX document.

Compile with lualatex.

\documentclass{article}
\usepackage{luacode}
\newcommand\points{%
\luaexec{
if a == nil then
a = #1
else
a = a + #1
end
}}
\newcommand\totalpoints{\luaexec{tex.sprint(a)}}

\begin{document}
\points{3} Solve equation [...]
\points{5} Give proof of [...]

Max points: \totalpoints{}
\end{document}

• Examples like this will gain new LuaTeX fans. Really. – egreg Nov 21 '11 at 22:28

The exam class provides the command \numpoints which will calculate the total points for you.

See the documentation for full details- a MWE follows

\documentclass[addpoints]{exam}

\begin{document}

%\pointsdroppedatright          % try uncommenting this line
%\pointpoints{point}{points}

\cfoot{\footnotesize Page \thepage {} of \numpages}
\lfoot{\footnotesize TOTAL POINTS : \numpoints\ }

This exam has \numquestions\ questions, for a total of \numpoints\ points. The number of points for each  part is given in brackets.

\begin{questions}
%+++++++++++++++++++++++++
%   QUESTION
%+++++++++++++++++++++++++
\question What is your favourite fruit?

\vspace{\fill}

%+++++++++++++++++++++++++
%   QUESTION
%+++++++++++++++++++++++++

• @Noio: No problem! It's well worth investigating the exam class for future projects :) – cmhughes Nov 24 '11 at 16:08