Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <cstdio>
- using namespace std;
- /* Prints a Daimond of characters to the screen.
- Explanation: We want to use printf to generate a diamond,
- and we want to use as few for loops as possible.
- We need two things.
- -First, the * specifier, which specifies the
- desired width of the string. If the string we print
- out is less than the number we specify for *, then it
- gets padded to the left by spaces.
- -Second, the .* specifier. This specifies the number
- of letters that we want to print from our string.
- By combining *.* we get to use both of these together,
- which lets us customize the shape. The full print statement is
- printf("%*.*s\n", stringWidth, numChars, chars.c_str());
- -stringWidth is the desired width, and we get it with the formula:
- stringWidth = halfHeight + i + 1;
- when i >= 0 and i < halfHeight. This is because we need at least
- halfHeight + 1 to be our width, and each time i increases, we want
- the string to get bigger by 1, since we are adding 2 characters to
- the end but moving the string to the left by 1. 2 - 1 = 1.
- numChars is the number of letters we want the string to print.
- At the top, it should be 1. Then as we go down the diamond towards
- the middle, it should increase by 2 each time. So 1, 3, 5, 7 ect.
- so we can use the formula:
- numChars = i * 2 + 1;
- when i >= 0 and i < halfHeight;
- when we want to print the bottom half of the diamond, we just do
- the exact same formulas, but with a for loop that goes backward
- starting at halfHeight and ending at 0.
- Made by: Ben Arnold
- */
- int main() {
- //this is the letter we want to use
- char inputChar;
- //this is the height of the daimond
- int height;
- cout << "*** Daimond Generator! ***\n\n";
- cout << "Enter the height of the Daimond: ";
- cin >> height;
- cout << endl;
- cout << "Enter the character you want to use to draw it: ";
- cin >> inputChar;
- cout << endl;
- int halfHeight = height / 2;
- int maxWidth = height + 1;
- //the chars string will hold maximum number of chars in
- //a single row so we can easily print it to the screen
- //This specific constructor makes a string of size HEIGHT
- //that has all inputChar's for characters!
- string chars(height * 2 + 1, inputChar);
- //the width of the string to put on the screen
- int stringWidth;
- //number of chars to put on the screen
- int numChars;
- //top half
- for (int i = 0; i < halfHeight; i++) {
- stringWidth = halfHeight + i + 1;
- numChars = i * 2 + 1;
- printf("%*.*s\n", stringWidth, numChars, chars.c_str());
- }
- //bottom half (backwards for loop)
- for (int i = halfHeight; i >= 0; i--) {
- stringWidth = halfHeight + i + 1;
- numChars = i * 2 + 1;
- printf("%*.*s\n", stringWidth, numChars, chars.c_str());
- }
- system("PAUSE");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment