LOOP: DOING IT OVER AND OVER
One of the strengths of the computer is its ability to repeat a process over and over without getting tired or threatening to strike. The program that you have written to perform a single task can now be repeated to perform the same task as many times as you wish. This process of going over and over is known as repetition and is called a loop. Can you think of a loop? Of course! Our everyday activities, including getting up, eating, working, studying, and sleeping are examples of a loop. Can you identify other loops? With a little thought, I know you can.
Did you know that your computer is in a constant cycle of input, process, and output? This constant cycle of input, processing, and output means that your computer is in a loop. It waits for you to enter data, takes your input, analyzes it, performs the required task, and finally displays the result. We can generalize and say that every automated system, from the bank ATM machine, supermarket pricing, through the search engine of the Internet all use the loop.
It is very simple to create a loop. Just follow these three steps:
1) Use a reserved word (construct) from the C/C++ language to tell the program to loop.
2) Set a condition as to whether to continue or to terminate the loop.
3) Set aside the body of a loop to determine what you want to loop.
There are various ways to loop in a program, and for each way there is a construct (reserve word) from C/C++ that instructs the program to loop. These loop constructs are:
1) while
2) for
3) do while
4) goto label
Each of the above four loop constructs can do the same job. However, some are better suited in some situations and there are others that are rarely used, such as the goto. For simplicity we will concentrate on the while command, and later the others will be introduced.
TO CONTINUE THE LOOP OR TO TERMINATE
The condition part of the loop is based on true or false values. The true value is like a green light for the loop, and the false value is like a red light that will stop it. The condition part can be shown as the comparison of two values or the testing of one value as true or false. The action of the loop will depend on the resulting value of the loop’s condition. As long as the value of the condition is true then the loop will go on, but if the condition of the loop becomes false, the loop will terminate.
To compare two values, comparison (relational) operators are used. The comparison operators are situated between two values (operands) that will result in either a true (1) or false (0) value. The less than operator is shown as <, the greater than operator is shown as >, and the equal to operator is shown as = = (double equal sign). The operator <= stands for less than or equal to and, similarly, the operator >= stands for greater than or equal to. The not equal to operator is shown as !=. The ! (exclamation mark) alone stands for the not operation, which means to negate. Negation makes a true value become false, and a false value become true. The above relational operators can be used as loop conditions.
Depending on the relational operator and its operands, a true or a false value will be set. What would be the result of each of the following comparison (relational) operators?
|
True vs False |
|
|
2 < 3 will be true |
2 > 3 will be false |
|
2 = = 2 will be true |
2 != 2 will be false |
|
5 != 4 will be true |
4 = = 5 will be false |
|
5 <= 5 will be true |
5 >= 6 will be false |
|
! 0 will be true |
! 1 will be false |
![]()
What would be the result of m > n?
Answer: It all depends on the current values of variable m and n at the time of comparison.
C/C++ PHILOSOPHY OF WHAT IS TRUE AND WHAT IS FALSE
Surprisingly, in C/C++ every value is true except zero. For example, 2 is true, -5 is true, but 0 is false (C/C++ philosophy). Additionally, zero is the ASCII value of NULL, which means nil (nothing) and can be used as a terminator.
The while loop has the following common syntax (form): The word while is followed by an open “(" and a close ")” parenthesis. Within the parenthesis there will be a test (condition) resulting in either true or false, such as a relational operation. An open brace “{“ with a close “}“ determine the beginning and the end of the loop, where the body of the loop (statements) is placed within these braces. However, if the loop only contains one statement, there is no need for braces. Figure 3.1 shows the format of the while loop.

![]()
Be careful not to place a semicolon after the closed parenthesis because this may cause the body of the loop not to be iterated. To ensure this, place the open brace right after the close parenthesis.
Note that if the loop has only one statement, then there is no need for the braces because the next statement, by default, will automatically belong to the loop. However, for clarity, we suggest that you always use braces.
RUNNING FOREVER (INFINITE LOOP)
Figure 3.2 illustrates a loop that never terminates. The reason is that the condition for the loop is always true.

