Its C programming only! I am trying to make a program that sorts scanned numbers
ID: 3816793 • 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
#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-i-1;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
void main()
{
int a[SIZE];
load(a,SIZE);
print(a,SIZE);
sort(a,SIZE);
print(a,SIZE);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.