nested For loops

This is a discussion on nested For loops within the C++ Programming forums, part of the General Programming Boards category; Hey everyone, I feel like I've asked this question before, and I searched through all my posts and couldnt find ...

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    153

    nested For loops

    Hey everyone,
    I feel like I've asked this question before, and I searched through all my posts and couldnt find it, so I may just be going crazy, and if not I apologize for the redundancy.

    So, I'm trying to use nested for loops to created a pyramid of X's,
    as in:
    ......X
    ....XXX
    ..XXXXX
    XXXXXXX etc...the dots are there to be abe to format the triangle, I don't need them in the program...

    and I have the following code, but I have absolutely no idea how to insert the X's and I was looking for a push in the right direction NOT THE ACTUAL CODE...thanks a lot! <Helpless Chap

    Code:
    //Chapter 3
    //Exercise 5
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	const char X = 'X';
    	const char SPACE = '.';
    	unsigned int i;
    
    	for (i = 0; i < 21; i++)
    	{
    		for (int spaces = 0; spaces < 21; spaces++)
    		{
    			cout << SPACE;
    			if (spaces == 10)
    			{
    				cout << X;
    				//I want to use a for loop to print X to screen
    			}
    		}
    		cout << endl;
    	}
    	return 0;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,312
    Assume that you're using a monospace font.

    The nth row has (2n-1) Xs, by observation.
    The nth row also has N-n preceding spaces, where N is the number of Xs in the last row.

    Effectively,
    Code:
    Given n rows to be printed
    for i=1 to i=n
    	for j=1 to j=n-i
    		print space
    	for k=1 to k=2i-1
    		print X
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Nested array vs. tree
    By KONI in forum Tech Board
    Replies: 1
    Last Post: 06-07-2007, 05:43 AM
  2. deriving classes
    By l2u in forum C++ Programming
    Replies: 12
    Last Post: 01-15-2007, 05:01 PM
  3. nested switch issue
    By fsu_altek in forum C Programming
    Replies: 3
    Last Post: 02-15-2006, 10:29 PM
  4. Displaying Data from a Nested Structure
    By shazg2000 in forum C++ Programming
    Replies: 1
    Last Post: 01-09-2005, 10:16 AM
  5. Nested Classes
    By manofsteel972 in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2004, 11:57 AM

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