Easy Tutorial
❮ C Examples Sizeof Operator C Standard Library Setjmp H ❯

C Exercise Example 67

C Language Classic 100 Examples

Title: Input an array, swap the largest element with the first element, and the smallest element with the last element, then output the array.

Program Analysis: The answer in Tan Haoqiang's book is problematic.

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&lt;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&lt;n;j++)
    {
        if(s[j]&lt;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&lt;n;i++)
        printf("%d ",s[i]);
    printf("\n");
}

int main()
{
    int s[20];
    int i,n;
    printf("Set array length (&lt;20):");
    scanf("%d",&n);
    printf("Input %d elements:\n",n);
    for(i=0;i&lt;n;i++)
        scanf("%d",&s[i]);
    fun(s,n);
    printf_s(s,n);
    return 0;
}

Output result:

Set array length (&lt;20): 5
Input 5 elements:
12 123 4 65 21
123 12 21 65 4

C Language Classic 100 Examples

❮ C Examples Sizeof Operator C Standard Library Setjmp H ❯