Aimee
Aimee

Reputation: 11

How do I increment a specific number when I have two variables in a for loop

For my homework i'm supposed to use '*' to make a picture prescribed in the notes. Basically what I would like help with is how to use subtraction in a for loop.

My code:

public class Starshapesver2{
    public static void main(String[] args){

        star(31) ;
        System.out.println(); //I initialize 'star' and 'space' later on

        for(int i=1; i<=7; i=i+1){
            star(14);
            blank(5);
            star(14);
        }
        ...

basically how would I add 4 to 'blank' and subtract 4 from 'spaces' inside the for loop (and so that it would keep adding on so the first blank would be 4 then 8 then 12 and so on)

sorry if this is confusing

Upvotes: 1

Views: 636

Answers (4)

Albert Laure
Albert Laure

Reputation: 1722

I assume you want to continually add 4 to blank and subtract 4 from Spaces until the loop ends. Well you can do this:

public static void main(String[] args)
{
    star(31) ;System.out.println(); //I initialize 'star' and 'space' later on
    int Blankint = 5;
    int spacesint =4// i cannot see your spaces in the code
    for(int i=1; i<=7; i=i+1)
    {
        Star(14);
        blank(5+Blankint);
        Blankint =Blankint+4;
        spaces(20 - spacesint); //assuming this where your space is because you didnt indicated it above.
        spacesint = spacesint+4;
        star(14);
    }
}

With this code your blank increments evert loop adding 4 to blanks and subtracting 4 to spaces

So if your initial blank is 5 next would be 9 then after the loop it would be 13 etc etc.

Upvotes: 1

alexroussos
alexroussos

Reputation: 2681

If I understand correctly, you want to have the arguments you pass to star() and blank() change each time through the loop. So you need to make them variables. Declare them outside of the loop, and modify them with each pass. Something like this:

int numBlanks = 5;

for (int i = 0; i <= 7; i++) {
    blanks(numBlanks);
    numBlanks = numBlanks + 4; // numBlanks will increase by 4 each time through the loop
}

Upvotes: 1

Floris Velleman
Floris Velleman

Reputation: 4888

Assuming you mean: "How would I add 4 to blank and substract 4 from spaces each iteration". At the same time assuming that these are methods which take an int.

for(int i=1; i<=7; i=i+1)
{
    star(14);
    //Make the call with the starting 5 adding i * 4 which varies each iteration
    blank(5 + i * 4);
    star(14);
}

You didn't show spaces in the loop itself but assuming it is there it could look like:

spaces(startingNumber - i * 4);

Upvotes: 0

upog
upog

Reputation: 5531

are you expecting something like below

 for(int i=1,increment=4; i<=7; i=i+1,increment=increment+4)
        {
        star(14 - increment);
        blank(5 + increment);
        star(14 - increment);
        }

Upvotes: 2

Related Questions