0

What am I doing wrong? the program run but the output isn't in the right order.

#include <stdio.h>
int main () { /*program to ask user to input array values and sort them in ascending order.*/
    int n,j,i,temp;
    printf ("how many numbers?\n");
    scanf ("%d",&n);
    int a[n];
    for (i=0;i<n;i++){
        printf ("enter number");
        scanf ("%d",&a[i]);
    }
    for (i=0;i<n;i++); {
     for (j=i+1;j<n;j++){
            if (a[i]>a[j]){
                temp=a[i];
                a[i]=a[j];
                a[j]=temp; }
    } }
    printf("The numbers arranged in ascending order are given below \n");
    for (i = 0; i < n; ++i)
        printf("%d\n", a[i]);
}
1
  • Because you didn't indent your code you never saw that you have a stray ; immediately after for (i=0;i<n;i++); {. Commented Nov 21, 2014 at 9:07

2 Answers 2

3

Change

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

To

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

Semicolon was executed instead of following błock {}

Sign up to request clarification or add additional context in comments.

3 Comments

Minor: your nested loop starts j From i+1 so clipping i by 1 let inner loop on j execute at least once even for last iteration on i
I think no need to do this. because its checking j<n.
Yes, you are right, in this small piece of code it is clearly not needed. But this is a good habbit to limit iterators to correct range. Otherwise in more complex code you could fall into serious troubles accessing data out of range of allocation.
0

Element form right/end cant propagate to left, because for example first element of array can be swapped only at first check with second element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.