The output of the program illustrated above will repeat, and forever display the message: I WILL LIKE YOU FOREVER. One way to terminate the infinite loop is to externally interrupt the execution through the operating system (for example, in the DOS environment, pressing Ctrl + C at the same time will interrupt program execution.) The applications that are required to work around the clock can do so by the inclusion of this infinite loop. The traffic light system, credit card transactions, and the Internet information retrieval system are just a few examples of loops with the infinite concept.
IT'S AS IF IT NEVER HAPPENED (NOWHERE LOOP)
Figure 3.3 illustrates a loop that never runs. The reason is that the condition for the loop is always false.

![]()
Since the condition of the loop is false, the body of the loop will never be executed. Therefore, the message I WILL NEVER HATE YOU will not be displayed. One reason to set the condition of the loop to zero is to trace and track down errors in a program.
Once you know how to go forever or never to loop, it is desirable to learn how to control the loop. It is possible to loop a program a number of times, or loop it until some designated value has been reached. One way to accomplish that is to use a variable, instead of just a number, for the condition part of the loop. By using a variable, a loop can be controlled. Control depends on the value of the variable or the value of the variable in a comparison. For instance, while the value of a variable is true (non-zero) the loop will continue, but as soon as the control variable tested is false (zero) the loop will stop.
In order to use a control variable in a loop, the following steps must be taken into consideration:
1) Declaration of the control variable - A name must be chosen for a control variable and its data type should be specified. You can use any legal variable names, such as counter, count, c, i, j, k. Programmers frequently use these variable names. The data type of a control variable is most often chosen as an integer, such as int counter. Other data types, such as char and float, can be selected depending on the nature of the program.
2) Initialization of a control variable - A control variable must be set to a value that determines the number of times it loops. For example, for a loop of five, a control variable can be initialized to either 5 or 0, which can be written as counter = 5 or counter = 0, depending on how counter is changed later in the loop.
3) Condition of the control variable - The condition of the loop must result in a true value in order for the loop to continue and, similarly, the condition of the loop must result in a false value in order for the loop to stop. For example, while (counter) is the same as while (counter > 0), which means as long as counter is not zero the body of loop will be executed.
4) Body of the loop - the task that the loop has to perform plays an important role. Without the loop, the body will be executed one time only. The body could be the computation of an employee’s entire salary or just printing a message.
5) Update of the control variable - The control variable update should be written in such a way that it leads the condition of the loop to become false, which will then terminate the loop. For example, when the control variable is initialized to its end value, such as 5, then you must decrement the control variable by one. For example, setting counter to counter -1(see Figures 3.4a and 3.4b). Similarly, in the case when the initialization is set to a starting value, such as 0, you must increment by one. For example, counter = counter + 1. Figure 3.4c illustrates the incrementing of a counter.








Each of the following programs is supposed to loop five times, and display the message I LIKE YOU. However, each program has logical errors that will not allow this to happen. For example, the first program (figure 3.5a) will never display the message, the second program (figure 3.5b) will display the message repeatedly, and the third program (figure 3.5c) will be off by one. Can you identify these problems and fix them?
The first program’s initialization is set wrong, since it should be set to 5. In the second program you should increment the counter rather than decrement it. In the third program you must either change the condition test to <= or set the initialization to 0.












It is important to make the start, the body, and the end of the loop visible for the purpose of clarity and to avoid errors. One way to accomplish this is by the use of indentation and comments. If the body of the loop is only one statement then there is no need for braces, although in the case of beginners, it is recommended to use them. Another recommendation is to leave a blank line before and after the loop.

![]()


A common error of a beginning programmer is to place a ; right after the closed parenthesis of a loop. By placing an open brace right after the closed parenthesis in a loop, an error can be avoided.
LOOPING THE PAYROLL PROGRAM TO COVER MORE EMPLOYEES
After you finish writing a program for one employee, you will soon realize how much easier it is to make it for more than one. The example of this would be a payroll program, in which a loop is included to cover more than one employee, or where a loop is placed around the payroll program. The condition of the loop will determine how many times the loop should be repeated, such as the number of employees. The loop should be placed after the declaration of the loop control variable, and the closing of the loop should be placed before return 0; of the main program. See figure 3.7a for the complete program.
LOOPING THE INVOICE PROGRAM
You can simply loop the Invoice Program by placing the loop construct while after the declaration of the program, and terminate the loop right before the return 0; of the main program.
The loop can be 5, 50, 5000, or more times. In any case, only the condition test value will change to 5, 50, 5000, or any other number. See figure 3.8 for the program.
A variable represents a memory location, where a value can be stored and retrieved. However, each memory location can hold only one value at a time. An assignment can be used to initialize or change the value of a memory location. An equal sign = represents an assignment where the result value of the right-hand side of the equal sign is placed in the memory location of the variable in the left-hand side of the equal sign. An example of an assignment statement would be counter = 0; counter = counter + 1; where 0 is assigned to the variable counter in the first statement, and in the second statement the value of 1 is added to the old value of counter to produce a new value of 1 for counter. The process of assigning a value to a variable for the first time is called initialization. Remember that when a new value is assigned to a variable, the old value will be replaced. What do you do if you want to keep adding to a variable or subtracting from a variable? Simply add the value to the variable, and assign the result into the same variable. Similarly, subtract the new value from the variable.
![]()

![]()
![]()
![]()


![]()


INCREMENT OR DECREMENT BY ONE: VARIATIONS
The following examples in Table 3.2 illustrate different ways to increment or decrement a variable by 1.
|
Increment vs Decrement |
|
|
counter = counter + 1 |
counter = counter -1 |
|
counter++ |
counter - - |
|
++counter |
--counter |
|
counter+=1 |
counter -=1 |
![]()
Table 3.3 contains common assignment statements used by programmers, as well as sample initialization and the update of assignments.
|
Initialization and Assignment |
|
counter = 0; counter = counter +1;
|
|
counter = 1; counter = counter+2;
|
|
sum = 0; sum = sum + number;
|
|
pocket = 0; pocket = pocket + money;
|
|
c = 5; c = c - 1;
|
|
balance = 0; balance = balance + deposit
|
|
subtotal = 0; subtotal = subtotal + itemprice;
|
|
quotient = numerator / denominator; remainder = numerator % denominator;
|
C/C++ is known as a compact language, meaning that most of the time there is a shortcut for typing a statement or an expression. For example, the shortcut for counter=counter+1 would be counter++ or counter+=1 and even ++counter. Similarly, a shortcut for
sum = sum + price would be sum+=price.
There are many ways to loop 10 times. Start the control variable with 1 and loop as long as it is less than or equal to 10, and increment the variable by 1. Similarly, you can start from 0 and then continue, as long as it is less than 10. You can start from 100 and stop by 110. Another way would be to start from 10 and stop once 0 is reached. An example would be the space shuttle countdown program below.
![]()


![]()

The above loop goes through 1, 2, 3,…. 32767, -32768, -32767,…..,-1. Once the number reaches the largest positive number (32768), it then turns to the smallest number (-32768). Eventually the number will reach –1 and finally 0, where the loop will stop. Depending on the compiler the maximum range of integer varies. Therefore, wait until the maximum positive number is reached, or add the reserve word short before the reserved word int. E.g. change line 4 of above program to short int.
A loop can be stopped interactively by pressing a keyboard key such as the Esc key. In this case the ASCII value of a key is used as a terminator value. The following program
computes the subtotal and total price of items and conclude when the Esc key is pressed. The ASCII value of the Esc key is the value 27. As long as the variable more is not equal to 27, the program will continue.

CONTROLLING THE CONTROL VARIABLE: INTERACTIVE LOOP

Another variation of looping is the do while, where the condition is placed at the end of the loop. The codes within the do while will be executed at least one time before the condition is tested. The advantage of the do while is that it eliminates the input of data twice, such as was the case with the Esc key program above. As you can see from studying the program, there is user interaction before and within the while loop. The disadvantage of the do while loop is that the invalid data will be processed if additional checking is not performed. Similar to the while loop, the do while stops when the condition of the loop becomes false. Figure 3.13 illustrates a menu program using the do while.


FOR LOOP: A COMPACT LOOP
Another version of the loop where the initialization, testing, and update of the loop are positioned one after the other (same line), is known as the for loop, and it is the quickest way to write a loop. The for loop is preferable when the number of repetitions is known.
The form of the for loop is listed in figure 3.14.

![]()
A simple example of a for loop is shown in Figure 3.15 below.


When is a loop within a loop called a nested loop? How does a nested loop work? Start with an outer loop. Finish each inner loop until the outer loop is completely finished. When there is more than one loop nested, the innermost loop should be closed first. A time clock analogy can be a useful example in the sense that for every hour of a day there would be sixty minutes, and for every minute there would be sixty seconds. Figure 3.16 illustrates the analogy.

![]()
![]()

![]()

MULTIPLICATION TABLE: A NESTED LOOP EXAMPLE

![]()
![]()

The least-used and oldest kind of loop is known as a goto loop. The use of goto was controversial for a period of time, and as a result its usage is not recommended. The goto keyword allows program flow to go back and forth anywhere within a program. Hence, following the logic of a program becomes difficult at best. Figure 3.19 shows the use of the goto loop.

![]()
The previous loop is infinite. However, in the next chapter we will discuss the condition statement, which will allow the above code to terminate.
Inserting the keyword break can stop a loop. A loop can be made to continue by using the keyword continue. In either case, the break or continue keywords will be used in conjunction with a condition that we will discuss in the next chapter.




A user can control whether a loop should be continued or stopped by responding to a loop control variable. Figures 3.21a and 3.21b show the use of a control variable using a while loop and a do…while loop respectively.

![]()

![]()
A loop can be terminated by a “dummy” value that is not a valid input data. This dummy is called a sentinel value. An example of a sentinel value would be a dummy number such as 9999 or a dummy name such as zzzzzzzz. Historically, sentinel values were widely used before the introduction of the end of file. In the selection of a sentinel value you must be careful not to use a value that is within the range of valid data.

![]()


There is a possibility that the condition of a loop will never be met and the loop will run infinitely. The following example demonstrates how a user intends to display the first ten odd numbers. However, the value of control variable odd never becomes 10. The variable odd increments by 2, and therefore contains the value of 9, then 11, and so on.
![]()


![]()
The input routines of C/C++ expect to receive entry values that are identical to the expected data type. A contradiction will result to a false value (0), which can be used to terminate the loop. For example, the employee’s id data type of input routine cin is an integer. Any non-integer values entered by the user will result in false value, which can be used as the terminator of the loop. In the below program, you can type any word to stop the loop.
LOOP WITH END OF DATA FILE

![]()

There are situations when the size of the data is not known in advance, or the number of times the loop occurs is constantly changing. Thus, the use of a loop with a control variable will not be effective. The use of an end of file marker within the program will resolve this problem. At the end of each data file, there is a marker (character) that can be used as a terminator. The loop will cease when this indicator has been reached, meaning no more data is to be read. The following illustrates end of file usage as a loop terminator.
1) while (cin >> inputdatavariable) {……………..}
In this example, the end of file is implicit and the loop condition becomes false as the end of file is reached.
2) cin >> inputdatavariable; while(!cin.eof ()){……...cin>>inputdatavariable;}
In this example, the end of file is explicit, although data must be read once prior to the check of end of file.
3) while (cin.get()!=EOF){……….}
In this example, when the end of file is reached, the number –1, which in this case represents the end of file, will be returned. If the test for –1 is true, then the loop will stop. For the example above, data is being read character by character instead of by whole word or by whole number. For interactive data input, an end of file character can be produced by pressing operating system control keys. An example would be pressing CTRL + Z at the same time in DOS, and CTRL + D at the same time in Unix to indicate the end of file character.
![]()
![]()
When data becomes large, entering it interactively or retyping becomes costly and troublesome. Can you imagine entering supermarket data every time you need it? To avoid repetition, data is entered and saved in a file for future usage. The data file can be created the same way the program is created, except that the extension is not going to be a .cpp or .c. The file extensions, such as .in, .dat and .txt, are commonly used with the data file. The majority of C/C++ compilers come with an environment that allows editing a program that can be used to create the data file as well. However, the operating system text editors or word processors can be used to create a data file. In the case of a word processor it is safe to save the file as text.
Operating systems provide utilities the means to execute a program with the data file. The linkage of data with a program can be similarly used with a DOS or Unix command, which is known as redirection “<”. For example, for a payroll program “payroll.cpp” and its executable file “payroll.exe”, the following can be used where “payroll.in” contains the input data:
payroll < payroll.in
Similarly, the output file can be created using “>” redirection:
payroll < payroll.in > payroll.out
Input data, instead of coming from the keyboard, comes from the input file (e.g. in this example from payroll.in). The output, instead of being shown on the screen, goes into a file (e.g., payroll.out). The operating system commanding “<” for the input file and “>” for the output file has nothing to do with C/C++ operator signs “<”, “>”, “<<”, “>>”. In Chapter 8, you will learn how to access and create a data file directly with your program without using the above commands.
The numbers listed in Figure 3.26 are examples of an input data file that is saved as “payroll.in.” Just remember that the order of data values written in the data file is important, since the program needs to read these values in a specific order. For clarity, each line is dedicated to an individual employee and contains the employee’s ID, hours worked, and the hourly rate. Also, note that the line that reads the data file (cin>>id>>hw>>hr; from Figure 3.25 ) matches the format of the data file. The created data file must be in the same directory as the payroll program executable file in order for the payroll program to be able to read the data.

