Thread: Nested For Loop

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    63

    Question Nested For Loop

    Using nested for loops I'm suppose to create a pyramid that looks like this:

    Code:
                                1
                            1   2   1
                        1   2   4   2   1
                    1   2   4   8   4   2   1
                1   2   4   8  16   8   4   2   1
            1   2   4   8  16  32  16   8   4   2   1
        1   2   4   8  16  32  64  32  16   8   4   2   1
    1   2   4   8  16  32  64 128  64  32  16   8   4   2   1
    I have everything working except the spacing between the numbers. Notice that between the single digit numbers like 1 and 2 there are three spaces, but between double digit numbers like 32 and 64 there are only two spaces, etc. Any suggestions on how to do this type of spacing, here is my code so far.

    Code:
    /*
    
    My name is Jack Trocinski
    
    */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    int main()
    {
    	int row; // row number
    	int space; // white space
    	int column; // column number
    	int n; // degree of power
    	int i; // used in for loop
    	int a; // result obtained by pow
    	
    	for (row = 0; row <= 7; ++row) {
    		
    		column = (7 - row) * 4;
    		n = 0;
    		
    		for (space = column; space > 0; --space) {
    			printf(" ");			
    			}
    			
    		for (i = 0; i <= row; ++i) {
    			a = pow(2, n);
    			printf("%d", a);
    			++n;
    			}
    			
    			--n;
    			--n;
    			
    		for (i = 0; i < row; ++i) {
    			a = pow(2, n);
    			printf("%d", a);
    			--n;
    			}
    		
    		printf("\n");
    	
    	
    	
    	}
    	
    	system("pause");
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    You can set field width with printf, I would use that.

    printf("%5d", num);

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    63
    Oh, nice! I'll try that and let you know.
    Last edited by yacek; 12-07-2010 at 10:53 PM.

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    63
    Got it to work, but I needed to use "%4d" not 5. Thanks Subsonics!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with Nested Structures and Arrays of Structures
    By Ignoramus in forum C Programming
    Replies: 4
    Last Post: 03-02-2010, 01:24 AM
  2. Nested array vs. tree
    By KONI in forum Tech Board
    Replies: 1
    Last Post: 06-07-2007, 04:43 AM
  3. deriving classes
    By l2u in forum C++ Programming
    Replies: 12
    Last Post: 01-15-2007, 05:01 PM
  4. Problem constructing a class with a nested struc
    By pliang in forum C++ Programming
    Replies: 3
    Last Post: 04-14-2005, 07:43 PM
  5. Nested Classes
    By manofsteel972 in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2004, 11:57 AM