简体   繁体   中英

I don't understand how to write such program

Write a program that receives from the user a string consisting of the letters "a" and "b", which is 10 characters long (each character must be read separately). The program should also detect the signal if there is an abba sequence at the input. (For this, you cannot use arrays and sorting) I had a similar option, but it does not fit:

void abba();
int main()
{
abba();
return 0;
}

void abba()
 {
int a, b, c, d, e, f, g, h, k, l;
printf("Enter 10 characters");
scanf_s("%c", &a);
scanf_s("%c", &b);
scanf_s("%c", &c);
scanf_s("%c", &d);
scanf_s("%c", &e);
scanf_s("%c", &f);
scanf_s("%c", &g);
scanf_s("%c", &h);
scanf_s("%c", &k);
scanf_s("%c", &l);

if (a == 'a' && b == 'b' && c == 'b' && d == 'a')
printf("'abba' is found!");
if (b == 'a' && c == 'b' && d == 'b' && e == 'a')
printf("'abba' is found!");
if (c == 'a' && d == 'b' && e == 'b' && f == 'a')
printf("'abba' is found!");
if (d == 'a' && e == 'b' && f == 'b' && g == 'a')
printf("'abba' is foun d!");
if (e == 'a' && f == 'b' && g == 'b' && h == 'a')
printf("'abba' is found!");
if (f == 'a' && g == 'b' && h == 'b' && k == 'a')
printf("'abba' is found!");
if (g== 'a' && h == 'b' && k == 'b' && l == 'a')
printf("'abba' is found!");

}

If you can't use arrays then you can use flags to know what you've read so far and what character you expect next to get your desired sequence. The code would be:

void abba(){
    int i = 0; //chars read counter
    int j = 0; //sequence counter "a" = 1, "ab" = 2, "abb" = 3, "abba" = 4
    int flag = 0; //set to 1 if j hits 4
    char a;
    printf("Enter 10 characters\n");
    while(i<10){
        scanf_s(" %c",&a);
        i++; if(i>10)break;
        if(a == 'a'){
            if(j==3){
                j++;
                flag=1;
            }
            else j=1;
        }
        else if(a == 'b' && (j==1 || j==2)){
            j++;
        }
        else{
            j=0;
        }
    }
    if(flag==1){
        printf("abba found!");
    }
    else printf("not found");
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM