| Main |< C & C++ while & do-while loop 1 | C & C++ if, if-else and switch-case-break 1 >| Site Index | Download |


 

 

 

 

 

 

C LAB WORKSHEET 7a_1

Another C & C++ Repetition Construct:  while Loop and do-while Loop 2

 

 

 

 

 

 

 

Items in this page:

 

  1. More for/while/do-while loop control activities, questions and answers.

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

 

 

 

 

 

 

 

#include <stdio.h>

 

int main()

{

    int k = 0, i, m;

    printf("Enter an integer as count: \n");

    scanf_s("%d", &m);

    printf("Enter the %d integers: \n", m);

    for( i = 1; i <= m; i = i + 1)

    {

      scanf_s("%d", &k);

      printf("The data is: %d \n", k);

    }

    return 0;

}

 

  1. Was there any difference between the outputs of this experiment and the previous one?

  2. Which of these two experiments preserved the number of times the loop was performed? That is, in which experiment did the value of m remain the same?

  3. If the <= were changed to !=, then how many times would the loop have been executed? i would have gone up to what value?

  4. Draw a flowchart for this program.

for loop, scanf_s() and reading inputs

  1. No difference.

  2. This experiment because it uses index i for iteration.

  3. 3 times. i = 3. i = i + 1 = 3 + 1 = 4.

  4. See below

 

for loop flowchart reading inputs example
   

#include <stdio.h>

 

int main()

{

    int n, m;

    printf("Enter an integer: \n");

    scanf_s("%d", &m);

    printf("Enter another integer: \n");

    scanf_s("%d", &n);

    for( ; m < n;)

    {

      printf("The data is: %d \n", m);

      m = n;

      scanf_s("%d", &n);

    }

    return 0;

}

// try these input pair: 3, 3 then 3, 4 and finally 4, 3

 

  1. The first time the for loop is encountered, which variable was read in before the other, m or n?

  2. Once inside the loop, there are two numbers available: the one that was read in earlier (outside for loop scanf_s()) and the one that was read in later (inside the for loop scanf_s()). Inside the loop, which one is printed, the earlier one or the later one?

  3. Inside the loop, does the earlier number now become the later one, or does the later one now become the earlier one?

  4. Inside the loop, which one does the scanf_s() read, the earlier one or the later one?

  5. After the scanf_s(), is m the earlier number or the later number?

  6. Without using the names of the variables but instead the terms earlier number and later number, state when the loop continues and when it terminates.

  7. Draw a flowchart and/or tracechart.

 

reading input example in for loop C program 1

 

reading input example in for loop C program 2

  1. m and then n.

  2. The earlier, that is m. The for loop only executed when m < n, that is the earlier value less than the later value else the for loop is skipped. That is why for the 3, 3 and 4, 3 input pairs, the for loop is skipped.

  3. Earlier becomes the later, that is m becomes n. Then both will have same value.

  4. The later, that is n.

  5. Earlier number.

  6. The loop continues only when the earlier number is less than the later number. Other value pairs will make the for loop being skipped.

  7. See below.

flowchart for loop program control example
   

 

It is very interesting for us to study the flow and behavior of the program. During the debugging process it is a repetitive process of editing, re-editing and commenting out the code. For example by adding suitable codes in the previous program as shown, we can see the program flow and behavior clearer as shown by a flowchart and a more details by tracechart.

 

#include <stdio.h>

 

int main()

{

    int n, m;

    printf("Enter an integer: \n");

    scanf_s("%d", &m);

    printf("Enter another integer: \n");

    scanf_s("%d", &n);

    // see the current values

    printf("The data m = %d and n = %d\n", m, n);

    for( ; m < n;)

    {

        printf("The data is: %d \n", m);

        // assign n's value to m

        m = n;

        // see the current values

        printf("The data m = %d and n = %d\n", m, n);

        // waiting or reading next input

        scanf_s("%d", &n);

        // see the current values

        printf("The data m = %d and n = %d\n", m, n);

    }

    return 0;

}

for loop program control flow

   

Now change the conditional operator as shown below. Can you determine what will be printed?

 

#include <stdio.h>

 

int main()

{

    int n, m;

    printf("Enter an integer: \n");

    scanf_s("%d", &m);

    printf("Enter another integer: \n");

    scanf_s("%d", &n);

    for( ; m != n; ) 

    {

      printf("The data is: %d \n", m);

      m = n;

      scanf_s("%d", &n);

    }

    return 0;

}

 

  1. State what numbers are printed and when the loop terminates?

