Logo

Programming-Idioms

  • Fortran
  • Rust

Idiom #163 Print list elements by group of 2

Print all the list elements, two by two, assuming list length is even.

for pair in list.chunks(2) {
    println!("({}, {})", pair[0], pair[1]);
}
write (*,'(2I8,:," ")') list

This writes out an integer array of any length. The format string, 2I8 means two integers of eight digits each. When the format is exhausted, a new line is started (this is called "format reversion"). As an extra bonus, the space between the two integers is only printed if there is an even number of items in the array, otherwise it is skipped.
#include <stdio.h>
for (unsigned i = 0; i < sizeof(list) / sizeof(list[0]); i += 2)
	printf("%d, %d\n", list[i], list[i + 1]);

I'm treating list as an array not a list because C doesn't have lists built in.
The length had better be even or there'll be undefined behaviour to pay!

New implementation...