# Extract outputs from a WHILE loop in a table format

How can I convert my multiple outputs of a while loop in a table form and save it for later use. Here is a sample code:

i = 1;
While[i < 6, c = 2^i; d = 3^i; Print[c "           ", d]; i++]


The actual output should look like this: Eventually, my goal is to eliminate certain rows based on a specific condition that values in column 2 satisfy.

(Here, my while loop is essential in what I am doing in my actual code. So assuming that cannot be changed is there a way to convert the output in table format? I apologize for any confusion)

Use Table instead of a While loop:

table = Table[{2, 3}^i, {i, 5}]


{{2, 3}, {4, 9}, {8, 27}, {16, 81}, {32, 243}}

Or

table = Transpose[Table[i^Range, {i, 2, 3}]]


{{2, 3}, {4, 9}, {8, 27}, {16, 81}, {32, 243}}

You can use Grid to display:

Grid[table, Dividers -> All] Update: If you have to use While you can AppendTo a list that is initialized to {}:

i = 1;
tab = {};
While[i < 6, AppendTo[tab, {2, 3}^i++]]
tab


{{2, 3}, {4, 9}, {8, 27}, {16, 81}, {32, 243}}

Alternatively, you can use Reap / Sow combination:

i = 1;
Reap[While[i < 6, Sow[ {2, 3}^i++]]][[2, 1]]


{{2, 3}, {4, 9}, {8, 27}, {16, 81}, {32, 243}}

• Thanks for the suggestion. However, the while loop is essential in what I am doing in my actual code (which I am not able to provide). Even with the while loop can I use the table function as you mention? Sorry for any confusion. Aug 13, 2019 at 23:10
• @primefinder, please see the update.
– kglr
Aug 13, 2019 at 23:30
• Why is a While loop necessary? Could you use NestWhileList? Aug 14, 2019 at 1:47
• What about Reap and Sow @primefinder ? Aug 19, 2019 at 11:16

It's not an issue for small lists such as provided in the example. However, AppendTo has issues for large ones.

With that in mind, an alternative approach is to assign your output list before entering the While[] block as in

i = 1;
out = Range;
While[i < 6,
out[[i]] = {2, 3}^i;
i++
]
out


Format, using TableForm or Grid as you like.

But as @kglr suggests, his first Table[] example is more typical of Mathematica. While you can write Fortran (C, Pascal, ...) in any language, often there are better approaches.

• Could you expand on the AppendTo issues? Will it cause problems if I am storing say around 20 million outputs which are "large" numbers in a list generated using AppendTo ? Aug 14, 2019 at 15:28
• I'd refer you to this answer (mathematica.stackexchange.com/questions/72624/…) from @Leonid Schifrin. "The reason is that AppendTo and PrependTo actually replace the whole list with a new one, rather than only changing a single element."
– dwa
Aug 15, 2019 at 0:19