| Main |< C scanf(), scanf_s() family | C & C++ for loop 2 >| Site Index | Download |


 

 

 

 

 

 

 C LAB WORKSHEET 7

The C & C++ Repetition: The for Loop 1

 

 

 

 

 

 

Items in this page:

 

  1. C program controls or loop - repetition.

  2. The for loop.

  3. The related tutorial reference for this worksheet are: C & C++ program control 1 and C/C++ program control 2.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Flowchart and tracechart

 

  1. Declare an integer variable, j and set an initial value to -4, j = -4.

  2. Check the condition for j, j <= 0 true or false?

  3. Print the j’s value.

  4. Increment j by 1.

  5. Repeat the iteration process until j <= 0 is false.

  6. If the condition j<=0 is false, stop exit the loop and continue the execution of the next code if any.

The C for loop flowchart

 
  • From the Figure:

  1. The flowchart starts at the oval Start (some use Begin) and continues until the oval called Stop (some use End) is encountered – start or stop of the program execution.

  2. Assignment statements are shown in rectangles – assignment or operation statements.

  3. A decision is shown in a diamond – decision, yes or no, true or false.

  4. Printing and reading of values use parallelograms – printing and reading values (input/output).

  5. The flow directions are represented by arrows – flow direction.

  • You may find other shapes such as small circle used in the flowchart but those used in the previous Figure are the common shapes.

  • From the flowchart we can describe the detail of the steps taken for the loop execution in a tracechart. For this example we have 17 steps to complete the loop execution. The C/C++ code optimization for speed and program size can be done by reducing the steps taken and simplify the code used, provided the output still retained.

The C for loop tracechart

  • From the flowchart we can do the program coding and test the output as shown below with a variation of coding styles. Create a project named progcontrol. Then add C++ source file named progcontrolsrc to the project. Don’t forget to set your project to be compiled as C code. Try the following example and see the output. Study the for loop construct and the many faces of coding styles.

#include <stdio.h>

 

void main()

{

      int j;

      j = -4;

      for( ; j <= 0 ; )

      {

            printf("%d\n", j);

            j = j + 1;

      }

}

The C for loop program example output sample

   

#include <stdio.h>

 

void main()

{

      int j = -4;

      for( ; j <= 0 ; )

      {

            printf("%d\n", j);

            j = j + 1;

      }

}

   

#include <stdio.h>

 

void main()

{

      int j;

      for(j = -4; j <= 0 ; )

      {

            printf("%d\n", j);

            j = j + 1;

      }

}

   

#include <stdio.h>

 

void main()

{

      int j;

      for(j = -4; j <= 0 ; j = j + 1)

            printf("%d\n", j);

}

   

#include <stdio.h>

 

void main()

{

      int j;

      for( j = -4; j <= 0 ; )

            printf("%d\n", j++);

}

   

#include <stdio.h>

 

void main()

{

      int j;

      for( j = -4; j <= 0 ; j++)

            printf("%d\n", j);

}

 

for(initial value; condition; iteration)

{

      C/C++ statement(s);

}

#include <stdio.h>

 

void main(void)

{

      int count;

      char name[15];

      printf("What is your name in less than 15 characters? ");

      // scanf("%s", &name);  // older version

      scanf_s("%s", &name, 14);

      printf("How many times to display your name? ");

      // scanf("%d", &count); // older version

      scanf_s("%d", &count, 1);

      // iterate descendingly and the two following

      // commented out are the 'for' variations...

      // for(; count != 0; count = --count)

      // for(; count != 0; count = count--)

      for(; count != 0; count = count - 1)

            printf("count #%d - %s\n", count, name);

}

The C for loop - iteration

Another C for loop flowchart

 

Activities And Questions

 

Run the following program, show the output and answer the question.

#include <stdio.h>

 

void main()

{

      int i;

      i = 0;

      for( ; i <= 3; )

      {

            printf("%d\n", i);

            i = i + 1;

      }

}

  1. What is the first value of i?

  2. What is the last value of i that is printed?

  3. Build a flowchart for the program.

  4. Change the i = 0; to i = 1 in the program and rebuild. What is the first value of i? What is the last value of i that is printed?

  1. 0.

  2. 3.