C program for loop program control behaviour

 

for loop program behaviour C programming

  1. Numbers are printed and the for loop been executed when the condition of m != n is TRUE. When we input number pairs that less than or greater than, the for loops is TRUE forever because the scanf_s() will read new different n value. Numbers printed are interchangeably between n and m. You need to terminate the program execution manually (Ctrl + C). If m == n, the for loop will terminate because m != n is FALSE.

   

#include <stdio.h>

 

int main()

{

    int k = 0, i;

    printf("Enter integers: \n");

    scanf_s("%d", &k);

    for(i = 0; k != 11; i = i + 1)

    {

      printf("The data is: %d \n", k);

      scanf_s("%d", &k);

    }

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

    return 0;

}

 

  1. What does i represent when it is printed after the loop? And why?

the for loop sample output

  1. i represents an index of iteration. For three values, 3, 7 and 8, the index of iterations are 0, 1 and 2. So, the final value of i = i + 1 = 2 + 1 = 3.

   

#include <stdio.h>

 

int main()

{

    int k = 0, i, sum = 0;

    printf("Enter a sample input: \n");

    scanf_s("%d", &k);

    for(i = 0; k != 11; i = i + 1)

    {

      sum = sum + k;

      scanf_s("%d", &k);

    }

    printf("sum = %d, i = %d, ((sum*1.5)/i) = %.2f\n", sum, i, ((sum*1.5)/i));

    return 0;

}

 

  1. After the loop, what do the three numbers represent?

  2. Draw a flowchart and/or a tracechart.

for loop control program output sample

  1. The three numbers represent the first three inputs.

  2. See below.

 
C programming program for loop flowchart example

 

   

Show the output for the following programs and from the output, study the program behaviors.

 

#include <stdio.h>

 

int main()

{

    int k = 0, i, sum1 = 0, sum2 = 0;

    printf("Enter the sample input: \n");

    for(i=1; i<=2; i=i+1)

    {

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

      sum1 = sum1 + k;

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

      sum2 = sum2 + k;

    }

    printf("sum1 = %d, sum2 = %d\n", sum1, sum2);

    return 0;

}

// sample input: 2 40 30 90 10 40 on one line or separate line

for loop control for C program output example

   

#include <stdio.h>

 

int main()

{

    int k = 0, sum = 0;

    printf("Enter the sample input: \n");

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

    for(; k != 10;)

    {

      sum = sum - k;

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

      printf("sum = %d ", sum);

    }

    printf("\nfinal sum = %d\n", sum);

    return 0;

}

// sample input: 2 40 30 90 10 40 on one line or separate line

program output for C programming for loop control

   

Write C code snippet solutions for the following problem statements. Before writing and testing the codes you might want to create a pseudocode and a flowchart and/or tracechart.

 

Ask the user how many numbers to be added. Read in that many numbers and print their sum at the end.

#include <stdio.h>

 

int main()

{

    int i, k, j = 0;

    double sum = 0.0;

    // prompt the number of count

    printf("Enter number count to be summed up: \n");

    // read and store the count

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

    // prompt for the integers

    printf("Enter those integers: \n");

    for(i = 1; i <=k; i++)

    {

        // start reading & storing the first input and so on

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

        // sum the input

        sum = sum + j;

        // check, i <= k?, if TRUE, repeat, else

        // stop or exit the loop

    }

    // print the final sum

    printf("\nFinal sum = %.2f\n", sum);

    return 0;

}

 

C for loop control program example output

 

 

Read in grades for two quizzes (floats) on each line (for each student) until a -1 is entered for the first quiz. Print the average of each quiz at the end.

#include <stdio.h>

 

int main()

{

    int i;

    float mark = 0.0, sum = 0.0;

    printf("Enter the 1st & 2nd marks, 1st mark -1 to stop: \n");

    scanf_s("%f", &mark);

    for(i = 0; mark != -1.0; i = i + 1)

    {

        sum = sum + mark;

        scanf_s("%f", &mark);

    }

    printf("Total mark = %.2f, number of mark = %d,\n Average: %  .2f\n", sum, i, (sum/i));

    return 0;

}

 

C program control example for loop control

 

 

Read in grades with a value between 0 and 100 until a negative grade is read in. Stop the loop once a negative grade is read in. At the end print the average of all the other grades except for the negative one.

