{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

#6 Loop Control Structures

# #6 Loop Control Structures - Mapua Institute of Technology...

This preview shows pages 1–3. Sign up to view the full content.

Mapua Institute of Technology School of Information Technology CS103 – Fundamentals of Problem Solving and Programming 1 Lecture #5 Loop Control Structures What is a loop? Consider first the following problem. Write a program that will output the numbers from 1 to 5. The output should look like: 1 2 3 4 5 Using what was presented so far, one possible solution to this problem is: #include <iostream.h> void main( ) { cout<<“1\n”; cout<<“2\n”; cout<<“3\n”; cout<<“4\n”; cout<<“5\n”; } The solution is simple and it works. However, what will happen if we modify the problem such that we would like to output the values from 1 to 100? Following the simple solution above, we need to type in 95 more cout statements, i.e., from cout<< “6\n” to cout “100\n” . To make the situation worse, what if we would like to output the values from 1 to 5000? Of course we can still modify the program such that we will need to have 5000 cout statements in the program. Such a simple solution, however, is totally unacceptable. Why? it would require a lot of typing (especially if you don’t know how to use copy and paste!) the program source code will be quite long an experienced C++ programmer will laugh at such a solution (read: you will be humiliated!) We say that such a simple but poorly written solution was conceptualized using a brute-force approach. So what’s a better way to write the program? Before we go into that, try to understand the following program first. #include <iostream.h> void main( ) { int i; i = 1; cout <<i << endl; i = i + 1; cout <<i << endl; i = i + 1; cout <<i << endl; i = i + 1; cout <<i << endl; i = i + 1; cout <<i << endl; Prepared: akdbalan Page 1 of 5

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Mapua Institute of Technology School of Information Technology CS103 – Fundamentals of Problem Solving and Programming 1 } You would probably say that this program is not much better than the simple solution. Moreover, you would probably comment that it is longer in terms of the source code, and takes more time in the operation.
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}