+ 12

Diamond pattern

I have a code of mine which I believe can be simplified. Please help me https://code.sololearn.com/cQZosG9dtP1k/?ref=app

9th Aug 2019, 3:19 PM
Ankith R V
Ankith R V - avatar
6 Antworten
+ 9
Thank you .😊😊
10th Aug 2019, 2:32 PM
Ankith R V
Ankith R V - avatar
+ 2
I found a few ways to simplify and make the code more understandable to people. Here are a few improvements explained: - Replaced "\n" with endl. Sending "\n" out to break a line works but endl is generally what c++ uses for the job. endl will also get replaced with \r\n, \r in operating systems that use different line break character combinations. - Output "* " together instead of "*" << " ". "* " is shorter and a little easier to read. - Created printLine function. Your code had 2 sections duplicating the effort of printing a line with appropriate spaces followed by the asterisk pattern. Instead of duplicating the code, the new printLine function can be called twice. - Renamed a couple variables. diamondSize seemed more understandable than n. - Added more comments. A few steps and the function looked like it would be more easily understood by a few comments. - Added more spaces and blank lines. This might be a tiny improvement in readability but it could just be my personal preference too. Here is my tweaked version: // Creates a diamond pattern of * //where n is the maximum number of dots. //Example n=4 //Pattern is // * // * * // * * * //* * * * // * * * // * * // * #include <iostream> using namespace std; // Prints a line of spaces and asteriskCount asterisks // Assumption: asteriskCount < 27. void printLine(int asteriskCount) { int i; for (i=27 - asteriskCount;i>=0;i--) cout << " "; for (i = 0; i < asteriskCount; i++) cout << "* "; cout << endl; } int main() { int i, diamondSize; cout << "Enter the maximum number of dots "; cin >> diamondSize; cout << endl; // Print top triangle. for (i=0; i<=diamondSize; i++) { printLine(i); } // Print bottom triangle. for (i-=2; i>0; i--) { printLine(i); } return 0; }
10th Aug 2019, 12:35 PM
Josh Greig
Josh Greig - avatar
+ 1
#include <iostream> using namespace std; int main() { int space=10,n,i; cin>>n; for ( i=0;i<n;i++) { for (int j=0;j<=space;j++) cout<<" "; for (int k=0;k<i;k++) cout<<"*"; cout<<endl; space--;} for (i=n;i>=0;i--) { for (int j=0;j<=space;j++) cout<<" "; for (int k=0;k<i;k++) cout<<"*"; cout<<endl; space++; } }
10th Aug 2019, 12:27 PM
Wesam Nabeel
Wesam Nabeel - avatar
+ 1
it's super cute!!
12th Aug 2019, 12:36 PM
Maize Wallin
Maize Wallin - avatar
0
#In python, Single line of code using Comprehension n=5 print('\n'.join([('* '*i).center(2*n) for i in range(1,n+1)] + [('* '*i).center(2*n) for i in range(n-1,0,-1)]))
1st Apr 2020, 6:58 AM
Akbar Ali Quazi
Akbar Ali Quazi - avatar
21st Jul 2020, 12:53 AM
shubham kumar
shubham kumar - avatar