![]()
In order to use the operating system redirection operators, you must use the command line prompt, such as the MS-DOS prompt if your machine is running the Windows operating system. However, an executable file has to be built before you may use the command line. Building an executable file is dependent upon your compiler and you should consult the documentation of your compiler for specific information. For simplicity, we will use the Microsoft Visual C++ Version 6.0 compiler.
Within the MS Visual C++ compiler, an executable file is created by first compiling the source code file by clicking on the menu item named Build and clicking Compile payroll.cpp ( or using the keyboard keys Ctrl + F7 ). Once the source code is compiled with no errors, the payroll.exe ( executable ) file can be created by clicking the menu item Build and then clicking Build payroll.exe ( or using the keyboard key F7 ).
After the payroll executable file has been created, open up a MS-DOS prompt by selecting Startà ProgramsàMS-DOS prompt from the Windows task bar. Once the MS-DOS prompt window has been displayed, move to the directory that holds your executable file. Once again, for simplicity, we are using a directory named Cexample off of the root of C. Table 3.4 shows a list of simple DOS commands that will help you navigate through DOS based directories to reach the directory where your executable file is stored.
|
MS-DOS PROMPT COMMANDS
|
|
|
Command |
Description |
|
CLS |
Clears the screen. |
|
DIR |
Displays the current directory. |
|
CD\ |
Go to the root directory ( such as C: ) |
|
CD.. |
Go one level up from the current directory ( up from subdirectory ) |
|
CD directoryname |
Changes the directory from current directory to new directory. |
|
Executablename |
Runs an executable file. Do not type in the .exe extension. |
|
< filename.in |
Indirection Operator – Use file to the right of the operator as the input file. |
|
> filename.out |
Indirection Operator – Use file to the right of the operator as the output file.
|

When using the Microsoft Visual C++ compiler, the executable file created will be in a subdirectory of the directory, in which your payroll.cpp file is located. For our example, the C++ source file named payroll.cpp is located in the directory C:\Cexample. Therefore, when the source code is built into an executable file, the file will be placed into the following directory: C:\Cexample\Debug. The Microsoft Visual C++ compiler automatically creates the Debug directory if it does not exist. The Debug directory is where the payroll.in file must be located so that the payroll.exe file may read the input data via help from the operating system indirection operators.
Figure 3.27a and 3.27b show the output of the program of Figure 3.25. Figure 3.27a shows the MS-DOS prompt and how to travel to the correct directory as well as how the system indirection operators work. For example, the following system command produces output directed to the MS-DOS Window:
C:\Cexample\Debug>payroll<payroll.in
Figure 3.27b illustrates the output directed to a file that is created named payroll.out. The file is overwritten if it already exists. The following system command produces the new output file rather than displaying the information back to the MS-DOS Window.
C:\Cexample\Debug>payroll<payroll.in>payroll.out
The file named payroll.out can be opened from the MS-DOS Window from the MS-DOS prompt by typing the following command:
EDIT payroll.out
The file may also be opened using Windows applications, such as Notepad.




