LEC02_notes - 1 14:440:127– Introduction to Computers for...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1 14:440:127– Introduction to Computers for Engineers Notes for Lecture 02 Rutgers University, Spring 2011 1 Instructor - Brenda V. Cortez Introduction In the previous lecture notes, you learned about variables, their data types, the different variety of operators and their functionality, and you also learned how to interact with the user. Those lecture notes also mentioned that when you receive data from the user, it is most likely because the user wants some information back, so in these lectures notes you will be introduce you to concepts you can use to do more than just print a message. An example of a program in which the user wants information back would be the previously mentioned program of the student who wants to know the equivalent letter grade of his/her score. In order to accomplish this task, the program would have to be able to make a decision about the letter grade based on the range in which the student’s score falls. Now consider the case of a professor who wants to know how many students passed the class. He/she would have to be able to repeat (loop) the task of determining the student’s status, based on the student’s score, for however many students there are in the class. 2 Compound Statements & Escape Sequences Compound statements refer to a block of statements that are enclosed within { }. When the program is compiled, the compiler treats this block of statements as a single statement. The main function you have been working with so far, is an example of a compound statement, but you can also have compound statements within the main function. These embedded blocks of code are called nested statements and as you continue to program, you will have to use them in your code. Consider the following example illustrating a nested statement : #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ int age = 21; if (age >= 21){ cout << ‘‘You can legally drink.\n’’; } else cout << ‘‘You shouldn’t be drinking.\n’’; return 0; } 2 NOTE: When printing strings to the screen, you can introduce a new line escape sequence, \n, as I did above, instead of << endl;. This will send your cursor to a new line, so that your cursor does not end up on the same line as the message to the user. Without a newline, the user will be forced to type right after the message, which can get messy, so don’t forget to include a new line after each statement. There are other escape sequences you can use as part of your strings, when needed. Following is a list of those which you may have to use in your programs: \n \’ \" \\ used to introduce a new line, such that your curser will be positioned on the line after your output when you need to have single quote character double quotes character use it if you need to have a backslash character Exercise 1: Write a program that has a three variables, each containing a character from the list above (skip \n). Then print them to the screen as part of the sentence: I can use use ’, ”, or \ in my code. Exercise 2: statement. I am having fun with C++. Write a program that prints the following messages to the screen using a single 3 3 Scope In the lecture notes, you have come across the word scope and what is meant by this in the context of the topics covered in this class, is that some topics cannot be “seen” (covered) in this class (because they are more advanced) and therefore are out of scope. The basic concepts you are learning in this class can be used to develop solutions to simple programming challenges, but in higher-level programming classes, you will learn more complex concepts that will be in the scope of that class. Similarly, in programming, when we talk about a variable’s scope, we are referring to “who” can see that variable and where in the code can the variable be used. So far, you have been creating local variables, which are simply variables declared within a block of code, and are seen only within that particular block - block scope. In other words, you will only be able to access the variable in the block of code in which it is declared. For instance, if you have multiple functions in a single .cpp file, a variable defined inside a function’s block of code will be seen only by the function in which the variable is defined. Variables defined outside the functions’ code blocks will be accessible by all the functions in that program file; these are called global variables. Because of this, global variables are said to have program scope since they can be used by any function defined inside the program file and across all other files (we will not be dealing with multiple file programs in this class). Consider the following example where a global variable with the value of π has been declared, and then used in the main function to calculate the area of a circle with radius r = 3.5. #include <iostream> using namespace std; float pi = 3.14159265; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ float r = 3.5; cout<<‘‘The are of a circle with radius = ’’ << r << ‘‘ is "<< pi*(r*r) << endl; return 0; } NOTE: Redundant parenthesis have been used in the equation expression above to emphasize the operation. This is considered good programming practice because it makes the expressions clearer; so when you are programming, do not hesitate to include redundant parenthesis. As you cans see, even though the variable pi was not declared inside the code block for the function main, it was still accessible within main because it was declared as a global variable - outside the main block. As an important side note regarding global variables, it is not recommended to use them because since they can be used anywhere they are called from, there is also the danger that they can also be changed by any function that calls them. You would not want this to happen in the case of the program shown above, because π has a value that should never be changed. Furthermore, in very large programs with hundreds of lines of code, finding an error of this sort would not be an easy task. In this class, you should not use global variables, and should limit yourself to using local or file scope variables. A file scoped variable is a variable that can only be accessed within the file it is declared in. 4 These type of variables are variables that can only be used within a single program file, and to defined them as such, you need to prefixed them with the keyword static and declare them outside the main code block. Furthermore, these variables can also be accessed by functions within the same file, but not by functions in separate files. If you can imagine a single program file with a few functions, then you should realize that if your variable is being changed incorrectly, you could easily find the error, as opposed to trying to find this error in a multiple-file program using global variables. Consider the following example illustrating the declaration and use of a file-scoped variable: #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs static float pi = 3.14159265; // file scoped variable void area(); // MAIN FUNCTION int main() { area(); return 0; } //FUNCTION void area() { float r = 3.5; cout<<‘‘The are of a circle with radius = ’’ << r << ‘‘ is "<< pi*(r*r) << endl; } NOTE: Variables are destroyed once your program has stopped running. 4 Function Overview Let’s take a closer look at the code above, which not only has the main function, from which the program starts execution, but also has a function call to another function called area, which has been defined in the same .cpp file. You should always take a few minutes to type in the examples, so if you have been doing this, you would noticed that the two previous examples give you the same answer. The only difference is that the later code example makes a function call. The expression area();, found in the main function, is called a function call that stops the processor from executing the current function (main) and allows the execution of the called function, in this case the function area. You yourself may relate to this process. For instance, lecture notes are pretty lengthy and full of examples that you should try, but once in a while you will stop doing this and will take a short break. You will get up and go get a snack, go to the restroom, or check Facebook, and after this break you will come back to continue reading. In the same way, when you call a function from within another function, you are temporarily stopping the function 5 from which you made the call, at the place from which the call was made, so that the called function can execute. When the called function is finished executing, the processor returns to place from which the function was called in the original function and continues executing that function. Likewise, if you stopped reading after this sentence, in this section, you would come back to this section and continue reading from this sentence on (unless you are like me an like to reread paragraphs). Observe that a call to a function means that the function being called will execute and this is why the called function has to finish, before the processor can come back to the calling function and finish executing this function. To illustrate this concept, consider the following program, which calls a function called askUser. The function askUser prompts the user to enter two numbers of data type int and prints a message to the screen telling the user the result of calculating the sum of the two numbers entered. #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs void askUser(); // function declaration // MAIN FUNCTION int main(){ askUser(); return 0; } //FUNCTION void askUser(){ int a, b; cout<<‘‘Enter two numbers: ’’; cin>> a >> b; cout<<‘‘The sum of ’’<< a << ‘‘ + ’’<< b <<‘‘ = ’’<< (a+b) <<endl; } Have you been wondering why the name of the function keeps creeping up at the top of the program file? You should. When you define a function that will be used within a program file (file scope ), you must always include a function declaration at the top of the program file, terminated by a semicolon (;). The basic form of this declaration is: return_type function_name(parameter list); Examples: // with no parameters/arguments void area(); void askUser(); //with one argumet float triangleArea(float radius); // or 6 float triangleArea(float); // with two arguments int add(int num1, int num2); // or int add(int, int); 4.1 Functions Definition Start first with the function header, which similarly to its declaration, includes the return type of the function, the function signature, which is the function name, and the types and identifiers of the arguments it takes enclosed in parenthesis, ( ). In addition to this, it requires the block of code that defines the function itself. The functions defined before, area and askUser, were functions with return type void; this means that nothing is being returned. Also, neither one of the two functions took in any arguments, so the ( ) after their signatures were empty. Here is the basic form: returnType functionName(dataType identifier1, dataType identifier2){ // code to execute when this function is called return variableOfreturnType; } Now let’s consider functions that will return something (int triangleArea()) as opposed to void functions, and functions that take in one or more parameters (int addTwoNums(int, int)). To specify that a function requires (takes in) arguments that will be used in its body, you have to include them within the ( ) after its name - these arguments are collectively known as the parameter list. When writing the function definition (function compound statement), you must include the data type and the identifiers of each of the arguments within the ( ). Consider the following example: // This is the function definition with two arguments of type int // and return type int int add(int x, int y){ // statements to execute when this function is called } Once you have defined a function, you can call the function from within another function in the same file: #include <iostream> using namespace std; int add(int, int); void main(){ int x = 3, y = 5; // don’t forget this if you are using cout or cin // always put this in your programs 7 cout<< x << ‘‘ + ’’<< y << ‘‘ = ’’ << add(x,y) <<endl; return 0; } int add(int x, int y){ int addXY; addXY = x + y; return addXY; } // end function add As a side note, notice that the definition for the add function can be simplified to the following: int add(int x, int y){ return (x + y); } // end function add However, it may be instructional for you to write out the steps in between as I did previously. Exercise 3: Modify the code above, such that you will have additional functions called subtract, multiply, divide and remainder. Call each function from the main function and display the result to the user using the same format shown above. 8 5 Decision Making 5.1 If/Else If Scenario: We want to write the program that will tell a student his/her letter grade based on their numerical score, which they will be prompted to enter. In order for the computer to be able to make this decision, we need to tell it to check whether or not the student’s score meets the criteria of some condition - for instance, being greater than or equal to 90. If it does, then it will be true that the score is greater than or equal to 90, but if the score doesn’t meet the criteria of the condition, then it will be false that the score is greater than or equal to 90. In programming, we can accomplish this task by using if/else statements, which will allow our program to tell the computer to make a decision based on whether a condition evaluates to true or false. The basic skeleton of an if/else statement is the following: if(condition1) some_statements_to_execute_if_condition1_is_true else some_other_statements_that_apply_to_everything_that_makes_condition1_false What if you have more than one condition to check? if(condition1) some_statements_to_execute_if_condition1_is_true statements1 else if(condition2) some_statements_to_execute_if_condition1_is_false_but_condition2_is_true statements2 else if (condition3) ... else statements_that_apply_to_everything_that_makes_all_other_conditions_false statements_for_else The way the if/else statement works is as follows: 1. If condition1 evaluates to true, execute the statements1 2. If condition1 evaluates to false, skip statements1 and check the next condition 3. If condition2 evaluates to true, execute the statements1 4. If condition2 evaluates to false, skip statements2 and check the next condition 5. Continue doing this until a condition evaluates to true, but if no condition evaluates to true, then go to the else part 6. Execute the statements_for_else under else if all previous conditions evaluated to false 9 The conditions that you want to create will be conditions formed with equality operators (== and !=) and relational operators. Some examples are: C++ Relational Operator > < >= <= Equality Operators == != Example Verbal Meaning x>y x is greater than y x<y x is less than y x >= y x is greater than or equal to y x <= y x is less than or equal to y x == y x != y x is equal to y x is not equal to y Now, let’s write the program to determine the letter grade of a student. #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ float gradeNum; char gradeLetter; cout<<‘‘Enter your numerical grade, to see your letter grade: "; cin>>gradeNum; if(gradeNum>=90) cout<<‘‘Your letter grade is a A"<<endl; else if(gradeNum>=80) cout<<‘‘Your letter grade is a B"<<endl; else if(gradeNum>=70) cout<<‘‘Your letter grade is a C"<<endl; else if(gradeNum>=60) cout<<‘‘Your letter grade is a D"<<endl; else cout<<‘‘Your letter grade is an F"<<endl; return 0; } NOTE: The else part of this code will apply to all grades that are less than 60, which means that including the else part handles input that caused all previous conditions to evaluate to false. In the following example, the program is doing the same thing as the one right above, but has nested if/else statements: #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ float gradeNum; char gradeLetter; cout<<‘‘Enter your numerical grade, to see your letter grade: "; 10 cin>>gradeNum; if(gradeNum>=90) cout<<‘‘Your letter grade is a A"<<endl; else if(gradeNum>=80) cout<<‘‘Your letter grade is a B"<<endl; else if(gradeNum>=70) cout<<‘‘Your letter grade is a C"<<endl; else if(gradeNum>=60) cout<<‘‘Your letter grade is a D"<<endl; else cout<<‘‘Your letter grade is an F"<<endl; return 0; } Hopefully it is obvious that the first version is clearer to understand and therefore recommend instead of the second version. When you develop your solutions to the recitation problems, avoid the nested if\else statements, if possible. Exercise 4: Write a program that checks if two integer variables are the same, and if they are, it prints “x equals y”, otherwise if the two integers are not the same, it prints “x is not equal to y”. You can make up the variables. Exercise 5: Write a program that asks the user to enter a number from 0 to 5, and if the user enters a number correctly in this range, it prints “You correctly entered a number from 0 to 5.”, but if it is not in this range it prints “You didn’t enter a number from 0 to 5.” 11 In some other cases, you will want to check if a variable meets the criteria of multiple conditions at a time, before executing a particular set of statements, and in order to evaluate multiple conditions you will need to use logical operators. Consider the following examples: int x = 5; if (x >= 0 && x < 10) cout << ‘‘The number is between 0 and 10.\n’’<<endl; else cout << ‘‘The number is not within the range of 0 to 10.\n’’<<endl; Lets work through the logic of the code above: • x has the value 5 stored in it • if (x is greater than or equal to 0 AND x is less than 10), means that: x is greater than or equal to 0 is TRUE x is less than 10 is TRUE so, TRUE && TRUE = 1 && 1 = 1 therefore, the condition (x >= 0 && x < 10) evaluates to 1 (TRUE) and “The number is between 0 and 10.” is printed to the screen Here is second example. Try to go through each line of code mentally and then go over the logic written below and see if it matches what you thought, as you went through the code. int hrs = 40; if (hrs >= 0 && hrs <= 40) cout << ‘‘You will not get overtime.\n’’; else if (hrs > 40) cout << ‘‘You will get payed for overtime.\n’’; else cout << ‘‘Your hours worked are invalid.\n’’ • hrs has the value 40 stored in it • if (hrs is greater than or equal to 0 AND hrs is less than or equal to 40) means that: hrs is greater than or equal to 0 evaluates to TRUE hrs is less than or equal to 40 evaluates to TRUE so, TRUE && TRUE = 1 && 1 = 1 therefore, the condition (hrs >= 0 && hrs <= 40) evaluates to 1 (TRUE) and “You will not get overtime.” is printed to the screen Exercise 6: Write a program that asks the user for an integer, and returns a message telling the user if the number is not only greater than zero, but if it is also even. You will need to check two conditions at the same time. Hint: use the %. 12 5.2 Conditional Operator The conditional operator is ?:, it takes three operands and works similarly to an if/else statement. The format of a conditional statement is: someVariable = (condition) ? value1 : value2; If you notice, we simply rearranged the previously mentioned skeleton of the if/else statement to get that of a conditional expression. if(condition1) some_statements_to_execute_if_condition1_is_true else some_other_statements_that_apply_to_everything_that_makes_condition1_false Except, you can only check ONE condition. Let’s analyze the format of the conditional statement someVariable = (condition) ? value1 : value2;, 1. if condition evaluates to true, the value1 will be the value of the conditional expression ((condition) ? value1 : value2), 2. but if the condition evaluates to false, then the value2 will be the value of the conditional expression. For example: if (grade >= 60) cout<<‘‘Passed’’<<endl; else cout<<‘‘Failed’’<<endl; would be re-written as follows: (grade >= 60) ? condition cout<<‘‘Passed’’ : value1 cout<<‘‘Failed’’; value2 NOTE: Get used to putting conditions within parenthesis, ( ). This will help you avoid precedence errors. Exercise 7: Given that x = 3 and y = 5, write a conditional statement for each relational and each logical operator calculation, except for the >= operator, which was already illustrated above. If the condition is true, then the value of the conditional expression should be 1, otherwise 0. 13 5.3 Switch Statement Another way in which we can tell our computer to make a decision is by using what is called a switch statement. This type of statement will allow the program to make a selection based on the possible values of a variable, which must be discrete. Consider a situation, where you are asked your age, you would have to give a discrete value for your age, namely an integer. It would be unexpected that you answer: “My age is >15.”, and instead would be expected to reply with: “My age is 19.” - 19 is a discrete value for age. Therefore, when a switch statement checks the possible values of a variable, it is expecting discrete constants and not conditions. Be careful to not make this mistake, since it is a common one. Following is the format of a switch statement : switch (variableName) { case value1: statements_to_execute_if_variableName_has_the_value_value1 break; case value2: statements_to_execute_if_variableName_has_the_value_value2 break; ... case valueN: statements_to_execute_if_variableName_has_the_value_valueN break; default: statements_to_execute_if_variableName_doesn’t_have_of_the_values_listed break; } The valueN case refers to the fact that variableName can have N number of values, which will depend on the problem at hand. The default is included to handle variableName values that are not listed as cases, so the statements under default would be executed if in fact this was the case. Notice that after each case there is a keyword break, which allows the program to break-out of the switch statement when the variableName has the value in that particular case. Another example would be a program that asks the user, a student, to enter their letter grade, so that they could be returned the range in which their letter grade fell. For a problem like this, we would know exactly what the possible values of the letter grade would be and could use a switch statement to make the correct selection. The input from the user would be limited to a few letters, and those possible letter values are: A, B, C, D and F. Anything else would have to be considered as an error. Having done this analysis, and knowing the format of a switch statement, we can implement the solution. #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ // the user’s input will be a char (A, B, C, D, or F) in uppercase/lowecase 14 char gradeLetter; cout<<"Enter your letter grade, to see the range of the grade: "; cin>>gradeLetter; switch (gradeLetter){ case ‘A’: // If gradeLetter is equal to capital letter A case ‘a’: // If gradeLetter is equal to lower case letter a cout<<‘‘You grade is in the range of 90 to 100+."<<endl;break; break; case ‘B’: // If gradeLetter is equal to capital letter B case ‘b’: // If gradeLetter is equal to lower case letter b cout<<‘‘You grade is in the range of 80 to 89."<<endl; break; case ‘C’: // If gradeLetter is equal to capital letter C case ‘c’: // If gradeLetter is equal to lower case letter c cout<<‘‘You grade is in the range of 70 to 79."<<endl; break; case ‘D’: // If gradeLetter is equal to capital letter D case ‘d’: // If gradeLetter is equal to lower case letter d cout<<‘‘You grade is in the range of 60 to 69."<<endl; break; case ‘F’: // If gradeLetter is equal to capital letter F case ‘f’: // If gradeLetter is equal to lower case letter f cout<<‘‘You grade is below 60 - ouch!"<<endl; break; default: // catch all other characters entered by user cout<<‘‘You entered an incorrect letter grade."<<endl; break; } return 0; } NOTE: In the above code, the default case is included to handle all characters entered that do not match any of those in the cases defined. It is a good idea to have a default case that may indicate to the user what went wrong, but if you don’t include it, the program will continue with whatever is after the end of the switch; in the program above, there is nothing, so it would exit. Lets go over the logic in this program assuming that the user entered c: • the variable gradeLetter stores the character c • the program will evaluate the switch statement 15 • first the program checks to see if gradeLetter has the value A or a but it does not, so it checks the next case • now the program checks to see if gradeLetter has the value B or b but it does not, so it moves to the next case • so the program checks if gradeLetter has the value C or c gradeLetter is storing the character c, so it does match the case “Your grade is in the range of 60 to 69.” is printed to the screen the program reaches the break keyword, and it breaks out of the switch statement • the program continues on the line after the switch statement, which in this program is simply the return 0; statement telling program that it has reached the end successfully. Exercise 8: Write a program that asks the user to enter a number from 0 to 5. Then using a switch statement determine the number the user entered. If the user enters a number from 0 to 5, output a message saying: “ You entered ...”, where “...” is the number the user entered. However, if the user enters a number that is not from 0 to 5, send a message to the screen saying: “Your number is not in the range from 0 to 5.”. 16 5.4 Switch Statement to If/Else Statement and Vise Versa So far you have seen how to create programs that allow you to select different options using either an if/else or a switch statement, and in most cases you can go back and forth. Following is an example of an if/else statement and its equivalent switch statement. As you go through each line of the if/else statement code, determine what the variable is, its possible values, and what the default case could be. The following program asks the user to enter two numbers and it also asks the user to enter one of four operation symbols (+, -, *, /). Based on the symbol entered, the program will make the calculation: operand1 operation operand2, and will send the result to the screen. #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ float input1, input2; // why do you think I am using float and not int? char operation; cout << "Enter 2 numbers, separated by a space: "; cin >> input1 >> input2; cout << "What operation would you like to perform (+, -, *, /)? "; cin >> operation; // Check which operation the user wants to perform if (operation == ‘+’) cout<< input1 << ‘+’ << input2 << ‘=’ << input1 + input2 else if (operation == ‘-’) cout<< input1 << ‘-’ << input2 << ‘=’ << input1 - input2 else if (operation == ‘*’) cout<< input1 << ‘*’ << input2 << ‘=’ << input1 * input2 else if (operation == ‘/’) cout<< input1 << ‘/’ << input2 << ‘=’ << input1 / input2 else cout<< "You entered an incorrect operation.\n"; return 0; } << endl; <<endl; <<endl; <<endl; Since the operations are discrete values (+, -, * and /) we can use these as the values of an operation variable to construct an equivalent switch statement. In addition to this, we can defined a default case, so that any operation that doesn’t match +, -, * or / will be handled as an error. Following is the equivalent switch case statement. #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ float input1, input2; // why do you think I am using float and not int? char operation; 17 cout << "Enter 2 numbers, separated by a space: "; cin >> input1 >> input2; cout << "What operation would you like to perform (+, -, *, /)? "; cin >> operation; // Check which operation the user wants to perform switch (operation){ case ’+’: cout<< input1 << ’+’ << input2 << ’=’ << input1 + input2 << endl; break; case ’-’: cout<< input1 << ’-’ << input2 << ’=’ << input1 - input2 <<endl; break; case ’*’: cout<< input1 << ’*’ << input2 << ’=’ << input1 * input2 <<endl; break; case ’/’: cout<< input1 << ’/’ << input2 << ’=’ << input1 / input2 <<endl; break; default: cout<< "You entered an incorrect operation.\n"; break; } return 0; } Whenever you write an if/else or switch statement, try to determine whether you need an else or default in your statement part. It may not always be necessary, but if it is, do not forget it. Also, remember the colon (:) that goes after each case value, the break after each case and the semicolons (;) - incorrect syntax will result in errors. Exercise 9: Transform the if/else statement you created to solve Exercise 8 and transform it to a switch case statement. 18 6 Loops So far you have been able to accomplish the task of telling the student user what his/her letter grade is based on his/her numerical course grade. Now we need to write a program for the Instructor, that can be use to determine how many student scores were entered, the average of the scores and how many students passed the class. You will agree that this program sounds like it is a little more elaborate than the problems you have written solutions for, right? This is in fact the case, and for such problems, it is best that you develop some pseudocode for your algorithm, before attempting to code it. Therefore, let’s go over the definitions of an algorithm and of pseudocode. An algorithm is, according to Wikipedia, “an effective method for solving a problem expressed as a finite sequence of steps.” This definition is closely related to the definition of pseudocode, because Pseudocode is “almost code”, because it only resembles the actual code. At this point in the class you will be writing C++ pseudocode, and later on in the class you will have to write MatLab pseudocode, and both will be “fake code”. Pseudocode helps a programmer to develop an algorithm without worrying about the exact syntax. If I wanted to write the pseudocode for the Instructor’s program, I would write something as follows: Define and set a user counter variable to 0 Define and set a pass counter variable to 0 Define and set a sum variable to 0 While user doesn’t enter 00 prompt user to enter student score if the score is >= 60, add one to the pass counter add student score to sum add one to the user counter Calculate Print the Print the Print the the average using the sum and the counter number of student scores entered - user counter average of the scores number of students that passed the class Using this pseudocode, you would only need to know how to write loops in order to write the actual code that would implement this algorithm pseudocode. C++ provides the programmer with while, do-while, and for statements, which allow the programmer to develop the logic needed by the program to repeat a task. 6.1 While Statement First, think of a few sentences in which the word while is used. Let’s say: 1. while I am hungry, I will continue to eat . 2. while my pizza gets delivered, I will study. 3. while my parents pick me up, I will wait at the student center. 4. I will continue to add the input numbers, while the input numbers are positive. 19 Notice how in each example sentence, something was being done while something else happened. In other words, while the first part of the sentence was true, I would continue to do the second part, and stop as soon as the first part became false. For the most part, this is how you can think of a while loop, which in programming will use the same logic presented here. In the previous pseudocode, you can read the sentence “While user doesn’t enter 00”, which means that as long as this condition, “user entering 00”, is not true, this loop will continue to repeat. Consider the basic form of a C++ while loop: while(condition){ statements_to_execute_if_condition_is_true } So, how would we write a while loop for our Instructor’s program? Well, the condition that we have to check is that the user doesn’t enter 00, right? This means that the condition we need to check is based on the user’s input, so before we can check the condition, we must have the user’s input. Let’s start with that: #include <iostream> using namespace std; int main(){ // Why do you think that studentScore is of type float? float studentScore; // Get score from user and instruct user that the program can be exited cout<<‘‘Enter student score or 00 to quit program: ’’; cin>>studentScore; while(condition){ statements_to_execute_if_condition_is_true } return 0; } Now you have a value stored in studentScore, which you can check to see if it makes the condition evaluate to true or false. The condition has to be written so that it logically makes sense to have the statements within the while-loop repeat. An example of a condition that logically doesn’t make sense is: while(studentScore == 00){ statements_to_execute_if_condition_is_true } Can you see why? Well, if the studentScore is equal to 00 why would we want to loop? On the contrary, if studentScore was in fact equal to zero, then we want the program to stop looping. Therefore, it makes more sense to create a condition that check the opposite: while(studentScore != 00){ statements_to_execute_if_condition_is_true } 20 Now that we have this condition that make logical sense, we can write a compound statement that allows our program to perform the operations described in the pseudocode above. Let’s add this to the previous code block: #include <iostream> using namespace std; int main(){ float studentScore; // Get score from user and instruct user that the program can be exited cout<<‘‘Enter student score or 00 to quit program: ’’; cin>>studentScore; // We don’t want the studentScore to be 00 while(studentScore != 00){ statements_to_execute_if_condition_is_true } return 0; } The condition studentScore != 00 is saying that the input from the user is not equal to 00, and in conjunction with the while-loop, it can be read as “while studentScore is not equal to 00”, do whatever is inside the { }. Now comes the tricky part, because we don’t want to perform some operations once only, instead we also want to repeat those operations until the input is 00. In order to accomplish this, we must have input from the user again and again, and this has to be done inside the loop. Therefore, we must ask the user to enter and a new student score on each iteration (repetition) of the loop, and as soon as the value is 00, the while-loop should stop looping. Let’s start by writing a loop that only prints the studentScore until the user enters 00. #include <iostream> using namespace std; int main(){ float studentScore; // Get score from user and instruct user that the program can be exited cout<<‘‘Enter student score or 00 to quit program: ’’; cin>>studentScore; // We don’t want the studentScore to be 00 while(studentScore != 00){ // Print current score to screen cout<<‘‘You entered: ’’<<studentScore<<endl; // Have user enter a new studentScore cout<<‘‘Enter student score or 00 to quit program: ’’; cin>>studentScore; // Using this new studentScore, the while-loop condition is re-evaluated } return 0; } 21 NOTE: When writing a loop, the condition being checked will rely on the value of a variable so, it is very important that your program changes/updates/increments the value of this variable within your loop’s code. If you fail to do this, your loop will never stop and will continue of forever - this is known as an infinite loop. Therefore, before you execute your code, always check that the variable in the loop condition is not the same after the first execution (iteration) of your loop. You should have noticed that this code works just like we wanted and expected it, so we can move on to performing the calculations described in the pseudocode. However, it should be clear that these calculations must be done before the user is asked for a new studentScore, right? Your wouldn’t want to ask the user for a new input, until you had manipulated the data as you needed. Ok, so let’s implement this idea: #include <iostream> using namespace std; int main(){ float studentScore; float studentCount = 0.0; float sum = 0.0; int passed = 0; // Get score from user and instruct user that the program can be exited cout<<‘‘Enter student score or 00 to quit program: ’’; cin>>studentScore; // We don’t want the studentScore to be 00 while(studentScore != 00){ // Print current score to screen cout<<‘‘You entered: ’’<<studentScore<<endl; // BEFORE asking user for new studentScore // Increment the studentCount studentCount = studentCount++; // Remember that ++ adds one to the variable // Add studentScore to the sum sum = sum + studentScore; // Determine if student passed the class and keep track of this if(studentScore >= 60){ passed = passed++; } // Have user enter a new studentScore cout<<‘‘Enter student score or 00 to quit program: ’’; cin>>studentScore; // Using this new studentScore, the while-loop condition is re-evaluated } // AFTER while-loop is exited cout<<‘‘You entered ’’<<studentCount<<‘‘ scores.’’<<endl; 22 cout<<‘‘The average is ’’<<(sum/studentCount)<<‘‘.’’<<endl; cout<<passed<<‘‘ students passed the class.’’<<endl; return 0; } The previous pseudocode algorithm has been successfully implemented using a while-loop, so let’s take a look at a very useful application of while-loops before moving on. In many occasions, you will want to make sure that the user enters data within some valid range, and before you can move on to manipulating data, you will need to validate the data. For instance, if you run the previous program and enter negative numbers for scores, which are invalid, the program will not tell you it is wrong, so the results will also be wrong. You can use a while-loop to validate the input, and following is the the code for validating the studentScore: // Validate the user’s input while(studentScore < 0){ cout<<‘‘You can’t enter negative scores - they are invalid.’’<<endl; cout<<‘‘Enter student score or 00 to quit program: ’’; cin>>studentScore; } Where do you think this code would have to be placed? If your answer was: “right after the code that asks the user to enter the a studentScore”, you are correct! Before you can move on with any calculation, and for that matter the while-loop that repeats those calculations, you must check to see that the input data is valid - that it makes sense. If you think logically about what this program should be doing, you will realize that the validation needs to be done not only after the first time the user is asked for input, but also inside the while-loop, after the calculations, when the user is asked to enter a new value. In general, there are three steps you need to remember when writing a loop: 1. Initialize the variable that will control the loop. 2. Use this control variable in the while-loop condition. 3. Update/change/increment the value of the control variable on each loop iteration. Exercise 10: Go back to “Notes for Lecture 01” and review how to do type-check, by doing a type-check for the previous program. 23 Exercise 11: Using your knowledge of while-loops, write a program that asks the users to enter integers from 0 to 100 and add them. Your loop should stop when the user enters an integer out of range. When the loop is done executing, print the total of integers that were entered and the sum of those integers. 6.2 Do-While Statement You have seen the implementation of a pseudocode algorithm using a while-loop, so it should not be too difficult to see that the do-while loop is very similar. The difference between the while-loop and the do-while-loop is that the condition for the do-while-loop is at the end of its compounded statements, as opposed to the beginning and that it has to be terminated by a semicolon (;). do { statements_will_execute_at_least_once }while(condition); This structure allows the statements in the { } to execute at least once, since the condition is not checked until after. At that point, if the condition is false, the loop will stop, but the statements will have executed once. To illustrate the use of the do-while-loop, take a look at the following example: #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ int counter = 0; do { counter += 2; cout<<counter<<endl; }while(counter < 50); return 0; } 24 Notice that at the beginning of the program an integer counter is declared and initialized to zero. Then inside the do-while-loop, this counter is incremented by 2 and this value is printed to the screen. Suppose the condition was counter < 1; this would cause the statements in the loop to execute and a 2 would still be printed to the screen, but when the condition is checked, since counter has a value of 2, the condition would evaluate to false. This would stop the loop and the program would continue with the following statements in the program, i.e. return 0;. However, the condition is counter < 50, so this will check counter, which has a value of 2 on the first iteration, so the condition would evaluate to true and the loop will iterate once again. On the second iteration, counter is incremented by 2, so it would not have a value of 2 stored in it, but instead a 4. This value would be printed and the same process would be repeated until the counter reaches a value of 50. After 50 is printed to the screen, the condition is checked and it evaluates to false, since 50 is not < 50. This stops the loop and the program is exited. Exercise 12: What would happen if the condition was counter <= 50? Explain. The following example of a do-while-loop simply prints numbers from 0 to the number entered by the user. For instance, if the user enters 5, the program will print 1 2 3 4 5 to the screen. #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ int num, initialVal = 1;; cout<<"This program prints numbers from 1 to the number you want.\n"; cout<<"Up to what number would you like to print? "; cin>>num; // Validate input while(num < 0){ cout<<"Enter non-negative integers.\n"; cout<<"Up to what number would you like to print? "; cin>>num; } // Now input should be validated do { cout<<initialVal<<" "; initialVal++; }while(initialVal <= num); 25 cout<<endl; return 0; } This is a sample output: This program prints numbers ranging from 1 to the number you want. Up to what number would you like to print? 5 12345 Notice how I used a while-loop to validate the input before I did anything else. You are encourage you to go line by line and assuming the user entered the number 5, work out every single line of this code to ensure that you understand what is happening. Exercise 13: Modify the code above, so that there is no user input and you are printing numbers from 1 to 10. 6.3 For Statement The best time to use a while-loop or do-while-loop is when you have a condition you can check, but you do not know how many iterations the loop will have to make. However, there will be times when you will need to perform a calculation a discrete number of times, and for these type of problems you will want to use a for-loop. Following is the format of a C++ for-loop, which differs from the while/do-while loops in that it’s counter-controlled repetition details are all in a single line. for(initialization; condition; increment){ statements_to_execute_on_each_iteration } Remember that in the while-loop section your were told to follow three steps when writing a loop? Well, those steps can be applied to a for-loop as well, and as a matter of fact you could go back and forth between a for-loop and a while-loop, so make sure you know those steps. 26 As you can see in the for-loop format shown above, you must initialize a control variable, defined the controlling condition, and increment the control variable. The control variable will be a counter that will tell the computer to execute this block of code however many times are specified in the condition. Here is an example of a for-loop: for(int count = 1; count <= 99; count += 2){ statements_to_execute_on_each_iteration_of_for_loop } Let’s look at each part: • the initialization is accomplished by int count = 1, which declares a variable named count and assigns 1 to it • the condition is count <= 99, which means that this loop will continue to iterate as long as this condition is true, that is, that count is <= 99 • the third part, the increment, is defined by count += 2, so that on each iteration the variable count is incremented by 2. Remember that when working with loops you must update/change/increment the variable in the controlling condition or you will end up with an infinite loop. Using this information, suppose you have to write a program that uses a for-loop to determine and print all the number from 100 to 1 that are divisible by 5. First, write some pseudocode: Initialize a variable counter to one hundred Iterate until the counter is greater or equal to one On each iteration decrement the counter by one Determine if the counter is divisible by five - if the modulus of counter and five is zero, then the counter must be divisible by five Print those numbers that are divisible by 5 Now let’s implement the pseudocode algorithm using the above C++ concepts: #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ // Initialize counter variable // Define condition // Decrement counter by one for(int counter = 100; counter >= 1; counter--){ // Determine if counter is divisible by 5 and print it if it is if((counter % 5) == 0) cout<<counter<<endl; } } 27 As you can see, not only can you increment, but you can also decrement your counter variable in the for-loop header. Exercise 14: Write a for-loop header to vary a control variable k from 1 to 100 in increments of 1. Exercise 15: Write a for-loop header to vary a control variable k from 100 down to 1 in increments of -1. Exercise 16: Write a for-loop header to vary a control variable k from 7 to 77 in steps/increments of 7. Exercise 17: Write a for-loop header to vary a control variable k from 30 down to 3 in steps of -3. Exercise 18: Write a for-loop header to vary a control variable k over the following sequence of values: 2, 5, 8, 11, 14, 17, 20. Exercise 19: Write a for-loop header to vary a control variable k over the following sequence of values: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0. 6.4 From While-Loop to For-Loop & Vise Versa It was briefly mentioned earlier that you could rewrite a while-loop (while statement) as a for-loop (for statement), and here is how to do it. First, consider the while-loop code below: #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ int k = 1; while(k <= 10){ cout << k << endl; k++; } return 0; } 28 This simple program begins by initializing a variable, of type int, to 1. This this the variable that is used to create the condition that controls the while-loop. Once the value of k is printed to the screen on each iteration, the value in k is incremented by one. At some point the value stored in k will make the condition k <= 10 evaluate to false. When this happens, the program exist the loop and exits the program since return 0; is the next statement in the code. Now think how you would transform this to a for-loop. Let’s restate the format of a for-loop: for(initialization; condition; increment){ statements_to_execute_on_each_iteration } Let’s break it up into parts and assign the while-loop equivalent: 1. initialization is k = 1 2. condtion is k <= 10 3. increment is k++ Having identified the equivalent parts to a for-loop, consider the following equivalent code for the above while-loop: #include <iostream> using namespace std; // don’t forget this if you are using cout or cin // always put this in your programs int main(){ for(int k = 1; k <= 10; k++){ cout << k << endl; } return 0; } Exercise 20: What is the output of the following code? Rewrite it as a while-loop and verify that you get the same answers. int sum for(int sum } cout << = 0; count = 1; count <= 50; count += 2){ += count; sum << endl; ...
View Full Document

Ask a homework question - tutors are online