Nested for loops - programming.

Computer Science
Tutor: None Selected Time limit: 1 Day

student stud[20],t;

int i,j;

int n = 3;

void input (void){

for(i=0;i<n;i++)

{

scanf("%d",&stud[i].mscore);

scanf("%d",&stud[i].escore);

stud[i].avg =(stud[i].mscore+stud[i].escore)/2;

void top (void){

    int a=1;

for(i=0;i<n-1;i++)

{

for(j=i+1;j<n;j++)

{

if(stud[i].avg<stud[j].avg)

{

*t=stud[i];*

*stud[i]=stud[j];*

*stud[j]=t;*

}

This program is to find the top three students in a class by average. I dont understand what is being done in the areas where i have placed *. Somebody please explain. 

Dec 4th, 2015

Thank you for the opportunity to help you with your question!

Let me explain to you this part so that you can understand better.

if(stud[i].avg<stud[j].avg)

{

*t=stud[i];*

*stud[i]=stud[j];*

*stud[j]=t;*

}

This program is meant to perform a sort and so the part is the one which does the sorting.

The Array stud[] contains Data which is being compared and so, if the the value stored at stud[i] is less than the value stored at stud[j] * which is the same as i +1 then the value is held up in a temporary variable called t and the value of stud[i] is changed to the what was initially the value of stud[j]. After it has been changed, then we change the value of stud J to the value we assigned to t.

 The reason why we assign it to another variable, is because we are doing an actual replacement to the variables therefore making it impossible to just assign  it directly.


Assume you have this data as the data in the Array:

stud[]={7,3,8,5,9,5,8,1,5,2}

Assume we are at position 5 where the value is 9 . The value of stud[j] is 5 which is smaller.

We want to swap positions so that 5 comes to the stud[5] while 9 goes to stud[6]



Please let me know if you need any clarification. I'm always happy to answer your questions.
Dec 4th, 2015

Are you studying on the go? Check out our FREE app and post questions on the fly!
Download on the
App Store
...
Dec 4th, 2015
...
Dec 4th, 2015
Dec 5th, 2016
check_circle
Mark as Final Answer
check_circle
Unmark as Final Answer
check_circle
Final Answer

Secure Information

Content will be erased after question is completed.

check_circle
Final Answer