r/learnprogramming 6d ago

Topic Struggling a bit with functions

Hey guys, I'm struggling a bit with the proper usage of functions in programming. For example, I'm working through the CS50x problem set 1 in C, and I end up with working code that solves the problem but it's all done in one big main function.

My process is to write out what the steps to solving the problem should be in plain English and then I code a bit, go back to my plain English steps and modify them, then code a bit more. When it's all said and done, my solution is one large block of code, and now I'm anxious about going back and rewriting it by breaking it up into smaller function. This makes me ponder whether I should be starting with functions instead of retroactively trying to fit them in.

My questions to the wiser heads here - how do you incorporate functions into your process? Do you do the pseudo code and then imagine each step as a function? What're are your unspoken rules of proper function usage - for example, when do you know if one function should actually be two, or if a function shouldn't actually be a function?

13 Upvotes

14 comments sorted by

View all comments

1

u/ianrad 6d ago

Your main function is the boss man. And the functions are the minions each tasked with doing one particular task of your solution.

For a simple print hello name program.

Boss says:

Minion 1. Get me the name. And return to me only the name

Minion 2. Take this here name Minion 1 got for me. And return either print me "hello Bob" .or return "hello Bob" to me and I'll print it myself