When I print out a pyramid, the last line of the pyramid or the base prints out an integer which represents how many hashes, instead of a string of hashes.
like such:
Height: 3
#
##
3
when its supposed to be:
Height 3:
#
##
###
I'm supposed to print out a pyramid with a height based on the user's input, but instead of the base being printed out as a string it prints out an integer of how many hashes there should be for the base. I understand that this is because I'm returning n but I don't know how to go about it in a way where it still returns the loop.
I've tried changing the class to void instead of int, but that throws an error as it's conflicting types. I'm thinking I should print out an empty string but it messes with my bounds.
#include <cs50.h>
#include <stdio.h>
int get_height(string prompt);
int main(void)
{
int ask = get_height("Height: ");
printf("%i\n", ask);
}
int get_height(string prompt) {
int n;
do {
n = get_int("%s", prompt);
}
while (n < 1 || n > 8);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
printf("#");
}
printf("\n");
}
return n;
}
The last line of output is the height because that is the last thing printed in your main function:
printf("%i\n", ask);
get_height will actually only print n-1 lines because the first iteration (i=0,j=0) is skipped.
the 3 should be output
The problem is this statement;
for (int j = 0; j < i; j++) {
which stops too early. Suggest:
for (int j = i; j >=0; j--) {
The output after making the above change:
#
##
###
3
Related
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");
}
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");
}
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;
}
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;
}
I am working on this problem from the CS50 class. I am still a beginner. What I need to program is this:
Toward the end of World 1-1 in Nintendo’s Super Mario Brothers, Mario
must ascend right-aligned pyramid of blocks, a la the below.
screenshot of Mario jumping up a right-aligned pyramid
Let’s recreate that pyramid in C, albeit in text, using hashes (#) for
bricks, a la the below. Each hash is a bit taller than it is wide, so
the pyramid itself is also be taller than it is wide.
#
##
###
####
#####
######
#######
########
The program we’ll write will be called mario. And let’s allow the user
to decide just how tall the pyramid should be by first prompting them
for a positive integer between, say, 1 and 8, inclusive.
However I have tried many ways, two of which are these:
code mariov1
After looking at some Stack Overflow attempts, it now looks like this:
#include <cs50.h>
#include <stdio.h>
string hash(int);
int main(void)
{
int n;
do
{
n = get_int("Height: ");
}
while (n < 0 || n > 8);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n-1-i; j++)
{
for(int j = 0; j < i+1; j++)
{
printf(".");
}
printf("#");
}
printf("\n");
}
}
What can I try next?
Suriyu, to add to what Weather Vane said. To pass it through Check50, you'll still need to make small tweaks to the code so that it passes through all CS50 tests.
For the do-while loop, n <=0 instead of n < 0 to ask for an input when n = 0, because the specification demands a minimum of one brick (1 to 8 both inclusive).
You need only the two loops, don't print extra characters not specified in the problem set, ex: printf(".");
All the best with CS50, it's going to be a fun experience!
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int n;
do
{
n = get_int("Height: ");
}
while (n < 1 || n > 8);
// this for loop makes new lines
for (int i = 0; i < n; i++)
{
// here I have two for loops nested inside the above for loop,
// I previously made the mistake of having two inner loops nested.
// this 2nd for loop prints n-1-i spaces
// because if n=5, then in the 4th row, there will be 5-1-3 spaces/dots
for (int j = 0; j < n - 1 - i; j++)
{
printf(" ");
}
// this 3rd for loop prints i+1 hashes
// because if n=5, then in the 4th row, there will be 3+1 hashes.
// (3 because you count from 0)
for (int j = 0; j < i + 1; j++)
{
printf("#");
}
printf("\n");
}
}
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int n;
do
{
n = get_int("Height of the pyramid is:\n");
}
while (n < 1 || n > 8); //condition to get a number from 1-8 from the user
for (int i = 0; i < n; i++) //loop for height
{
for (int j = 0; j < n - 1 - i; j++) //loop for spaces on left pyramid
{
printf(" ");
}
for (int k = 0; k < i + 1; k++) // loop for hashes on left pyramid
{
printf("#");
}
printf(" "); // spacing between pyramids
for (int p = 0; p <= i; p++) //loop for right pyramid
{
printf("#");
}
printf("\n");
}
}
This is the advanced version of the problem if you decide to try it.
Here's a different approach. Instead of iteratively printing blanks, followed by iteratively printing number signs, this version creates a buffer (size defined by a precompiler constant - currently set to 8, change it if you want to allow bigger pyramids), then for each row in the pyramid it first fills the buffer with number signs, then overlays the beginning of the line with the proper number of spaces, and then prints it:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#define MAXSIZE 8
int main(void)
{
int size, spaces;
char buf[MAXSIZE+1];
do
size = get_int("Height: ");
while (size < 0 || size > MAXSIZE);
buf[size] = '\0';
for(spaces = size-1 ; spaces >= 0 ; --spaces)
printf("%s\n", (char *)memset(memset(buf, '#', size), ' ', spaces));
}
EDIT
And here's yet another approach which builds the entire output block in an array in memory and then prints it using a single call to puts:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#define MAXSIZE 8
#define TOTSIZE ((MAXSIZE+1) * MAXSIZE)
int main(void)
{
int size, spaces;
char buf[TOTSIZE+1];
do
size = get_int("Height: ");
while (size < 0 || size > MAXSIZE);
memset(buf, '\n', (size+1)*size);
buf[((size+1)*size)] = '\0';
for(char *p = buf, spaces = size-1 ; *p != '\0' ; p += size+1, --spaces)
memset(memset(p, '#', size), ' ', spaces);
puts(buf);
}
This is an option that likely works best:
from cs50 import get_int
while True:
n=get_int("Enter Height: ")
if n>=1 and n<=8:
break
for i in range(0, n-1):
print(" " * (n - (i+1)) + "#" * (i+1))
I thought long and hard before asking this in here but I've spent too much time now trying to figure this one out without cheating.
The CS50 mario ps1 (less comfortable) asks for a *simple left align (at first) pyramid, but my code is giving me it upside down and I can't figure why.
#include <cs50.h>
#include <stdio.h>
int main (void)
{
int n;
do
{
n = get_int("Pyramid Height: ");
}
while (n < 1 || n > 8);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i ; j++)
printf("#");
for (int j = 0; j < n - i; j++)
{
printf(" ");
}
printf("\n");
}
}
I'm sorry if this type of questioning shows up regularly here but I really do need your help.
Thanks in advance.
edit:
expected result:
........#
.......##
......###
.....####
....#####
...######
..#######
.########
I can change the dots to spaces afterwards, this is just for visualisation;
the restriction for height is 8, so I guess that each line has always eight characters;
I actually added trailing spaces so that the pyramid could be right aligned, I've metioned wrong before;
I'm going to check the How to debug small programs?;
Sorry, I'm new to this, I didn't know there was a difference between here and stack exchange, gonna look into that.
*Sorry for the "meh" english, it is not my native language.
See what is the difference between my and your code (especially how to count):
void draw(int n, int align, int dir)
{
for (int i = 1; i <= n; i++)
{
if(align)
{
for(int s = 0; s < (dir ? (n - i) : i - 1); s++)
{
printf(" ");
}
}
for (int j = 0; j < (dir ? i : (n - i + 1)) ; j++)
{
printf("#");
}
printf("\n");
}
}
int main (void)
{
draw(8,1,0);
printf("\n");
draw(8,1,1);
printf("\n");
draw(8,0,0);
printf("\n");
draw(8,0,1);
}
https://godbolt.org/z/7YT16j
my code is giving me it upside down and I can't figure why
Let's see what the code looks like
// There's a loop executed n times. The body prints a line, so n lines are printed.
// In case you have doubts, the characters are normally printed top to bottom and
// left to right.
for (int i = 0; i < n; i++)
{
// The following loop prints (n - i) characters '#' at the beginning
// of each line. That's NOT what you are supposed to do, kind the opposite.
for (int j = 0; j < n - i ; j++)
printf("#");
// You should first print the spaces, then the '#'s, starting from 1 '#' at
// the first line and increasing the number by one at each line (so you have
// to change the condition in the loop accordingly).
// This loop prints the right amount of spaces, but only after
// all the '#'s and just before the end of the line, so that you just
// can't see them (change the printed char to '.' to visualize those).
for (int j = 0; j < n - i; j++)
{
printf(" ");
}
// Note that you could use putchar('\n'), here and previously, to print
// only one char, instead of using printf() to print string literals.
printf("\n");
}
I want to define two variables called x and y.
Depending on that the program shall fill the array from 0 to x and from 0 to y.
I tried filling it with a for and it's kind of working, but I can't print it out properly.
#include <stdio.h>
#define x 4
#define y 4
void build(){
int i=0, k=0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i;
matrix[i][k] = k;
}
}
printf("\t\n%d\n", matrix[x][y]);
}
I expect an array looking like this in the console.
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3
You see, in order to print an array you will have to loop over the whole data. You can't print an array in that simple a way in C.
What your code is printing is a garbage value, because at index 4,4 your array has no value. Its indexes go from 0,1..3 in both x and y direction.
Hope it helps.
#include <stdio.h>
#define x 4
#define y 4
void main(){
int i=0, k=0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i ;
}
}
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
printf("\t%d", matrix[i][k]);
}
printf("\n");
}
}
In C there is no way to print an array in one go. You have to loop through each element of the array and print it.
for(int i = 0; i < x; ++i){
for(int j = 0; j < y; ++j){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
I have tried to guess at your misunderstandings and commented and edited your code to make an explanation of how it works and what you need to understand.
#include <stdio.h>
#define x 4
#define y 4
void build(){
int i=0, k=0;
int matrix[x][y]; // top allowed indexes are x-1 and y-1
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i; // first write getting ignored/overridden by next
matrix[i][k] = k;
// printing here gets you many values, note the removed \n
printf("\t%d", matrix[i][k]);
}
// printing line break here gets you lines instead of single values
printf("\n");
}
// not inside any loop, so only one %d value gets printed
// printf("\t\n%d\n", matrix[x][y]); // accessing beyond both dimension
// also your attempt to let printf figure out how to print the whole 2D array,
// at least that is what I think you try, does not work in C
}
I have an array with 100 numbers in it, and I am trying to print it out with only 10 ints on each line, and a tab between each number. It is only printing the first 10 integers and then stopping, which makes sense because of my for loop. I am clearly missing part of it to allow for it to continue through the array. I was going to try to add the line
for(int line_num = 0; line_num < 10; line_num+=10)
before the for statement after the while loop
int array_value;
int length_of_array = 100;
while (length_of_array <= 100){
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
I was also thinking of including a line like
if (array_value % 10 == 0)
printf("\n");
I figured it out! Posted the answer below.
This might be what you're looking for:
/* test.c */
#include <stdio.h>
#define ELEMENTS 100
int main (void)
{
int array [ELEMENTS];
for ( int i = 0; i < ELEMENTS; ++i )
array [i] = i;
for ( int i = 0; i < ELEMENTS; ++i ) {
printf ("%i", array[i]);
if ( (i + 1) % 10 != 0 )
printf ("\t");
else
printf ("\n");
}
return 0;
}
edit: Because of the way the tab can extend to the next line at the end of the line you have to be careful with the tab and new line character.
For clarity, rename length_of_array to offset_in_array and then set it to zero at the start. I renamed array_value and corrected your length check. I also added a check to the inner loop in case the array length gets changed and doesn't divide by 10.
Something like:
int i;
#define ARRAY_LENGTH 100
int offset_in_array = 0;
while (offset_in_array < ARRAY_LENGTH){
for(i = 0; i < 10 && offset_in_array < ARRAY_LENGTH; ++i){
printf("%d ", A[offset_in_array]);
++offset_in_array;
}
}
I haven't tried running this but it should be closer.
Just print a newline every tenth number... If it's not a tenth number, then print a tab.
for (size_t i = 0; i < array_length; ++i) {
printf("%d%c", A[i], i % 10 != 9 ? '\t' : '\n');
}
Live code available at onlinedbg.
Just change the value of length_of_array to 0 and print \n after a for loop.
int array_value;
int length_of_array = 0;
while (length_of_array <= 100) {
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
printf("\n");
}
You can use the following solution to print 10 lines of 100 array values in C:
for (int i = 0; i < 100; ++i){
printf("%i\t", A[i]);
if ((i+1)%10 == 0){
printf("\n");
}
}