Search info in an array of struct variables & Shows how a function can return a structure variable.

#include <stdio.h>

typedef struct student
{
int rollno;
char name[20];
float percent;
}Student;

Student findByRollNo(Student *, int, int);
Student findByName(Student *, int, char *);

int main(void)
{
Student sarr[5] = { { 101, "Ram", 76.22 },
{ 102, "Sita", 77.98 },
{ 103, "Gopal", 65.89 },
{ 104, "Radha", 63.28 },
{ 105, "Raghu", 78.20 } };

int rollno, choice;
char name[20];

Student result;

printf( "\nSearch By [ 1. Roll No, 2. By Name ] : " );
scanf( "%d", &choice );

if(choice == 1)
{
/* Search by Roll No */
printf( "\nEnter Roll No: " );
scanf( "%d", &rollno );

result = findByRollNo(sarr, 5, rollno);
if(result.rollno == 0)
printf("\nRoll No %d NOT FOUND", rollno);
else
{
printf("\nStudent Info : " );
printf("\nRoll No : %d", result.rollno);
printf("\nName : %s", result.name);
printf("\nPercent : %f", result.percent);
}
}
else if( choice == 2 )
{
/* Search by name - H/W */
}

return 0;
}

Student findByRollNo(Student *sarr, int n, int rollno)
{
Student result = { 0, "", 0.00 };
int i;

for( i = 0; i < n; i++ )
{
if( sarr[i].rollno == rollno )
{
result= sarr[i];
break;
}
}

return result;
}

Student findByName(Student *sarr, int n, char *name)
{
/* To be done as Home-Work */
}

No comments:

Post a Comment

kiss on google ads if you are anonymous because your ip is trackable.thank you.

......from.admin