Re: [Help Needed] Converting C++ program into Mathematica Function
- To: mathgroup at smc.vnet.net
- Subject: [mg71209] Re: [Help Needed] Converting C++ program into Mathematica Function
- From: Bill Rowe <readnewsciv at sbcglobal.net>
- Date: Fri, 10 Nov 2006 06:38:16 -0500 (EST)
On 11/9/06 at 3:39 AM, ms-z- at hotmail.com (a1b2c3d4) wrote:
>i've tried for quite some time but am still stuck at it.
>the C++ program is as follows:
<C code snipped>
It has been quite a while since I've used C. So, my C is quite
rusty. But if I understand your code correctly it performs the following:
gets a number of lines to print then for each line
outputs lines-lineNo spaces
outputs 2*lineNo-1 stars
outputs a single newline
This can be implemented in Mathematica as follows
printLines[k_] :=
Table[
Print@StringJoin[
Nest[# <> " " &, "", k - n],
Nest[# <> "*" &, "", 2 n - 1]
],
{n, k}]
here
the argument to supply printLines is the desired number of lines
your outer loop is being replaced by Table
the first Nest command uses the <> operator (shorthand for
StringJoin) to build a string of spaces
the second Nest command uses the same technique to build a
string of stars
these are joined using StringJoin then printed using Print
Since Print has an implicit newline, that is each invocation of
Print results in a separate line of output, I've not included a
newline in the string being created.
>The Mathematica function i've tried to write is as follows:
<attempt snipped>
It is possible to write Mathematica code to implement the same
thing using For and Do. However, the usage of For in Mathematica
is like the usage of goto in C --- it is possible to do so, but
generally results in poorer performance, harder to maintain code.
--
To reply via email subtract one hundred and four