Jump to content

For nested loop


phpnub2

Recommended Posts

Hello i am new here, and new to php too.

I try to learn php from about 20 days, and i am getting stuck in something, somebody asked me to make a program that will produce the following output, i have to use a nested for loop:

1

22

333

4444

55555

........etc

 

The code for is:

for($a=1;$a<10;$a++)
{
   echo "<br>";

   for ($b=0;$b<$a;$b++)
   echo $a;

}

I do know this is something elementary, but really i cannot understand how it works is there any saint that will comment the code and explain step by step whats happening there?

Thank you.

 

 

Link to comment
Share on other sites

You have an outside loop and an inside loop. Each time the outside loop executes the inside loop spins through its entire range. So the outside steps one at a time; the inside spins.

 

Your outside loop is "for($a=1;$a<10;$a++)" it will step from 1 to 9 and gives that value to $a.

 

The inside loop is "for ($b=0;$b<$a;$b++)" it goes from zero to one less than $a (which is determined by the outside loop) Or we can say it spins $a times.

 

First step $a = 1, the inside loop spins once and prints $a which is 1.

 

Second step of the outside loop is $a = 2. Inside loop spins from $b = 0 to $b = 1. Two times and prints $a (2) twice.

 

Third step $a = 3 and $b goes from 0 to 2 (3X) and prints $a (3) three times.

 

etc.. hope this helps

Link to comment
Share on other sites

Hello i am new here, and new to php too.

I try to learn php from about 20 days, and i am getting stuck in something, somebody asked me to make a program that will produce the following output, i have to use a nested for loop:

1

22

333

4444

55555

........etc

 

The code for is:

for($a=1;$a<10;$a++)
{
   echo "<br>";

   for ($b=0;$b<$a;$b++)
   echo $a;

}

I do know this is something elementary, but really i cannot understand how it works is there any saint that will comment the code and explain step by step whats happening there?

Thank you.

 

In addition to what sunfighter said, the nested loop still acts even though it doesn't have the curly brackets ({ and }) after it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.