Problems, small program- HELP!

This is a discussion on Problems, small program- HELP! within the C++ Programming forums, part of the General Programming Boards category; HEY, I'm trying to print out a pattern of stars where it starts with 5 stars on the top, then ...

  1. #1
    Registered User ProgrammingDlux's Avatar
    Join Date
    Jan 2002
    Posts
    86

    Problems, small program- HELP!

    HEY, I'm trying to print out a pattern of stars where it starts with 5 stars on the top, then 3 next line, then 1 on the last line..all centered..

    IT would look like this:
    *****
    ..***
    ... *

    the periods you see on the second and third lines
    are only to fill space in the post..not part of the program


    My problem is the last star, I don't know how to get it centered without actually doing it in the cout statement..how can i do it in the loop? Here is my code...

    #include<iomanip.h>
    #include<stdlib.h>
    main()
    { int i, j; char star='*';

    for(i=5;i>=1;i=i-2)
    {
    for(j=1;j<=i;j++)
    cout<<star;
    cout<<endl<<" ";


    }
    system("PAUSE");
    return 0;
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    With your current algorithm the best solution would be to add a line counter that will determine the number of spaces. At the 0th line you print no spaces and for every newline you print, the counter gets incremented by one and you print that many spaces.
    Code:
    cnt = 0, i = 5: *****
    cnt = 1, i = 3:  ***
    cnt = 2, i = 1:   *
    Code:
    #include<iomanip.h> 
    #include<stdlib.h> 
    main() 
    { 
      int i, j, k, cnt=0; char star='*'; 
    
      for(i=5;i>=1;i=i-2) {
        for(k=0;k<cnt;k++)
          cout<<" ";
        for(j=1;j<=i;j++) 
          cout<<star; 
        cout<<endl;
        cnt++;
      }  
      return 0; 
    }
    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User ProgrammingDlux's Avatar
    Join Date
    Jan 2002
    Posts
    86
    GENIUS!...Thanks a lot Prelude..I appreciate the help..and for yesterday also..Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help writing small program
    By guitarhead2000 in forum C++ Programming
    Replies: 2
    Last Post: 10-13-2004, 12:42 PM
  2. Small program that has to calculate miles per gallon
    By Guti14 in forum C++ Programming
    Replies: 6
    Last Post: 01-06-2004, 01:47 PM
  3. How can I run a small ftp script from C program
    By bazeemuddin in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 07-01-2003, 05:04 PM
  4. a small program
    By Absy in forum C++ Programming
    Replies: 13
    Last Post: 11-11-2002, 10:51 PM
  5. A small problem with a small program
    By Wetling in forum C Programming
    Replies: 7
    Last Post: 03-25-2002, 08:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21