One way to look at the question of Hamlet's madness is to rephrase your question to ask why it was that Shakespeare caused Hamlet to act mad. This is a crucial difference, because we are not actually talking about the motivations of a real person, but about a character in a play, whose actions may actually be motivated for reasons of dramatic effectiveness.
Mad scenes were a standard part of the genre of the revenge tragedy in this period and provided opportunities for actors to display a range of dramatic abilities. Audiences also enjoyed them. On a plot level, Hamlet's feigned madness leads, with a sort of tragic irony, to Ophelia's real madness.
Finally, by pretending to be mad, Hamlet appears harmless – a lovesick fool rather than a methodical plotter or assassin – although, as Polonius figures out, there is a "method to his madness."
Hamlet "puts on antic disposition" or feigns madness because as Prince of Denmark, he does not want to pose a threat to the new King of Denmark, Claudius, who has newly married his mother Gertrude. Remember, the ghost his dad has revealed to Hamlet who shares with Horatio and Marcellus that Cladius is his murderer. Hamlet is not a warrior; rather, he is a scholar who has returned home from college at the University of Wittenburg to attend his dad's funeral and his mom's marriage. Quite confused, he does not know who to trust. Also, Catholics in Shakespeare's audience would have believed that a ghost returned to complete some task in a purgatory stage before crossing to eternal life. Protestants in his audience would have thought a ghost was truly the devil in a familiar form, coming to lead your sould to hell. The ghost asks for revenge. Hamlet, our scholar, needs proof that this ghost is credible before he acts, so he plays crazy so as not to pose a threat. His enterng Ophelia's bedchamber half naked is part of his crazy scheme. This delay will be his tragic flaw.