Multiple Starting Values, Ending Values and Step Values in Looping Constructs for Structured Programming Languages

Posted by Rey Dacoco in

For starters, loop is a repetition structure that enables your program to execute the same statement(s) over and over and over and over and over again.There are several looping constructs that can be used for structured languages such as for, while,do-while,while-until and do-until. It's just so sad that most books showed us to use those statements by using only a single starting value,an ending value, and counter which made us conclude that it isn't possible to use compound loop elements.But did you know that you can use several initializations,loop conditions, and starting values in any looping constructs? You heard me right my friend. Here's how.

Syntax:

startingvalue1;
startingvalue2;
startingvaluen;
while((endingvalue1)&&(endingvalue2)&&(endingvaluen))
{
statement1;
statement2;
statementn;
stepvalue1;
stepvalue2;
stepvaluen;
}
For the sake of example I will be using while statement in PHP.

Example:
<?php
$intcount1=1;
$intcount2=10;
$intcount3=21;
while(($incount1<=10)&&($intcout2>=1)&&($intcount3<=30))
{
echo "$intnum1 $intnum2 $intnum3 
";
$intcount1++;
$intcount2--;
$intcount3++;
}
?>
The script above produces the following outputs:

1 10 21
2 9 22
3 8 23
4 7 24
5 6 25
6 5 26
7 4 27
8 3 28
9 2 29
10 1 30

You can use this as a good alternative for nested loops. Or if you wanted to hit several birds in one stone, that is, several outputs in one looping statement.

0 comments

Post a Comment

Contributor

My photo
I am just a simple man with a simple mind. And this is my simple blog. New Posts will be available soon. Enjoy reading and never stop learning:)

Total Pageviews

Link List

Archives

Got questions? You can reach me here: