A.11. Control Statements

You can control the order in which statements are executed in your C program using control statements like if, if-else, and for loops. Control statements make decisions about what is to be executed next in the program sequence.

A.11.1. if Statement

An if statement is a type of conditional control statement. The format of an if statement is:

if (logical-expression)
  {statements} 

where logical-expression is the condition to be tested, and statements are the lines of code that are to be executed if the condition is met.

A.11.1.1. Example

if (q != 1)
  {a = 0; b = 1;} 

A.11.2. if-else Statement

if-else statements are another type of conditional control statement. The format of an if-else statement is:

if (logical-expression)
  {statements} 
 else
  {statements} 

where logical-expression is the condition to be tested, and the first set of statements are the lines of code that are to be executed if the condition is met. If the condition is not met, then the statements following else are executed.

A.11.2.1. Example

if (x < 0.)
    y = x/50.;
 else
    {
     x = -x;
     y = x/25.;
    } 

The equivalent FORTRAN code is shown below for comparison.

  IF (X.LT.0.) THEN
     Y = X/50.
  ELSE
     X = -X
     Y = X/25.
  ENDIF 

A.11.3. for Loops

for loops are control statements that are a basic looping construct in C. They are analogous to do loops in FORTRAN. The format of a for loop is

for (begin ; end ; increment)
  {statements} 

where begin is the expression that is executed at the beginning of the loop; end is the logical expression that tests for loop termination; and increment is the expression that is executed at the end of the loop iteration (usually incrementing a counter).

A.11.3.1. Example

/* Print integers 1-10 and their squares */
 
 int i, j, n <= 10;
 
 for (i = 1 ; i = n ; i++)
   {
    j = i*i;
    printf("%d %d\n",i,j);
   } 

The equivalent FORTRAN code is shown below for comparison.

   INTEGER I,J
   N = 10
   DO I = 1,10
   J = I*I
   WRITE (*,*) I,J
   ENDDO