Showing posts with label for Loop. Show all posts
Showing posts with label for Loop. Show all posts

Monday, October 13, 2014

Looping in C

How can you tell whether a loop ended prematurely?
Generally, loops are dependent on one or more variables. Your program can check those variables outside the loop to ensure that the loop executed properly. For instance, consider the following example:

#define REQUESTED_BLOCKS 512
int x;
char* cp[REQUESTED_BLOCKS];
/* Attempt (in vain, I must add...) to
   allocate 512 10KB blocks in memory. */
for (x=0; x< REQUESTED_BLOCKS; x++)
{
     cp[x] = (char*) malloc(10000, 1);
     if (cp[x] == (char*) NULL)
          break;
}
/* If x is less than REQUESTED_BLOCKS,
   the loop has ended prematurely. */
if (x < REQUESTED_BLOCKS)
     printf("Bummer! My loop ended prematurely!\n");

Notice that for the loop to execute successfully, it would have had to iterate through 512 times. Immediately following the loop, this condition is tested to see whether the loop ended prematurely. If the variable x is anything less than 512, some error has occurred.

Wednesday, February 5, 2014

Php program using loops



<html>
<body>

<?php
for ($i=1; $i<=5; $i++)
  {
  echo "The number is " . $i . "<br />";
  }
?>

</body>
</html>

Monday, January 27, 2014

for Loop

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (init; condition; increment)
  {
  code to be executed;
  }
Parameters:
  • init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
  • condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop)
Note: Each of the parameters above can be empty, or have multiple expressions (separated by commas).