Home > Software engineering >  Print front and back from an array c
Print front and back from an array c

Time:05-30

how can i print from array once from back and once from front c ?

for examble:

char c[] = { 'A','B','C','D' };
for (int i = 0; i < size(arr); i  )
{
    cout << c[i]; 
}

the output will be ABCD

but the output that i want should be ADBC

print one from front and one from end c[0],c[3],c[1],c[2]

CodePudding user response:

You can use. Here we iterate for only half number of times the size of the array. Note that this assumes you have even number of elements in the array.

int main()
{
    char c[] = { 'A','B','C','D','E' };
    std::size_t len = std::size(c);
    //---------------------v------------->divide by 2 so that we iterate only half the size times
   for (int i = 0; i < len/2; i  )
   {
        std::cout << c[i]<<c[len - i - 1];
   }
   if (len % 2) {//in case we have odd number of elements 
        std::cout << c[len/2];
    }
    
}

Working demo

  •  Tags:  
  • c
  • Related