1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ printing and positioning with loops

  1. Jan 22, 2005 #1

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I am working on a little piece of a program that prints two diagonal lines. I am using a variable "num" to specify how far down to draw each diagonal.
    What I would like to do is be able to start at a position on the screen
    and have the printing begin at that position, and also track the position
    so that after the first diagonal line prints, the next one will start directly
    under it.

    Example:

    if the starting position is 10, I should get this:
    Code (Text):


              *
               *
                *
                *
               *
              *
     
    I know it's a simple problem, and I need a variable to store position, but I am not sure I know how to handle it after that.

    right now, I can only do this

    Code (Text):

    *
     *
      *
      *
     *
    *
     
    Here's what I have:
    Code (Text):

    # include <iostream>
    using namespace std;

    main()
    {
    int num = 3;

    for(int r = 0; r< num;++r)
    {
        for (int c = 0; c< r; ++c)
        {
             cout<<" ";            
        }
        cout<<"*"<<endl;
    }


    for(int m = 1; m <= num;++m)
    {
        for (int c =num; c>m; --c)
        {
             cout<<" ";        
        }
        cout<<"*"<<endl;   
    }

    return 0;
    }

     
    Thank you!!

    -MIH :smile:
     
  2. jcsd
  3. Jan 22, 2005 #2

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    one more question: it was my understanding that once I declared and used a variable in a "for" loop, it would not persist after the loop terminated. I used an int variable "r" in my 1st "for" loop, but I got errors (about reinitialization) when I tried to use it in the next "for" loop that handles the second diagonal - that's why I used "m" there.
    I'm not sure why I had problems with this. In both my inner loops I was able to use "c".
     
  4. Jan 22, 2005 #3

    Dr Transport

    User Avatar
    Science Advisor
    Gold Member

    try putting a

    cout.width(10);

    It will allow you to have formatted output......
     
  5. Jan 22, 2005 #4

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks, Doc!
    OK, this worked well - I used cout.width(position) using an int called position so I could change it. Only thing is, we haven't been taught any dot syntax stuff (this is only week 2 of the class) yet, so I might need to figure out another way of writing it.
     
  6. Jan 22, 2005 #5

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    So, for the first line, you want to print out 10 spaces before the asterisk, right? ...
     
  7. Jan 22, 2005 #6

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Hi, Hurkyl, that is correct. At least for this little test program I was working on. I was just trying to get an idea of how to handle the position.

    Actually, the whole thing I am going to try to build is this:
    http://www.math.ucla.edu/~rclark/10a.1.05w/hw2/hw2.html

    He has posted a sample and I have to try to "reverse engineer" it using his hints.
     
  8. Jan 22, 2005 #7

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Sounds like a fun problem.


    Back to your toy example:

    Maybe it might help to break the problem up into two parts: for each line you first determine what the X-position of the '*' is, and then you print a line containing the right number of spaces, then the '*'.



    As for the oddities on loops, it various popular compilers handle declaring a variable inside the for statement differently.

    IIRC, MSVC++ treats it as if the variable was declared just before the loop (so that beyond the loop, the variable is still in scope and cannot be declared again). gcc, however, treats the declaration as if it occured inside the block of the loop, so the variable has left scope when you move onto the next loop.

    For maximum portability (and so I don't have to remember what the standard is), I usually avoid ever declaring variables inside the for statement itself. Thus:

    Code (Text):

    int c;
    for(c = 0; c < 10; ++c) {
      do stuff
    }

    for(c = 10; c >= 0; --c) {
      do stuff
    }
     
    In fact, I usually declare my index variables at the top of my function. e.g.

    Code (Text):

    int i, j;

    for(i = 0; i < 10; ++i) {
      for(j = 0; j < 10; ++j) {
        do stuff
      }
    }

    for(i = 3; i < 7; ++i) {
      for(j = 6; j >=3; --j) {
        do stuff
      }
    }

     
     
  9. Jan 22, 2005 #8

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks, Hurkyl - though I am a little confused about your idea of "fun"! :wink: :biggrin:
    I appreciate the feedback and I am going to go do some more work on this with your comments in mind.
     
  10. Jan 23, 2005 #9

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Anyone got time for a little more help? I am making good progress, but ran into some snags.
     
  11. Jan 23, 2005 #10

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Here's what I have so far. The problem I am dealing with now is that if the user doesn't enter a number before any of the commands, the default should be 1 time to execute the loop. The commands are d for down, r for right downward diagonal and l for left downward diagonal.

    For instance entering d3rd should print one asterisk down, three diagonally down and right, then one down.
    Code (Text):


                                            *
                                             *
                                              *
                                               *
                                               *

     
    I tried to set num to 1, if num was 0, but that only worked properly for the first command and not the subsequent ones. Somewhere I need to reset num back to 0, I think, but I am not sure where. :confused:

    Code (Text):

                                //[COLOR=Red] [B]this didn't work[/B][/COLOR]
                //[COLOR=Red] if (num == 0);[/COLOR]
                //[COLOR=Red] num = 1;[/COLOR]
                 
     
     
    Last edited: Jan 23, 2005
  12. Jan 23, 2005 #11

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Becuase that statement says:
    (1) If num is zero, do nothing.
    (2) Set num to 1.

    You need to remove the first semicolon, so that "num = 1" is in the "then" block of the if statement.
     
  13. Jan 23, 2005 #12

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    *smacks head hard*

    DOH!

    thanks, Hurkyl!
     
  14. Jan 24, 2005 #13

    plover

    User Avatar
    Homework Helper

    Fun Problem

    Some general comments:
    • Style nit: While most stylistic details I might point out would just reflect my own practice and prejudices, there is one I feel worth mentioning:
      Code (Text):
      cout<<"*"<<endl;

      cout << "*" << endl;
       
      Spaces in C++ output statements do really help readability.
      &nbsp;
    • Efficiency nit: While efficiency is hardly an issue for this program, it's probably worthwhile to note that it's better to output single characters as characters rather than strings, i.e. :
      Code (Text):
      cout << '*' << endl;
       
    • Gratuitous questioning of instructor: The sequence "HLHDHR" produces a slanted line when fed into the teacher's program, which seems strange to me. (In other words, L and R move the conceptual "cursor" before printing a given line rather than after.) This does seem to accord with some details in the "Hints", so it seems likely the instructor intended this behavior. However, it means that if, say, you want a slanted line (of length n) that actually starts at H, you would need to input: "HDxL" where x = n-1. I just have to wonder why it was done this way. :confused:
      &nbsp;
    • Regarding variable scope: The C++ standard states that for-loops should work like you say (i.e. a variable declared as an initializer of the for-loop should go out of scope at the end of the statement block). As for the inner loops, any variable declared inside a block (i.e. inside {}s) goes out of scope at the end of the block. This is true even if the block is not part of another statement. For example, you could take the code from your original post and add
      Code (Text):
      {
          int num = 20;
          cout << num << endl;
      }
       
      right after your original declaration of num and it would print out a line reading '20', but the value of num would not be affected for your original loops.

      MSVC++ version 6 came out before the C++ standard was finalized and does not follow the standard in several respects (including the scoping of for-loop initializers); I don't know what more recent versions do.
     
    Last edited: Jan 24, 2005
  15. Jan 24, 2005 #14

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks for the tips, plover. I have the program built now. I just have a couple of small bugs to sort out and I am going to try to conquer them with the TA tomorrow.
    As far as MSVC++, I am working on version 6 at home but I am using MSVC++ .NET at work, but I still run into that issue with "variable reinitialization" complaints (when using reusing a variable name for a "for" loop in another "for" loop) when I build the program even when I am using visual studio .NET. Not a big deal, but I just remember my teacher saying the .NET version WAS standardized. I am going to try it again at the computer lab tomorrow since they have the "latest and greatest" software. They may have a newer version than what I've got.
     
    Last edited: Jan 24, 2005
  16. Jan 25, 2005 #15

    plover

    User Avatar
    Homework Helper

    In order that recent compilers can compile old code that may have been written to an obsolete set of expectations, this kind of behavior can often be affected by various kinds of command switches sent to the compiler (such a switch exists in gcc). In Visual Studio, I would guess this entails setting something in the project options, but I have never used .NET. My guess would also be that if .NET loads a project file from an earlier edition of Visual Studio that it would send the compiler the appropriate commands to act like the earlier compiler version; so if you are transferring the project file when going from home to work, this might produce the behavior you mention. My suggestion in this case would be to explicitly create a .NET version project, and run some snippet of test code.
     
  17. Jan 25, 2005 #16

    Personally, whenever i'm writing code in any languauge, i think most people will disagree with me, but i find making variable declarations global is better. This is simply because it keeps me from making mistakes on where variable a can be used. Your professor may frown on this, but doing that has been the make or break for me more thna a few times.

    I once wrote a program that solved the motion of a simple pendulum--not a simple task. There were eight or ten internal variables in functions, and five or six out put variables from those functions. After a few days of trying to get it to work, and still getting compiler errors about undeclared variable usage (to this day i'm still convinced i had declared them correctly and Dev C++ jsut didn't like me ) i just moved them all to global variables. I marked them off with comment marks on the lines before and after, placing a note explaining their presence, just for good measure. Sure enough, the program functioned fine after that. So now as a general rule, unless i ahve some specific reason not to, i try to keep variables global.
     
    Last edited: Jan 25, 2005
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: C++ printing and positioning with loops
  1. Printing error or? (Replies: 15)

Loading...