C Exercise Example 67
Title:Input an array, swap the largest with the first element, swap the smallest with the last element, and output the array.
Program analysis:There are problems with the answers in Tan Haoqiang's book.
Example
#include<stdio.h>
#include<stdlib.h>
void fun(int *s,int n)
{
int i;
int max=s[0];
int a=0;
for(i=0;i<n;i++)
{
if(s[i]>max)
{
max=s[i];
a=i;
}
}
s[a]=s[0];
s[0]=max;
int j;
int min=s[n-1];
int b=n-1;
for(j=0;j<n;j++)
{
if(s[j]<min)
{
min=s[j];
b=j;
}
}
s[b]=s[n-1];
s[n-1]=min;
}
void printf_s(int *s,int n)
{
int i;
for(i=0;i<n;i++)
printf("%d ",s[i]);
printf("\n");
}
int main()
{
int s[20];
int i,n;
printf("Set array length (<20):");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&s[i]);
fun(s,n);
printf_s(s,n);
return 0;
}
The output result is:
设置数组长度(<20):5 输入 5 个元素: 12 123 4 65 21 123 12 21 65 4other extensions