Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPS120: Introduction to Computer Science

Similar presentations


Presentation on theme: "CPS120: Introduction to Computer Science"— Presentation transcript:

1 CPS120: Introduction to Computer Science
Basic Structure

2 Using Relational Operators
Relational operators provide the tools with which programs make decisions with true and false evaluations == equal to NOTE: this is two equals symbols next to each other, not to be confused with the assignment operator, = > greater than < less than >= greater than or equal to <= less than or equal to != not equal to

3 Using Logical Operators
When complex decisions must be coded into an algorithm, it may be necessary to "chain together" a few relational expressions (that use relational operators) This is done with logical operators (also called Boolean operators.) && is the logical AND operator || is the logical OR operator ! is the logical NOT operator

4 Complete order of operations
The complete order of operations including all of the arithmetic, relational, and logical operators including all of the basic arithmetic, relational, & logical operators is: *, /, % +, - <, >, <=, >=, ==, != ! && ||

5 Decision Making in C++ if statement switch statement
? conditional operator statement goto statement

6 Selection Statements that include if statements and switch statements
Selection statements are sometimes called conditional or decision statements. if (score >= 60) { cout << "I passed" << endl; } else { cout << "I'll do better next time!" << endl; }

7 Structural Review: Types of Statements
sequence selection (if and switch structures) iteration (for and while loops) invocation (functions)

8 Compare and Branch A program can instruct a computer to compare two items and do something based on a match or mismatch which, in turn, redirect the sequence of programming instructions. There are two forms: IF-THEN IF-THEN-ELSE

9 IF-THEN false true Entry Exit True statement a Test condition p

10 Use the “IF” structure Practically all computer languages have some sort of if structure. In C++, the if structure is a one-way selection structure: if (number == 3) { cout << "The value of number is 3"; } IF structures use a control expression to determine if the code in the braces is to be executed or not

11 Compound Conditionals
You must use the AND operator (&&) to form a compound relational expression: if (0 < number && number < 10) { cout << number << " is greater than 0 but less than 10." << endl; }

12 IF-THEN-ELSE Entry Exit Test condition p “true” statement a
false true Entry Exit Test condition p “true” statement a “false” statement a

13 General Form if (test expression) { True-block statements; } else
False-block statements; next statement; if (c= = 'm') { male = male + 1; } else fem = fem +1 ;

14 The If … Else statement Two-way selection structure since either the block of code after the "if" part will be executed or the block of code after the "else" part will be executed but not both The “If" part is executed if the control expression is TRUE while the "else" part is executed if the "if" part is FALSE, guaranteeing one part of the expression to be executed or the other

15 Nested If Statements If structures and if/else statements can be nested within one another in order to model complex decision structures. Use the braces and semicolons properly when coding such structures.

16 General Form if (test condition 1) { // true-block1 statements
} else false-block2 statements; false-block1 statements; if (number % 3 == 0) { // true-block1 statements { cout << number << " is divisible by 3." << endl; if (number % 5 == 0) { cout << number << " is divisible by 3 and 5." << endl; } else { cout << number << " is divisible by 3 but not 5." << endl; } // false-block1 statements cout << number << " is not divisible by 3." << endl; number++

17 Switch Structure The switch structure is a multiple-selection structure that allows even more complicated decision statements than a two-way if/else structure allows. It chooses one of the "cases" depending on the result of the control expression. Only variables with the INT or CHAR data types may be used in the control expressions (i.e. parentheses) of switch statements. Single quotes must be used around CHAR variables Single quotes are NOT used around the integer values Open menuOne.cpp

18 Sample Switch Structure
switch (character_entered) { case ‘A’ : cout << “The character entered was A.\n”; break; case ‘B’: cout << “The character entered was B.\n”; default: cout << “Illegal entry\n”; }

19 Grouping Cases switch (number) { case 1: case 3: case 5: case 7:
cout << number << " is an even number." << endl; break; case 2: case 4: case 6: case 8: cout << number << " is an odd number. " << endl; default: cout << number << " is not a value between or including 1 and 9." << endl; break; }

20 Iterate A program loop is a form of iteration. A computer can be instructed to repeat instructions under certain conditions.

21 Iteration Statements that allow the compiler to return to a point higher in the program in order to continuously repeat one or more statements All loops including while, do/while, and for loops are prime examples of iteration statements while (num < 10) { cout << "hello world" << endl; num = num + 1; }

22 Looping Statements Count-controlled loops
Repeat a specified number of times Use of a special variable called a loop control variable Flow of control of while statement

23 ‘For’ Loops A for loop always executes a specific number of iterations. Use a for loop when you know exactly how many times a set of statements must be repeated A for loop is called a determinant or definite loop because the programmer knows exactly how many times it will iterate

24 Syntax of a for Loop for (initializing expression; control expression; step expression) { // one or more statements } The initializing expression sets the counter variable for the loop to its initial value. The control expression ends the loop at the specified moment. The step expression changes the counter variable Semi-colons, not commas, divide the expressions Example 1: Open simpFor.cpp for (num = 1; num <= 3; num++ ) // the counter variable num is initialized to the value 1 { // the loop will iterate while num is less than or equal to 3 cout << num; // the counter variable num increments by 1 on each iteration cout << endl; } // both statements are executed in the body of the loop on each iteration

25 Things to Remember About For Loops
It is possible to have variable increase by a value other than one for (num = 1; num <= 10; num = num + 3) It is possible to initialize the loop variable within the initializing expression. But I recommend against it Declare loop variables at the top of the function where they belong If an if statement only contains one body statement, the compiler doesn't require the use of curly braces

26 Looping Statements The while statement is used to repeat a course of action Let’s look at two distinct types of repetitions

27 Iteration Control Structures
Iteration control structures are looping mechanisms. Loops repeat an activity until stopped. The location of the stopping mechanism determines how the loop will work: Leading decisions Trailing decisions

28 Leading Decisions If the stop is at the beginning of the iteration, then the control is called a leading decision. The command DO WHILE performs the iteration and places the stop at the beginning.

29 WHILE Loop No Yes Entry Exit Test condition p Loop statement a

30 While Loops A while loop does not necessarily iterate a specified number of times As long as its control expression is true, a while loop will continue to iterate An indeterminate or indefinite loop because only at run-time can it be determined how many times it will iterate While is considered a top-checking loop The control expression is located on the first line of code If the control expression initially evaluates to FALSE, the loop will not execute even once.

31 While Loop Syntax while (control expression) { // one or more statements } The control expression must evaluate to TRUE in order for the while loop to iterate even once Example2 – open whileLoop.cpp: while (num > 100 ) // the control expression is TRUE if the variable num is greater than 100 { cout << num; num = num / 2; // the variable num is reassigned a new value during each iteration }

32 Trailing Decisions If the stop is at the end of the iteration, the control mechanism is called a trailing decision. The command DO UNTIL performs the iteration and puts the stop at the end of the loop.

33 DO WHILE Loop No Yes Entry Test condition p Exit Loop statement a

34 While Loops A while loop does not necessarily iterate a specified number of times As long as its control expression is true, a while loop will continue to iterate An indeterminate or indefinite loop because only at run-time can it be determined how many times it will iterate While is considered a top-checking loop The control expression is located on the first line of code If the control expression initially evaluates to FALSE, the loop will not execute even once.

35 While Loop Syntax while (control expression) { // one or more statements } The control expression must evaluate to TRUE in order for the while loop to iterate even once Example2 – open whileLoop.cpp: while (num > 100 ) // the control expression is TRUE if the variable num is greater than 100 { cout << num; num = num / 2; // the variable num is reassigned a new value during each iteration }

36 Break and Continue Statements
A break statement is used to stop the execution of a loop immediately and to continue by executing the statement that comes directly after the loop A continue statement is used to stop the execution of the statements in the loop's body on that particular iteration and to continue by starting the next iteration of the loop Example 4: Open breakLoop.cpp #include <iostream.h> main() { float num, squared; do cout <<"Enter a number (Enter 0 to quit): "; cin >> num; if (num == 0) { break; } squared = num* num; cout << num << " squared is " << squared << '\n'; } while (1); return 0; Example 5: Open contLoop.cpp int i; for (i = 1; i <= 10; i++ ) if (I == 5) continue; cout << i << '\n'; Return 0;

37 In Summary Loops goto loops -- simple if…then structure for -- fixed number of loops while may never be run while (true) -- always true, needs break do … while -- always run once continue causes while, do… while, and for loops to start over break causes while, do … while, for and switch statements to end

38 Invocation Statements that allow you to place a block of statements that you wish to use several times during a program in one section You then have the ability to "call" those statements whenever you wish to execute them without having to retype the block of statements over and over again within the program In C++, we use "function calls" as invocation statements displayHelloWorld( ); will call (i.e. invoke) the function below void displayHelloWorld() { cout << "hello world" << endl; }

39 Functions

40 Function / Subprogram Statements
We can give a section of code a name and use that name as a statement in another part of the program When the name is encountered, the processing in the other part of the program halts while the named code is executed

41 Subprogram / Function Statements
Subprogram flow of control

42 Subprogram Statements
Subprogram flow of control

43 Functions Every C++ program must have a main function
C++ may also have a number of user-defined functions Each of the smaller tasks (let's say, subtasks) can be coded as C++ functions that go together with the to make up a structured program.

44 Library Functions There are many functions available to C++ programmers which were written by other programmers Use the #include compiler directive at the top of your program to take advantage of these functions. To use the you do not even have to know exactly how they work You do have to know how many arguments to send to the functions and what datatypes to use for those functions.

45 Function Statements There are times when the calling unit needs to give information to the function to use in its processing A parameter list is a list of the identifiers with which the subprogram is to work, along with the types of each identifier placed in parentheses beside the function name

46 Describing a Function The first line of a function is called the function header Before the name of the function you must specify a "return type." The return type is the data type of the value that is returned by the function to the calling function If the function does not return any value, you must type the word void as the return type After the name of the function in the function header, you must include a parameter list. Immediately preceding each parameter, you must identify the data type of that parameter. Sample function header: double computeTax(double myPrice, double myTaxRate)

47 Function Syntax Functions are given valid identifier names, just like variables and constants. A function name must be followed by parentheses Coded functions are placed at the bottom of a C++ program, after the main function. If the functions are listed after the main function, then function prototypes must be included at the top of the program, above the main function An error will definitely result if you call a function from within the main function that has not been prototyped. The function prototypes "warn" the compiler about the eventual use of the prototyped function and allocate memory Example 1: A program with a function: #include <iostream.h> void printMyMessage(int numOfTimes); // Displays a literal a number of times int main( ) { int userInput = 0; cout << "Enter a number between 1 and 10 (0 to Exit): " ; cin >> userInput; if (userInput != 0) printMyMessage (userInput); } else cout << "Thanks, Bye!"; return 0; } // end of main void printMyMessage(int numOfTimes) int i=0; for (i=0; i<= numOfTimes; i++) {cout << "Let's Go State!!" << endl;} } //end of printMyMessage

48 Structure of Functions in C++
function-name(argument list) argument declaration; {  local variable declarations;  executable statement1;  executable statement2;      return (expression); }             

49 An Example of A Function
#include <iostream.h> void printMyMessage(int numOfTimes); // PROTOTYPE and NAME int main( ) { int userInput = 0; cout << "Enter a number between 1 and 10 (0 to Exit): " ; cin >> userInput; if (userInput != 0) printMyMessage (userInput); // CALL STATEMENT WITH ACTUAL PARAMETER } else cout << "Thanks, Bye!"; return 0; } // end of main void printMyMessage(int numOfTimes) // FUNCTION HEADER WITH RETURN TYPE AND // ACTUAL PARAMETER int i=0; // LOCAL VARIABLE WITHIN THE FUNCTION for (i=0; i<= numOfTimes; i++) // BODY {cout << "Let's Go State!!" << endl;} // OF THE } //end of printMyMessage // FUNCTION

50 Passing Data Data is passed to functions as arguments
When a function is "called" by the main function one or more arguments are passed to the function On the receiving end, the function accepts these arguments The variable names of the arguments from the "calling" function do not have to be the same as the names in the "called" function. The data types of the arguments and the parameters should match exactly

51 More About Passing Arguments
There are technically three ways to pass data as arguments to functions passing by value is the preferred method. You simply use a variable name, an actual numeric literal, or an expression in the parentheses of the call statement passing by reference is to be used when you want the function to actually and permanently change the values of one or more variables You must use an ampersand (&) before the formal parameter names in the function header (the first line of the function definition) to denote passing by reference passing by address is technically what happens when you pass an array to a function Pass by Value Example: #include <iostream.h> double addTax(double); int main() { double price = 10.00; double finalPrice = 0.0; finalPrice = addTax(price); cout << "The final price with tax is " << finalPrice << endl; return 0; }// end of main double addTax(double initialPrice) { return (initialPrice + initialPrice * 0.06); }// end of addTax Passed by reference example #include <iostream.h> void addTax(double &); int main() { double price = 10.00; addTax(price); cout << "The final price with tax is " << price << endl; return 0; }// end of main void addTax(double & incomingPrice) { incomingPrice = incomingPrice + incomingPrice * 0.06; }// end of addTax

52 Returning Values If the function is not a void function, there must be a return statement at the end of the function double computeTax(double myPrice, double myTaxRate) { return (myPrice * myTaxRate); }// end of computeTax A slight modification for readability occurs if you use a local variable to first store the computed amount of tax and then return the same value as in: double computeTax(double myPrice, double myTaxRate) { double result = 0.0; result = myPrice * myTaxRate; return result; }// end of computeTax

53 Another Look at Return Values
Often, though, you want your function to return a computed value to the calling function It is not possible in C++ to execute two return statements within a function It is not possible to return two values in the same return statement

54 Scope of Variables The scope of a variable is the area in which it can be legally referenced Variables are either global or local in nature Global variables are ones that are declared outside and above the main function They can be used in any function throughout the program. It is not wise to use global variables any more than you have to. Local variables are ones that are declared inside of a function, including main. They cannot be used or referred to in other functions


Download ppt "CPS120: Introduction to Computer Science"

Similar presentations


Ads by Google