How structures can be used within functions?
– TWO WAYS
1. Sending individual members of structures to a function (Passing Structure
Members as Arguments)
2. Sending the Whole Structure (Passing an entire structure to a function)
1. Sending individual members of structures to a function (Passing Structure
Members as Arguments)
Aim is to pass the numerator and denominator as arguments in a function called multFr
which multiplies the corresponding numerators and denominators, ie, multiply fractions.
=2/3 * 4/5 =8/15
• #include <stdio.h>
• struct FractionNumber {
• int numerator;
• int denominator;
• };
• // Function to multiply fractions
// the return type of the function is also structure
•
• struct FractionNumber multFr(int n1, int d1, int n2, int d2) {
• struct FractionNumber result;
• [Link] = n1 * n2;
• [Link] = d1 * d2;
• return result;
• }
• int main() {
• struct FractionNumber fr1, fr2, fr3;
• printf("Enter numerator and denominator of first fraction: ");
• scanf("%d %d", &[Link], &[Link]);
• printf("Enter numerator and denominator of second fraction: ");
• scanf("%d %d", &[Link], &[Link]);
• // Multiply using the function
• fr3 = multFr([Link], [Link], [Link], [Link]);
• printf("\nMultiplication Result: %d/%d\n", [Link], [Link]);
• return 0;
• }
2. Sending the Whole Structure - Passing an entire structure to a function
Sample output
=2/3 * 4/5 =8/15
Program
#include <stdio.h>
struct FractionNumber {
int numerator;
int denominator;
};
// Function that multiplies two FractionNumber structures
struct FractionNumber multFr(struct FractionNumber f1, struct
FractionNumber f2)
{
struct FractionNumber result;
[Link] = [Link] * [Link];
[Link] = [Link] * [Link];
return result;
}
int main() {
struct FractionNumber fr1, fr2, fr3;
printf("Enter numerator and denominator of first fraction: ");
scanf("%d %d", &[Link], &[Link]);
printf("Enter numerator and denominator of second fraction: ");
scanf("%d %d", &[Link], &[Link]);
// Calling the function with the whole structure
fr3 = multFr(fr1, fr2);
printf("\nResult of Multiplication = %d/%d\n", [Link], [Link]);
return 0;
}