Problem:
Matrix-like Computation

Your task is to develop a tiny little part of spreadsheet software.

Write a program which adds up columns and rows of given table as shown in the following figure:

Input

The input consists of several datasets. Each dataset consists of:

n (the size of row and column of the given table)
1st row of the table
2nd row of the table
:
:
nth row of the table

The input ends with a line consisting of a single 0.

Output

For each dataset, print the table with sums of rows and columns. Each item of the table should be aligned to the right with a margin for five digits. Please see the sample output for details.

Sample Input

4
52 96 15 20
86 22 35 45
45 78 54 36
16 86 74 55
4
52 96 15 20
86 22 35 45
45 78 54 36
16 86 74 55
0

Output for the Sample Input

52 96 15 20 183
86 22 35 45 188
45 78 54 36 213
16 86 74 55 231
199 282 178 156 815
52 96 15 20 183
86 22 35 45 188
45 78 54 36 213
16 86 74 55 231
199 282 178 156 815

Solution in Scala (judge verdict: Accepted)

object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.stdin.getLines()
    def loop(it: Iterator[String]): Stream[Table] = {
      readTable(it) match {
        case None => Stream.empty
        case Some((table, it2)) => table #:: loop(it2)
      }
    }
    loop(lines).foreach(printTable)
  }

  case class Table(rows: Seq[Seq[Int]])

  def printTable(table: Table): Unit = {
    val totalRow =
      for (i <- 0 until table.rows.head.length) yield {
        table.rows.map(_.apply(i)).sum
      }
    (table.rows :+ totalRow).foreach{ row =>
      (row :+ row.sum).foreach{ c => print(f"${c}%5d") }
      println()
    }
  }

  def readTable(lines: Iterator[String]): Option[(Table, Iterator[String])] = {
    val n = lines.next().toInt
    if (n <= 0)
      None
    else {
      val (it1, it2) = lines.duplicate
      val table = Table(it1.take(n).map(_.split(" ").map(_.toInt).toSeq).toSeq)
      val rest = it2.drop(n)
      Some((table, rest))
    }
  }
}