Friday, 15 February 2013

Looping

Loops

—A loop allows a program to repeat a group of statements, either any number of times or until some loop condition occurs
—
—Convenient if the exact number of repetitions are known
—
—Loop Consists of
—Body of the loop
—Control Statement











Steps in looping
—Initialization of condition variable
—Execution of body of the loop
—Test the control statement
—Updating the condition variable

Common loops
for    while     do while

Repetition occurs as long as a condition is true








for
Syntax:
                 for (expr1; expr2; expr3)
                      statement;
§expr1 controls the looping action,
—
§expr2 represents a condition that ensures loop continuation,
—
§expr3 modifies the value of the control variable initially assigned by expr1







Examples
§Vary the control variable from 1 to 100 in increments of 1
for (i = 1; i <= 100; i++)
—
§Vary the control variable from 100 to 1 in increments of -1
for (i = 100; i >= 1; i--)
—
§Vary the control variable from 5 to 55 in increments of 5
for (i = 5; i <= 55; i+=5)
Examples 2
#include <stdio.h>
void main()
{
  /* a program to produce a Celsius to Fahrenheit conversion chart for the numbers 1 to 100 */
  int celsius;
    for (celsius = 0; celsius <= 100; celsius++)
        printf(“Celsius: %d Fahrenheit: %d\n”, celsius, (celsius * 9) / 5 + 32);
    }
Nested for loops

—Nested means there is a loop within a loop
—
—Executed from the inside out
—Each loop is like a layer and has its own counter  variable, its own loop expression and its own loop body
—
—In a nested loop, for each value of the outermost counter variable, the complete inner loop will be executed once
General form
 
    for (loop1_exprs) {
          loop_body_1a
          for (loop2_exprs) {
          loop_body_2
          }
          loop_body_1b
    }





No comments:

Post a Comment

String functions

Read This: strncpy() strncat() strstr () strlen() — Predefined function defined in string.h . — — Returns the len...