Course Content
History of C Language
0/2
Basic Structure of C Program
0/1
Types of Errors
0/1
Language Fundamentals
0/1
Data Types and Modifiers
0/1
Programming with C Language
About Lesson

STRUCTURES AS FUNCTION ARGUMENTS

Since structure variables are also like regular variables declared out of a certain data types, they can be passed to functions as arguments.

/*Example Program to demonstrate passing a structure to a function*/

#include

/*Declare and define a structure to hold the data.*/

struct data{

float amt;

char fname [30];

char lname [30];

}per;   //declaration of per which is the global variable of data

void main()

{

void printPer (struct data); //declaration of print_per function

printf(“Enter the donors first and last names separated by a space:”);

scanf (“%s %s”, per.fname, per.lname);

printf (“\nEnter the amount donated in rupees:”);

scanf (“%f”, &per.amt);

printPer (per);  //invocation of function print_per

}

void printPer(struct data x)  //definition of function print_per

{

printf (“\n %s %s gave donation of amount Rs.%.2f\n”, x.fname, x.lname, x.amt);

}

STRUCTURE AS FUNCTION RETURN VALUE

/* Example Program to show how structure variable can be returned by a function

The purpose of the program is to accept the data from the user and calculate the salary of the person*/

#include

struct sal {    //definition of sal structure

char name[30];

int no_days_worked;

int daily_wage;

};

int main()

{

struct sal salary; //salary is the variable of sal type

float amount_payable; /* variable declaration*/

struct sal get_data(void); /* function prototype*/ //declaration of function get_dat

float wages(struct sal); /*function prototype*/

salary = get_data();  //invoking get_data function by passing salary variable

printf(“\n\nThe name of employee is %s”,salary.name);

printf(“\nNumber of days worked is %d”,salary.no_days_worked);

printf(“\nThe daily wage of the employees is %d”,salary.daily_wage);

amount_payable = wages(salary);

printf(“\n\nThe amount payable to %s is %.2f”,salary.name,amount_payable);

return 0;

}

struct sal get_data() //definition of get_data function

{

struct sal income;  //income is a variable of sal type

printf(“Please enter the employee name:\n”);

scanf(“%s”,income.name);

printf(“Please enter the number of days worked:\n”);

scanf(“%d”,&income.no_days_worked);

printf(“Please enter the employee daily wages:\n”);

scanf(“%d”,&income.daily_wage);

return(income);

}

float wages(struct sal amt)

{

float total_salary ;

total_salary = amt.no_days_worked * amt.daily_wage;

return(total_salary);

}

You cannot copy content of this page