Quickly learn the basics of for looping in the C language

  • 2020-05-05 11:37:24
  • OfStack

There are many ways to write a program for a particular task. The following code can also implement the previous temperature converter function: #include


<stdio.h>
/* Print the Fahrenheit - Celsius temperature cross - reference table */
main()
{
 int fahr;
 for (fahr = 0; fahr <= 300; fahr = fahr + 20)
 printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
}

The lower limit, upper limit, and step size of the temperature are constants, and the third argument to the   printf function must be a floating point value that matches %6.1f, so any floating point expression can be used here.

The for statement is a circular statement that generalizes the while statement. If you compare the for statement with the while statement described earlier, you will find that the operation of the for statement is more intuitive. The parentheses contain three parts separated by semicolons. The first part, fahr = 0, is the initialization part and is executed only once before entering the loop. Part 2 fahr < = 300 is the test or condition part of the control loop. The loop control evaluates this condition, and if the result value is true (true), the loop body (in this example, the loop body contains only one printf function call statement) is executed. After that, the third part fahr = fahr + 20 is executed to increase the loop variable fahr by a step and evaluate the condition again. If the calculated conditional value is false (faise), the loop terminates. As with while statements, the body of an for loop can be a single statement or a set of statements enclosed in curly braces. The initialization part (part 1), the condition part (part 2), and the increment step part (part 3) can be any expression.

In actual programming, you can choose either of the whi1e or for loops, depending on which is clearer to use. The for statement is better suited to situations where both the initialization and increment steps are single statements and logically related because it sets the loop control statements together and is more compact than the while statement.

Exercise: modify the temperature conversion program to print the temperature conversion sheet in reverse order (that is, from 300 degrees to 0 degrees).


#include <stdio.h>
/* Print the Fahrenheit - Celsius temperature cross - reference table */
main()
{
 int i;
 int fahr;
 for (fahr = 300; fahr >= 0; fahr = fahr - 20)
 printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));

 scanf("%d", &i);
}


Related articles: