Dfwfw Essay

283 WordsMar 10, 20152 Pages
CSCI 1470 – Spring 2012 University of Central Arkansas Lab 6 In-class Assignment Topics: for loop. Reading: Ch. 4-5 Objectives: • To learn the for loop construct provided in C++ • To learn various for loop control methods • To provide experience in using the for loop construct and nester for loops. In this lab we will discuss the C++ for and while loops. For Loops The for statement is a looping structure designed specifically to simplify the implementation of count-controlled loops (That is, a count-controlled While loop can be replaced by a For loop.). The loop-control variable, the beginning value, the ending value, and the incrementation are explicitly part of the For loop heading itself. The syntax template for a For statement is for (InitStatement; Expression1; Expression2) { Statement; } Usually, the InitStatement initializes a loop control variable. Expression2 increments or decrements the loop control variable. Expression1 is equivalent to a While condition. The following For loop reads 10 marks and sums them up. sum = 0; for (counter = 1; counter mark; sum = sum + mark; } The following For loop also reads 10 marks and sums them up. sum = 0; for (counter = 10; counter > 0; counter--) { cout > mark; sum = sum + mark; } Of course, all the For loops can be written as count-controlled While loops. For example, we can change the previous program segment to the following equivalent piece of code. sum = 0; counter = 1; while(counter mark; sum = sum + mark; counter++; } Exercise 1: How many iterations are there in the loop shown below? Hand trace this segment of code showing the output from each loop. What does the final output look like? |const int MAXCOUNT = 5; | |int x = 0; | |

    More about Dfwfw Essay

      Open Document