coinjo wrote:
I need to write a program, which takes two inputs:
â€¢ï€ ï€ a value n that represents the number of elements in the
longest row of a triangle.
â€¢ï€ ï€ a character c to be printed in place of each element.
My algorithm should produce an isosceles triangle of characters c. For
example,
for n=7 and c=’$’, the resulting triangle should be as follows:
$
$$$
$$$$$
$$$$$$$
It should work for only odd values of n.
Any hints please?
Study the output.
Are there any obvious relationsships?
Hmm. Each line starts with some blank characters followed by some '$' characters.
How many are there in each line? Lets make a table:
Line Nr | Nr of ' ' Nr of '$'
----------|---------------------------
$ 0 | 3 1
$$$ 1 | 2 3
$$$$$ 2 | 1 5
$$$$$$$ 3 | 0 7
Now, can you come up with a formula, that describes the realtionship
between the line number and the nr of spaces? Same for nr of '$'?
And btw. Why are there 4 lines in the triangle when the input was 7?
(Hint: in allmost all formulas the 'side length' or the 'number of lines'
will apear somehow. Now formula use more then elementary arithmetic).
When you have your formulas, try them on paper with some more triangles
and see if they are correct.
Once you have correct formulas, the rest should be easy:
get side length from user
is the side length odd
if no, tell the user and exit (or let him retry the input)
calculate how many lines are needed
for( i = 0; i < NrOfLines; ++i ) {
Calculate how many ' ' are needed
Output that many ' ' using a loop
Calculate how many '$' are needed
Output that many '$' using a loop
Output '\n'
}
That is what programming is all about
: looking closely at the world and
figuring all relationships no one else then a programmer would see. Then
take what you noticed and write code for it. But first of all you need
to have those relationships and have converted them to a cook book recipe.
If you don't have them, then you can't write a program.
--
Karl Heinz Buchegger
kb******@gascad.at