TK2053_pp_04 2.pdf
Document Details
Uploaded by SimplerMaroon
Universiti Kebangsaan Malaysia
Tags
Full Transcript
Programing Paradigm TK 2053 Object Oriented Paradigm DR. WANDEEP KAUR [email protected] Block A, Level 1 COURSE STRUCTURE Coursework, Assessments & Week Topic...
Programing Paradigm TK 2053 Object Oriented Paradigm DR. WANDEEP KAUR [email protected] Block A, Level 1 COURSE STRUCTURE Coursework, Assessments & Week Topic Deliverables 1/5/2024 PUBLIC HOLIDAY (NO LECTURE + NO LAB) 8/5/2024 Introduction to Imperative Paradigm NO LAB 15/5/2024 Advanced Imperative Paradigm Weekly Lab Task: C (5%) 20/5/2024 MINGGU CABARAN DIGITAL (NO LECTURE + NO LAB) 29/5/2024 Advanced Imperative Paradigm (2) Weekly Lab Task: C (5%) 5/6/2024 Object-Oriented Paradigm Poster Presentation - Upload VIDEO ONLY to UKMFolio by 7 June 2024 (5PM) 12/6/2024 REVISION Lab Test (during Lab sessions) Date: 11/12/13 June 2024 Duration: 2 hours July 1 – July 21 FINAL EXAM 2 Recap Lecture 4 Types Arrays Pointers → 1D → pointer as value → 2D → pointer as address → Multidimensional → changing values of pointers S W Arrays & Pointers Passing arrays to functions Function & Pointers Dynamic Memory Allocation Strings Structures O T → Intialization, declaration → declaring structures → accessing structures → Pointers using string → typedef Function & Struct fgets(), puts() Unions 3 AGENDA FOR THE DAY First Second Last THE J BROTHERS Java Recap Core Principles of OOP 4 java beanies 5 HELLO WORLD! ______________________________________________________________________________________________________________________________________________________________________ 6 THE J BROTHERS (JVM JRE JDK) ______________________________________________________________________________________________________________________________________________________________________ 7 THE J BROTHERS (JVM JRE JDK) ______________________________________________________________________________________________________________________________________________________________________ 8 THE J BROTHERS (JVM JRE JDK) ______________________________________________________________________________________________________________________________________________________________________ 9 show me the inheritance 10 Inheritance ______________________________________________________________________________________________________________________________________________________________________ 11 Inheritance In the example, we have derived a subclass Dog from superclass Animal. Notice the statements, Here, labrador is an object of Dog. However, name and eat() are the members of the Animal class. Since Dog inherits the field and method from Animal, we are able to access the field and method using the object of the Dog. 12 Inheritance ______________________________________________________________________________________________________________________________________________________________________ 13 Inheritance ______________________________________________________________________________________________________________________________________________________________________ In the previous example, we see the object of the subclass can access the method of the superclass. However, if the same method is present in both the superclass and subclass, what will happen? In this case, the method in the subclass overrides the method in the superclass. This concept is known as method overriding in Java. 14 In the example, the eat() method is present in both the superclass Animal and the subclass Dog. Here, we have created an object labrador of Dog. Now when we call eat() using the object labrador, the method inside Dog is called. This is because the method inside the derived class overrides the method inside the base class. This is called method overriding. 15 Inheritance ______________________________________________________________________________________________________________________________________________________________________ 16 Types of Inheritance ______________________________________________________________________________________________________________________________________________________________________ Single Inheritance In single inheritance, a single subclass extends from a single superclass 17 Types of Inheritance ______________________________________________________________________________________________________________________________________________________________________ Multilevel Inheritance In multilevel inheritance, a subclass extends from a superclass and then the same subclass acts as a superclass for another class 18 Types of Inheritance ______________________________________________________________________________________________________________________________________________________________________ Hierarchical Inheritance In hierarchical inheritance, multiple subclasses extend from a single superclass 19 Types of Inheritance ______________________________________________________________________________________________________________________________________________________________________ Multiple Inheritance In multiple inheritance, a single subclass extends from multiple superclasses Note: Java doesn't support multiple inheritance. However, we can achieve multiple inheritance using interfaces. 20 Types of Inheritance ______________________________________________________________________________________________________________________________________________________________________ Hybrid Inheritance Hybrid inheritance is a combination of two or more types of inheritance 21 overriding 22 Method Overiding ______________________________________________________________________________________________________________________________________________________________________ In the program, the displayInfo() method is present in both the Animal superclass and the Dog subclass. When we call displayInfo() using the d1 object (object of the subclass), the method inside the subclass Dog is called. The displayInfo() method of the subclass overrides the same method of the superclass. 23 Method Overiding ______________________________________________________________________________________________________________________________________________________________________ 24 abstraction obsession 25 Java abstraction ______________________________________________________________________________________________________________________________________________________________________ 26 Java abstracti _________________________________________________________________ In the above example, we have created an abstract super class MotorBike. The superclass MotorBike has an abstract method brake(). The brake() method cannot be implemented inside MotorBike. It is because every bike has different implementation of brakes. So, all the subclasses of MotorBike would have different implementation of brake(). So, the implementation of brake() in MotorBike is kept hidden. Here, MountainBike makes its own implementation of brake() and SportsBike makes its own implementation of brake(). 27 in ter face 28 Java interface ______________________________________________________________________________________________________________________________________________________________________ 29 Implementing interface ______________________________________________________________________________________________________________________________________________________________________ In the example, we have created an interface named Polygon. The interface contains an abstract method getArea(). Here, the Rectangle class implements Polygon. And, provides the implementation of the getArea() method. 30 Advantages of interface ______________________________________________________________________________________________________________________________________________________________________ 31 all the -ism polymorphism 32 Java polymorphism ______________________________________________________________________________________________________________________________________________________________________ In the example, we have created a superclass: Polygon and two subclasses: Square and Circle. Notice the use of the render() method. The main purpose of the render() method is to render the shape. However, the process of rendering a square is different than the process of rendering a circle. Hence, the render() method behaves differently in different classes. Or, we can say render() is polymorphic. 33 Java polymorphism ______________________________________________________________________________________________________________________________________________________________________ 34 Java polymorphism ______________________________________________________________________________________________________________________________________________________________________ 35 Method Overiding ______________________________________________________________________________________________________________________________________________________________________ During inheritance in Java, if the same method is present in both the superclass and the subclass. Then, the method in the subclass overrides the same method in the superclass. This is called method overriding. In this case, the same method will perform one operation in the superclass and another operation in the subclass. 36 Method Overiding In the example, we have created a superclass named Language and a subclass named Java. Here, the method displayInfo() is present in both Language and Java. The use of displayInfo() is to print the information. However, it is printing different information in Language and Java. Based on the object used to call the method, the corresponding information is printed. Note: The method that is called is determined during the execution of the program. Hence, method overriding is a run- time polymorphism. 37 Method Overiding ______________________________________________________________________________________________________________________________________________________________________ 38 Method Overiding ______________________________________________________________________________________________________________________________________________________________________ 39 breaking open encapsulation 40 Java Encapsulation ______________________________________________________________________________________________________________________________________________________________________ 41 In the example, we have created a class named Area. The main purpose of this class is to calculate the area. To calculate an area, we need two variables: length and breadth and a method: getArea(). Hence, we bundled these fields and methods inside a single class. Here, the fields and methods can be accessed from other classes as well. Hence, this is not data hiding. This is only encapsulation. We are just keeping similar codes together. Note: People often consider encapsulation as data hiding, but that's not entirely true. Encapsulation refers to the bundling of related fields and methods together. This can be used to achieve data hiding. Encapsulation in itself is not data hiding. 42 Why Encapsulation? ______________________________________________________________________________________________________________________________________________________________________ 1. In Java, encapsulation helps us to keep related fields and methods together, which makes our code cleaner and easy to read. 2. It helps to control the values of our data fields. Here, we are making the age variable private and applying logic inside the setAge() method. Now, age cannot be negative. 43 OOP chronicles (P1) 44 Java Class and Objects ______________________________________________________________________________________________________________________________________________________________________ 45 Java Class and Objects ______________________________________________________________________________________________________________________________________________________________________ 46 Create a class in Java ______________________________________________________________________________________________________________________________________________________________________ 47 Java Objects ______________________________________________________________________________________________________________________________________________________________________ 48 Java Methods ______________________________________________________________________________________________________________________________________________________________________ 49 Declaring a Java Method ______________________________________________________________________________________________________________________________________________________________________ 50 Calling a Method in Java ______________________________________________________________________________________________________________________________________________________________________ 51 Java Method Return Type ______________________________________________________________________________________________________________________________________________________________________ 52 Method Parameters in Java ______________________________________________________________________________________________________________________________________________________________________ 53 Standard Library Methods ______________________________________________________________________________________________________________________________________________________________________ 54 Advantages of using methods ______________________________________________________________________________________________________________________________________________________________________ 55 Method Overloading ______________________________________________________________________________________________________________________________________________________________________ 56 Method Overloading ______________________________________________________________________________________________________________________________________________________________________ 57 How to perform method overloading in Java? ______________________________________________________________________________________________________________________________________________________________________ 58 How to perform method overloading in Java? ______________________________________________________________________________________________________________________________________________________________________ 59 How to perform method overloading in Java? ______________________________________________________________________________________________________________________________________________________________________ 60 Java Constructors ______________________________________________________________________________________________________________________________________________________________________ 61 Java Constructor ______________________________________________________________________________________________________________________________________________________________________ 62 Java Constructors : No-Arg Constructors ______________________________________________________________________________________________________________________________________________________________________ 63 Java Constructors : No Arg ______________________________________________________________________________________________________________________________________________________________________ 64 Java Constructors : Parameterized Constructor ______________________________________________________________________________________________________________________________________________________________________ 65 Java Constructors : Default Constructor ______________________________________________________________________________________________________________________________________________________________________ 66 Java Constructors : Default Constructor ______________________________________________________________________________________________________________________________________________________________________ 67 Java Constructors : Important Notes ______________________________________________________________________________________________________________________________________________________________________ 68 Constructors Overloading in Java ______________________________________________________________________________________________________________________________________________________________________ In this example, we have two constructors: Main() Main(String language). Here, both the constructor initialize the value of the variable language with different values. Based on the parameter passed during object creation, different constructors are called, and different values are assigned. It is also possible to call one constructor from another constructor. 69 Methods vs Constructors ______________________________________________________________________________________________________________________________________________________________________ To summarize: Methods are used to perform specific tasks and can be called multiple times from different parts of the program. Constructors are special methods used to create and initialize objects of a class, and they are called when the object is being created. Methods can have a return type, while constructors do not have a return type. Methods have any name you choose, while constructors have the same name as the class they belong to. 70 Java Strings ______________________________________________________________________________________________________________________________________________________________________ 71 Java Strings ______________________________________________________________________________________________________________________________________________________________________ 72 Java String Operations ______________________________________________________________________________________________________________________________________________________________________ 73 Java String Operations ______________________________________________________________________________________________________________________________________________________________________ 74 Java String Operations ______________________________________________________________________________________________________________________________________________________________________ 75 LAB FORMAT Q1 : PYTHON (5%) Q2 : C PROGRAMMING (5%) Q3 : PYTHON AND C PROGRAMMING (20%) TOTAL = 3 Qs BUT Answer scripts = 4 Total 2 hours 76 Summary Lecture 4 Intro to Java Java Flow Control → JVM → if → JRE → for → JDK → while / do while S W → break / continue OOP concepts (P1) O T → java class / objects → java methods → method overloading Java array → constructor → constructor overloading → Intialization, declaration → strings 77 Thanks! Any questions? 78 Programing Paradigm TK 2053 C Programming DR. WANDEEP KAUR [email protected] Block A, Level 2 COURSE STRUCTURE Coursework, Assessments & Week Topic Deliverables 10/5/2023 Introduction to Imperative Paradigm 17/5/2023 Mid Sem Break 24/5/2023 Advanced Imperative Paradigm 31/5/2023 Advanced Imperative Paradigm (cont) Lab01 Submission: C 7/6/2023 Minggu Cabaran Digital 14/6/2023 Introduction to Object Oriented Paradigm Lab02 Submission: C 21/6/2023 Advanced Object Oriented Paradigm Revision (Asynchronous) Recap (scripting, imperative and object oriented paradigm) 28/6/2023 Lab Exam & Poster Presentation July 17 – Aug 4 FINAL EXAM 2 Recap Lecture 2 If, If…Else, Nested If, If Ladder Break, continue For, While, Do…While Switch, Goto Types of functions → Standard Library Functions → User defined functions Recursion Storage → Local, Global, Static variables Call by Value, Call by Reference 3 AGENDA FOR THE DAY First Second Last Arrays Pointers Recap Strings Structures Unions 4 a ray of arrays 5 An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it. int data ; 6 7 8 Suppose the starting address of My Array is 2120d. Then, the address of the My Array will be 2122d. Similarly, the address of My Array will be 2124d and so on. This is because the size of a int is 2 bytes. 9 ARRAY DECLARATION _ 10 ARRAY INITIALIZATION _ 11 CHANGE VALUE OF ARRAY ELEMENT_ 12 INPUT AND OUTPUT ARRAY ELEMENT_ 13 Example: Array Input/Output _ 14 Example: Calculate Average _ 15 IMPORTANT NOTE! 16 17 18 19 20 21 22 23 24 PASSING ARRAYS TO FUNCTION _ OUTPUT? 25 PASSING ARRAYS TO FUNCTION _ OUTPUT? 26 PASSING ARRAYS TO FUNCTION _ 27 PASSING MULTIDIMENSIONAL ARRAYS TO FUNCTION _ 28 ring the strings 29 C PROGRAMMING STRINGS _ 30 STRING DECLARATION _ 31 STRING INITIALIZATION _ 32 STRING INITIALIZATION _ 33 ASSIGNING VALUE FOR STRINGS _ 34 Strcpy() 35 Example strcpy() Note: When you use strcpy(), the size of the destination string should be large enough to store the copied string. Otherwise, it may result in undefined behavior. 36 READING STRING FROM USER _ Enter name: Wonder Woman Your name is Wonder. WHY??? 37 PASSING STRING TO FUNCTION _ Strings can be passed to a function in a similar way as arrays 38 STRING AND POINTERS _ Similar like arrays, string names are "decayed" to pointers. Hence, you can use pointers to manipulate elements of the string What is the output? 39 String Manipulations In C Programming Using Library Functions You need to often manipulate strings according to the need of a problem. Most, if not all, of the time string manipulation can be done manually but, this makes programming complex and large. To solve this, C supports a large number of string handling functions in the standard library "string.h". #include 40 gets() AND puts() _ 41 TEST YOUR UNDERSTANDING 42 Q1 Q2 Is there any difference int the following declarations? int fun(int arr[]); int fun(int arr); 43 What is the output? 44 Q3 45 What is the output? 46 47 Student ID Name A177335 AIMAN NAJMUDDIN A174939 AZIMWAFI BIN MOHD NASIR A173458 HISYAM BIN MOHD JAIM A165926 NUR SYAZWANI BINTI MUHAMMAD FIRDAUS A184687 TONG YUESHENG A172568 YANG HAOZHE A184933 YANG HUANGZILONG A184590 ZHENG JIAWEN Group 13 (Thurs Lab) : CHENG XUANKANG, FENG SHUO, YU YUE 48 49 point called pointers 50 ADDRESSES IN C _ 51 POINTERS _ 52 POINTERS _ 53 POINTERS _ 54 POINTERS : Changing Value Pointed by Pointers 55 POINTERS : Changing Value Pointed by Pointers 56 POINTERS : Changing Value Pointed by Pointers 57 POINTERS : Changing Value Pointed by Pointers 58 POINTERS : Changing Value Pointed by Pointers 59 POINTERS : Changing Value Pointed by Pointers 60 POINTERS : Changing Value Pointed by Pointers 61 POINTERS : Changing Value Pointed by Pointers 62 POINTERS : Changing Value Pointed by Pointers 63 POINTERS : Common Mistakes _ 64 POINTERS : Common Mistakes _ 65 RELATIONSHIP BETWEEN POINTERS & ARRAYS 66 RELATIONSHIP BETWEEN POINTERS & ARRAYS 67 ARRAY & POINTERS EXAMPLE _ 68 ARRAY & POINTERS EXAMPLE _ What’s the output? 69 FUNCTION & POINTERS _ In C programming, it is also possible to pass addresses as arguments to functions. To accept these addresses in the function definition, we can use pointers because pointers are used to store addresses. What’s the output? 70 FUNCTION & POINTERS _ 71 FUNCTION & POINTERS _ 72 FUNCTION & POINTERS _ What’s the output? 73 FUNCTION & POINTERS _ 74 DYNAMIC MEMORY ALLOCATION _ 75 malloc() _ 76 calloc() _ 77 free() _ 78 Example: malloc() and free() _ 79 Example: calloc() and free() _ 80 realloc() _ 81 Example: realloc() _ 82 standing tall structures 83 What Are Structures? _ a struct (or structure) is a collection of variables (can be of different types) under a single name. 84 Creating struct variables _ 85 Accessing members of a structure _ 86 87 Keyword typedef _ 88 NESTED STRUCTURES _ 89 90 UNIONS _ C unions are used to save memory. To better understand an union, think of it as a chunk of memory that is used to store variables of different types. When we want to assign a new value to a field, then the existing data is replaced with new data C unions allow data members which are mutually exclusive to share the same memory. This is quite important when memory is valuable, such as in embedded systems. Unions are mostly used in embedded programming where direct access to the memory is needed 91 DEFINING UNIONS _ 92 UNION VARIABLES _ OR 93 ACCESSING MEMBERS OF UNION _ 94 UNIONS vs STRUCT _ Structs allocate enough space to store all of the fields in the struct. The first one is stored at the beginning of the struct, the second is stored after that, and so on. Unions only allocate enough space to store the largest field listed, and all fields are stored at the same space. 95 UNIONS vs STRUCT _ Here, the size of sJob is 40 bytes because the size of name is 32 bytes the size of salary is 4 bytes the size of workerNo is 4 bytes However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size of its largest element. In the example, the size of its largest element, (name), is 32 bytes. With a union, all members share the same memory. 96 UNIONS _ 97 TEST YOUR UNDERSTANDING 98 What is the output? 99 What is the output? 100 What is the output? 101 Q1 Q2 102 103 Summary Lecture 3 Types Arrays Pointers → 1D → pointer as value → 2D → pointer as address → Multidimensional → changing values of pointers Arrays & Pointers Passing arrays to functions Function & Pointers Dynamic Memory Allocation Strings Structures → Intialization, declaration → declaring structures → accessing structures → Pointers using string → typedef Function & Struct fgets(), puts() Unions 104 Thanks! Any questions? 105 Programing Paradigm TK 2053 C Programming DR. WANDEEP KAUR [email protected] Block A, Level 2 Recap Lecture 1 Introduction to C Variables, Constants etc Features of C Keywords Identifiers Programming Practices Variables Constant Literals Int Char printf() scanf() Arithmetic Logical Float Assignment Relational Double Data Types I/O, Operators 2 AGENDA FOR THE DAY First Second Last if function Recap loop recursion Break and continue Call by reference & Switch … case call by value goto Scope of variables 3 the if family 4 5 QUESTION: What happens when you enter -2? Enter an integer: -2 You entered -2. The if statement is easy. What happens when you enter 5? 6 7 8 QUESTION: What happens when you enter 7? Enter an integer: 7 7 is an odd integer. 9 10 11 Enter two integers: 12 23 Result: 12 < 23 12 13 Enter two integers: 9 5 Result: 9 > 5 14 jumping through loops 15 ▷ for ▷ while ▷ do while 16 17 18 QUESTION: What would the output be? 19 20 QUESTION: What would the output be? 21 22 23 24 25 QUESTION: What would the output be? 26 27 28 29 30 31 32 have a break 33 The break statement ends the loop immediately when it is encountered. Almost always used with if...else statement inside the loop 34 35 36 QUESTION: What happens if user does not enter negative number? 37 38 and then continue 39 CONTINUE ______________________________________________________________________________________________________________________________________________________________________ Skips the current iteration of the loop and continues with the next iteration 40 CONTINUE ______________________________________________________________________________________________________________________________________________________________________ 41 CONTINUE ______________________________________________________________________________________________________________________________________________________________________ 42 CONTINUE ______________________________________________________________________________________________________________________________________________________________________ 43 switch it up 44 45 46 47 goto 48 GOTO ______________________________________________________________________________________________________________________________________________________________________ Allows us to transfer control of the program to the specified label The label is an identifier. When the goto statement is encountered, the control of the program jumps to label: and starts executing the code 49 GOTO ______________________________________________________________________________________________________________________________________________________________________ 50 GOTO ______________________________________________________________________________________________________________________________________________________________________ Reasons to avoid goto The use of goto statement may lead to code that is buggy and hard to follow 51 52 Introducing functions 53 54 55 STANDARD LIBRARY FUNCTIONS_____ built-in functions in C programming. defined in header files For example, printf() → standard library function (display input to screen) → defined in the stdio.h header file. ❖ to use printf(), we need to include stdio.h header file using #include ❖ sqrt() function calculates the square root of a number. The function is defined in the math.h header file. 56 ADVANTAGES OF C LIBRARY FUNCTIONS They work One of the most important reasons you should use library functions is simply because they work. These functions have gone through multiple rigorous testing and are easy to use. The functions are optimized for performance Since, the functions are "standard library" functions, a dedicated group of developers constantly make them better. In the process, they are able to create the most efficient code optimized for maximum performance. 57 ADVANTAGES OF C LIBRARY FUNCTIONS It saves considerable development time Since the general functions like printing to a screen, calculating the square root, and many more are already written. You shouldn't worry about creating them once again. The functions are portable With ever-changing real-world needs, your application is expected to work every time, everywhere. And, these library functions help you in that they do the same thing on every computer. 58 Example: Square root using sqrt() function 59 60 USER DEFINED FUNCTIONS___________ You can also create functions as per your need. Such functions created by the user are known as user-defined functions 61 USER DEFINED FUNCTIONS___________ 62 USER DEFINED FUNCTIONS___________ Argument refers to the variable passed to the function Parameters a and b accepts the passed arguments in the function definition. These arguments are called formal parameters of the function Arguments passed to a function and the formal parameters must match, otherwise, the compiler will throw an error 63 USER DEFINED FUNCTIONS___________ Return statement terminates the execution of a function and returns a value to the calling function 64 TYPES OF USER DEFINED FUNCTIONS___________ 65 TYPES OF USER DEFINED FUNCTIONS___________ Type 1 No arguments passed and no return value 66 TYPES OF USER DEFINED FUNCTIONS___________ Type 2 No arguments passed but a return value 67 TYPES OF USER DEFINED FUNCTIONS___________ Type 3 Arguments passed but no return value 68 TYPES OF USER DEFINED FUNCTIONS___________ Type 4 Arguments passed and a return value 69 ADVANTAGES OF USER DEFINED FUNCTIONS___________ 1. The program will be easier to understand, maintain and debug. 2. Reusable codes that can be used in other programs 3. A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers. 70 71 Let’s talk recursion 72 C RECURSION _ A function that calls itself is known as a recursive function. And, this technique is known as recursion. To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the recursive call, and other doesn't 73 C RECURSION – Example _ 74 C RECURSION – Example _ 75 Advantages & Disadvantages of Recursion Recursion makes program elegant. However, if performance is vital, use loops instead as recursion is usually much slower. That being said, recursion is an important concept. It is frequently used in data structure and algorithms 76 Storage 77 C STORAGE CLASS _ Every variable in C programming has two properties: → type → storage class Type refers to the data type of a variable Storage class determines the scope, visibility and lifetime of a variable There are 4 types of storage class: 1.automatic 2.external 3.static 4.register 78 LOCAL VARIABLE (Automatic) _ The variables declared inside a block are automatic or local variables. The local variables exist only inside the block in which it is declared. 79 LOCAL VARIABLE _ 80 GLOBAL VARIABLE (External) _ Variables that are declared outside of all functions are known as external or global variables. They are accessible from any function inside the program. What is the output of the program? 81 REGISTER VARIABLE _ The register keyword is used to declare register variables. Register variables were supposed to be faster than local variables. However, modern compilers are very good at code optimization, and there is a rare chance that using register variables will make your program faster. Unless you are working on embedded systems where you know how to optimize code for the given application, there is no use of register variables. 82 STATIC VARIABLE _ A static variable is declared by using the static keyword. The value of a static variable persists until the end of the program. 83 Call by Value Call by Reference 84 85 86 87 88 89 Summary Lecture 2 If, If…Else, Nested If, If Ladder Break, continue For, While, Do…While Switch, Goto Types of functions → Standard Library Functions → User defined functions Recursion Storage → Local, Global, Static variables Call by Value, Call by Reference 90 Thanks! Any questions? 91 Programing Paradigm TK 2053 C Programming DR. WANDEEP KAUR Block A, Level 1 [email protected] COURSE STRUCTURE Coursework, Assessments & Week Topic Deliverables 10/5/2023 Introduction to Imperative Paradigm 17/5/2023 Mid Sem Break 24/5/2023 Advanced Imperative Paradigm 31/5/2023 Advanced Imperative Paradigm (cont) Lab01 Submission: C 7/6/2023 Minggu Cabaran Digital 14/6/2023 Introduction to Object Oriented Paradigm Lab02 Submission: C 21/6/2023 Advanced Object Oriented Paradigm Revision (Asynchronous) Recap (scripting, imperative and object oriented paradigm) 28/6/2023 Lab Exam & Poster Presentation July 17 – Aug 4 FINAL EXAM 2 COURSE STRUCTURE Poster Presentation = 10% Lab Exam (C Programming) = 15% Lab Submission (C Programming) = 10% → Lab01 (5%) → Lab02 (5%) 3 REFERENCE Modern C Jens Gustedt 1st Edition (2019) Manning Publication Hanly J.R. and Koffman E.B.2016. Problem Solving and Program Design In C, 8th edition. Addison-Wesley. 4 AGENDA FOR THE DAY First Second Last Introduction to C Variable & Recap Constants Data Types I/O in C Operators 5 Intro to C, Data type, Input-Output 6 7 8 Best Practices C Programming ▪ Be consistent with the formatting (spacing) Example: int count; int count; ▪ Use one statement per line int count; float squareRoot = 10.0; printf(“Square root =%f”, squareRoot); int count; float squareRoot = 10.0; printf(“Square root =%f”, squareRoot); 9 Best Practices C Programming ▪ Naming convention consistency int a, b: int counter, power: ▪ Use comments #include int main() { int x = 42; //x is a integer variable printf("%d", x); return 0; } 10 Character Sets Alphabets Digits Special Characters , < > Uppercase: 0123456789. _ ( ) ; A B C................................ X Y $ : Z % [ ] # ? Lowercase: ' & { } " a b c................................... x y ^ ! * z / | - \ ~ + 11 Keywords ▷ predefined, reserved words ▷ part of the syntax ▷ cannot be used as an identifier NOTE: C is a case sensitive, int money; ALL KEYWORDS must be written in lowercase Keyword Variable type int (integer) 12 Keywords auto double int struct break else long switch case enum register typedef char extern return union continue for signed void do if static while default goto sizeof volatile const float short unsigned 13 Variables ▷ container (storage area) to hold data ▷ To indicate storage area, each variable should be given a unique name (identifier). ▷ symbolic representation of a memory location NOTE: int playerScore = 95; value of variable can be changed, hence name variable Keyword Variable type int (integer) 14 Rules of Naming Variables 1. A variable name can only have letters (both uppercase and lowercase letters), digits and underscore. 2. The first letter of a variable should be either a letter or an underscore. 3. There is no rule on how long a variable name (identifier) can be. However, you may run into problems in some compilers if the variable name is longer than 31 characters. 15 Rules of Naming Variables C is a strongly typed language → variable type cannot be changed once it is declared. For example: Here, the type of number variable is int. int number = 5; //integer variable You cannot assign a floating-point (decimal) value 5.5 to this variable. number = 5.5 //error You cannot redefine the data type of the double number; //error variable to double. P/S: to store decimal values in C, you need to declare its type to either double or float. 16 Literals – Escape Sequences ▷ Sometimes, it is necessary to use characters that cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc. ▷ In order to use these characters, escape sequences are used. \n is used for a newline. The backslash \ causes escape from the normal way the characters are handled by the compiler. 17 18 CONSTANTS NOTE: You can also define a ▷ variable whose value cannot be changed, constant using ▷ you can use the const keyword the #define preprocessor directive Notice, we have added keyword const Here, PI is a symbolic constant; its value cannot be changed. 19 Data Types ▷ declarations for variables ▷ determines the type and size of data associated with variables int myVar;; NOTE: Size of int = 4 bites Data type Variable type int (integer) 20 Basic Types 21 Data Types - int Integers are whole numbers that can have both zero, positive and negative values but no decimal values For example, 0, -5, 10 We can use int for declaring an integer variable. Here, id is a variable of type integer. You can declare multiple variables at once in C programming The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -2147483648 to 2147483647. 22 Data Types – float & double used to hold real numbers In C, floating-point numbers can also be represented in exponential Size of float (single precision float data type) is 4 bytes. Size of double (double precision float data type) is 8 bytes. 23 Data Types – char & void char: used for declaring character type variables void: means "nothing" or "no type". You can think of void as absent. For example, if a function is not returning anything, its return type should be void. Note that, you cannot create variables of void type. 24 Data Types – short & long long: used for large number Store integer value Store floating point If you are sure, only a small integer ([−32,767, +32,767] range) will be used, you can use short You can always check the size of a variable using the sizeof() operator. 25 Data Types – signed & unsigned In C, signed and unsigned are type modifiers. You can alter the data storage of a data type by using them For example, Here, the variable x can hold only zero and positive values because we have used the unsigned modifier. Considering the size of int is 4 bytes, variable y can hold values from −231 to 231 −1, whereas variable x can hold values from 0 to 232 −1. 26 Data Types – Others Other data types defined in C programming are: bool Type Enumerated type Complex types Derived Data Types Data types that are derived from fundamental data types are derived types. For example: arrays, pointers, function types, structures, etc. 27 C Output – printf() printf() is one of the main output function sends formatted output to the screen OUTPUT 28 C Output - integer OUTPUT %d format specifier to print int types the %d inside the quotations will be replaced by the value of testInteger 29 C Output – float & double OUTPUT To print float : use %f To print double values : use %lf 30 C Output - char OUTPUT %c format specifier to print char types 31 C Input – scanf() scanf() is one of the commonly used function to take input from the user reads formatted input from the standard input such as keyboards OUTPUT 32 C Input – float & double 33 C Input – char 34 C Input – multiple values 35 36 Arithmetic Operators 37 Arithmetic Operators 38 Arithmetic Operators 39 Assignment Operators 40 Assignment Operators 41 Relational Operators 42 Relational Operators 43 Logical Operators 44 Logical Operators 45 PREPROCESSOR DIRECTIVES 46 Hello World! #include = preprocessor command → tells compiler to include contents of stdio.h (standard input & output) file in program < stdio.h> → contains functions like scanf() and printf() NOTE: printf() without #include → compiler error Execution starts at main() and return 0 = Exit status of program 47 Summary Introduction to C Variables, Constants etc Features of C Keywords Identifiers Programming Practices Variables Constant Literals Int Char printf() scanf() Arithmetic Logical Float Assignment Relational Double Data Types I/O, Operators 48 Thanks! Any questions? 49 SCRIPT PROGRAMMING WITH PYTHON – Turtle Graphics Associate Prof. Dr. Ravie Chandren Muniyandi Email: [email protected] Telegram: @ravieftsm (https://t.me/ravieftsm) Turtle Graphics 2 Coordinates Objects and methods from the module named "turtle." Given statements, window appears FIGURE 6.12 Turtle graphics window. Coordinates FIGURE 6.13 Coordinate system for canvas. Coordinates Think of the chevron as a small turtle with a pen attached to its tail Python statements – Raise, lower “tail” – Change color – Move turtle in variety of ways Functions from the turtle Module Functions provided – t.up( ), t.down( ) – t.hideturtle( ) – t.forward(distance), t.backward(distance) – t.goto(x,y) – t.pencolor(colorName) – t.setheading(deg) – t.left(deg), t.right(deg) – t.dot(diameter, colorName) Rectangles FIGURE 6.14 A general rectangle. Rectangles Two possible functions to draw rectangles Rectangles Two possible functions to draw rectangles Rectangles Example 1: Program draws a rectangle having a red border and a yellow interior. Rectangles Example 1: Flags Example 2: program draws flag shown on the right. Flags Example 2: Flags Example 2: Flags FIGURE 6.16 Five-Pointed Star Flags Example 3: program draws the five-pointed star in Fig. 6.16 (b). The write Method Given s, a string as argument in Displays the string s – Bottom left corner of the string approximately at current position of the pen Other options The write Method Example 4: Program displays the word Python with different alignments. Bar Charts Example 5: Program creates bar chart on the right. Bar Charts Example 5: Bar Charts Example 5: Bar Charts Example 5: Line Charts Tabular data can be visually displayed it in a line chart. Table 6.3 Percentage of college freshmen who smoke. Line Charts Example 6: Program uses data in Table 6.3 to create the line chart on the right Line Charts Example 6: Line Charts Example 6: Line Charts Example 6: Line Charts Example 6: TK2053 PROGRAMMING PARADIGM Script Programming with Python - Object and Class 2 Object and Class Python is an object oriented programming language. Everything is treated as an object be it functions, modules, data types etc. A class is simply a blueprint of a data that defines the characteristic and behaviour of its data members and member function Object is an instance of the class Creating object is like defining a variable of class type Objects are used to store data and functions defined inside a class 3 Object and Class A class doesn’t occupy any physical space in computer memory until an object of that class type is defined. The declaration of class develops a template but data members cannot be manipulated unless the object of its type is created. Attributes: data value which are stored inside an object Methods: the functions which are associated with the object 4 Object and Class Source: http://www.trytoprogram.com/python-programming/python-object-and-class/ 5 Built-in Class Python has several built-in class including String Lists Dictionary and so on For example, a String class that makes string objects such as ‘cat’ and ‘dog’ To identify the types of objects - Note the use of the word ‘class’ instead of ‘type’ - A specific literal from one of these classes is referred to as an instance of the class 6 User-defined Class When you write a class You defined the general behaviour of whole category of objects can have When you create (instantiate) objects from class Each object is equipped with the general behaviour You can give each object whatever unique traits desire Classes can be Typed directly into programs Stored in modules and brought into programs with an import statement 7 User-defined Class - Example 1 2 3 4 5 Each instance created from the Dog class will store a name and an age, and each dog will have the ability to sit() and roll_over(): 8 User-defined Class - Example 1 Define a class called Dog. Conventionally capitalized names refer to classes. 2 Docstring describing what the class does. 3 The __init__() method is a special method Python runs automatically whenever we create new instance based on the Dog class. *The two leading underscores and two trailing underscores is a convention that helps prevent Python’s default method names from conflicting with your method names. The self parameter is required as the first parameter in the method definition. Each method's self parameter references the object; it gives the individual instance access to the attributes and methods in the class. 4 The two variable defined have the prefix self. Any variable prefixed with self is available to every method in the class, and also accessible through any instance created from the class. These variables are called attributes. 9 User-defined Class - Example 5 The two other methods defined are sit() and roll_over(). They only have one parameter, self, since they do not need additional information like name or age. The instances created later will have access to these methods. 10 User-defined Class - Example To make an instance from a class Think of class as a set of instructions for how to make an instance 1 2 1 Tell Python to create a dog name ‘willie’ age 6 in the variable my_dog. When Python reads this line, it calls the __init__() method to creates an instance representing this particular dog and sets the name and age attributes using the values provided. 2 To access the attributes of an instance, use the dot notation, my_dog.name. This is the same attribute referred to as self.name in the class Dog. 11 User-defined Class - Example To call the methods in an instance To call a method, give the name of the instance (in this case, my_dog) and the method you want to call, separated by a dot. When Python reads my_dog.sit(), it looks for the method sit() in the class Dog and runs that code. 12 User-defined Class - Example To create multiple instances Each dog is a separate instance with its own set of attributes, capable of the same set of actions. 13 Hands-on Activities Make a class called User. Create two attributes called first_name and last_name, and then create several other attributes that are typically stored in a user profile. Make a method called describe_user() that prints a summary of the user’s information. Make another method called greet_user() that prints a personalized greeting to the user. Create several instances representing different users, and call both methods for each user. TK2053 PROGRAMMING PARADIGM Script Programming with Python - Errors and Exceptions Errors Errors or mistakes in a program are often referred to as bugs. The process of finding and eliminating errors is called debugging. Errors can be classified into three major groups: Syntax errors Runtime errors Logical errors Syntax Errors Python will find these kinds of errors when it tries to parse your program, and exit with an error message without running anything. Analogous to spelling or grammar mistakes in a language. Common syntax errors include: Leaving out a keyword Leaving out a symbol, such as colon, comma Misspelling a keyword Incorrect indentations Empty block Once a program is free from syntax error, it will be run by the Python interpreter. Runtime Errors A problem that are only revealed when a particular line is executed. The program may exit unexpectedly (crash) during execution if it encounters a runtime error Examples of runtime errors include: division by zero Performing an operation which has not been defined Trying to access a file which does not exist Accessing a list element or dictionary value which does not exist We should always try to add checks to our code to make sure it can deal with bad input and edge cases gracefully. (i.e., exception handling). Logical Errors Error that is caused by the mistake in the program’s logic. Logical errors are the most difficult to fix. They occur when the program runs without crashing, but produces an incorrect result. Need to review all the relevant parts of the code to find the error. Some examples of logical errors include: Using the wrong variable name Indenting a block to the wrong level Getting operator precedence wrong Hands-on Activities Can you see any error in the code? Hands-on Activities Find potential sources if runtime errors in the following code snippet: Find potential sources if logic errors in this code snippet: Handling Exceptions All the runtime (and syntax) errors that we have encountered are called exceptions in Python. If we know that a particular section of our program is likely to cause an error, we can tell Python what to do if it does happen. Instead of letting the error crash our program we can intercept it, do something about it, and allow the program to continue. Handling Exceptions When exception occurs Python check if line of code that cause the error is in a try block If yes, checks to see if any of the except blocks associated with the try block can handle that type of exception If an appropriate handler is found, the exception is handled, and the program continues from the next statement after the end of that try- except. If no, the program will terminate. Handling Exceptions: try-except block Python will try to process all the statements inside the try block. If a ValueError occurs at any point as it is executing them, the flow of control will immediately pass to the except block, and any remaining statements in the try block will be skipped. Handling Exceptions : try-except block Example: Handling Exceptions : try-except block Example: Error may occur when we try to convert the user’s input to an integer. If the input string is not a number, this line will trigger a ValueError – that is why we specified it as the type of error that we are going to handle. Handling Exceptions : try-except block Example: Error may occur when we try to convert the user’s input to an integer. If the input string is not a number, this line will trigger a ValueError – that is why we specified it as the type of error that we are going to handle. Handling Exceptions : try-except block It is possible for one except clause to handle more than one kind of error Can also have multiple except clause However, it is better to use exception handlers to protect small blocks of code against specific errors Handling Exceptions : try-except block The else and finally statement else will be executed only if the try clause does not raise an exception finally clause will be executed at the end of the try-except block no matter what TK2053 PROGRAMMING PARADIGM Script Programming with Python - Functions 2 What is a Function? A function is a sequence of statements which performs some kind of task. Function is used to eliminate code duplication Defined in one place and refer to it by the function name Functions makes your programs easier to write, read, test, and fix. There are two types of functions: Built-in functions User-defined functions 3 Built-in Functions Python comes with a set of built-in functions To use it, directly call them and provide the required arguments (if required). Eric Matthes, Python Crash Course 4 User-defined functions A function can take any number and type of input parameters Return any number and type of output results You can do two things with a function Defined it Call it Defining a function does not make it run. To run a function, we have to call it. 5 User-defined functions Structure of function definition 1 2 3 4 1 Function header. Starts with the keyword def, which means define. It is used to indicate the start of a function definition. Next is the function name and a parenthesized list of argument names (input parameters to the function). Finally the definition ends in a colon (:). Function name should explain as accurately as possible what the function does. 2 This is a comment called docstring, which describe what the function does. It is displayed when user enters help(functionName). 3 Everything indented thereafter is the body of the function. it can have various operations, loops, conditional statements, etc. 4 To return any value, use the return keyword. * Parameters and return statements are optional in function definitions. 6 User-defined functions Function having no parameter Example: A simple function named greet_user() that prints a greeting. Code: Calling the function Output: 7 User-defined functions Function having no parameter but returns a value Example: A simple function named agree() that prints a greeting. Code: Calling the function Output: 8 User-defined functions: Passing Information to a function Information passed is expressed as a series of input parameters (recall slide 5) Pass information into a function to tailor the function’s behaviour to our needs The variable in a function definition is a parameter The value in a function call is an argument. Argument is a piece of information that is passed from a function call to a function If the argument in a function call is a variable Object pointed to by the argument variable (not the argument variable itself) passed to a parameter variable Object is immutable, there is no possibility that value of the argument variable will be changed by a function call 10 User-defined functions: Passing Information to a function For example, recall the greet_user() that prints a greeting. We can personalize the greetings. parameter Code: argument Output: By adding username in the parenthesis allows the function to accept any value of username specify. The function expect you to provide a value for username each time you call it. The argument 'jesse' was passed to the function greet_user(), and the value was stored in the parameter username. 11 User-defined functions: Passing Information to a function Example: A simple function named average() that prints a greeting. Code: Calling the function Output: 12 User-defined functions: Passing arguments Function definition can have multiple parameters There are two ways to pass arguments to your function Positional arguments: need to be in the same order the parameters were written Keyword arguments: each arguments consists of a variable name and a value 13 User-defined functions: Passing arguments Positional argument When you call a function, Python must match each argument in the function call with a parameter in the function definition. Example: Function that display information about pets 14 User-defined functions: Passing arguments Keyword argument (name-value pair ) Directly associating the name and the value within the argument No need to worry about correctly ordering the arguments in the function call Example: * Be sure to use the exact names of the parameters in the function’s definition. 15 User-defined functions: Passing arguments Default values When writing a function, you can define a default value for each parameter. If an argument for a parameter is provided in the function call, Python uses the argument value. If not, it uses the parameter’s default value. Example: Note: When you use default values, any parameter with a default value needs to be listed after all the parameters that don’t have default values. This allows Python to continue interpreting positional arguments correctly. 16 User-defined functions: Return values A function can process some data and return a value or set of values The return statement takes a value inside a function and sends it back to the line that called the function Example: Note: When you call a function that returns a value, you need to provide a variable where the return value can be stored. 17 User-defined functions: Return values Example: Returning a Dictionary 18 User-defined functions: Passing a List It is useful to pass a list to a function, whether it’s a list of names, numbers, or more complex objects, such as dictionaries. 19 User-defined functions: Passing an Arbitrary Number of Arguments This is used when we do not know how many arguments a function needs to accept. Positional and arbitrary arguments Note: The asterisk in the parameter name *toppings tells Python to make an empty tuple called toppings and pack whatever values it receives into this tuple. 20 User-defined functions: Using Arbitrary Keyword Arguments If we do not know what kind of information will be passed to the function, write functions that can accept as many key-value pairs as the calling statement provides Note: The double asterisks before the parameter **user_info cause Python to create an empty dictionary called user_info and pack whatever name-value pairs it receives into this dictionary. 21 Lambda Function It is an anonymous function expressed as a single statement. You can use it instead of a normal tiny function. Compute a single expression Cannot be used as a replacement for complex functions Syntex: 22 Lambda Function Example: Sort names by their surename 23 Storing Functions in Modules Functions can be stored in a separate file called a module A module is a file with extension.py Contains functions and variables Can be used (imported) by any program can be created in IDLE or any text editor Looks like an ordinary Python program To gain access to the functions and variables place a statement of the form import moduleName at the beginning of the program 24 Storing Functions in Modules Several modules from the standard library 25 Namespaces and Scope Namespace is a mapping between object names in a program and the memory location where Python stores their value. Scope: the part of a program where a variable is accessible Lifetime: the duration for which the variable exists Each function defines its own namespace Variab