$\mathbf{f(x)=|x|=\frac{1}{2}a_0+ \sum_{n=1}^{\infty}(a_n \cos{nx}+b_n \sin{nx})}$
for $-\pi <x< \pi$
Since $|x|$ is even $\rightarrow b_n=0$
f(x) = \begin{cases} -x, & {-\pi<x<0} \\ x, & {0<x<\pi} \end{cases}
$a_0=\frac{1}{2\pi}[\int_{-\pi}^0 f(x)$ $dx$ + $\int^{\pi}_0 f(x)$ $dx$]
$a_0=\frac{1}{2\pi}[\int_{-\pi}^0 -x$ $dx$ + $\int^{\pi}_0 x$ $dx$]
$=\frac{1}{\pi}\int ^{\pi}_0 x$ $dx$
$\frac{1}{\pi}(\frac{\pi^2}{2})=\frac{\pi}{2}$
Similarly,
$a_n=\frac{1}{\pi}[\int_{-\pi}^0 -x \cos nx$ $dx$ + $\int^{\pi}_0 x \cos nx$ $dx$]
$=-\frac{4}{\pi}[\frac{1}{n^2}+\frac{(-1)^n}{n^2}]$
$\therefore |x|=\frac{\pi}{2}-\frac{4}{\pi}\sum^{\infty}_0[\frac{1+(-1)^n}{n^2} \cos nx]$
But the answer is
$\therefore |x|=\frac{\pi}{2}-\frac{4}{\pi}\sum^{\infty}_0[\frac{\cos (2n+1)x}{n^2}]$
In order for $1+(-1)^n \cos nx$ to become $\cos (2n+1)x$ , How do I reach here, unless there is an error somewhere.
Note that $$1+(-1)^n=\begin{cases} 2 & \text{if $n$ is even, i.e. } n=2k \\ 0 & \text{if $n$ is odd, i.e. }n=2k+1 \end{cases}$$ And since $\frac{\cos nx}{n}$ is indeterminate for $n=0$: $$\sum_{n=\color{red}{1}}^\infty\frac{1+(-1)^n}{n^2}\cos nx=\sum_{k=\color{red}{1}}^\infty\frac{2}{(2k)^2}\cos(2k x)+0=\frac{1}{2}\sum_{n=\color{red}{1}}^\infty\frac{\cos 2nx}{n^2}$$ So it looks like there is an error somewhere. Because $$\int_{-\pi}^{\pi}|x|\cos nx\,dx=\frac{2}{n^2}(\color{red}{-1}+(-1)^n)$$