This paper investigates the optimal control problem of a particular class of hybrid dynamical systems with controlled switching. Given a prespecified sequence of active subsystems, the objective is to seek both the continuous control input and the discrete switching instants that minimize a performance index over a finite time horizon. Based on the use of the calculus of variations, necessary conditions for optimality are derived. An efficient algorithm, based on nonlinear optimization techniques and numerical methods, is proposed to solve the boundary-value ordinary differential equations. In the case of linear quadratic problems, the two-point boundary-value problems can be avoided which reduces the computational effort. Illustrative examples are provided and stress the relevance of the proposed nonlinear optimization algorithm.