Im trying to sort an array in ascending order and print it out and Im having trouble of where to put my cout in my code.
for (int k=0; k<ARRAY_SIZE; k++) {
for (int l=1; l<ARRAY_SIZE-1; l++) {
if(numbers[l] > numbers[k]) {
temp = numbers[k];
numbers[k] = numbers[l];
numbers[l] = temp;
}
cout<<numbers[k];
}
}
Remove the actual cout
and put it after the sorting loop, in a new loop
for(int k = 0 ; k < ARRAY_SIZE; ++k)
cout << numbers[k] << " ";
如果要查看排序结果,则必须在新的 for 循环中打印数组
This is a program that finds the length of a number n
and converts it to an array arr
and sorts that array in ascending order. (possible aptitude question)
#include <iostream>
using namespace std;
int main()
{
int n,i=0,j,num,temp,len=0,arr[10]={0};
cin>>n;
num=n;
while(n!=0)
{
len++;
n/=10;
}
cout<<len<<endl;
for ( i = len; i >= 0; i--)
{
arr[i] = num%10;
num/=10;
}
for(i=1;i<=len;i++)
for(j=0;j<=len-i;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
for(i=1;i<=len;i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.