Subroutine

In computing, a subroutine is a set of instructions designed to perform a frequently used operation within a program.

Definition

A subroutine, sometimes referred to as a procedure, routine, or method, is a segment of code that is executed as a unit by a main program. It is designed to perform a specific task and can be called upon multiple times within a single program to avoid code duplication and facilitate code reuse and maintenance.

Examples

  1. BASIC Programming Language Example:

    110 PRINT "This is the main program."
    220 GOSUB 100
    330 PRINT "Returned from subroutine."
    440 END
    5
    6100 PRINT "This is the subroutine."
    7110 RETURN
    
  2. Python Example:

    1def greet():
    2    print("Hello, World!")
    3
    4print("Main program starts.")
    5greet()
    6print("Main program ends.")
    
  3. C++ Example:

     1#include <iostream>
     2using namespace std;
     3
     4void greet() {
     5    cout << "Hello, World!" << endl;
     6}
     7
     8int main() {
     9    cout << "Main program starts." << endl;
    10    greet();
    11    cout << "Main program ends." << endl;
    12    return 0;
    13}
    

Frequently Asked Questions (FAQs)

Q1: What is the purpose of having subroutines in a program?

A1: Subroutines help in breaking down complex programs into smaller, manageable, and reusable components. They facilitate code reuse, reduce redundancy, and improve overall code maintainability and readability.

Q2: How does a subroutine differ from a function?

A2: While both subroutines and functions are similar in that they encapsulate code for reuse, functions typically return a value and subroutines may not. In some programming languages, these terms are used interchangeably.

Q3: How do you call a subroutine in BASIC?

A3: In BASIC, a subroutine is called using the GOSUB statement, followed by the line number where the subroutine starts. The RETURN statement is used to return control back to the main program.

  • Function: A block of code designed to perform a specific task, usually with input parameters and a return value.
  • Method: A function associated with an object, common in object-oriented programming.
  • Procedure: Another term for a subroutine, used interchangeably in some programming languages.

Online Resources

Suggested Books for Further Studies

  • “Code Complete: A Practical Handbook of Software Construction” by Steve McConnell
  • “Clean Code: A Handbook of Agile Software Craftsmanship” by Robert C. Martin
  • “Programming Pearls” by Jon Bentley

Fundamentals of Subroutine: Computer Programming Basics Quiz

Loading quiz…

Thank you for exploring the fundamentals of subroutines in computer programming. Continue to delve into these concepts to enhance your understanding and application of efficient coding practices.