In formal grammar it is wrong to put prepositions at the end of sentences. In colloquial speech we do it all the time, and so by common usage thishas been practiced for such a long period of time that it often sounds weird to put the preposition where it belongs.
Therefore, it is fine in writing collequial speech, i.e. "What did you do that for?" is certainly what you would write rather than "For what did you do that?", which sounds strangely stilted and would actually read as wrong and interrupt that concentrative flow of the reader.
In formal writing it is best to avoid putting prepositions at the end.
However, if you are not a native speaker of English, say, and doing university courses, and your facility with formal English sentence structure is still not that good, I suggest that you go for clarity, even if it means the occasional preposition dangling at the end of a sentence.