I am working on a project and i want to print in order each 3 elements of a string array.So if the string is "cadgfacbda" i want to be printed in the console :
**"cad gfa cbd a"**
This is the code :
        string str("cadgfacbda");
        for(int i = 0 ; i < 3 ; i++)
        {
            for(int j = i ; j <  str.size() ; j +=3 )
            {
               cout << str[j]<<" ";
            }
        cout<<endl;
    }
But what i get is :
c g c a
a f b
d a d
Code in one loop only:
string str("cadgfacbda");
for(int i = 0 ; i < str.size() ; i++) {
   if(i && i%3==0)
      cout<<" ";
   cout << str[i];
}
cout<<endl;
                        I think it should go something like this:
        string str("cadgfacbda");
        for(int i = 0 ; i < str.size() ; i++)
        {
            cout << str[j]<<" ";
            if( i % 3 == 0 )
                cout<<endl;
        }
This ofcourse assumes you need new line after every three elements. If you just need spaces then you can try this instead:
        string str("cadgfacbda");
        for(int i = 0 ; i < str.size() ; i++)
        {
            cout << str[j];
            if( i % 3 == 0 )
                cout<<" ";
        }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With