While both saaahu's answer and Andy W's answer are on target, I will add my thoughts.
Make yourself known to the prof from whom you want the letter. You can do this in many ways. If you sit in the front or are particularly active in that class, the prof will naturally remember you (and naturally feel more comfortable that he/she know enough about you to write a recommendation letter).
If you want a letter from someone whose class you took a while ago and you did not do anything to stand out, then you must take up some extra work now (see if you can help that prof with some projects so he/she can get to know you more).
For me, I don't expect students to develop a relationship with me long before they need a letter but I do expect them to make their abilities known to me. I've had students who are silent in my classes then come to me and ask for a reference. When I tell them 'sorry, I don't know enough about you' they get a little sad but they also understand quite quickly when I explain things to them.
So, if you want a letter, help the prof to help you.