Thread: nested For loops

  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
    28,413
    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
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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, 04: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