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);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.