C++ Program to Check If Given String Is Of Form a^n b^n c^n Where n>=1

  1. #include<iostream>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. using namespace std;
  5. int main()
  6. {
  7.    char a[50];
  8.    int i,j,k,len;
  9.    cout<<“Enter the string to check\n”; //input the string
  10.    cin>>a;
  11.    if(strlen(a)%3!=0)  //if string length is not multiple of 3 , reject it
  12.    {
  13.        cout<<“Not accepted\n”;
  14.        exit(0);
  15.    }
  16.    len=strlen(a)/3;  //len= length of the input string
  17.    for(i=0;i
  18.    {
  19.        if(a[i]!=’a’)
  20.        {
  21.            cout<<“Not accepted\n”;
  22.            exit(0);
  23.        }
  24.    }
  25.    for(j=i;j<i+len;j++)  //checks if next len/3 characters are ‘b’
  26.    {
  27.        if(a[j]!=’b’)
  28.        {
  29.            cout<<“Not accepted\n”;
  30.            exit(0);
  31.        }
  32.    }
  33.    for(k=j;k<j+len;k++)  //checks if next len/3 characters are ‘c’
  34.    {
  35.        if(a[k]!=’c’)
  36.        {
  37.            cout<<“Not accepted”;
  38.            exit(0);
  39.        }
  40.    }
  41. /*if all conditions are satisfied, it shows that input is accepted*/
  42.    cout<<“Accepted\n”;
  43.    return 0;
  44. }

Output:

Enter the string to check

aabbcc

Accepted

Leave a comment