Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

Check if the array is descending up to the local minimum and then ascending after it in C

**My task is: The user should input numbers until -1 is pressed. The array consisting of those elements should be formed. I need to check is the array is descending up to the local minimum and ascending after it. If this condition is satisfied 'Yes' should be printed, 'No' in the opposite case. I don't know what is wrong with my code, so I hope you could help. I am beginner.

int main() {
    int a[100],n=0,b,i,j=0,c=0,h;
    for (i=0;i<100;i++){
        if (b==-1)
            break;
        else {scanf("%d", &b);
            a[i]=b;
            n++;
        }
    }
    if (n<3)
        printf("Not enough elements");

    else{
        for (i=0;i<n;i++){
            for(j=0;j<n;j++)
                a[j]=a[i];
        }
        for (i=0;i<n;i++){
            if (a[i]>a[i+1] && i!=n-1)
                continue;
            else if (a[i]<a[i+1]){
                c=1;
                h=i;
                break;
            }
        }    


        if (c==1 && h==i){
            for(j=i;j<n;i++){
                if(a[j]<a[j+1])
                    continue;
                else if(a[j]>a[j+1] || a[j+1]==a[j]){
                    break;
                    c=0;
                }

            }
            if(j==n-1 && c==1)
                printf("Yes");
            else if (c==0)
                printf("No");   
        }

    }


}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This code can help you :

#include <stdio.h>

int main() {
    int a[100],n=0,b,i,j=0,c=0,h;
    do
    {
        printf("Give me a number :");
        scanf("%d", &b);
        a[j]=b;
        j++;
    }while(b!=-1);
    i=0;
    j--;
    if (j<3)
    {
        printf("Not enough elements");
    }
    else
    {
        i=0;
        while(i<j-1 && a[i]>a[i+1])
        {
            i++;
        }
        if(i==j-1)
        {
            printf("No");
            return 0;
        }
        else
        {
            c=i;
            while(a[c+1]>a[c]&&c<j-1)
            {
                c++;
            }
        }
    }
    if(c==j-1)
    {
        printf("Yes");
    }
    else
    {
        printf("No");
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...