LaTeX Programming

Learning Objectives:

  • Variable: \newcommand, newenvironment
  • Conditional: if
  • Iteration: for loop

Newcommand

Basic Newcommand

\newcommand\NUS{National University of Singapore}

I like \NUS{}. Do you like \NUS{}?

Math newcommand

\newcommand\sumx{\ensuremath{x_1+\cdots+x_n}}

I like \sumx{}.

Newcommand with argument

\newcommand\poem[1]{#1 eats an apple.}

\poem{Peter}
\poem{Mary}

\newcommand\poems[2]{#1 eats #2.}

\poems{Peter}{apple}
\poems{John}{banana}

Math newcommand with argument

\newcommand\sumint[1]{\ensuremath{1+\cdots+#1}}

I like to do \sumint{3} and \sumint{n}.

\newcommand\sumints[2]{\ensuremath{#1+\cdots+#2}}

 I like to do \sumints{1}{2} and \sumints{3}{n}.

New Environment

Baisc newenvironment

\newenvironment{important}
{\begin{center}\color{red}}
{\end{center}}

I like think the following is important:
\begin{important}
I eat an apple.
\end{important}

Newenvironemt with argument

\newenvironment{important}[1]
{\begin{center}\color{#1}}
{\end{center}}
 
I like think the following is important:
\begin{important}{blue}
I eat an apple.
\end{important}

Newenvironment with arguments

\newenvironment{important}[2]
{\begin{center}\textbf{#2:} \color{#1}}
{\end{center}}

I like think the following is important:
\begin{important}{blue}{Peter}
I eat an apple.
\end{important}

Conditional

Conditional If

\newenvironment{important}[2]
{\begin{center}\textbf{#2:} \color{#1}}
{\end{center}}

I like think the following is important:
\begin{important}{blue}{Peter}
I eat an apple.
\end{important}

Conditional If else

\newif\ifcond
\condfalse % try \condtrue
\ifcond
Yes, this is not me. % run if true
\else 
No, this is you. % run if false
\fi

Iteration

Iteration for each loop

\usepackage{pgffor}

\foreach \person in {Peter, John, Mary}
{\person{} eats an apple.\par}

\foreach \n in {1,...,10}
{\n +}
Previous
Next