Login Form

Continuing our discussion of understanding programming syntax, previously we have spoken about functions, and we're going to continue with a little bit more discussion on that before moving into some other key aspects of underlying program syntax.

Functions (cont.)

Using functions is, as we've covered, a vital part of programming. One consideration we briefly started to introduce at the end of our last "Understanding programming syntax (Part 1)" post was the concept of returning values. Great care should be taken when you're thinking about this, and it's a common mistake made by beginners to assume that you should be returning every part of altered variable in a specific return scope.

This is untrue, and a dangerous assumption to make! Rather than throwing huge objects around your program, it is often significantly easier to use variables passed by reference to modify the variable values in-memory instead of moving them around different functions. However, this is absolutely something you should try to maintain consistency of across your program. It can be incredibly confusing for collaborative programming (especially if you're doing it remotely!) to have some functions which take variables by reference and directly operate on them while others take variables by value and return changed value pairs. There can be times at which you would want to do this, but it's always best to try to make sure that you keep consistent across your code base. 

While Loops (and do while loops)

Another key aspect of basic syntax is the use of while loops and do-while loops. We'll start by defining the difference between them because this is often an area where beginners misunderstand key aspects of the syntax and can be very confusing if you're using incorrect logic.

  • While loops take an initial condition and then will iterate through a loop if this condition holds as true. The conditionality is checked at the start of every loop iteration, and the code block is then executed provided the condition still holds...whereas...
  • Do-While loops execute a code block and will then check a condition, looping back to execute the code block again if the condition holds as true. This means that the conditionality is checked at the end of every loop iteration, and the code block is then executed again if the condition still holds.

As you can see, the difference here is whether or not the code block is always executed at least once - it is in do-while loops, and not in while loops. This is an incredibly basic but vital thing to understand, and easily illustrates when you should use a dowhile loop in comparison to a while loop.

This being said, utilizing while loops is the primary way of keeping something executing until a specific condition is reached - such as performing a mathematical function on a number over and over until it reaches a base case (similar in type to recursion).