Sunday, February 25, 2018

C program : Create a database using Structure

Create a database of students using structures, where in each entry of the database will have the following fields:
  1. a name, which is a string with at most 128 characters
  2. their marks in physics which is an int between 0 and 100
  3. their marks in chemistry which is an int number between 0 and 100
  4. their marks in mathematics which is an int number between 0 and 100
You have to output a list of students in the following order.
  1. if a student 'A' has lower marks in physics than a student 'B', then A's data is listed before B.
  2. If A and B have the same physics marks and A has lower chemistry marks than B, then A is listed before B.
  3. If A and B have the same marks in physics and chemistry, and A has lower marks in mathematics than B, then A is listed before B.
  4. If all marks are equal and A's name precedes B's name in the dictionary order, then A is listed before B.
Input Format :First line contains the number of students n, where 1<=n<=100.
In following n lines each line contains(space separated)  a name and their respective marks in physics, chemistry, maths, where 0<=marks<=100.

Output Format :Sorted database of n lines.


 #include<stdio.h>
#include<string.h>
struct stu
{
  char name[128];
  int p,c,m;
};
void main()
{
  int i=0,n=0,j=0;
  scanf("%d",&n);
  struct stu db[n],temp;
  if(n==1)
  {
    scanf("%s%d%d%d",db[0].name,&db[0].p,&db[0].c,&db[0].m);
    printf("%s\t%d\t%d\t%d",db[0].name,db[0].p,db[0].c,db[0].m);
  }
  else
{

  for(i=0;i<n;i++)
  {scanf("%s%d%d%d",db[i].name,&db[i].p,&db[i].c,&db[i].m);}
  for(i=0;i<n;++i)
  {
    for(j=i+1;j<n;++j)
    {

       if(db[i].p>db[j].p)
          {
                  temp=db[i];
                  db[i]=db[j];
                  db[j]=temp;
           }

          else if(db[i].p==db[j].p && db[i].c>db[j].c)
            {
                temp=db[i];
                db[i]=db[j];
                db[j]=temp;
              }

          else if(db[i].p==db[j].p && db[i].c==db[j].c && db[i].m>db[j].m)
        {
            temp=db[i];
            db[i]=db[j];
            db[j]=temp;
        }


      else  if(db[i].p==db[j].p && db[i].c==db[j].c && db[i].m==db[j].m)
        {

                  if(strcmp(db[i].name,db[j].name)>0)
                    {
                      temp=db[i];
                      db[i]=db[j];
                      db[j]=temp;
                    }

          }


    }
  }
  for(i=0;i<n-1;i++)
  {printf("%s\t%d\t%d\t%d\n",db[i].name,db[i].p,db[i].c,db[i].m);}
    printf("%s\t%d\t%d\t%d",db[n-1].name,db[n-1].p,db[n-1].c,db[n-1].m);
}
}

No comments:

Post a Comment

Sacred Thought

26 April 2024  Dear friends, I write the explanation of two verses of Geets for all of you, I hope you all will like it and benefit from it....