Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ read each 3 elements in array

Tags:

c++

arrays

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

like image 894
Reznicencu Bogdan Avatar asked Mar 09 '16 11:03

Reznicencu Bogdan


2 Answers

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;
like image 178
Zia Qamar Avatar answered Sep 30 '22 01:09

Zia Qamar


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<<" ";
        }
like image 38
usamazf Avatar answered Sep 30 '22 02:09

usamazf