Here is a copy of my code:
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height = get_int("Please enter a height between 1 and 8 (inclusive)\nHeight: ");
if(0 < height && height < 9)
for(int i = 0; i <= height; i++)
{
for(int s = (height - 1); s >= 1; s--)
{
printf("a");
}
for(int h = 1; h <= i; h++)
{
printf("#");
}
printf("\n");
}
else
printf("Please try again.\n"),
main();
}
The part I cannot seem to get right is printing the correct number of spaces as it does not seem to reduce the variable "s" after each loop. (I have replaced the spaces with the letter "a" so I can see where the code has gone wrong.)
The aim of the code is to print a pyramid of #'s that is right-aligned.
Where have I gone wrong here?
So for example, if the user inputs a height of 3, the output will be:
aa
aa#
aa##
aa###
however, I would like the output to be:
aa#
a##
###
The main issue is the 2nd for loop in your code when you print "a". Everytime you hit in this particular loop, you basically print (height - 1) times "a". In fact, you should print every time one less "a" (and one more hashes). To achieve this, we need to tweak condition of s.
Instead of this
int s = height - 1; s >= 1
Use this
int s = height - i; s > 1
Since your main loop has iterator i, we can use it here.
Second issue is that according to CS50 problem set description, you should actually print " " (spaces), not "a". For this, you should replace "a" with " ".
Third issue is your code prints an extra line with full of space in the begining. You need to tweak the main for loop with this condition to remove one extra line.
i < height
And in the for loop where you print # symbol, you need to start iterator h from zero, so that it prints right away with the first line.
int h = 0
The better solution is to use the built-in functionality of printf that is already in place, reducing the problem to a single, simple loop.
#include <stdio.h>
int main(void) {
int height = get_int("Please enter a height between 1 and 8 (inclusive)\nHeight: ");
unsigned char blocks[height];
memset(blocks, '#', height);
for(int i=0; i<height; ++i)
{
printf("%*.*s\n", height, i+1, blocks);
}
return 0;
}
Output
Success #stdin #stdout 0s 4212KB
#
##
###
####
#####
Related
Apologies in advance, I am very new to c and programming.
I'm currently working on understanding how recursive functions work and have a major mental block.
I was provided an example of a recursive function that creates a "pyramid" of sorts out of hash symbols (see below). I can't understand why the output is not flipped horizontally, with n hashes on top and 1 hash on bottom.
In trying to make sense of it, I created a table with the number of loops, n value, n - 1 value, and how man hashes I think it should print.
On loop 1, n starts out as 4 and the "for loop" should run 4 times since "i" goes through during 0, 1, 2, and 3.
Line break
On loop 2, n is now 3 and the "for loop" should run 3 times since "i" goes through during 0, 1, and 2.
And so on and so forth...
I created nested for loops that I thought would provide the same result: n (height) is 4 originally and works down to 0, i works upwards from 0 printing hashes but the result is the exact opposite.
#include <cs50.h>
#include <stdio.h>
void draw(int n);
int main(void)
{
// prompt user for height of pyramid
int height = get_int("Height ");
// call recursive 'draw' function
draw(height);
printf("\n");
// my nested loop function I made that I can't tell how is different from the recursive function
for (int n = height; n >= 0; n--)
{
for (int i = 0; i < n; i++)
{
printf("#");
}
printf("\n");
}
}
// recursive function example I was given that I cannot make sense of
void draw(int n)
{
if (n <= 0)
{
return;
}
draw(n - 1);
for (int i = 0; i < n; i++)
{
printf("#");
}
printf("\n");
}
Result below. Their result on top. Mine below it.
If someone could please help clarify what I'm missing I would greatly appreciate it.
Look to see when this recursion will emit its first out put
void draw(int n)
{
if (n <= 0)
{
return;
}
draw(n - 1);
for (int i = 0; i < n; i++)
{
printf("#");
}
printf("\n");
}
see that it keeps calling itself before the printf, it only stops doing that one n reaches 0, then it starts returning and calling the prints, but in reverse order of n.
ie it goes
draw(4)->draw(3)->draw(2)->draw(1)->draw(0)
printf loop *1
printf loop * 2
printf loop * 3
printf loop * 4
You have called the draw(n-1); before the for loop. Therefore the function recursively called like this.
First Draw(4); function calls from main function. Then calls Draw(4-1); -> Draw(3); Then again Draw(3-1); -> Draw(2); it doesn’t go to the line which has for loop until base condition. So, next again calls Draw(2-1); -> Draw(1);
After that Draw(1-1); -> Draw(0); since n=0 function will return.
Next go backwards now. Because you haven’t completed the Draw(n) function. You only did recursively calling it self. After finishing that you have printing part. Since you are now in Draw(1), you starts printing from 1. You came to Draw(1) from Draw(4). So now you have to go again back to Draw(4) from Draw(1). That’s why we go backwards.
Path explanation:
Now you are in Draw(1); so it prints #. Then finishes Draw(1); next Draw(2); so it prints ##. next Draw(3); so it prints ###.
next Draw(4); so it prints #### .
That’s how the recursion function works. Therefore the output is,
#
##
###
####
In your nested loop it starts from 4. Because you have used n=height. So your code should start from n=1 like below code.
for (int n = 1; n <= height ; n++)
{
for (int i = 0; i < n; i++)
{
printf("#");
}
printf("\n");
}
This question already has answers here:
How do I check out a remote Git branch?
(42 answers)
Closed 1 year ago.
I just started with C programming and have some difficulty implementing a program which is giving a staircase with 'Height' amount of steps.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
height = get_int("Height: ");
}
while(height > 8 || height == 0 || height < 0);
int width = 0;
int length = height;
while(width < height)
{
printf(" ");
printf("#");
for(width = 0; width < height; width++)
{
printf("\n");
}
}
}
The first lines with the Height are working, but I have difficulties with actually writing a staircase. I wanted something like this or similar to this.
Height: 3
#
#
#
I just want to learn how to implement something like this if I face a problem like this in the future. If somebody could help me further I would really appreciate it!
This works:
#include <stdio.h>
int main() {
// gets height input - replace with your get_int method
int height;
printf("Height: ");
scanf("%i",&height);
// loop over all the steps: 0 - height
for (int i = 0; i < height; i++) {
// add a space i number of times (where i is our current step number and so equal to width)
// notice that if we take top left as (0,0), we go 1 down and 1 right each time = current step
for (int j = 0; j < i; j++) {
printf(" ");
}
// finally, after the spaces add the character and newline
printf("#\n");
}
return 0;
}
I see three issues here:
You're printing newlines (\n) instead of spaces ( ).
Why print the single space character?
You're printing the "#" before (what should be) the spaces.
Print a newline after the spaces and the #.
Also... the staircase's width is always equal to its height; it's just the line you're printing that's advancing... that's a bit confusing.
#include <stdio.h>
int main(void)
{
int height = 5;
for(int i=0; i<height; printf("%*s\n", ++i, "#"));
}
Output:
Success #stdin #stdout 0s 5572KB
#
#
#
#
#
This question already has an answer here:
Trouble implementing isalpha
(1 answer)
Closed 2 years ago.
Addmitedly and obviously I am new to this coding thing. I'm enjoying working it out but I feel stuck on this problem. Any guidance would be appreciated!
I am attempting to count all of the letters of a particular text from the user, but my counter (i) comes out as 1 when I run the program regardless of input. Below is my code.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
string a = get_string("Text: \n"); // Get input
for (int i = 0, n = strlen(a); i < 1; i++) //Set counter for number of letters
{
if isalpha(a[i]). // Count only if character is a letter
{i++;}
printf("%i\n", i); // print counter
}
}
Again, any guidance (in as simple of terms as possible!) is appreciated as I've been trying to figure this out for two days.
So i've edited your code a bit to where it would make sense and I'll try to explain why I changed some stuff. I'm a bit rusty with c/c++ so I'd appreciate if anyone can point out what I'm wrong with.
so here's a snippet of code that would count the number of letters.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char a[] = "test";
int n = strlen(a);
int i = 0;
for (i = 0; i < n; i++) //Set counter for number of letters
{
}
printf("%i\n", i); // print counter
}
So with your code a couple things.
(1) for (int i = 0, n = strlen(a); i < 1; i++)
A for loop looks like this
for(where you start your loop at ; where you stop; count up or down)
so with your code I did this:
for (i = 0; i < n; i++) //Set counter for number of letters
where we start i with 0, we go till i hits n and we count up
now you can do this if it makes more sense:
for (i = 0; i < n; i++) //Set counter for number of letters
{
i++;
}
but they'll both do the same thing (I think) since we are iterating i, but I do think this is better due to readability.
(2) printf("%i\n", i); // print counter
As you probably know this prints out the number of letters and you had this in your for loop and that's fine when you're doing something like a countdown. So if we put it in the for loop it would look like this:
for (i = 0; i < n; i++) //Set counter for number of letters
{
printf("%i\n", i); // print counter
}
where it would print out 0 1 2 3 (Remember arrays always start at 0), so by keeping it outside of the for loop, you just have a counter for how many times 'i' was iterated in the for loop, so you get 4.
in your for loop, the i < 1 part means you will loop while i is smaller than 1, it is initialised to 0 on the first loop, so it runs (and counts to 1), and then at the end of the loop, i increments to 1, and therefore the loop will not run again. You need to put i < n instead of i < 1. and you also need to change the counter to j (or another variable), as mentioned in the comments.
I'm currently going through CS50 through edx and doing problem set 1, Mario.
The objective is to create a print out using pound signs. With the help of some videos I got the code for the first one but I don't understand fundamentally how the math works/ what the computer is understanding.
So I figure if I don't learn I'm crippling myself later.
if n= 5
Then i has 1 added to it until it is not less than 5 which means 5 times yes?
Take a look at this line for the space loop >
for (int j = 0; j < n -1 - i; j++)
If n is 5, then it ends up being j(0) < 3...
So why on the first line are there four spaces and not three spaces?
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int n;
do
{
n = get_int("Pyramid Height: ");
}
while (n < 0 || n >= 24);
//print out this many rows
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n -1 - i; j++)
{
printf(" ");
}
// print out this many columns
for (int j = 0; j < i + 2; j++)
{
printf("#");
}
printf("\n");
}
}
I get the correct pyramid yet i don't understand the logic behind the spacing and prints
if n=5 then n-1-j would be equal 5-1-0 i.e. 4 for the first time executing the loop that is the reason why you are seeing four spaces. The first loop condition should be n-2-j if you want the number of spaces to be three because total no of columns is 5 and the pounds expected in the first row are 2, therefore you should be subtracting 2 from n.
That looks way too complicated.
Here's a simple version I whipped up:
#include <stdio.h>
int main(void) {
int height = 5;
char blocks[height];
memset(blocks,'#',height);
for(int i=0; i<height; ++i)
{
printf("%*.*s\n", height, i+1, blocks );
}
return 0;
}
Output:
Success #stdin #stdout 0s 9424KB
#
##
###
####
#####
Let us try to figure out the pattern here. Like for the left pyramid if the height of the pyramid is 8, check the pattern of spaces and hashes from top to bottom. In this case we need 8 lines, every line has same characters and no of spaces decreases and no of hashes increases from top to bottom.
Now we have the pattern for the left half, the right half is the same, mirror image. So now we can write down the loop as we know the no of spaces and hashes from top to bottom. In programming we need to understand the underlying principle. Plug in the code afterwards becomes easy.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int h;
do
{
h = get_int("Pyramid height: ");
}
while (h<1 || h>8);
int n = 8, i, j;
for (i=0; i<h;++i)
{
// left half
for (j=0;j<h-1-i;++j)
printf(" ");
for (j=0;j<i+1;++j)
printf("#");
// two spaces in middle
printf(" ");
// right half, we have omitted the space code as it is not required.
for (j=0;j<i+1;++j)
printf("#");
printf("\n");
}
return 0;
Currently doing the CS-50 course and was wondering if anyone could help me with this. I'm supposed to create a program which will ask a user for a height between 1-23 (and continuously prompt the user until a valid answer is given) --- I was able to code that part.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
printf("please give me a height between 1-23: ");
height = GetInt();
}
while (height < 1 || height > 23);
}
The do while loop seems to do what its intended. Now, the program, given the variable "height" now needs to create a pyramid of that height. The bottom of the pyramid is to be aligned with the bottom left hand of the terminal and its last "row" is to finish with 2 hashes as such:
Sample pyramid of height 4:
##
###
####
#####
But the code needs to be generic for any height of pyramid 1-23.
This is where I'm having a hard time (in actually making a code to draw this).
Ive noticed that for each row, the number of hashes needed (if we call the top row "row 1" and the subsequent "row 2" and so on... is
row number+1. As for the amount of spaces that are needed, can be represented by height-row number.
If someone would be able to explain to me how I could write this program using C, it would be much appreciated! :)
Here is a way you can implement this. Basically, you need to build the pyramid from the bottom up. The task is easy once you see the loop structure, its just tricky to get the math down for printing the correct number of spaces and hash symbols:
#include <stdio.h>
int main(void)
{
int height, i, j;
do
{
printf("please give me a height between 1-23: ");
height = GetInt();
}
while (height < 1 || height > 23);
printf("\n");
for (i = 0; i < height; i++) {
for (j = 0; j < height - i - 1; j++)
printf(" ");
for (j = 0; j < i + 2; j++)
printf("#");
printf("\n");
}
}
For more clarification on whats going on, and why each loop is necessary:
Outer for loop: the variable i corresponds to a row in the pyramid. the value of i will remain constant for each of the second two loops
First inner for loop: for any row, there needs to be height - i - 2 spaces. You can figure this out because the total row width will be height, and any row has i + 2 hash symbols, so there needs to be height - (i + 2) = height - i - 1 spaces. So basically, this loop just prints the required spaces. You can track this with the variable j
Second inner for loop: This loop is similar to the first inner loop, but you need to now print the hash marks. At the beginning of the loop you reset j and count up to the required number of hash marks
Here is a version that may offer some insight:
#include <stdio.h>
#include <cs50.h>
int main(void) {
//initialize variables
int height, n, j, k, i;
printf("Height: \n");
// Get user input
height = GetInt();
n = height;
for(i = 0; i < height; i++) {
// create n spaces based off height
for(k = n; k > i; k--)
printf("%c", ' ');
// create hash tags
for(j = 0; j < i+2; j++)
printf("#");
printf("\n");
}
return 0;
}
Result if user entered a height of 5:
Height:
##
###
####
#####
######
The 1st for loop essentially prints the number of rows matching the height entered
The 2nd for loop involves printing the number of spaces based on the height entered
The 3rd for loop involves printing the number of hashes (with respect to the height value) after the amount of spaces on the same line
Cheers