Write a program that returns 3 numbers from a function using a structure in c.
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
-
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; };
-
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.
-
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.
-
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.