My code is supposed to make a pyramid as such, but just gives me a line, why? I've tried changing the conditions of the for and while loops and haven't found any solution. Any help would be appreciated!!
#
##
###
####
#####
######
#######
########
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n = get_int("Add the height of the pyramid: ");
int j = 0;
for(int i = 0; i < n ; i ) {
while (j <= i) {
printf("#");
j = j 1;
}
printf("\n");
}
CodePudding user response:
Declare j
inside the for
loop so it starts at 0 on each iteration.
for(int i = 0; i < n; i ) {
int j = 0;
while (j <= i) {
printf("#");
j = j 1;
}
printf("\n");
}
The inner loop could also be rewritten as a for
loop.
for(int i = 0; i < n; i ) {
for (int j = i; j >= 0; j--) printf("#");
printf("\n");
}
CodePudding user response:
While the answer from @Unmitigated is correct, this would be a great place to break out some functionality into a function.
void print_n_ln(char *str, int n) {
for (; n > 0; n--) {
printf("%s", str);
}
printf("\n");
}
Then:
int main(void) {
int n = get_int("Add the height of the pyramid: ");
for (int i = 1; i <= n; i )
print_n_ln("#", i);
return 0;
}
CodePudding user response:
While an iterative solution (nested for()
loops) would be simplest, this might be a good time to discover recursion. As long as the pyramid is not so tall as to risk stack overflow, the following works (leaving gathering/validating user input as an exercise.)
#include <stdio.h>
#include <cs50.h>
void print( int n ) {
if( n > 1 )
print( n - 1 );
while( n-- )
putchar( '#' );
putchar( '\n' );
}
int main() {
print( 7 );
return 0;
}
putchar()
is a much simpler function than printf()
and should be used when outputting a simple single character (for speed and efficiency.)
If you think your way through the operation presented, you will come to understand recursion and how it may sometimes be used to solve problems.
Another (albeit 'limited') solution follows:
int main() {
char wrk[] = "################";
int i = sizeof wrk - 1; // 'i' starts as the 'length' of the string
int want = 7;
while( want-- )
puts( wrk --i ); // adding decreasing values of 'i' prints longer strings
return 0;
}
puts()
will output a string to stdout while appending a 'newline'.
NB: Its more general sibling function (fputs()
) works in a similar fashion, but does NOT append the LF for you.
There are often many ways to do things.
EDIT:
Here's another minimalist solution using pointers. This one uses a "compile time" string, so is not easily amenable to influence by a user (but it could be made so, if you're clever.)
#include <stdio.h>
#include <string.h>
int main() {
char want[] = "#######";
char *p = want strlen( want );
while( --p >= want) puts( p );
return 0;
}