The first value of i is 1 and the last value of i is 3.

   

Try the following program.

#include <stdio.h>

 

void main()

{

      int i;

      i = 0;                      // Statement 1

      for( ; i <= 4; )        // Statement 2

      {

            printf("%d\n", i);

            i = i + 2;         // Statement 3

      }

}

  1. What is the first value of i? What is the last value of i that is printed?

  2. Which statement determines the initial value? 1, 2 or 3?

  3. Which statement determines the final value?

  4. Which statement determines how the value of i is increased?

  1. First value of i is 0 and the last value is 4.

  2. Statement 1.

  3. Statement 2.

  4. Statement 3.

   

Run the following program.

#include <stdio.h>

 

void main()

{

      int i;

      i = 0;                        // Statement 1

      for( ; i <= 4; )           // Statement 2

      {

            printf("%d\n", i);

            i = i + 2;              // Statement 3

      }

      printf("***** %d\n", i);      // Statement 4

}

  1. What is the first value of i?

  2. What is the last value of i that is printed inside the loop?

  3. Is statement 3 inside the loop? What about statement 4?

  4. Which statement is done before the loop?

  5. Which one is done after the loop?

  6. How can we tell which statements are inside the loop?

 

  1. 0.

  2. 4.

  3. Statement 3 is inside the loop and Statement 4 is outside the loop.

  4. Statement 1.

  5. Statement 4.

  6. Statements that are inside the curly braces ({ }) immediately after the for loop. These statements construct the for loop body.

   

Next, let simplify the previous program. Run and show the output.

#include <stdio.h>

 

void main()

{

      int i;

      for(i = 0; i <= 4;  i = i + 2)   // Statement 1

            printf("%d\n", i);            // Statement 2

      printf("***** %d\n", i);         // Statement 3

}

The for loop now shows three expressions. We will call the first expression as i = 0, the second expression i <= 4, and the third expression is i = i + 2.

 

  1. Which of these three expressions determines the terminal condition of the loop?

  2. Which one determines the incremental value of i?

  3. Which one determines the initial value of i?

  4. Is statement 2 in the loop or after it?

  5. Is statement 3 in the loop or after it?

 

  1. i <= 4.

  2. i = i + 2.

  3. i = 0.

  4. In the loop.

  5. After the loop. Without curly braces, only the first statement immediately after the for loop statement will be in the loop.

   

#include <stdio.h>

 

void main()

{

      int i;

      for(i = 8; i <= 11;  i = i + 1)    // Statement 1

            printf("%d\n", i);               // Statement 2

      printf("***** %d\n", i);            // Statement 3

}

  1. The for loop has three expressions separated by two semicolons. Which of these parts are assignments, that is a statement where a variable is being changed?

  2. Which part sets the initial value of i?

  3. Which part terminates the loop?

  4. Which part increment i?

  1. i <= 11 and i = i + 1.

  2. i = 8.

  3. i <=11.

  4. i = i + 1.

   

#include <stdio.h>

 

void main()

{

      int i;

      for(i = 8; i <= 11;  printf("%d\n", i))   // Statement 1

            i = i + 1;                          // Statement 2

      printf("***** %d\n", i);          // Statement 3

}

  1. Why didn’t the 8 get printed this time?

  2. Why did 12 get printed twice, once inside the loop and once after the loop?

  1. It is because when the initial value of i is 8, the statement 2, i = i + 1 makes i = 9 and then printed by the printf("%d\n", i) statement. Compared to the previous example, the code in the for loop will be executed first whereas the expressions in the for statement are just evaluated at the beginning, executed on the second and later iteration.

   

#include <stdio.h>

 

void main()