For your own observation: Change the terminal condition in the for statement:  (mark > 0) & (mark <100) to the following, rebuild and re-run your program and see the effect, error or warning.

  1. 0<mark<100.

  2. 0<=mark<=100.

  3. (mark >0) | (mark < 100).

  4. (mark >=0) | (mark <= 100).

  5. 100>mark>0.

  6. (100 > mark) & (0 < mark).

#include <stdio.h>

 

int main()

{

    int i;

    float mark = 0.0, sum = 0.0;

    printf("Enter marks, -ve to stop: \n");

    scanf_s("%f", &mark);

    for(i = 0; (mark > 0) & (mark <100); i = i + 1)

    {

        sum = sum + mark;

        scanf_s("%f", &mark);

    }

    printf("Total mark = %.2f, number of mark = %d,\n Average: %.2f\n", sum, i, (sum/i));

    return 0;

}

 

C program output example for loop program control

 

 

Keep reading in characters until two consecutive characters are equal. Then print the total number of characters except for the last two.

 

#include <stdio.h>

int main()

{

    char n, m;

    int i;

    // read char & store in m

    printf("Enter a character, same char to terminate: ");

    scanf_s(" %c", &m);

    // then read char & store in n

    printf("Enter another character, same char to terminate: ");

    scanf_s(" %c", &n);

    // if m!=n, that is different char, execute for loop..

    // else just go to the next statement

    // after the for loop body

    // i used to calculate the total character minus the

    // last similar character

    for(i = 0; m != n; i=i+1)

    {

        printf("More character, same char to terminate: ");

        // assign n's value to m, so m will hold n's value

        m = n;

        // then read next char & store in n, so

        // n will hold new value, different with m

        // Then both will hold fresh values...

        // though the first n and m are outside the for loop...

        scanf_s(" %c", &n);

    }

    printf("Total character: %d\n", i);

    return 0;

}

 

C for loop control program output sample

 

C program output example for loop control tutorial

 

   

More Practice

 

Run the following programs and answer the questions.

 

#include <stdio.h>

 

int main()

{

      int i, k, total;

      total = 0;

      printf("Enter 3 integers: ");

      for(i=1; i <=3; i=i+1)

      {

            // 1st iteration, read and store the first input

            // next iteration, read and store next input

            scanf_s("%d", &k);

            // sum up for every iteration

            total = total + k;

            // increment i & check the terminal condition

      }

      printf("Total = %d\n", total);

      return 0;

}

 

  1. How many times is this loop executed? Does this answer depend on what the data was?

  2. How many numbers will the loop read?

  3. If 40, 50 and 20 were read in, what would be the value of total:

 

1.    At the end of the first iteration?

2.    At the end of the second iteration?

3.    At the end of the third iteration?

4.    After the loop when it is printed?

 

  1. If 90, 10 and 30 were read in, then what would be printed?

 

C tutorial program output example for loop control

  1. 3 times. No. though you enter more than 3 inputs, the loop been executed 3 times only.

  2. 3 numbers.

  3. 1. 40 2. 90 3. 110 4. 110

You can see this effect by adding the following code after total = total + k;. Re-build and re-run the program.

printf("total hold: %d value at this moment.\n", total);

 

C programming tutorials - program output example for loop control

  1. 130.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

#include <stdio.h>

 

int main()

{

      int i, k, total;

      total = 0;

      printf("Enter an integer:\n");

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

      printf("More integers:\n");

      for(i=1; i <=3; i=i+1)

      {

            total = total + k;

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

      }

      printf("Total = %d\n", total);

      return 0;

}

 

  1. How many times is the loop performed?

  2. How many times is each of the statements in the loop performed?

  3. How many times is scanf_s() executed before, during and after the loop?

  4. How many data items are read in?

  5. If the data items are 40, 20, 50 and 10, then what is the value of total after the first time, second time and the third times through the loop?

  6. Is the first data item added into the loop? What about the last one?

  7. Draw a flowchart and/or tracechart for this program. The data items are 40, 20, 50 and 10. For the tracechart, make columns for k, i, total and i<3?

C programming program output example for loop control with answer to questions

  1. 3 times.

  2. 3 times.

  3. Before the loop is once. During the loop is 2 times. Not  executed after the loop.

  4. 3 data items. In this case: 10, 20 and 30.

  5. 40, 60 and 110. We put the following line of code just after total = total + k; code.

printf("total holds before: %d\n", total);

The output is shown below.

 

C programming program output and answers for loop control

  1. The first data item was added but the last one was not. This is because the i index already equal to 3.

  2. See below

C programming flowchart example for loop control

   
   

