Close
Close

[NEWBIE] C++ Diamond ( * ) problem using loops

   Zwischenzug

Hello, I have solved a problem about Diamond asterisks using loops. However, my code is too long and is there any solution that can provide a better and much shorter code?
My code looks like this. Thank you :)

 

#include <iostream>
int main()
{
	using namespace std;
	int x, y, n, m;
	for (x = 1; x <= 5; x++)
	{
		n = x % 2; //determines if even or odd
		switch (x)
		{
			case 1:
				for (y = 1; y <= 5; y++)
				{
					m = y % 2; //determines if even or odd
					if ((m == 1) && (y != 3))
					{
						cout<<" ";
					}
					else if (m == 0)
					{
						cout<<" ";
					}
					else if ((m == 1) && (y = 3))
					{
						cout<<"*";
					}
				}
				cout<<"\n";
				break;
			
			case 2:
				for (y = 1; y <= 5; y++)
				{
					m = y % 2; //determines if even or odd
					if ((m == 1) && (y != 3))
					{
						cout<<" ";
					}
					else if (m == 0)
					{
						cout<<"*";
					}
					else if ((m == 1) && (y = 3))
					{
						cout<<"*";
					}
				}
				cout<<"\n";
				break;
			
			case 3:
				for (y = 1; y <= 5; y++)
				{
					cout<<"*";
				}
				cout<<"\n";
				break;
			
			case 4:
				for (y = 1; y <= 5; y++)
				{
					m = y % 2; //determines if even or odd
					if ((m == 1) && (y != 3))
					{
						cout<<" ";
					}
					else if (m == 0)
					{
						cout<<"*";
					}
					else if ((m == 1) && (y = 3))
					{
						cout<<"*";
					}
				}
				cout<<"\n";
				break;
			
			case 5:
			for (y = 1; y <= 5; y++)
				{
					m = y % 2; //determines if even or odd
					if ((m == 1) && (y != 3))
					{
						cout<<" ";
					}
					else if (m == 0)
					{
						cout<<" ";
					}
					else if ((m == 1) && (y = 3))
					{
						cout<<"*";
					}
				}
				cout<<"\n";
				break;
		}
	}
	return 0;
}

 


Answers

Ask Yours
Post Yours
Write your answer