Hi All, I'm new to "C" Learning basic Programmes(& also in this forum) in C. I wrote a program Ascending order of an Array. unfortunately its not working. I believe logic is correct, Is there any thing I'm missing in it Code: void main() { int a[5],i,j,temp; clrscr(); printf("\nenter 5 no.'s:); for(i=0;i<5;i++) scanf("%d",&a[i]); for(i=0;i<5;i++) { for(j=i+1;j<5;j++) { if(a[i]>a[j]) temp=a[i]; a[j]=a[i]; a[j]=temp; } } printf("\nAscending no.'s:); for(i=0;i<5;i++) printf("\n%d",a[i]); getch(); } Now running prog.: entering no 11 5 9 3 2 giving me: 2 3 9 11 11 Can someone please tell me what is it I'm missing..Any file to include is there any logic going wrong?
try this:- Code: void main() { int a[5],i,j,temp; clrscr(); printf("\nenter 5 no.'s:); for(i=0;i<5;i++) scanf("%d",&a[i]); for(i=0;i<5;i++) { for(j=i+1;j<5-i;j++) //i made change here... { if(a[i]>a[j]) temp=a[i]; a[j]=a[i]; a[j]=temp; } } printf("\nAscending no.'s:); for(i=0;i<5;i++) printf("\n%d",a[i]); getch(); }
The correct code for arrenging an array in asendind order is given below:- Code: #include<stdio.h> #include<conio.h> void main() { int a[5],i,j,temp; clrscr(); printf("\nenter 5 no.'s:"); for(i=0;i<5;i++) scanf("%d",&a[i]); for(i=0;i<5;i++) { for(j=i+1;j<5;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } printf("\nAscending no.'s:"); for(i=0;i<5;i++) printf("\n%d",a[i]); getch(); } Your logic is correct but while swapping the numbers you did the wrond logic...
As Sanket pointed out you are swapping the numbers wrongly. You are doing Code: temp=a[i]; a[j]=a[i]; a[j]=temp; Where as your a remains unchanged. You should use what Sanket has as swapping logic