I want to "multiply" a string by an int
variable that the user inputs.
#include <cs50.h>
#include <stdio.h>
// Height < 24
string block = "#";
string output;
int main(void) {
printf("Height: ");
int height = GetInt();
while (true) {
if (height < 24 && height > 0) {
output = "#" + block * height;
printf("%s\n", output);
break;
} else {
printf("Height: ");
height = GetInt();
}
}
return 0;
}
Using the Height
variable I want to multiply the string variable block (#)
by Height
, and add that to another "#"
.
I tried implementing it in the only way I could think of it making sense however it doesnt seem the syntax is right.
I've looked over StackOverflow on this subject and can only find C# and C++ topics with this question in mind.
EDIT: After being printed the output should look like this:
##
###
####
#####
######
#######
########
#########
And the lines of "#" being outputted depends on the Height variable that the user inputs. Say the user inputs a height of "5":
Height: 5
##
###
####
#####
######
Should be output.
So you need 2 loops to do this. One for iterating through the characters you want to print on a line, one to iterate through the entire height (number of lines).
So what we want to do is:
e.g.
int lineno;
int height = GetInt();
...
for (lineno = 1; lineno <= height; lineno++) {
int column;
for (column = 0; column < lineno; column++) {
putchar('#');
}
putchar('\n');
}
This will be a left adjusted tree. I'll leave it up to you to right adjust it, i.e. print spaces in front of the '#', or start by printing 2 #'s instead of 1.
You don't multiply a string, you simply use a loop and output the character repeatedly.
int j;
for (j = 0; j < (1 + height); ++j) {
printf ("#"); /* Or putchar('#') */
}
printf ("\n");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With