Subprograms 1

Subprograms 1

Understanding Subprograms

What is a Subprogram?

  • A subprogram is a sequence of instructions that perform a specific task, grouped as a unit.
  • Similar to a recipe, subprograms have a name, they might need some inputs, they do some processing and then they may provide an output.
  • They are known by various names such as function, procedure, method, or routine, depending on the language and the context.

Why use Subprograms?

  • To break down a complex task into small manageable parts. This is also known as Modular Programming.
  • For reusability. Once created, they can be reused in other parts of the program, or even in other programs.
  • To simplify maintenance. If there is an issue or an update is needed, you just have to modify the subprogram and not the entire code.

Defining a Subprogram

  • The first line of a subprogram is generally known as the header. This includes the subprogram’s name, the parameters it accepts, if any, and the type of data it returns, if any.
  • The body of a subprogram contains the instructions to be executed when the subprogram is called.

Subprogram Parameters

  • Parameters are a way by which we can pass values/data to the subprogram. This data is used in the execution of the subprogram.
  • Parameters can be of two types: input (also known as arguments) and output.
  • Input parameters are used to pass data into the subprogram. Output parameters are used for the subprograms to return data back.

Calling a Subprogram

  • A subprogram is put to use by a call statement. The subprogram will not run until it is called.
  • The subprogram call is like a bridge that allows us to get inside the subprogram and execute the instructions in it.

Key Takeaway

  • Subprograms are fundamental to good software design. They promote modular, reusable, simple to read, and easy to maintain code. They also make complex tasks more manageable by breaking them into smaller parts. Understanding subprograms and their correct use is crucial for becoming a proficient programmer.