# For Loop Trouble

Show 80 post(s) from this thread on one page
Page 1 of 2 12 Last
• 02-07-2011
Jackbenimble
For Loop Trouble
I'm trying to write a code that prints out a diamond like shape when input is entered by the user. For example a user might enter the number 3 and this would print out
Code:

```        *       ***          *```
Or a user might enter the number 7, and this would print out
Code:

```      *     ***     *****   *******     *****     ***       *```
Basically I'm trying to write a for loop for the top half of the diamond, ie before the amount of stars reach a max. So in example 2, I'm trying to write a for loop for the first three rows.

I want to write a for loop within a for loop. So far this is my code,

Code:

``` #include <stdio.h> int main(void) {     int row, num;     char c=42;     printf("enter ODD size > 0: ");     scanf("%i", &num);     if (num%2 == 1)           {                 for (row = 1; row <= num/2; row++)                       {                               /* this is where I'm stuck. I don't know what for loop I need to embed                                   in my first for loop. */                       }             } return 0; }```
I know this coding is very rough, but I just need to start the first loop. Once I get that, I'm fairly certain I'll be able to figure out the rest of the program. I hope I didn't violate any rules and that my code is clean enough for you all to read. If anyone knows a method to figure this out or even any hints on where to get started please let me know.

Thanks,

Jack
• 02-07-2011
anduril462
Take some graph paper or the like, and draw some example diamonds of different sizes. On each row, write the row number, the number of leading spaces and the number of stars. Look for a pattern in the way each number changes, and try to find equations that give the number of spaces or stars in terms of the row number.
• 02-07-2011
Jackbenimble
star = (row*2-1)

but I don't know to implement this in a for loop. Like when row = 1, print (1*2-1) =1 stars. When row = 2 print 3 stars.

I also can't figure out a formula to relate spaces and rows. Arghhh, I'm very confused here. Does anyone know what a for loop might look like embedded in my first for loop?
• 02-07-2011
anduril462
That's the formula. To implement it, you need a second loop inside your row loop. Each time through that loop, you print a single star. As for spaces, the process for finding the formula is similar to that for stars, but you're decreasing, and only shrinking by 1. You may find it useful to make a variable that represents num/2 since it will come in handy in several places, including the spaces calculation. I also changed your loop to start at zero (changes in red), since I think having row start at zero will make the spaces calculation easier, and it's more traditional. Just a suggestion though

Code:

```half_width = num / 2; for (row = 0; row < half_width; row++) {     spaces = ???     stars = 2 * row + 1;     for (...) {  // use a new loop variable, like i         // print a space     }     // similar loop for printing stars }```
• 02-07-2011
renzokuken01
??
"that's it??? that's your crowning achievement??? knowing how to properly use a for loop?? you sure caught a big fish!!"
• 02-09-2011
Jackbenimble
I managed to figure out how to print the top half of the diamond. However, I am still unsure on how to do the spacing. I can do the spacing backwards, but I can't manage to print it in the right direction. Please take a look.
Code:

```#include <stdio.h> #include <math.h> int main(void) {   /*Initialize variables*/   int row, num, space, stars, i;   char c=42;   printf("enter ODD size > 0: ");   scanf("%i", &num);     /*if (num%2 == 1)*/           for (row = 1; row <= num; row+=2 )         {           for (i=1 ;i<=row/2; i++)                 {                   printf(" ");                 }           for (stars = 1;stars <= row; stars++)                 {                   printf("*");                 }                                           printf("\n");         }   return 0; }```
• 02-09-2011
anduril462
Here's what a diamond of size 7 looks like. I'm using code tags for fixed-width and a dot to represent a space.
Code:

```...*          // row = 1, stars = 1, spaces = 3 ..***        // row = 2, stars = 3, spaces = 2 .*****        // row = 3, stars = 5, spaces = 1 ******* .***** ..*** ...*```
For size of 7, the half_width that I mentioned is 7 / 2 or 3. Now, notice that as row goes from 1 to 3, the number of spaces starts at 3, then goes to 2, then 1. So, your formula is going to involve addition and subtraction of half_width and row, and you will probably need to add/subtract a 1 in there since you are starting counting your rows at 1.
• 02-09-2011
Jackbenimble
Ok, I'm still confused on how to embed it. Also, my row sizes start at 1 and increase by 2. So it goes row 1, row 3, row 5...etc.

Should it be

Code:

