For example, if num were 4, it should print:
****If num is 8, then it should print
********This is really a challenging problem! Try to do it!
Here's the only solution that I can think of, given what you know:
public void printStars( int num )
{
if ( num == 1 )
System.out.println( "*" ) ;
else if ( num == 2 )
System.out.println( "**" ) ;
else if ( num == 3 )
System.out.println( "***" ) ;
else if ( num == 4 )
System.out.println( "****" ) ;
}
And this code only handles up to 4 stars! How many lines
would you need if you wanted up to 100 stars? You'd need
two lines for each value up to 100, so that would be 200 lines
of Java code. And if you wanted 1000 stars?
It seems like a huge waste of space. It seems like there should be a way to say "repeat this num times".
That's why we need loops. Loops allow us to repeat statements many times. It's a very powerful control flow construct.
As it turns out, there is a formula for this, which you should use if you really wanted to sum up these numbers. The sum is (num * (num + 1))/2. There's a proof for this, using a mathematical technique called induction.
However, there are problems similar to this that do not have a formula. Again, try writing a method that does this computation, and you may find yourself writing may if statements.
Programming needs the ability to compute over and over again, until some condition is reached. That's what a loop is for. We'll see more details in the next section.