7

Is it possible to have "if .. then .. else" in a single line?

I am looking for ways to condense simple conditional statements that is taking much space in my write-up. So, any help is appreciated.

\documentclass[conference]{IEEEtran}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage[noend]{algpseudocode}

\begin{document}
    \title{HOWTO Single Line If Then Else}
    \author{Author}
    \maketitle

\begin{abstract}
    This is an abstract.
\end{abstract}

\hspace{10pt}

\begin{IEEEkeywords}
    a, b, c, d.
\end{IEEEkeywords}
\IEEEpeerreviewmaketitle

\section{Introduction}

\begin{algorithm}
    \caption{Single line IF THEN ELSE}\label{alg:IfThenElse}
    {\fontsize{8}{8}\selectfont
        \begin{algorithmic}[1]
            \If {$\text{foo} \leq \text{bar}$} $doh$ = 0
            \Else {} $\text{duh}$ = 1
            \EndIf
        \end{algorithmic}
    }
\end{algorithm}
\end{document}
6

A fairly elementary (but effective) way of achieving this is to use \IfThenElse{<if>}{<then>}{<else>} defined by

\algnewcommand{\IfThenElse}[3]{% \IfThenElse{<if>}{<then>}{<else>}
  \State \algorithmicif\ #1\ \algorithmicthen\ #2\ \algorithmicelse\ #3}

It just sets a \State with all the components needed right next to one another.

enter image description here

\documentclass[conference]{IEEEtran}

\usepackage{amsmath}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}

\algnewcommand{\IfThenElse}[3]{% \IfThenElse{<if>}{<then>}{<else>}
  \State \algorithmicif\ #1\ \algorithmicthen\ #2\ \algorithmicelse\ #3}

\begin{document}

\title{HOWTO Single Line If Then Else}
\author{Author}
\maketitle

\begin{abstract}
This is an abstract.
\end{abstract}

\begin{IEEEkeywords}
a, b, c, d.
\end{IEEEkeywords}
\IEEEpeerreviewmaketitle

\section{Introduction}

\begin{algorithm}
  \caption{Single line IF THEN ELSE}
  \begin{algorithmic}[1]
    \If {$\text{foo} \leq \text{bar}$} $\text{doh} = 0$
    \Else {} $\text{duh} = 1$
    \EndIf
    \IfThenElse {$\text{foo} \leq \text{bar}$}% If ...
      {$\text{doh} = 0$}% ...then...
      {$\text{duh} = 1$}% ...else...
  \end{algorithmic}
\end{algorithm}

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.