Maybe this can meet your spectations
\documentclass{article}
\usepackage{xcolor}
\newcommand{\gfcb}[1]{%
\fcolorbox{white}{gray!10!}{\quad\strut #1\quad}
} % gfcb := gray fcolorbox
\newcommand{\cop}[1]{%
\gfcb{\texttt{\detokenize{#1}}}
\ensuremath{\quad\longrightarrow\quad #1}
} % cop := code output
\begin{document}
% Examples of usage
\cop{\ln x} \\
\cop{\sin x} \\
\cop{4\cdot a^n} \\
\cop{\sqrt{x^2+y^2}} \\
\cop{\displaystyle\int\cot^2 x\,dx} \\
\cop{\overline x=\dfrac{\sum_{i=1}^n x_i}{n}} \\
\cop{\displaystyle\lim_{\lVert \Delta x\rVert\to0}\sum_{k=1}^{n}f(c_i)\Delta x_i} \\
\cmdc{f(x)=\begin{cases}
x-4 & \text{if } x\leq 4 \\
x^3 & \text{if } x>4
\end{cases}} \\
\end{document}
I casually made it a couple of months ago when I had the same question while I was wondering how to display a command and its output for a LaTeX
potential manual. And surfing TeX.SE I have just met this question.

The issue I got is that the code input can only be displayed in one line, so for big equations, that would not look good and would not fit the width of the page or paragraph.

UPDATE
In case you need to show large equations, you can use a tcolorbox
that displays a code listing and its output.
\documentclass{report}
\usepackage{amsmath,amsthm,amssymb,latexsym}
\usepackage{tcolorbox.doc.s_main}
\usepackage{xcolor}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\definecolor{midnightBlue}{RGB}{25,25,112}
\definecolor{webblue}{rgb}{0, 0, 0.5}
\begin{document}
\DeclareTCBListing{mybox}{ s O{} m }{%
colback=blue!10!,
colframe=webblue,
bicolor,
colframe=midnightBlue,
colbacklower=white,
after title={\hfill Output},
fonttitle=\bfseries,
IfBooleanTF={#1}
{text side listing}{listing side text},
title=#3,#2}
% Tcolobox with title
\begin{mybox}{Code}
$f(x)=\begin{cases}
x-4 & \text{if } x\leq 4 \\
x^3 & \text{if } x>4
\end{cases}$
\end{mybox}
% Tcolorbox without title
\begin{mybox}{}
$P(k):2(k+1)-3\leq2(k+1)-2$
\end{mybox}
\end{document}

verbatim
package?\verb!<code for formula>!
. If you want syntax highlighting then uselistings
package.\verb+latex_code+
.showexpl
package as per the links of @TorbjørnT's comment. That way you don't have to duplicate the code.