0

I am trying to print a tree with the help of "format" and a variables. But couldn't figure out how to pass in variable and get an output in a generalized form. The below code works for a particular example but not for any tree.

I used hard coded approach for getting the horizontal spacing right using the if statement as below. But i want to just pass-in the variable "count" which contains the height of the tree, and get a output directly.

    if (count .eq. 9) then
        write(6,9) t%element
            9   format (t12,I3)
    else if (count .eq. 8) then
        write(6,8) t%element
            8   format (t9,I3)
    else if (count .eq. 7) then
        write(6,7) t%element
            7   format (t6,I3)
    else 
        write(6,6) t%element
            6   format (t3,I3)
    end if  

The result you get is like this


 1
     2
 3
         4
 5
     6
 7
1

1 Answer 1

0

What I usually do is to have the format identifier as a string, like this:

character(len=len("(T02, I3)")) :: fmt

write(fmt, '("(T", I2.2, ", I3)")') count  ! if count=2, fmt will be "(T02, I3)"
write(*, fmt) t%element
Sign up to request clarification or add additional context in comments.

4 Comments

I am getting a compiler error as this, Error #6899: First non-blank character in a character type format specifier must be a left parenthesis. ['"(T", I2.2, ", I3)")']
You're right, I was missing an open parenthesis. Try it now.
Yeah it works, thanks; you were again missing a '(' . But i figured it out. So according to the above code, the spacing between them characters of the tree is 1 position. The reason for this is because of Specifying 'T' instead of T3 or T4. But if i change T to T3 it shows error in the final compilation output. I am just curious of how to increase the spacing it?
The count variable gives the number of spaces. You can say write(fmt, ...) 2*count+1 if you want 1, 3, 5, etc spaces.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.