You might want to print or display these three files together for further need or development.
WHO DOES DETECT THE END OF FILE?
The input routines of a program are those responsible for getting the data from the data file. The input routines either detects the end of file character, acknowledges it by returning a value of –1, or, in the case of a mismatch, the input routines will return a value of 0. Tables 3.5 and 3.6 show the C Syntax and C++ Syntax respectively for detecting the end of file.
|
DETECTION OF END OF FILE |
|
C SYNTAX
|
|
Implicit EOF mismatch:
while (scanf(....)) {....... }
while(scanf(“%d”,&employeeid){..........}
Explicit EOF – return value of -1 for comparison:
Same as saying while (scanf(…..) != -1){ ….}
while(scanf( ) != EOF) {......... }
while(c=get()) != EOF){…….. }
|
![]()
|
DETECTION OF END OF FILE
|
|
C++ SYNTAX
|
|
Implicit EOF mismatch:
while(cin>>…….){…….}
while(cin>>employeeid){….}
Explicit EOF – return value of -1 for comparison:
while(!cin.eof()){………………}
while (cin.get() != EOF){………}
|
![]()
Figure 3.28 illustrates an example of end of file using C where the program ECHOES the content of a file of employees’ ids. Figure 3.29 illustrates a C++ version.


Similarly, each of the following loops can be used as well:


OR


Similarly, the following can be used:



