C Language | Structure and Union: Structures And Functions

Structures And Functions

Questions:1
C program to declare a structure named student with attributes as roll, name and per. Take input for the details of two students and display them using functions and also calculate and print average per.
Sol:

#include<stdio.h>
#include<conio.h>
struct student
{
  int roll;
  char name[20];
  float per;
};
void show(struct student n);
float calavg(struct student n1,struct student n2);
int main()
{
  struct student s1,s2;
  float a;
  //clrscr();
  printf("Enter roll,name and per of 1st student ");
  scanf("%d %s %f",&s1.roll,s1.name,&s1.per);
  printf("Enter roll,name and per of 2nd student ");
  scanf("%d %s %f",&s2.roll,s2.name,&s2.per);
  show(s1);
  show(s2);
  a=calavg(s1,s2);
  printf("average per %f\n",a);
  getch();
  return(0);
}
void show(struct student n)
{
  printf("roll %d  name %s  per %f\n",n.roll,n.name,n.per);
}
float calavg(struct student n1,struct student n2)
{
  return((n1.per+n2.per)/2);
}
/* Output */
Enter roll,name and per of 1st student 101 abc 98
Enter roll,name and per of 2nd student 102 xyz 99
roll 101  name abc  per 98.000000
roll 102  name xyz  per 99.000000
average per 98.500000

Question:2
C program to declare a structure named employee with attributes as empno, name and salary. Take input for details of 2 employees, display the details using functions. Also calculate and print average salary of both the employees.
Sol:

#include<stdio.h>
#include<conio.h>
struct employee
{
int empno;
char name[20];
float sal;
};
void show(struct employee n);
float avg_sal(struct employee n1,struct employee n2);

int main()
{
 struct employee s1,s2;
 float a;
 //clrscr();
 printf("Enter empno,name and sal of 1st employee ");
 scanf("%d %s %f",&s1.empno,s1.name,&s1.sal);
 printf("Enter empno,name and sal of 2nd employee ");
 scanf("%d %s %f",&s2.empno,s2.name,&s2.sal);
 show(s1);
 show(s2);
 a=avg_sal(s1,s2);
 printf("Average salary = %f\n",a);
 getch();
 return(0);
}
void show(struct employee n)
{
 printf("empno %d name %s sal %f\n",n.empno,n.name,n.sal);
}
float avg_sal(struct employee n1,struct employee n2)
{
  return((n1.sal+n2.sal)/2);
}


/* Output */
Enter empno,name and sal of 1st employee 1001 Kapil 58000
Enter empno,name and sal of 2nd employee 1002 Mohan 75000
empno 1001 name Kapil sal 58000.000000
empno 1002 name Mohan sal 75000.000000
Average salary = 66500.000000

C Language Programming Tutorial

C Language Tutorial Home     Introduction to C Language     Tokens     If Condition      goto statement and Labelname     Switch Statements     For loop     While Loop     Do while loop     break and continue     Functions     Recursion     Inbuild Functions     Storage Classes     Preprocessor     Arrays     Pointers     Structures and Unions     File Handling     Projects