Nested for loops - programming.

label Computer Science
account_circle Unassigned
schedule 1 Day
account_balance_wallet \$5

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

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]

Dec 4th, 2015

...
Dec 4th, 2015
...
Dec 4th, 2015
Oct 22nd, 2017
check_circle