New answers tagged

2

Rather than creating strings (as @L.F. has done) I'd consider using the stream's setw manipulator to place the asterisks as needed (at least for all but the last row). So, given a width, we can then define a center. For what I'm going to call row 0, the first asterisk gets printed at the center: cout << std::setw(center) << "*\n";. For rows 1 ...


3

First of all, please avoid using namespace std;. It is considered bad practice and will cause many problems. See Why is using namespace std; considered bad practice? for more information. Now let's try to simplify the logic. The following loop: for (int j = 1; j <= spaces_before; j++) { cout << ' '; } is a very verbose way to write std::...


2

First I will propose only some simple changes to make the code more readable. 1. add #!/bin/bash as first line then it is guaranteed that bash is used 2. use consistent indentation 3. when you do arithmetic evaluation you don't need the $ character to evaluate the variables, 4. use consistent spacing to structure expressions, e.g. (( j=max; j>=i; j-- )) 5....


3

My Bash complains about sum=`expr $sum + 1`, and it ain't pretty: *expr: syntax error What to make of that? Good ol' Bash won't treat you nicely if you don't treat it nicely! If I use set -u, things become clearer: *script.sh: line 13: sum: unbound variable Aha! Don't forget to initialize variables, sum=0 in this case. Speaking of sum=`...`, use sum=...


4

Shell programs should start with a shebang, so that when executed, the OS can select the correct interpreter: #!/bin/bash With Bash, we can read prompted input using read -p: read -p "Enter the mininum number of stars: " min We should check that we have a valid positive integer before using $min. The same comments also apply to $max. For both variables,...


Top 50 recent answers are included