You have to transport a maximum of 15 different loads from one port to another. Carrying capacity of a cargo ship, which will transport those loads, is 50 tons. Loads are enumerated and the information about the weight of every load is given as input.
Suppose that the weight of every load is smaller than or equal to 50 tons and greater than 0.
You will read the weight of every load from the input in a single line. Your input will end with a -1. You will print the number of trips necessary.
Sample Input:
50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 -1
Output:
15
But I get this error and whenever I give input to program
./vpl_execution: line 5: 15093 Bus error (core dumped) ./main
By the way I seached about this situation, I think I am not out of array index or wrong using wrong pointers. Also, I saw same question in here with some solution but I want to know why code is not working and then solve the question on my own. Thank you so much for your help, all.
#include <stdio.h>
int main()
{ int w,i,t,sum,index;
int list[16];
w = 1;
do
{
scanf("%d",&w);
list[index] = w;
index++;
}while(w >= 0);
t = 0;
for(i = 0;i < ((sizeof(list)/sizeof(list[0]))+1);i++)
{
sum =0;
if(sum <= 50)
{sum += list[i];}
else
{t++;}
}
printf("%d",t);
return 0;
}
I get a segmentation error on my do while loop
The first segmentation fault happens at this line:
list[index] = w;
What do you think is the value of index?
You did not initialize it with a value, which probably should have been 0.
Therefore, accessing list[index] is undefined behaviour. In your case, it caused a segmentation fault.
Then inside for(i = 0;i < ((sizeof(list)/sizeof(list[0]))+1);i++)
Accessing list[i] here can cause another segfault at the final value of i. You should remove the +1 from ((sizeof(list)/sizeof(list[0]))+1).
Solution:
Do index = 0; once (initialization) before doing list[index] = w;
Remove the +1 from ((sizeof(list)/sizeof(list[0]))+1)
But it would be better to change
for(i = 0;i < ((sizeof(list)/sizeof(list[0])));i++) to
for (i = 0; i < 15; ++i)
Because you already know the size of your list and list[15] is guaranteed to be -1 if there are 15 weights. So, you just need to traverse upto list[14].
This just removes the segfault, but there are still other problems in your code.
I want to know why code is not working and then solve the question on
my own.
The logic inside your for-loop is wrong.
sum =0;
if(sum <= 50)
This condition is always true, and your else block which increments the value of t is never executed. Therefore, the output is always the initial value which you assign to t.
first you have used an uninitialized variable index use index=0.
also as question said a maximum of 15 different , but you are using ((sizeof(list)/sizeof(list[0]))+1) which aside from +1 at the end of it ,which will cause passing boundaries of your array which will lead to undefined behavior, is wrong , because you will traverse array completely while it's possible that you have less elements in array. you should add a counter while you are scanning data and your second loop should be based on that.
also your code is different from question , if input is always 0 < input <= 50 you will never enter else statement(t++) and you will always print 0. you are finding sum of weights and not count of them , and with the input explained in question you will always print t=0.
I am writing a program in C that first prompts the user for an integer , then prints two strings: a blank space and a # on a variable number so that the result would be a right sided pyramid, like this:
#
##
###
####
#####
######
The problem i have resides in my for loop, here's what it looks like :
(n is the integer that the user prompts)
for (int i = 0 ; i < n ; i++)
{
printf("%c",n-1,' '); // printing the blank spaces gradually
printf("%c\n",i+2,'#'); // printing the hashes gradually
}
The idea is to print an decreasing number of spaces and an increasing number of hashes depending on the int.
P.S : Please consider helping me by saying what is wrong with my code, not giving me an actual new working one.
First, the problem with the code. It is based on an incorrect understanding of printf. printf cannot be used in the way desired in the code. Furthermore, even if did, it wont be printing spaces 'gradually' because you have fixed 'n-1'. You probably meant 'n-i' so it can gradually shrink.
Anyways, to fix:
There are a number of solutions, including rewriting with new logic. For your homework though, the code can still be 'fixed' by writing your own printf variant with desired functionality. e.g:
void mprintf(const char *fmt, int n, char c)
{
while (n--)
{
printf("%c", c);
}
}
And your code becomes:
for (int i = 0 ; i < n ; i++)
{
mprintf("%c",n-i,' '); // printing the blank spaces gradually
mprintf("%c",i,'#'); // printing the hashes gradually
printf("\n");
}
Extra credit:
Find out how you can simplify this code by removing certain useless thing.
You know every row has the same number of chars, counting the spaces and #, which is n. In the first row you have only one #, so n - 1 spaces, on the second you have 2 #'s, so n - 2 spaces, and so on. So you iterate from 0 to n - 1, and print a char every iteration, and you just have to keep count of how many chars you've already print. Start printing spaces and as soon as you have printed enough spaces, print a #. Code for it:
for (int i = 0 ; i < n ; i++)
{
int j = 0;
while (j < n)
{
if (j < n - i - 1)
printf(" ");
else
printf("#");
j++;
}
printf("\n");
}
You say:
Please consider helping me by saying what is wrong with my code, not giving me an actual new working one.
Ignoring cosmetic changes, your loop body is currently:
for (int i = 0; i < n; i++)
{
printf("%c", n-1, ' '); // printing the blank spaces gradually
printf("%c\n", i+2, '#'); // printing the hashes gradually
}
Problems include:
Too many arguments to the printf() calls.
%c requires a single argument, which is the character to be printed.
For n = 6, you will be printing Control-E rather than any blanks with the first print.
For the second print, you'll be printing Control-B through Control-G and no hashes.
You could use:
printf("%.*s", n - i - 1, " ");
to print a field of blanks of the appropriate width. You can't repeat a single character with printf(), though, so you'd have to use some other technique, such as a loop using putchar(), to print the appropriate number of hashes.
You should read, and re-read, and re-re-read the specification for printf(). I have to read it a couple of times a year to try and keep current; I usually find something new (or forgotten) on a given re-reading. Of course, I've only been coding in C for 30 years, and the specification has changed a few times over the years (and it hasn't gotten any simpler yet!), so it isn't very surprising.
The task is to find the length of the longest subsequence in a given array of integers such that all elements of the subsequence are sorted in ascending order. For example, the length of the LIS for { 15, 27, 14, 38, 26, 55, 46, 65, 85 } is 6 and the longest increasing subsequence is {15, 27, 38, 55, 65, 85}.
Following is the code I wrote. I am not sure if my logic is fine but the code fails to run properly. If I try to input the following test case
9
15
27
14
The program stops reading the values after 14 and gives me the output 2. It should read 9 values but the code is reading only 3 values. I have checked my code several times but unfortunately, I am unable to spot the error.
#include<stdio.h>
int main()
{
int N,max_val,i,j,k,l=1;
int a[100000], track[100000];
track[0]=0;
max_val=1;
scanf("%d",&N);
for(i=0;i<N;++i)
{
printf("x");
scanf(" %d",&a[i]);
if(i!=0)
{
for(j=0;j<l;++j)
{
if(a[i]>a[track[j]])
{
max_val++;
track[0]=i;
l=1;
break;
}
else
{
track[l]=i;
l++;
}
}
}
}
printf("%d",max_val);
return 0;
}
Help is appreciated. Thanks!
Oh, nicely convoluted. You have undefined behavior here, and the way it expresses itself is instructive. The general problem is that
if(a[i]>a[track[j]]) // <-- when i == 2, this first is false with
{ // your input
max_val++;
track[0]=i;
l=1;
break;
}
else
{
track[l]=i; // <-- and you end up here, where you write
l++; // into track[l] and increase l.
}
After l is increased, you go back to the loop
for(j=0;j<l;++j)
Here j is increased, but since l has also increased, the condition is never (except not really, see below) false, and the loop continues. From this point on, the condition
a[i]>a[track[j]]
is always false, because you keep comparing the same two numbers, so l is incremented every turn, and this just keeps happening.
This goes on until track is full with twos (because i remains 2). In fact, it goes on after track is full, writing into whatever happens to lie behind track in memory. What this is is not defined in the C language standard; for me this happens to be first a, then N, max_val and so forth in order of declaration (found that out with a debugger, a tool I encourage you to look into). YMMV. So, for me, a is also filled, and then N is overwritten with 2, max_val etc. are also overwritten with 2, then l is overwritten with 2, and only then does the loop end. And then you go back to
for(i=0;i<N;++i)
...where now N is 2 and i is just being incremented to 3. Then the loop ends, and then the program ends.
Perhaps needless to say, this is not behavior you can depend upon. The compiler doesn't have to arrange the stack variables in this order, and an optimising compiler can even generate code that doesn't hold certain variables in memory (or at all). But that is what happens.
I have a small problem with a program I am working on.
My program executes a function on an array. The function only can execute the commands on the first 16 elements of the array.
I now want to make a loop so that the function can work on more than 16 elements of the array. Here's my thought, but it ended up in an infinite loop:
int l = 0;
for (int i=0; i<=size; i+16)
{
for (int j=0; j<=16;j++)
{
FUNCTION(INARRAY; OUTARRAY);
}
}
Next problem is that the function will only walk through 16 Elements of the array and ignore the rest.
What is the best way to make it walk through the next 16 elements and save it in the outbuffer as the following elements?
As I adapt the solution it still does only process through the first 16 elements and then doesn't continue with the next 16.
This:
i + 16
does nothing to change the value of i, so that loop never terminates. That expression just computes the value of i + 16, but the result is thrown away.
To change the value of a variable, use assignment (=) operator, like i = i + 16 or i += 16.
I think I have what you are looking for. You would have to implent it and check it out. Be warned though that this worked if your arrays size is a multiple of 16, otherwise there will be remaining elements paired with already processed elements.
int count16 = 0;
var tempAr[16];
for (int i=0; i<numOfArraysToGoThrough; i++)
{
tempAr[count16]=numOfArrayToGoThrough[i];
if ( count16 == 15)
{
FUNCTION (tempAr, OUTARRAY);
count16=0;
}
else
count16+=1;
}
figured this one out some time ago
here's how it worked for me
for (uint64_t i=0; i<size; i+=16)
{aes_encrypt(tfm, &tempbuffer[i], &inbuffer[i]);}
this does the following
calling aes_encrypt will encrypt the first 16 bytes of data in the array,
the for loop then jumps to the 16th entry and performs the encryption again
This is my first time posting in here, hopefully I am doing it right.
Basically I need help trying to figure out some code that I wrote for class using C. The purpose of the program is to ask the user for a number between 0 and 23. Then, based on the number the user inputted, a half pyramid will be printed (like the ones in the old school Mario games). I am a beginner at programming and got the answer to my code by mere luck, but now I can't really tell how my for-loops provide the pyramid figure.
#include <stdio.h>
int main ( void )
{
int user_i;
printf ( "Hello there and welcome to the pyramid creator program\n" );
printf ( "Please enter a non negative INTEGER from 0 to 23\n" );
scanf ( "%d", &user_i );
while ( user_i < 0 || user_i > 23 )
{
scanf ( "%d", &user_i );
}
for ( int tall = 0; tall < user_i; tall++ )
{
// this are the two for loops that happened by pure magic, I am still
// trying to figure out why are they working they way they are
for ( int space = 0; space <= user_i - tall; space++ )
{
printf ( " " );
}
for ( int hash = 0; hash <= tall; hash++ )
{
printf ( "#" );
}
// We need to specify the printf("\n"); statement here
printf ( "\n" );
}
return 0;
}
Being new to programming I followed what little I know about pseudocode, I just can't seem to understand why the for-loop section is working the way it is. I understand the while loop perfectly (although corrections and best practices are welcomed), but the for-loop logic continues to elude me and I would like to fully understand this before moving on. Any help will be greatly appreciated.
I will explain the process of how I would come to understand this code to the point where I would be comfortable using it myself. I will pretend that I did not read you description, so I am starting from scratch. The process is divided into stages which I will number as I go. My goal will be to give some general techniques which will make programs easier to read.
Stage 1: Understand coarse structure
The first step will be to understand in general terms what the program does without getting bogged down in details. Let's start reading the body of the main function.
int main(void) {
int user_i;
printf("Hello there and welcome to the pyramid creator program\n");
printf("Please enter a non negative INTEGER from 0 to 23\n");
scanf("%d", &user_i);
So far, we have declared in integer, and told the user to enter a number, and then used the scanf function to set the integer equal to what the user entered. Unfortunately it is unclear from the prompt or the code what the purpose of the integer is. Let's keep reading.
while (user_i < 0 || user_i > 23) {
scanf("%d", &user_i);
}
Here we possibly ask the user to enter additional integers. Judging by the prompt, it seems like a good guess that the purpose of this statement is to make sure that our integer is in the appropriate range and this is easy to check by examining the code. Let's look at the next line
for (int tall = 0; tall < user_i; tall++) {
This is the outer for loop. Our enigmatic integer user_i appears again, and we have another integer tall which is going between 0 and user_i. Let's look at some more code.
for (int space = 0; space <= user_i - tall; space++) {
printf(" ");
}
This is the first inner for loop. Let's not get bogged down in the details of what is going on with this new integer space or why we have user_i - tall appearing, but let's just note that the body of the foor loop just prints a space. So this for loop just has the effect of printing a bunch of spaces. Let's look at the next inner for loop.
for (int hash = 0; hash <= tall; hash++) {
printf("#");
}
This one looks similar. It just prints a bunch of hashes. Next we have
printf("\n");
This prints a new line. Next is
}
return 0;
}
This means that the outer for loop ends, and after the outer for loop ends, the program ends.
Notice we have found two major pieces to the code. The first piece is where a value to user_i is obtained, and the second piece, the outer for loop, must be where this value is used to draw the pyramid. Next let's try to figure out what user_i means.
Stage 2: Discover the meaning of user_i
Now since a new line is printed for every iteration of the outer loop, and the enigmatic user_i controls how many iterations of the outer loop there are, and therefore how many new lines are printed, it would seem that user_i controls the height of the pyramid that is created. To get the exact relationship, lets assume that user_i had the value 3, then tall would take on the values 0,1, and 2, and so the loop would execute three times and the height of the pyramid would be three. Notice also that if user_i would increase by one, then the loop would execute once more and the pyramid would be higher by one. This means that user_i must be the height of the pyramid. Let's rename the variable to pyramidHeight before we forget. Our main function now looks like this:
int main(void) {
int pyramidHeight;
printf("Hello there and welcome to the pyramid creator program\n");
printf("Please enter a non negative INTEGER from 0 to 23\n");
scanf("%d", &pyramidHeight);
while (pyramidHeight < 0 || pyramidHeight > 23) {
scanf("%d", &pyramidHeight);
}
for (int tall = 0; tall < pyramidHeight; tall++) {
for (int space = 0; space <= pyramidHeight - tall; space++) {
printf(" ");
}
for (int hash = 0; hash <= tall; hash++) {
printf("#");
}
printf("\n");
}
return 0;
}
Stage 3: Make a function that gets the pyramid height
Since we understand the first part of the code, we can move it into a function and not think about it anymore. This will make the code easier to look at. Since this part of the code is responsible for obtaining a valid height, let's call the funcion getValidHeight. After doing this, notice the pyramid height will not change in the main method, so we can declare it as a const int. Our code now looks like this:
#include <stdio.h>
const int getValidHeight() {
int pyramidHeight;
printf("Hello there and welcome to the pyramid creator program\n");
printf("Please enter a non negative INTEGER from 0 to 23\n");
scanf("%d", &pyramidHeight);
while (pyramidHeight < 0 || pyramidHeight > 23) {
scanf("%d", &pyramidHeight);
}
return pyramidHeight;
}
int main(void) {
const int pyramidHeight = getValidHeight();
for (int tall = 0; tall < pyramidHeight; tall++) {
for (int space = 0; space <= pyramidHeight - tall; space++) {
printf(" ");
}
for (int hash = 0; hash <= tall; hash++) {
printf("#");
}
printf("\n");
}
return 0;
}
Stage 4: understand the inner for loops.
We know the inner for loops print a character repeatedly, but how many times? Let's consider the first inner for loop. How many spaces are printed? You might think that by analogy with the outer for loop there are pyramidHeight - tall spaces, but here we have space <= pyramidHeight - tall where the truly analogous situation would be space < pyramidHeight - tall. Since we have <= instead of <, we get an extra iteration where space equals pyramidHeight - tall. Thus we see that in fact pyramidHeight - tall + 1 spaces are printed. Similarly tall + 1 hashes are printed.
Stage 5: Move printing of multiple characters into their own functions.
Since printing a character multiple times is easy to understand, we can move this code into their own functions. Let's see what our code looks like now.
#include <stdio.h>
const int getValidHeight() {
int pyramidHeight;
printf("Hello there and welcome to the pyramid creator program\n");
printf("Please enter a non negative INTEGER from 0 to 23\n");
scanf("%d", &pyramidHeight);
while (pyramidHeight < 0 || pyramidHeight > 23) {
scanf("%d", &pyramidHeight);
}
return pyramidHeight;
}
void printSpaces(const int numSpaces) {
for (int i = 0; i < numSpaces; i++) {
printf(" ");
}
}
void printHashes(const int numHashes) {
for (int i = 0; i < numHashes; i++) {
printf("#");
}
}
int main(void) {
const int pyramidHeight = getValidHeight();
for (int tall = 0; tall < pyramidHeight; tall++) {
printSpaces(pyramidHeight - tall + 1);
printHashes(tall + 1);
printf("\n");
}
return 0;
}
Now when I look at the main function, I don't have to worry about the details of how printSpaces actually prints the spaces. I have already forgotten if it uses a for loop or a while loop. This frees my brain up to think about other things.
Stage 6: Introducing variables and choosing good names for variables
Our main function is now easy to read. We are ready to start thinking about what it actually does. Each iteration of the for loop prints a certain number of spaces followed by a certain number of hashes followed by a new line. Since the spaces are printed first, they will all be on the left, which is what we want to get the picture it gives us.
Since new lines are printed below old lines on the terminal, a value of zero for tall corresponds to the top row of the pyramid.
With these things in mind, let's introduce two new variables, numSpaces and numHashes for the number of spaces and hashes to be printed in an iteration. Since the value of these variables does not change in a single iteration, we can make them constants. Also let's change the name of tall (which is an adjective and hence a bad name for an integer) to distanceFromTop. Our new main method looks like this
int main(void) {
const int pyramidHeight = getValidHeight();
for (int distanceFromTop = 0; distanceFromTop < pyramidHeight; distanceFromTop++) {
const int numSpaces = pyramidHeight - distanceFromTop + 1;
const int numHashes = distanceFromTop + 1;
printSpaces(numSpaces);
printHashes(numHashes);
printf("\n");
}
return 0;
}
Stage 7: Why are numSpaces and numHashes what they are?
Everything is coming together now. The only thing left to figure out is the formulas that give numSpaces and numHashes.
Let's start with numHashes because it is easier to understand. We want numHashes to be one when the distance from the top is zero, and we want numHashes to increase by one whenever the distance from the top does, so the correct formula is numHashes = distanceFromTop + 1.
Now for numSpaces. We know that every time the distance from the top increases, a space turns into a hash, and so there is one less space. Thus the expression for numSpaces should have a -distanceFromTop in it. But how many spaces should the top row have? Since the top row already has a hash, there are pyramidHeight - 1 hashes that need to be made, so there must be at least pyramidHeight - 1 spaces so they can be turned into hashes. In the code we have chosen pyramidHeight + 1 spaces in the top row, which is two more than pyramidHeight - 1, and so has the effect of moving the whole picture right by two spaces.
Conclusion
You were only asking how the two inner loops worked, but I gave a very long answer. This is because I thought the real problem was not that you didn't understand how for loops work sufficiently well, but rather that your code was difficult to read and so it was hard to tell what anything was doing. So I showed you how I would have written the program, hoping that you would think it is easier to read, so you would be able to see what is going on more clearly, and hopefully so you could learn to write clearer code yourself.
How did I change the code? I changed the names of the variables so it was clear what the role of each variable was; I introduced new variables and tried to give them good names as well; and I moved some of the lower level code involving input and output and the logic of printing characters a certain number of times into their own methods. This last change greatly decreased the number of lines in the main function
, got rid of the nesting of for loops in the main function, and made the key logic of the program easy to see.
First off, let's get the body of the loops out of the way. The first one just prints spaces, and the second one prints hash marks.
We want to print a line like this, where _ is a space:
______######
So the magic question is, how many spaces and #s do we need to print?
At each line, we want to print 1 more # than the line before, and 1 fewer spaces than the line before. This is the purpose "tall" serves in the outer loop. You can think of this as "the number of hash marks that should be printed on this line."
All of the remaining characters to print on the line should be spaces. As a result, we can take the total line length (which is the number the user entered), and subtract the number of hash marks on this line, and that's the number of spaces we need. This is the condition in the first for loop:
for ( int space = 0; space <= user_i - tall; space++ )
// ~~~~~~~~~~~~~
// Number of spaces == number_user_entered - current_line
Then we need to print the number of hash marks, which is always equal to the current line:
for ( int hash = 0; hash <= tall; hash++ )
// ~~~~
// Remember, "tall" is the current line
This whole thing is in a for loop that just repeats once per line.
Renaming some of the variables and introducing some new names can make this whole thing much easier to understand:
#include <stdio.h>
int main ( void )
{
int userProvidedNumber;
printf ( "Hello there and welcome to the pyramid creator program\n" );
printf ( "Please enter a non negative INTEGER from 0 to 23\n" );
scanf ( "%d", &userProvidedNumber );
while ( userProvidedNumber < 0 || userProvidedNumber > 23 )
{
scanf ( "%d", &userProvidedNumber );
}
for ( int currentLine = 0; currentLine < userProvidedNumber; currentLine++ )
{
int numberOfSpacesToPrint = userProvidedNumber - currentLine;
int numberOfHashesToPrint = currentLine;
for ( int space = 0; space <= numberOfSpacesToPrint; space++ )
{
printf ( " " );
}
for ( int hash = 0; hash <= numberOfHashesToPrint; hash++ )
{
printf ( "#" );
}
// We need to specify the printf("\n"); statement here
printf ( "\n" );
}
return 0;
}
A few things:
Consider "bench checking" this. That is, trace through the loops yourself and draw out the spaces and hash marks. Consider using graph paper for this. I've been doing this for 15 years and I still trace things out on paper from time to time when they're hairy.
The magic in this is the value "user_i - tall" and "hash <= tall". Those are the conditions on the two inner for loops as the middle values in the parenthesis. Note what they are doing:
Because tall is "going up" from the outer-most loop, by subtracting it from user_i, the loop that prints the spaces is "going down". That is, printing fewer and fewer spaces as it goes.
Because tall is "going up", and because the hash loop is just basically using it as-is, it's going up too. That is, printing more hash marks as you go.
So really ignore most of this code. It's generic: the outer loop just counts up, and most of the inner loops just do basic initialization (i.e. space = 0 and hash = 0), or basic incrementation (space++ and hash++).
It is only the center parts of the inner loops that matter, and they use the movement of tall from the outermost loop to increment themselves down and up respectively, as noted above, thus making the combination of spaces and hash marks needed to make a half-pyramid.
Hope this helps!
Here's your code, just reformatted and stripped of comments:
for(int tall = 0;tall<user_i;tall++)
{
for(int space=0; space<=user_i-tall; space++){
printf(" ");
}
for(int hash=0; hash<=tall; hash++){
printf("#");
}
printf("\n");
}
And the same code, with some explanation interjected:
// This is a simple loop, it will loop user_i times.
// tall will be [0,1,...,(user_i - 1)] inclusive.
// If we peek at the end of the loop, we see that we're printing a newline character.
// In fact, each iteration of this loop will be a single line.
for(int tall=0; tall<user_i; tall++)
{
// "For each line, we do the following:"
//
// This will loop (user_i - tall + 1) times, each time printing a single space.
// As we've seen, tall starts at 0 and increases by 1 per line.
// On the first line, tall = 0 and this will loop (user_i + 1) times, printing that many spaces
// On the last line, tall = (user_i - 1) and this will loop 0 times, not printing any spaces
for(int space=0; space<=user_i-tall; space++){
printf(" ");
}
// This will loop (tall + 1) times, each printing a single hash
// On the first line, tall = 0 and this will loop 1 time, printing 1 hash
// On the last line, tall = (user_i - 1) and this will loop user_i times, printing that many hashes
for(int hash=0; hash<=tall; hash++){
printf("#");
}
// Finally, we print a newline
printf("\n");
}
This type of small programs are the one which kept fascinating me in my earlier days. I think they play a vital role in building logics and understand how, when, where and in which situation which loop will be perfect one.
The best way one can understand what happening is to manually debug each and every statement.
But to understand better lets understand how to build the logic for that, I am making some minor changes so that we can understand it better,
n is no of lines to print in pyramid n =5
Replacing empty spaces ' ' with '-' (dash symbol)
Now pyramid will look something like,
----#
---##
--###
-####
#####
Now steps to design the loop,
First of all we have to print n lines i.e. 5 lines so first loop will be running 5 times.
for (int rowNo = 0; rowNo < n; rowNo++ ) the Row number rowNo is similar to tall in your loop
In each line we have to print 5 characters but such that we get our desired figure, if we closely look at what logic is there,
rowNo=0 (Which is our first row) we have 4 dashes and 1 hash
rowNo=1 we have 3 dashes and 2 hash
rowNo=2 we have 2 dashes and 3 hash
rowNo=3 we have 1 dashes and 4 hash
rowNo=4 we have 0 dashes and 5 hash
Little inspection can reveal that for each row denoted by rowNo we have to print n - rowNo - 1 dashes - and rowNo + 1 hashes #,
Therefore inside our first for loop we have to have two loops, one to print dashes and one to print hashes.
Dash loop will be for (int dashes= 0; dashes < n - rowNo - 1; dashes ++ ), here dashes is similar to space in your original program
Hash loop will be for (int hash = 0; hash < rowNo + 1; dashes ++ ),
The last step after every line we have to print a line break so that we can move to next line.
Hope, the above explanation provides a clear understanding how the for loops that you have written will be formulated.
In your program there are only minor changes then my explanation, in my loops I have used less then < operator and you have used <= operator so it makes difference of one iteration.
You should use indentatation to make your code more readable and therefore easier to understand.
What your code does is print user_i lines that consist of user_i-tall+1 spaces and then tall+1 hashes. Because the iteration index tall increases with every pass this means that one more hash is printed. They are right aligned because a space is left out as well. Subsequently you have 'growing' rows of hashes that form a pyramid.
What you are doing is equivalent to this pseudo code:
for every i between 0 and user_i do:
print " " (user_i-i+1) times
print "#" (i+1) times
Analyzing your loops:
The first loop
for ( int tall = 0; tall < user_i; tall++ ){...}
is controlling the row. The second loop
for ( int space = 0; space <= user_i - tall; space++ ){...}
for the column to be filled by spaces.
For each row , it will fill all the user_i - tall columns with spaces.
Now the remaining columns are filled by # by the loop
for ( int hash = 0; hash <= tall; hash++ ){...}
#include <stdio.h>
// Please note spacing of
// - functions braces
// - for loops braces
// - equations
// - indentation
int main(void)
{
// Char holds all the values we want
// Also, declaire all your variables at the top
unsigned char user_i;
unsigned char tall, space, hash;
// One call to printf is more efficient
printf("Hello there and welcome to the pyramid creator program\n"
"Please enter a non negative INTEGER from 0 to 23\n");
// This is suited for a do-while. Exercise to the reader for adding in a
// print when user input is invalid.
do scanf("%d", &user_i);
while (user_i < 0 || user_i > 23);
// For each level of the pyramid (starting from the top)...
// Goes from 0 to user_i - 1
for (tall = 0; tall < user_i; tall++) {
// We are going to make each line user_i + 2 characters wide
// At tall = 0, this will be user_i + 1 characters worth of spaces
// At tall = 1, this will be user_i + 1 - 1 characters worth of spaces
// ...
// At tall = user_i - 1, this will be user_i + 1 - (user_i - 1) characters worth of spaces
for (space = 0; space <= user_i - tall; space++)
printf(" "); // no '\n', so characters print right next to one another
// because of using '<=' inequality
// \_
// At tall = 0, this will be 0 + 1 characters worth of hashes
// At tall = 1, this will be 1 + 1 characters worth of hashes
// ...
// At tall = user_i - 1, this will be user_i - 1 + 1 characters worth of spaces
for (hash = 0; hash <= tall; hash++)
printf("#");
// Level complete. Add a newline to start the next level
printf("\n");
}
return 0;
}
The simplest answer to why that is happening is because one loop prints spaces like this represented by -.
----------
---------
--------
-------
------
-----
and so on.
The hashes are printed like this
------#
-----##
----###
---####
--#####
-######
since hash printing loop at second stage needs to print equal no of hashes more to complete the pyramid it can be solved by two methods one by copying and pasting hash loop twice or by making the loop run twice next time by following modification
for ( int hash = 0; hash <= tall*2; hash++ )
{
printf ( "#" );
}
The logic to build such loops is simple the outermost loop prints one line feed to seperate
loops,the inner loops are responsible for each lines contents.
The space loop puts spaces and hash loop appends hash at end of spaces.
[My answer can be redundant because i did not read other answers so much carefully,they were long]
Result:
#
###
#####
#######
#########
###########
for ( int tall = 0; tall < user_i; tall++ ) { ... }
I think of this in natural language like this:
int tall = 0; // Start with an initial value of tall = 0
tall < user_i; // While tall is less than user_i, do the stuff between the curly braces
tall++; // At the end of each loop, increment tall and then recheck against the condition in step 2 before doing another loop
And with nice indentation in your code now it's much easier to see how the for loops are nested. The inner loops are going to be run for every iteration of the outer loop.