- Write a program in C to return multiple values form a function using array, pointers and structures.
- How to return more than one value form a function in C programming language.
Here is the syntax of function declaration in C:
- Basic data types: int, float, char, double stc.
- Pointer : Pointer to a basic data type variable(like integer pointer), base address of an array, pointer to a structure.
- Structure : A structure variable.
Returning multiple values from a function using array
If we want to return multiple values of same data type then we should return the base pointer of an array of that data type.#include<stdio.h> int* getNEvenNumbers(int N, int *array){ int i; for(i = 0; i < N; i++){ array[i] = 2*(i+1); } return array; } int main(){ int i, N, array[100]; printf("Enter one integers\n"); scanf("%d", &N); getNEvenNumbers(N, array); printf("%d Even Numbers\n", N); for(i = 0; i < N; i++) printf("%d ", array[i]); return 0; }Output
Enter one integers 8 8 Even Numbers 2 4 6 8 10 12 14 16
Returning multiple values from a function by passing variable address as parameter
We can pass multiple addresses of variables as input parameters to a function. Inside function body, we can store the return values at the passed memory locations.#include<stdio.h> int getSumAndProduct(int a, int b, int *product){ *product = a * b; return a + b; } int main(){ int a, b, sum, product; printf("Enter two integers\n"); scanf("%d %d", &a, &b); sum = getSumAndProduct(a, b, &product); printf("Sum = %d\nProduct = %d", sum, product); return 0; }Output
Enter two integers 3 8 Sum = 11 Product = 24
Returning a structure variable from a function.
Structure is a user defined data type that groups different data types into a single unit. If we want to return values of different data types, then we can encapsulate all return values in a structure variable and return it from a function.#include<stdio.h> struct data { int sum, product; }; typedef struct data myStruct; myStruct getSumAndProduct(int a, int b){ myStruct s; s.sum = a + b; s.product = a * b; return s; } int main(){ int a, b; myStruct result; printf("Enter two integers\n"); scanf("%d %d", &a, &b); result = getSumAndProduct(a, b); printf("Sum = %d\nProduct = %d", result.sum, result.product); return 0; }Output
Enter two integers 3 7 Sum = 10 Product = 21