#include <stdio.h>

 

int main()

{

      int i, k, total;

      total = 0;

      printf("Enter an integer:\n");

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

      printf("More integers:\n");

      for(i=1; i <=3; i=i+1)

      {

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

            total = total + k;

      }

      printf("Total = %d\n", total);

      return 0;

}

// try the sample input: 40, 20, 50 and 10

 

  1. How many times is the scanf_s() done before, during and after the loop?

  2. After the first iteration of the loop, what is the value of total?

  3. Was the first data item added into total?

  4. Was the last data item added into total?

  5. What will be the final printout?

C programming program output sample for loop control

  1. Before is once. During the loop is three and after the loop is none.

  2. 20.

  3. No.

  4. Yes.

  5. 80. To see the behavior of this program add the following code just after the total = total + k;

printf("Current total = %d\n", total);

 

C programming program output example for loop control - debugging code

  1. 80.

   

#include <stdio.h>

 

int main()

{

      int i, k, total;

      total = 0;

      printf("Enter an integer:\n");

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

      printf("More integers:\n");

      for(i=1; i <=3; i=i+1)

            scanf_s("%d", &k, 1);   // statement 1

      total = total + k;      // statement 2

      printf("Total = %d\n", total);

      return 0;

}

// sample input: 40, 20, 50 and 10

 

  1. Which statement(s) are in the body of the loop?

  2. Which statement is indented incorrectly?

  3. Will 40 be added to total?

  4. Which numbers are added to total?

  5. Out of the numbers that were added to the total, which ones were added inside the loop and after the loop?

C programming program output example for loop

  1. scanf_s("%d", &k, 1);, Statement 1

  2. total = total + k;, Statement 2

  3. No.

  4. The last one, 10.

  5. None were added inside the loop. 10 was added outside the loop.

   

Using the following for loop:

 

for(i=1; i <= count; i = i + 1)

 

Write a program that will first read the variable count as a data item, read in that many more data items and print their total. For example, if the data were 3, 40, 20, 50, and 10; count would become 3 and the sum of the next 3 data items would be calculated as 110.

 

  1. Was the first data item that was read added to total?

  2. What was the purpose of the first data item?

  3. If the first data item were a 7, how many numbers would the program attempt to add?

C output example for loop control

  1. No.

  2. As a counter used as terminal condition in the for loop statement.

  3. 7 numbers as shown in the following output.

 

   

#include <stdio.h>

 

int main()

{

      int i, k;

      printf("Enter an integer:\n");

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

      for(i=1; k !=0; i=i+1)

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

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

      return 0;

}

// sample input: 4, 2, 9, 11, 4 and 0

 

  1. What is the output if the input were 4, 2, 9, 11, 4 and 0?

  2. Rewrite the program so that the code will not print the count of data items that were read in, but instead will print out the average of all numbers except the 0. Use sum as the variable to add the numbers.

  3. Rewrite the program in (b) so that the loop stops when the new number is less than the previous one. That is, if the data items were 30, 70, 85, 80, then the loop should stop at 80 but print out the average of all the numbers up to 85, the one before the last one. You will need two variables, call them last and curr. You will also need two scanf() or scanf_s() before the loop. Clue: as long as curr is greater than last, the loop continues.

  4. Draw a flowchart and/or tracechart for (c).

C programming output example for loop control

  1. 6.

  2. #include <stdio.h>

int main()

{int i, k, sum = 0;

printf("Enter integers:\n");

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

for(i=1; k !=0; i=i+1)

{

    sum = sum + k;

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

}

printf("The integers sum = %d\n", sum);

return 0;

}

 

C program output example for loop control

  1. #include <stdio.h>

int main()

{

    float i, last, current, sum = 0.0, average = 0.0;

    printf("Enter an integer: ");

    scanf_s("%f", &current);

    printf("Enter another integer: ");

    scanf_s("%f", &last);

    sum = current + last;

    for(i = 1; current < last; i=i+1)

    {

         printf("More integer: ");

        // the current become the last value

        current = last;

        // read & store a fresh last value

        scanf_s("%f", &last);

        sum = sum + last;

    }

    printf("Sum of integers: %.2f and average = %.2f\n", (sum - last), (sum-last)/i);

    return 0;

}

 

C programming program output example for loop control

C programming program control for loop example

 

 

 

 

 

 

 

| Main |< C & C++ while & do-while loop 1 | C & C++ if, if-else and switch-case-break 1 >| Site Index | Download |


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