Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Its C programming only! I am trying to make a program that sorts scanned numbers

ID: 3816792 • Letter: I

Question

Its C programming only!

I am trying to make a program that sorts scanned numbers from smallest to largest but there is a problem with my void sort function but I dont really know what is wrong.. any help would be appreciated. Its C programming only!

#include<stdio.h>
#define SIZE 5

void load(int a[], int n)
{
int i;

for(i=0; i<n; i++)
{
printf("Enter a number: ");
scanf("%d", &a[i]);
}
}

void print(int b[], int n)
{
int i;
for(i=0; i<n; i++)
printf("%d", b[i]);

printf(" ");
}

void sort(int a[], int n)
{
int i,j,t;

for(i=0; i<n-1; i++)
for(j=0; j<n-1;j++)
if(a[j]>a[j++])
{
t=a[j];
a[i]=a[j++];
a[j++]=t;
}

}

void main()
{
int a[SIZE];

load(a,SIZE);
print(a,SIZE);
sort(a,SIZE);
print(a,SIZE);
}

Explanation / Answer

Hi,

You are passing copy of your array values to the void sort function and in function the sorting approach was incorrect.I have made changes to your code.In the Main function,Changes were made to pass the reference to the array and in sort method I have made the necessay changes.

Find below working code .

#include<stdio.h>
#define SIZE 5

void load(int a[], int n)
{
    int i;

    for(i=0; i<n; i++)
    {
        printf("Enter a number: ");
        scanf("%d", &a[i]);
    }
}

void print(int b[], int n)
{
    int i;
    for(i=0; i<n; i++)
        printf("%d", b[i]);

    printf(" ");
}

int *sort(int a[], int n)
{
    int i,j,t;

    for(i=0; i<n; i++)
      for(j=i+1;j<n;j++)
        if(a[i]>a[j])
           {
            t=a[i];
            a[i]=a[j];
            a[j]=t;
           }
return a;
}

void main()
{
    int a[SIZE];

    load(a,SIZE);
    print(a,SIZE);
    int *sorted=sort(a,SIZE);
    print(a,SIZE);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote