Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Statements and Functions

Similar presentations


Presentation on theme: "C++ Statements and Functions"— Presentation transcript:

1 C++ Statements and Functions
B.Ramamurthy CS114B 12/31/2018 BR

2 Selection Control structure
In many applications, choices are to be made depending on some conditions related to the problem. Selection or decision structures are used to model such situations. C++ supports the implementation of “selection” through the “if” and “switch” statements. 12/31/2018 BR

3 Boolean expressions Any expression (variable) that evaluates to TRUE or FALSE is a Boolean expression (variable). example: bool Raining; Boolean expression can be formed using logic operators (AND, OR , NOT) and/or relational operators used for comparison. 12/31/2018 BR

4 Logical Operators These are also known as Boolean operators.
Operator Meaning && logical AND , conjunction || logical OR, disjunction ! negation Example: bool WipersOn, Dark, HeadLightsOn; // input current conditions into WipersOn, Dark HeadLightsOn = WipersOn || Dark; 12/31/2018 BR

5 Logical expressions bool OnProbation, OutOfSchool, BackInSchool;
float GPA; /* if OnProbation and GPA < 2.0 then OutOf School is TRUE else OutOfSchool is FALSE*/ /* if OnProbation and GPA >= 2.0 then BackInSchool is TRUE else BackInSchool is FALSE*/ OutOfSchool = OnProbation && (GPA < 2.0); BackInSchool = OnProbation && ( GPA >= 2.0); /*Actually OutOfSchool is the negation of BackInSchool */ 12/31/2018 BR

6 “if” statement Syntax: if (condition) Statements for condition True
else Statements for condition False Semantics: If the condition evaluates to TRUE then execute the statements “statements for condition True”. If the condition evaluates to FALSE then execute the statements “statements for condition False”. After the execution of either continue on to the next statement after the “if” 12/31/2018 BR

7 Multi-condition selection
Some applications require multi-level decision making and some multi-way decisions. A multi-level choice is usually implemented using nested-if and the multi-way, using the “switch” which we will discuss later. Problem: Find the largest of a set of three distinct integers. 12/31/2018 BR

8 Nested if Let the integers be N1, N2 and N3. if ( N1 > N2)
Largest = N1; else /* ASSERT : N3 > N1 and N1 > N2 */ Largest = N3; else /* ASSERT : N2 > N1 */ if (N2 > N3) Largest = N2; else /* ASSERT : N3 > N2 and N2 > N1 */ 12/31/2018 BR

9 Switch ... syntax switch (selector) { case label1: statements1; break;
..... case labeln : statementsn; default : statementsd; } 12/31/2018 BR

10 switch ... semantics Switch statement is used when there are more two alternatives to select from.. selector is an ordinal expression: That means that the values it can take should be finite, countable: integer, char, bool types are acceptable but not float. The selector type and case label type should be same. Each case label must be distinct. The selector expression is evaluated and compared to each of the case labels. If the value of the selector is one of the case labels, say label x, then the statementsx is executed. 12/31/2018 BR

11 switch ... semantics Execution continues on until a break statement is encountered. At this point, control is transferred to the next statement after the switch. If the selector value matches none of the labels, the default statements are executed, if one is provided. Though default provision is optional, it is a good programming practice to always have a default clause. 12/31/2018 BR

12 switch ... Example Problem: Write a switch statement to print out the grade points corresponding to the letter grades “A”, “B” , “C”, “D”, and “F”. switch (letter) { case ‘A’ : points = 4.0; break; case ‘B’ : points = 3.0; case ‘C’ : points = 2.0; break; case ‘D’ : points = 1.0; break; case ‘F’ : points = 0.0; break; default : cout << “error in grade” << endl; } cout << points << endl; 12/31/2018 BR

13 Control structures Selection: if, if … else, switch
Selection is used to implement “mutual exclusion”; when selective execution of a piece of code is needed. Iteration : while, for, do..while Iteration is used when repeated execution of a piece of code is needed. 12/31/2018 B. Ramamurthy

14 Arrays An array is a collection of elements of the same type.
Good programming practice: always define a new type of the array type needed in your application. Example: This illustrates typedef and arrays: const int NumDays = 31; typedef int MonthAray [NumDays]; Usage : MonthAray ThisMonth, NextMonth; 12/31/2018 B. Ramamurthy

15 Multi-dimensional arrays
typedef int arraytype [2][3]; // is this stylish? or const int NumRow = 2; const int NumCol = 3; typedef int ArrayType [NumRow][NumCol]; // or is this? Usage with initialization: ArrayType X = {2,3,4,5}; Reference : X[1][2] = X[1][2] + X[1][1]; 12/31/2018 B. Ramamurthy

16 Strings string is a special type of array: an array of characters terminated by a null or ‘\0’ Standard library string.h provides functions that can be used with string data type. Some of the functions: strcpy, strcmp, strcat Strings can be input and output using the regular cin and cout respectively. You can declare string type and variables as follows: const int MAX_LEN = 30; typedef char string [MAX_LEN + 1]; Usage: string Name; 12/31/2018 B. Ramamurthy

17 Structures struct is a collection of elements not necessarily of the same type. Good programming practice: create a new type for struct using typedef. typedef struct PersonType { string Name; int Age; float GPA; }; persontype Student; 12/31/2018 B. Ramamurthy

18 File IO Six steps in using File IO: 1. #include <fstream.h>
2. Instantiate an object of type needed: ifstream InFile; ofstream OutFile; 3. Open and attach the file object with appropriate mode. Infile.open(“Bank.dat”, ios::in); OutFile.open(“Bank.report”, ios::out); 12/31/2018 B. Ramamurthy

19 File IO (contd.) 4. Make sure the “open” worked fine by using fail predicate function: if (InFile.fail()) {cout<< “Error in file opening\n”; return 1;} 5. Use the file just like you used cin and cout. InFile >>.. OutFile << … 6. Close files when done using: Infile.close(); OutFile.close(); 12/31/2018 B. Ramamurthy

20 Input, Output using iostream
stream is a sequence of characters associated with an IO device. ios isa ostream istream ofstream iostream ifstream fstream class hierarchy of streams. 12/31/2018 B. Ramamurthy

21 Avoiding multiple inclusion
Enclose your header files with these directives: #ifndef unique_symbol #define unique_symbol header file contents #endif By convention, the unique_symbol is uppercase of file name inter-spaced with underscores. 12/31/2018 B. Ramamurthy

22 Function prototype, definition and call
Defines: 1) Header 2) Formal parameter names and types 3) Statements to be executed 4) Return statement(s) Specifies: 1) Name of the function 2) The actual parameters Tells compiler: 1) function return type 2) Name of the function 3) Number of the parameters 4) Types of the parameters 5) Order of the parameters 12/31/2018 BR

23 Sample Design Prototypes: void GetInput (int &, int &, int &);
: Average three integers. MAIN N1,N2,N3 N1,N2,N3 AVG AVG GetInput Average OutputAvg Prototypes: void GetInput (int &, int &, int &); float Average (int , int, int); void OutputAvg (int); 12/31/2018 BR

24 Function prototype Translates design into a blueprint for function definition. Syntax: return_type Func_name (parameter_type_list); Where to declare a prototype? Choice 1: Outside main or in a header file. Choice 2: For every func X called from func Y, then declare the prototype for func X inside Func Y. This truly reflects the design. Also this makes easier the transition to OOP. 12/31/2018 BR

25 Parameters SampleFunc Prototype 1: int SampleFunc (int, int &);
Function header: int SampleFunc (int P1, int & P2) ==================================== Prototype 2: void SampleFunc (int, int &, int &); Function header: void SampleFunc (int P1, int & P2, int & P3) 12/31/2018 BR

26 Types of functions Functions Library User-defined Language-defined
Examples GetInput abs , type casting sqrt from of Demo functions int, float math library See Appen.B 12/31/2018 BR

27 Why OO Design? Main FN1 FN2 FN3 Small Problem:
Solution: Functional decomposition Top-down Design Functions (Objects/Data) 12/31/2018 BR

28 Why OO Design? Now consider a large problem with top-down design
as shown. Solution: OO Design Principle: Identify Objects Associate functions Object (functions) main 12/31/2018 BR

29 From problem to OO solution
Identify the objects (“nouns”) in the problem. Define and implement classes to represent the objects. Class name Data members : public, private Function members (methods) Service functions (usually public) Utility functions (usually private) Predicate functions. Example: warnings, status indicators, error indicators, etc. Write a driver/controller that carries out the interaction among the objects. 12/31/2018 Ramamurthy

30 Summary Executable Preparation
Control structures: Selection, Repetition Function prototype, definition and call. Parameter passing. Using library function. Why Object-Oriented Design? 12/31/2018 BR


Download ppt "C++ Statements and Functions"

Similar presentations


Ads by Google