What happens if you don’t know the size of the input data, or your input keeps changing and becoming more or less? How many times do you loop? What happens if you do not want to type data over and over? The simple answer is to use a data file with your program. The combination of the end of file and looping is an amazing phenomenon, in which a program can visit a data file of any size without knowing in advance the number of cycles. Program repetition becomes independent of the data file; whether an employee is hired or fired the program remains the same. Every time the data changes we do not need to go to the program to make changes. The program continues until the end of file marker is reached. In fact end of file is a magical tool for the programmer.
CLOSING REMARKS AND LOOKING AHEAD
One unique feature of the computer is the fact that a task can be performed over and over as many times as is needed. A C++ loop, such as the while, for, or do…while, makes this possible. A loop can be repeated for a specific time, until a condition is satisfied, or can be stopped by the user. Moreover a loop can work with an external data file allowing all information within the data file to be accessed. These attributes make the loop an extremely valuable tool. It is important not to forget that looping ten times or ten thousand times is just a mater of adding additional zeros to the test condition of the loop. With a human being, the processes of repetition described above would be a huge effort. Obtaining an early start with the concept of the data file in this chapter will give a better understanding of the work load a program is capable of accomplishing.
The next chapter will introduce the concept of decision-making and selection, which is what makes programs intelligent. Selection allows a program to make decisions related to conditions within a program at a specific point in time.
SELF-TEST TRUE / FALSE CHAPTER 3: LOOP
__ 1. In C++ the expression 2<3 always evaluates to true, and 0 is always false.
__ 2. The statement while (Ø) { } in a program will loop forever.
__ 3. Reserved words while, for, and do while can be used to loop.
__ 4. The exclamation operator ( ! ), means not in a example such as !=.
__ 5. The assignment statement c = c +1 is same as c++ and c += 1.
__ 6. To loop five times we need: int counter =0; while (counter >5){ counter ++;}.
__ 7. ifstream fin(“filename.in”); will associate an output file instead of an input file.
__ 8. When using end of file it is necessary to stop the loop by a counter variable in a loop condition.
__ 9. To loop a program 5 times, you must write the program 5 times.
__ 10. To run a program with a large amount of data it is better to enter the data each time interactively.
__ 11. Every time you recompile a program you must also recompile its data file.
__ 12. A C++ compiler will convert a file.cpp to a file.exe.
__ 13. If there are no errors detected by the compiler, the program output is correct.
__ 14. Instead of ; in a statement you can put , (comma).
__ 15. There is a logical error in the following declaration: float id;
__ 16. The keywords: int, float, double, char, and bool are known as basic data types in C++.
__ 17. The statement: cin << “Hello”; is syntactically and logically correct.
__ 18. The following loop will repeat 3 times: c = Ø; do{ c = c + 1;cout << “Hello”; } while (c < 3);
__ 19. A dummy value that is used to stop a loop is known as a sentinel.
__ 20. Instead of <iostream.h> you can use <iostream> with using namespace std.
__ 21. The identifier: 1pay is a valid name (identifier) in C++.
__ 25. The position of braces in a loop is very important and you can’t choose your own style.
Q3a) Describe the different types of loops that can be used in a C++ program. Give one example for each from this or other chapters.
Q3b) What would be the output of the following program?
#include<iostream>
using namespace std;
main( ){
int counter=5;
while(counter){
cout<<”I LOVE YOU”<<endl;
counter--; }//WHILE
return 0; }//MAIN
Q3c) A loop needs a condition to determine whether it will continue to loop or to terminate. Relational operators are used to compare two values and the result will be either true or false (e.g. i=0; the expression i<10 is always true). Use a while loop that will print out the numbers from 0 to 9.
Q3d) Write a loop that will run forever, a loop that will never run, and a loop that can be terminated with the ESC key (ESC has ASCII value of 27).
Q3e) Write a supermarket-pricing program. Program inputs are: itemid, itemname, unitprice, itemquantity, and taxstatus. Use 1 to indicate taxable items and 0 for non-taxable items, and the tax rate should be constant at 10%. Program should compute the subtotal for each item and add the sales tax if the item is taxable, then compute the grand total for the entire purchase. Program outputs should include item id, item name, subtotal, sales tax, and the total price for each item, then print the total sales tax and the grand total.
1234 shoes 25.00 2 1
9834 milk 1.99 1 0
1278 watches 60.00 1 1
9912 bread 1.00 3 0
If you are not familiar with working with files in the Windows environment, use the following:
#include<fstream>
using namespace std;
ifstream fin(“customer.txt”);
while(fin>>itemid>>itemname…){ …}//WHILE
Q3f) Convert the following while loop to a for loop.
int i=1; while (i<= 5) { cout <<”GIVE ME”<<i<<endl; i++;}
Q3g) Convert the above while loop to a do while loop (hint: do while tests at the end)
Q3h) What would be the output of each of the following two programs?
#include<iostream> //for each of the below programs
using namespace std;
a) void main( ){ const int n=10; n=n+1; cout<<n;}
b) void main( ){ int n=0; n=n+1; cout<<n;}
Q3i) What would have to be changed in the following program to make it produce a multiplication table?
1. #include <iostream>
2. using namespace std;
3.
4. void main(){
5. int row,column;
6. for(row=1;row<10;row++){
7. for(column=1;column<10;column++)
8. cout<<row<<column<<"\t";
9. cout<<endl;}
10. }//MAIN
Q3j) You are to design a grading system from scratch for professor “T” to determine the grade for each student. The data file contains the following: STUDENTID, MIDTERM, FINAL, and ASSIGNMENT. Show your own data file. Expand the program to run for 5 students. In addition, include the student’s name in the data file.
Q3k) Expand the program to run for as many students as there are in the data file.
The main purpose of this phase is to get accustomed to the repetition of a program using a loop and reading data interactively as well from an external file.
hint: Use a while loop.
3A) Expand Payroll Program so that interactively repeats for 5 employees.
Example:
Enter Employee Id 6740
Enter Hours Worked 40
Enter Hourly Rate $ 10
Employee Id is 6740
The Hours Worked are 40
The Hourly Rate is $10
The Gross Pay is $400
The Tax is 0.30
The Net Pay is $280
Enter Employee Id 3578
Enter Hours Worked 30
Enter Hourly Rate 10
Employee Id is 3578
…………..
3B) Expand Payroll program so that repeats for 5 employees from an input file.
Data typed and saved under employee.in
#include <fstream.h> instead of <iostream.h>
Use ifstream fin(“employee.in”);
Use the same while loop as 3A
3C) Expand Payroll program so that repeats for as many employees as are entered interactively.
No loop counter needed.
cout <<”Enter employeeid”;
while(cin>>employeeid) {…
…..
cout<<”Enter employeeid”;
} //end while loop
Having cin>> in loop enables user to exit loop by pressing ctrl/z
3D) Expand Payroll program so that repeats for as many employees in the input file.
Enter more than 5 employees in employee.in
while(fin>>employeeid){…your program…..}//end loop
Don’t use any interaction or loop counter.