Results 1 to 3 of 3

Thread: C++ loop question

  1. #1

    C++ loop question

    I just started learning C++ through a class in college and we are on loops right now. We started with this simple program.

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	int row, column;
    	int maxRow = 5;
    	int maxCol = 4;
    	
    	for(row = 0;row < maxRow; row++)
    	{
    		for(column = 0; column<maxCol; column++)
    		{
    		cout << "*";
    		}
    	cout << endl;
    	}
    	return 0;
    }
    It simply produces the shape:
    ****
    ****
    ****
    ****
    ****
    My question is how can I manipulate this program to produce the following shape:
    Code:
    ********
    **    **
    **    **
    **    **
    **    **
    ********
    Any suggestions would be MUCH appreciated, thanks again.
    -aura2

  2. #2
    Senior Member
    Join Date
    Mar 2004
    Posts
    557
    Hi

    Two suggestions:

    1. You could either split your loop into 3 parts:
    "top", a loop to create your "** **" structure, "bottom"

    2. A slower method would be to replace
    Code:
    cout << "*";
    with a few if-statements, like
    Code:
    		if ( (row%(maxRow-1)!=0) &&
    			 ( column > 1) && (column<maxCol-2)  ) cout << " ";
    			else cout << "*";
    I am sure you could have worked this out by your own ?

    Cheers
    If the only tool you have is a hammer, you tend to see every problem as a nail.
    (Abraham Maslow, Psychologist, 1908-70)

  3. #3
    Senior Member
    Join Date
    Feb 2005
    Posts
    188
    Both the methods are good but the second one is judged on the basis of the output required. Though at the begineer level you need to focus on the output only but still if you divide the problem into parts then it would be easy to modify the same if more no. of star space rows are needed. if the no. of rows required changes all u have to do is to change digits in for loop.

    So try to make generic programs to solve problems of a particular category and dont go for the solution to a particular problem. This will help you in future when you create programs for generating complex patterns. If for each such pattern you try to find a mathematical expressioned if startements than it will be creating problems for urself. So try to break a problem into parts and reach the conclusion.
    \"The Smilie Wars\" ... just arrived after the great crusades

    .... computers come to the rescue .... ah technology at last has some use.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •