# Nested for loops - programming.

Anonymous
timer Asked: Dec 4th, 2015
account_balance_wallet \$5

### Question Description

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.

School: University of Maryland

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.

flag Report DMCA
Review

Anonymous
Thanks, good work

Brown University

1271 Tutors

California Institute of Technology

2131 Tutors

Carnegie Mellon University

982 Tutors

Columbia University

1256 Tutors

Dartmouth University

2113 Tutors

Emory University

2279 Tutors

Harvard University

599 Tutors

Massachusetts Institute of Technology

2319 Tutors

New York University

1645 Tutors

Notre Dam University

1911 Tutors

Oklahoma University

2122 Tutors

Pennsylvania State University

932 Tutors

Princeton University

1211 Tutors

Stanford University

983 Tutors

University of California

1282 Tutors

Oxford University

123 Tutors

Yale University

2325 Tutors