INF1002-W9-LEC-Function and Array and String.pdf

Full Transcript

FUNCTIONS AND ARRAY IN C DR FRANK GUAN INF1002 – PROGRAMMING FUNDAMENTALS WEEK 9 RECAP OF LAST WEEK – C programs consist of modules called functions – The main() function is the “starting point” fora C program – The pre-pr...

FUNCTIONS AND ARRAY IN C DR FRANK GUAN INF1002 – PROGRAMMING FUNDAMENTALS WEEK 9 RECAP OF LAST WEEK – C programs consist of modules called functions – The main() function is the “starting point” fora C program – The pre-processor (begins with #) executes before a program is compiled – definition of symbolic constants – the inclusion of other files in the file being compiled – A variable is a location in memory where a value can be stored for use by a program – printf(): the first argument, the format control string, describe the output format – scanf(): The first argument, the format control string, indicates the type of data that should be input by the user – control structures – if – else – switch – for – while – do - while 2 EXPERIENCE SHARING – “Practice makes perfect” – Truly common if you spend one week time on: – Debugging – Troubleshooting – Reference reading – Discussion – Self-learning – … 3 Agenda 1. Functions 2. Arrays 3. Characters and Strings 4 FUNCTIONS IN C FUNCTIONS – C’S BUILDING BLOCK Functions Exam promote department reusability. Student Lecturer management department Each function is print written once. student information 6 FUNCTIONS – C’S BUILDING BLOCK The Exam function can department be used Student repeatedly Lecturer management by many department other print functions student information 7 C FUNCTION CALLS Functions are invoked by specifying their name and parameters (or arguments) without knowing the actual implementation of the function. function_1(...){ 2 function_1_1(...)... { 1 function_1_1(...);...... } 3 main(){ 4 } function_1(...);... 5 function_2(...){ function_2(...);... 6... } function_n(...); } 7 function_n(...){... 8 } 8 FUNCTION DEFINITIONS The above function calculates the square of an integer y 9 FUNCTION DEFINITIONS return_value_type function_name() { } A comma-separated list of parameters received by the function when it is called. A type must be listed explicitly for each parameter. E.g int number, char grade 10 FUNCTION PROTOTYPES – A function prototype is a function definition without a body, e.g. int square(int); – Function prototypes are optional, but are used by the compiler to validate function calls – This prevents errors – Prototypes are usually declared at the top of a source file, or in a header file 11 FUNCTION DEFINITION - EXAMPLE The function #include int addition(int, int); prototype int main() { informs the int first, second, sum; compiler that addition() scanf("%d%d", &first, &second); sum = addition(first, second); expects to receive two integer printf("%d\n", sum); values and return 0; } returns an integer result. int addition(int a, int b) { int result; result = a + b; return result; } FUNCTION DEFINITION - EXAMPLE Whenever #include int addition(int, int); there’s a int main() { function call, the compiler int first, second, sum; will check scanf("%d%d", &first, &second); that call sum = addition(first, second); printf("%d\n", sum); against the return 0; } function int addition(int a, int b) { int result; result = a + b; prototype. return result; } MULTIPLE RETURN STATEMENTS #include int get_sign(int n) { #define POSITIVE 1 if (n < 0) #define NEGATIVE -1 return NEGATIVE; #define ZERO 0 if (n > 0) return POSITIVE; int get_sign(int n); return ZERO; int main() { } int n; int sign; printf("Type an integer: "); The function scanf("%d", &n); stops executing as sign = get_sign(n); soon as one if (sign == POSITIVE) return statement is printf("That is a positive number.\n"); else if (sign == NEGATIVE) else printf("That is a negative number.\n"); executed. printf("That is zero.\n"); return 0; } 14 CALLING FUNCTIONS BY VALUE – Call-by-value – A copy of the argument’s value is made and passed to the called function – Changes to the copy do not affect the original variable’s value in the caller – By default, all calls in C are by value 15 CALL-BY-VALUE – EXAMPLE Output #include void call_by_value(int); int main() { int a = 10; printf(“\nBefore call_by_value, a = %d.\n\n", a); call_by_value(a); printf("After call_by_value, a = %d.\n \n ", a); return 0; } void call_by_value(int x) { printf("Inside call_by_value, x = %d.\n \n ", x); x += 10; printf("After adding ten, x = %d.\n \n ", x); } 17 CALL-BY-VALUE – EXAMPLE #include Memory Address void call_by_value(int); a 0x0060FF03 10 int main() { int a = 10; printf(“\nBefore call_by_value, a = %d.\n\n", a); call_by_value(a); printf("After call_by_value, a = %d.\n \n ", a); return 0; } void call_by_value(int x) { printf("Inside call_by_value, x = %d.\n \n ", x); x += 10; printf("After adding ten, x = %d.\n \n ", x); } 18 CALL-BY-VALUE – EXAMPLE #include Memory Address void call_by_value(int); a 0x0060FF03 10 int main() { int a = 10; printf(“\nBefore call_by_value, a = %d.\n\n", a); call_by_value(a); printf("After call_by_value, a = %d.\n \n ", a); return 0; } void call_by_value(int x) { printf("Inside call_by_value, x = %d.\n \n ", x); x += 10; printf("After adding ten, x = %d.\n \n ", x); } 19 CALL-BY-VALUE – EXAMPLE #include Memory Address void call_by_value(int); a 0x0060FF03 10 int main() { int a = 10; Pass printf(“\nBefore call_by_value, a = %d.\n\n", a); by value call_by_value(a); printf("After call_by_value, a = %d.\n \n ", a); 10 return 0; } x 0x0060FF05 void call_by_value(int x) { printf("Inside call_by_value, x = %d.\n \n ", x); x += 10; printf("After adding ten, x = %d.\n \n ", x); } 20 CALL-BY-VALUE – EXAMPLE #include Memory Address void call_by_value(int); a 0x0060FF03 10 int main() { int a = 10; printf(“\nBefore call_by_value, a = %d.\n\n", a); call_by_value(a); printf("After call_by_value, a = %d.\n \n ", a); 20 return 0; } x 0x0060FF05 void call_by_value(int x) { printf("Inside call_by_value, x = %d.\n \n ", x); x += 10; printf("After adding ten, x = %d.\n \n ", x); } 21 CALL-BY-VALUE – EXAMPLE #include Memory Address void call_by_value(int); a 0x0060FF03 10 int main() { int a = 10; printf(“\nBefore call_by_value, a = %d.\n\n", a); call_by_value(a); printf("After call_by_value, a = %d.\n \n ", a); 20 return 0; } x 0x0060FF05 void call_by_value(int x) { printf("Inside call_by_value, x = %d.\n \n ", x); x += 10; printf("After adding ten, x = %d.\n \n ", x); } 22 CALL-BY-VALUE – EXAMPLE #include Memory Address void call_by_value(int); a 0x0060FF03 10 int main() { int a = 10; printf(“\nBefore call_by_value, a = %d.\n\n", a); call_by_value(a); printf("After call_by_value, a = %d.\n \n ", a); 20 return 0; } x 0x0060FF05 void call_by_value(int x) { printf("Inside call_by_value, x = %d.\n \n ", x); Value of “a” is x += 10; not updated! printf("After adding ten, x = %d.\n \n ", x); } 23 CALL-BY-VALUE – EXAMPLE Output #include void call_by_value(int); int main() { int a = 10; printf(“\nBefore call_by_value, a = %d.\n\n", a); call_by_value(a); printf("After call_by_value, a = %d.\n \n ", a); return 0; } void call_by_value(int x) { printf("Inside call_by_value, x = %d.\n \n ", x); x += 10; printf("After adding ten, x = %d.\n \n ", x); } 24 CALLING FUNCTIONS BY REFERENCE – Call-by-reference – The caller allows the called function to modify the original value – Call-by-reference can be simulated by using the address operator (&) – More will be covered later… 25 FUNCTIONS FROM THE STANDARD C LIBRARY The Standard C Library provides many commonly-used functions, e.g. Header Functions Character functions: isalpha(), isdigit(), etc. Mathematical functions: sqrt(), exp(), log(), sin(), cos(), tan(), etc. Miscellaneous functions: malloc(), free(), rand(), atoi(), etc. Input/output: printf(), scanf(), fopen(), fread(), fwrite(), etc. String functions: strcpy(), strcmp(), etc. 26 FUNCTIONS FROM THE STANDARD C LIBRARY Visit cplusplus.com for a complete list: – http://www.cplusplus.com/reference/clibrary/ 27 28 SCOPE RULES SCOPE RULES The scope of an identifier is the portion of the program in which the identifier can be referenced. – The same identifier can be re-used in different scopes. – Tip: the scope of an identifier should be as small as possible. – Why? 29 SCOPE RULES – FILE SCOPE – An identifier declared outside any function has file scope. – A file-scope identifier is accessible from its declaration until the end of the file. – Variables with file scope are often called global variables. 30 FILE SCOPE - EXAMPLE i is declared #include outside any int i = 1; function so i has int main() { file scope int x = 4; printf("add_i outputs %d\n", add_i(x)); printf("i is %d\n", i); printf("x is %d\n", x); return 0; } int add_i(int n) { This statement int x = n + i; updates the global variable i i++; return x; } 31 SCOPE RULES – BLOCK SCOPE – Identifiers defined inside a block delimited by braces {…} have block scope. – Any block may contain variable definitions. – Variables with block scope are often called local variables. 32 BLOCK SCOPE - EXAMPLE #include int i = 1; This x has block scope within int main() { main() int x = 4; printf("add_i outputs %d\n", add_i(x)); printf("i is %d\n", i); This x has block printf("x is %d\n", x); return 0; } scope within int add_i(int n) { add_i() int x = n + i; i++; return x; } add_i outputs 5 Output: i is 2 x is 4 33 34 ARRAYS ARRAYS An array is a group of memory locations that all have  the same name  the same type 36 The position number contained within square brackets is called a subscript or index. 37 The index starts at zero. The index can be any integer expression, e.g. int a = 1; c[a+2] += 2; The index ends at the number of array elements, minus 1 38 HOW TO USE #include #define MAX_STUDENTS 10 int main() { Define int studentId[MAX_STUDENTS]; Initialize for (int i = 0; i < MAX_STUDENTS; i++) studentId[i] = i + 1; printf("%7s%13s\n", "Element", "Value"); for (int i = 0; i < MAX_STUDENTS; i++) Use printf("%7d%13d\n", i, studentId[i]); return 0; } 39 DEFINING ARRAYS To define an array we need to specify: the type of the elements int b, x; the name of the array Type Name Number the number of elements VS int a, y; 40 ARRAY INITIALISATION We can use a loop to initialise array elements: Define an array #include #define MAX_STUDENTS 10 Initialize the array int main() { int studentId[MAX_STUDENTS]; for (int i = 0; i < MAX_STUDENTS; i++) studentId[i] = i + 1; printf("%7s%13s\n", "Element", "Value"); for (int i = 0; i < MAX_STUDENTS; i++) printf("%7d%13d\n", i, studentId[i]); return 0; } Use the array 41 ARRAY INITIALISATION We can also use an initialiser list: #include #define MAX_STUDENTS 10 int main() { int studentId[MAX_STUDENTS] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; printf("%7s%13s\n", "Element", "Value"); for (int i = 0; i < MAX_STUDENTS; i++) printf("%7d%13d\n", i, studentId[i]); return 0; } 42 MULTI-DIMENSIONAL ARRAYS – The most commonly used are two dimensional arrays or double-subscripted arrays. – In general, an array with m rows and n columns is called an m-by-n array. 43 DECLARING MULTIDIMENSIONAL ARRAYS int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; Declare and initialise a two-dimensional array of integers. The values in the initialiser list are grouped by row. 1 2 b 3 4 44 STRINGS FUNDAMENTALS OF CHARACTERS A program may contain character constants – A character constant is denoted by single quotes and has an integer value according to the character set – E.g. in ASCII: – 'z' has an integer value of 122 – '\n' has an integer value of 10 – Some mathematical operators can be applied to characters – + and – move up and down the character set – , ==, != compare according to the character set 46 CHARACTER HANDLING LIBRARY 47 FUNDAMENTALS OF STRINGS A string in C is an array of characters ending in the null character ('\0'). String literals (constants) are written in double quotation marks: – "SIT-DNA" – "Thinking Tinkerers" – "Able to Learn, Unlearn and Relearn" – "Catalyst for Transformation" – "Grounded in Community" 48 STRING INITIALISATION This is how you can initialise a string: char colour[] = "blue"; When defining a character array to contain a string, the array must be large enough to store the string and its terminating null character. This creates an array of 5 elements as follows: b l u e \0 If no size is specified, the size will be determined based on the number of initialisers in the list. E.g.: 5 in this case 49 STRING INITIALISATION A string can be stored in an array using scanf: char word; scanf("%9s\n", word); Variable word is an array, which is a memory address, so the address operator & is not needed with argument word. 50 STRING INITIALISATION A string can be stored in an array using scanf: char word; scanf("%9s\n", word); Note that scanf will read characters until a space, tab, newline or end-of-file indicator is encountered. So it is possible that the user could exceed 9 characters and your program might crash. 51 STRING INITIALISATION A string can be stored in an array using scanf: char word; scanf("%9s\n", word); It is good practice to use the conversion specifier %9s so that scanf reads up to 9 characters and saves the last one for the null character. 52 STANDARD I/O FUNCTIONS FOR STRINGS & CHARACTERS 53 STANDARD I/O FUNCTIONS FOR STRINGS & CHARACTERS #include #include #define MAX_LENGTH 80 void print_reverse(const char[]); fgets() reads characters into an int main() { array of chars until a newline or the end-of-file indicator is encountered, char sentence[MAX_LENGTH]; or until the maximum number of printf("Enter a line of text:\n"); characters is read. fgets(sentence, MAX_LENGTH, stdin); printf("The input line written backwards:\n"); print_reverse(sentence); return 0; } 54 STANDARD I/O FUNCTIONS PUTS() AND GETCHAR() #include puts() takes a string as an argument and prints the string followed by a #define MAX_LENGTH 80 newline character. int main() { char sentence[MAX_LENGTH]; char c; int index = 0; puts("Enter a line of text: "); while ((c = getchar()) != '\n' && index < MAX_LENGTH - 1) sentence[index++] = c; sentence[index] = '\0'; puts("The input line was: "); puts(sentence); return 0; getchar() reads a character from the } standard input and returns the character as an integer. 55 STANDARD I/O FUNCTIONS FORMATTED DATA TO A STRING WITH SPRINTF() sprintf() prints formatted data into an #include array of characters. The function uses the same #define MAX_LENGTH 80 conversion specifiers as printf int main() { char s[MAX_LENGTH]; int x; double y; printf("Enter an integer and a double: "); scanf("%d%lf", &x, &y); sprintf(s, "integer: %d, double: %f\n", x, y); printf("The formatted string stored in the array is: %s", s); return 0; } 56 STRING MANIPULATION FUNCTIONS 57 STRING MANIPULATION LIBRARY EXAMPLE – WHAT DOES THIS PROGRAM DO? #include #include #include #include #define MAX_FULLNAME 80 #define MAX_USERNAME 9 #define RANDOM_DIGITS 3 int main() { char name[MAX_FULLNAME]; char userID[MAX_USERNAME]; int n, i; printf("Enter your name: "); scanf("%79s", name); strncpy(userID, name, MAX_USERNAME - RANDOM_DIGITS - 1); userID[MAX_USERNAME - RANDOM_DIGITS - 1] = '\0'; Ensure the string is n = strlen(userID); terminated by ‘\0’. for (i = 0; i < RANDOM_DIGITS; i++) userID[n + i] = '0' + rand() % 10; userID[n + RANDOM_DIGITS] = '\0'; printf("Your username is: %s\n", userID); srand() and rand() return 0; generate random } numbers. 58 STRING MANIPULATION LIBRARY EXAMPLE – OUTPUT Enter your full name: Cristal Ngo Minh Ngoc Your username is: Crist610 Enter your full name: Rachel Green Your username is: Rache822 59 STRING COMPARISON FUNCTIONS Note: strcmp() and strncmp() are both case-sensitive. 60 STRING COMPARISON FUNCTIONS EXAMPLE #include #include int main() { char word1, word2; printf("Enter two words, separated by a space: "); scanf("%19s%19s", word1, word2); int c = strcmp(word1, word2); if (c < 0) printf("\"%s\" comes first.\n", word1); else if (c > 0) printf("\"%s\" comes first.\n", word2); else printf("Those two words are the same.\n"); return 0; } 61 STRING CONVERSION FUNCTIONS 62 STRING CONVERSION FUNCTIONS EXAMPLES long l; convert the string "123456789" to the l = atol("123456789"); long integer 123456789 63 END-OF-WEEK CHECKLIST Function prototypes Characters Function definitions Strings Call by value String manipulation functions Scope rules String comparison functions Array declarations String I/O functions Array initialiser lists Multi-dimensional arrays 64 GROUP PROJECT – Group Project – Grouping – Each team is formed with members from the same lab session – Each team will have 5 members (adjustments will be made wherever needed) – The final grouping will be announced on LMS – Project specs will be uploaded to LMS soonest. – Plagiarism is strictly NOT allowed – The group project is designed to help you to learn better. – Do not copy from peers or from seniors or from other places – Do not share your code with others or onto other platforms (e.g. GitHub) 65 ABOUT USAGE OF AI TOOLS – For Group Project AI tools are NOT allowed A declaration is needed from each team – For Test AI tools are NOT allowed 66

Use Quizgecko on...
Browser
Browser