Solution (source code)

= Solution

The <homogeneous solution> is $A\cos x+B\sin x$. If $k\ne1$, the <method of undetermined coefficients> permits a <particular integral> $C\cos kx$. Substitution gives $(1-k^2)C=1$ and hence
$$
\boxed{y(x)=A\cos x+B\sin x+\frac{\cos kx}{1-k^2},\qquad k=2,3,\ldots}.
$$
For $k=1$, the forcing is itself a <homogeneous solution>, so this trial fails by <resonance in a differential equation>. Multiplying the sine trial by $x$ gives
$$
\left(\frac{d^2}{dx^2}+1\right)(x\sin x)=2\cos x.
$$
Thus the resonant <general solution> is
$$
\boxed{y(x)=A\cos x+B\sin x+\frac{x}{2}\sin x,\qquad k=1}.
$$
The <secular term> containing $x$ describes the increasing amplitude under undamped resonant forcing.