`for (space = (half_width-row+1); space = 0; space --)`
• 02-09-2011
anduril462
Oh man! What did you do? You were so close. You had a row variable that actually acted like a row variable (i.e. didn't skip even rows), a formula for the number of stars, that was based on the row number and was right, and we almost had a working space equation. You even gave the right space equation in your most recent post, but it wont work with your wacky new row-by-two method. Let's go back to where we were a few posts ago:
Code:

```half_width = num / 2; for (row = 1; row <= half_width; row++) {     stars = 2 * row - 1;     spaces = half_width - row + 1;     for (i = 0; i < spaces; i++)         // print a space     // similar loop for printing stars }```
Make more sense?
• 02-09-2011
Jackbenimble
It certainly makes sense, but it changes my method of operation. In the code where I skip even rows, I am able to print out all the way to the maximum star level. Ie, if the use enters 5, my code will print

Code:

```* *** *****```
However, using this method I cannot figure out a way to space it. So I tried using your method. Here's my code for that.

Code:

``` for (row = 1; row <= half_width; row ++)   {       stars = 2*row - 1;       spaces = half_width - row + 1;       for (i = 0; i < spaces; i++)             {                     printf(" ");             }       for (i = 0; i <= stars; i++)             {                     printf("*");             }       printf("\n"); }```
However, this results in an infinite loop for me. I'm not sure why. Any suggestions?
• 02-09-2011
You're writing up code before you have studied the problem sufficiently. Move away from the keyboard, get a paper and pencil/pen, and do it by hand, several times. Study what steps you are taking, to do this.

How does the row relate to the number of stars in that row? Think of the each loop as a completely separate entity. Focus on each loop, and what the variables are doing to make this diagram print out right.

Break it all down, find the relationships you need. Don't just "do it". Study it. You can't code up a problem until you can sufficiently understand it.
• 02-09-2011
Jackbenimble
Ok, thank you everyone for all the help and suggestions. I'm gonna step back and look at my for loops and the logic that occurs. However, I believe that I'm on the right track and that I should be able to get it. I'll post my new code when I get the first part of my problem.

Jack
• 02-10-2011
Jackbenimble
God save the queen, I figured out how to print a full, complete, correct diamond. Whew (brushes sweat off forehead).

Now, however, I need to add a few things to my code. After I print the diamond, I need to ask the user if he wants to print another diamond. Basically, if the user types in "y" or "Y", then the diamond prompt should pop up again.

So it would say
Code:

```enter ODD size > 0: 3  * ***  * more? y enter ODD size > 0: etc```
Now I know I can probably do this using a scanf function, but I've read that that isn't a very good function to use. I need an if statement that produces true if the user enters y or Y, and false for everything else. So I'm wondering, where do you all think I should start?
• 02-11-2011
anduril462
So the basic "keep doing this until the user wants to quit" idiom is something like:
Code:

```do {     get size     print diamond     ask to continue } while (try_again == 'y' || try_again == 'Y');```
You could use getchar or fgets if you're opposed to scanf. Just make sure if you use getchar, to eat up any leftover characters in the input buffer: Cprogramming.com FAQ > Flush the input buffer.
• 02-11-2011
Jackbenimble
Anduril, take a look at this.

Code:

``` /*This program should print diamond shapes composed of * characters*/ #include <stdio.h> #include <math.h> void flush(void) {   while (getchar() != '\n')     ; } int main(void) {   /*Initialize variables*/   int row, num=0, space, stars, i, star, spaces, count=0;   char yes, more ='a';   do{     do{       printf("enter ODD size > 0: ");       scanf("%i", &num);       count = scanf("%i", &num);       if (count == 0){         printf("must enter integer\n");         flush();       }     }while (count != 1);     do{       if ((int)num%2 != 1){         printf("%i is not odd and > 1\nenter ODD size > 0: ",num);             scanf("%i", &num);       }     }while ((int)num%2 !=1);                for (row = 1; row <= num; row+=2 )         {           i = (num/2 - row/2);                     for (space = i; space >= 1; space--)                 {                   printf(" ");                 }           for (stars = 1;stars <= row; stars++)                 {                   printf("*");                 }           printf("\n");         }       for (row = (num - 2); row >= 1; row -= 2)         {           i = (num/2 -row/2);             for (spaces = i; spaces >= 1; spaces--)                 {                   printf(" ");                 }             for (star = row; star >= 1; star--)               {                 printf("*");               }         printf("\n");         }           flush();       printf("more? ");       scanf("%c",&more);       }while (more == "y" || "Y"); return 0; }```
There are a few bugs. At first it asks for input, but it wont print anything unless I enter something (int/float/char) and then enter the number I want it to print. Also, for floating point values, I want to just truncate the value so it prints 7 instead of 7.25, etc. Any ideas?
Show 80 post(s) from this thread on one page
Page 1 of 2 12 Last