Write a program that returns 3 numbers from a function using a structure in c.

28 Dec 2022 Balmiki Kumar 0 C Programming

Writing a C Program to Return 3 Numbers Using a Structure

Introduction

In this tutorial, we will learn how to write a C program that returns three numbers from a function using a structure. This technique can be useful when you need to pass multiple values from a function to the caller.

Steps to Achieve This

  1. Defining the Structure

    First, let's define a structure that will hold the three numbers we want to return. We'll name it NumberSet for this example.

    struct NumberSet {
        int num1;
        int num2;
        int num3;
    };
  2. Creating the Function

    Next, we'll create a function that returns an instance of the NumberSet structure.

    struct NumberSet getNumbers() {
        struct NumberSet numbers;
        numbers.num1 = 10;
        numbers.num2 = 20;
        numbers.num3 = 30;
        return numbers;
    }

    In this example, the function getNumbers initializes a NumberSet structure with three numbers and returns it.

  3. Using the Function

    Now, let's call the getNumbers function to retrieve the numbers.

    struct NumberSet result = getNumbers();

    After this line, the variable result will contain the three numbers: num1, num2, and num3.

  4. Accessing the Numbers

    You can access these numbers using the dot notation.

    int firstNumber = result.num1;
    int secondNumber = result.num2;
    int thirdNumber = result.num3;

Example Code

Here's the complete code for reference:

#include 

struct NumberSet {
    int num1;
    int num2;
    int num3;
};

struct NumberSet getNumbers() {
    struct NumberSet numbers;
    numbers.num1 = 10;
    numbers.num2 = 20;
    numbers.num3 = 30;
    return numbers;
}

int main() {
    struct NumberSet result = getNumbers();

    int firstNumber = result.num1;
    int secondNumber = result.num2;
    int thirdNumber = result.num3;

    printf("First Number: %d\n", firstNumber);
    printf("Second Number: %d\n", secondNumber);
    printf("Third Number: %d\n", thirdNumber);

    return 0;
}

Conclusion

By using a structure to encapsulate multiple values, you can return them from a function in C efficiently. This technique is especially useful when you need to pass more than one value from a function.

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.