#include <iostream>
#include <cstdlib>
usingnamespace std;
constchar O = ' ';
constchar X = '*';
int main()
{
int M;
int i, j;
int first, last;
cout << "Input size: "; cin >> M;
for ( i = 1; i <= 2 * M - 1; i++ )
{
first = abs( M - i ) + 1;
last = 2 * M - first;
for ( j = 1; j <= last; j++ )
{
if ( j == first || j == last ) cout << X;
else cout << O;
}
cout << endl;
}
}
Characters go across one unit for every descent by one line, so the final aspect ratio of the diamond depends mainly on the height-to-width aspect ratio of characters on your console.
You need to seek for a pattern - largely by "try and see". What follows is how I saw the problem, but when I tried it on some colleagues they saw it a different way. Each to his own; a psychologist would probably have a field day here.
'first' is the position of the left-hand *; 'last' is the position of the right-hand *.
The position of 'first' runs:
1st row: M
2nd row: M-1
Mth row: 1 - for the ith row in the upper part, 'first' is M - i + 1
then
(M+1)th row: 2
(M+2)th row: 3
etc. - for the ith row in the lower part, 'first' is i - M + 1
A composite formula working for both parts is abs(M-i)+1. There are 2M-1 rows in total.
If you can find 'first' then you can find 'last'; since one always increases by 1 when the other decreases by 1 their sum is constant; i.e
last + first = constant ( = M+M from the first row)
Hence
last = 2M-first
You made a good attempt (but please use code tags when you post), so I don't mind giving you code.
If you enter a reply, or go back and edit your posts, you will see to the right of the text entry region a set of formats that can be applied. Select your source code with a mouse and press the <> in this table of possible formats. It will put the selected region within code tags.
Unfortunately, this doesn't seem to work in the initial posting. What you can do, however, is immediately after posting a new problem, go back, edit your post and apply these tags. (You can also put the relevant tags in by typing, but it's quicker with a mouse.)
The two big advantages of code in code tags are:
(a) indenting is preserved, making it much easier for us to see the structure of your code;
(b) a little "gear wheel" appears at the upper right-hand corner; pressing it allows you to try the code in C++ shell, which works as long as there are no file read/writes.
If you enter a reply, or go back and edit your posts, you will see to the right of the text entry region a set of formats that can be applied. Select your source code with a mouse and press the <> in this table of possible formats. It will put the selected region within code tags.