Using for-loop

this is a simple selection sort C program ok(sorry for letting me put up a C progam in a C++ forum, I hope its just the syntax change and this is a very basic program so you wont mind)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<stdio.h>

int main()
{
      int a[20],i,N,temp,j;
      printf("size of the array:");
      scanf("%d",&N);
      printf("enter the terms:");
      for(i=1;i<=N;i++);
      {
         scanf("\n\t\t%d",&a[i]);
         }
      for(i=1;i<=N-1;i++)
      for(j=i+1;j<=N;j++)
      if(a[i]>a[j])
      {
                   temp = a[i];
                   a[i]=a[j];
                   a[j]=temp;
                   }
                   
      printf("\n\t The ascending order list os ..:\n");
      for(i=1;i<=N;i++)
      print("\n\t\t%d",a[i]);
      }


Can some one explain the program properly?

1) Does the program doesnt have the value or N right? as in the no. of terms.?
2) first for loop, i=1, that 1 is the address of the set of numbers or it is the no it self?
3) If it is the numbers that are to be ordered in ascending order, then say N=5, it will be 1 2 3 4 5 right? So the first forloop i=1, the 1 is the address right?
4) The second for loop, N-1? Can you please explain how for loops exactly works

5) The main problem is that i am not able to get a proper perspective of coding to a computer. Step by step. please explain the program properly and also the for loops.

I understood the swapping part. But I dont understand where the comparing part is done .
This is how a for loop works
for(A;B;C)D;

1. A is executed
2. The condition B is evaluated. If it is false, loop ends
3. D is executed
4. C is executed
5. Jump to step 2

Line 13 should be for(i=0;i<=N-1;i++)
Line 14 should be for(j=i+1;j<=N-1;j++)

Here 2 loops have been used, as all pairs of terms have to be compared. Hence j should never be equal to i.

i is the no. of terms which are known to be in correct order.
For eg. in the beginning, all terms may be in wrong order, hence i is 0.
After the loop in line 13 is called again, i becomes 1 as we know that the first term is definately the smallest.
So, j should always be more than i.
Last edited on
Topic archived. No new replies allowed.