{

      int i;

      for(i = 0; i <= 4;  i = i + 2)      // Statement 1

      {          

            printf("%d\n", i);               // Statement 2

            printf("***** %d\n", i);      // Statement 3

      }

}

  1. Why is statement 3 being executed in the loop?

  2. We must have a pair of what items if more than one statement is to be executed in the loop?

  3. Remove the opening and closing curly braces of the for loop. Rebuild the program. Why statement 3 was not executed in the loop?

  1. Because statement 3 is in the for loop body.

  2. A curly braces ({ }).

Statement 3 was not executed because it is outside of the for loop body.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Add a semicolon at the end of the for and watch what happens.

#include <stdio.h>

 

void main()

{

      int i;

      for(i = 0; i <= 4;  i = i + 2);     // Statement 1

      {

            printf("%d\n", i);               // Statement 2

            printf("***** %d\n", i);      // Statement 3

      }

}

  1. Was statement 2 executed inside the loop?

  2. Was statement 3 executed inside the loop?

  3. What was the only difference between this experiment and the previous one?

 

  1. No.

  2. No.

  3. A semicolon was added at the end of the for statement. In this case the for loop becomes a single, isolated C statement. Only expressions in the for loop, that is (i = 0; i <= 4;  i = i + 2) have been evaluated and executed then the for loop terminates, leaving the final value of i equal to 6 = 4 + 2. The statements in the curly braces will print the final value of i, that is 6, once for each printf() statement.

   

Next, let try making i go backward (decrement) by changing <= to >= operator.

#include <stdio.h>

 

void main()

{

      int i = 4;

      for(; i >= 2;)

      {

            i = i - 1;

            printf("%d\n", i);

      }

}

  1. Initially, the condition i >= 2? True or false?

  2. With every iteration of the loop, this condition is closer and closer to becoming true or false?

  1. True.

  2. False.

   

What about the not equal to operator, != as shown below.

#include <stdio.h>

 

void main()

{

      int i;

      for(i = 10; i != 2; i = i - 1)

            printf("%d ", i);

      printf("\n");

}

 

The printf("%d ", i); statement will be executed except when i = = 2.

   

What happen to the following program output? How to stop it? How would you correct it?

#include <stdio.h>

 

void main()

{

      int i;

      // here we set the initial value to 3, but the condition

      // is != 2, print and increment the i by 1...

      // the i != 2 is true forever!

      for(i = 3; i != 2; i = i + 1)

            printf("%d ", i);

}

 

The output of this program will be infinite number because the for loop doesn't have a terminal condition. The output is 'overflow'. The i != 2 expression is always true in this case. To stop it press Ctrl + C.

We need to provide a terminal condition for the loop. In this case we can change the i = i + 1 to i = i - 1 to provide a terminal condition. So we need to provide a terminal condition in the for statement else the for loop won't terminate.

 

   

Compress or simplify the following code as much as possible by retaining the output.

#include <stdio.h>

 

void main()

{

      int i = 0;

      for(; i < 5;)

            printf("%d ", i);

      i = i + 1;

}

  1. Which part is the terminal condition? Which statement brings the loop closer to the terminal condition with every iteration? Which statement initializes the loop?

  2. What is the operator for the assignment statement? What is the conditional operator for equality? Which statement changes a value? Which statement checks only a value?

  3. If a loop doesn’t approach the terminal condition with every iteration but diverges from it, what kind of loop is it?

The program seems can't be simplified anymore. In this program i has been initialized to 0. Then the for statement only provide i < 5 condition expression. The for loop statement that has been executed indefinitely is printf("%d ", i);. In this program, the i < 5 is always true because there is no iteration (decrement or increment) to make it closer to the terminal value, i < 5. The for loop run continuously while printing the initial value of i = 0.

 

  1. There is no terminal condition. No statement will bring the loop closer to the terminal condition with every iteration. Statement int i = 0; initializes the loop.

  2. An equal sign, = is an assignment operator. Statement i = i + 1 changes a value. Statement i < 5 only check a value.

  3. An infinite loop.

 

 

 

 

 

 

| Main |< C scanf(), scanf_s() family | C & C++ for loop 2 >| Site Index | Download |


The C Repetition for, while and do-while: Part 1 | Part 2 | Part 3 | Part 4