CS 108 Computing Fundamentals March 3, 2016
Let's Review The Homework
Fundamentals of Characters and Strings Characters in C consist of any printable or nonprintable character in the computer's character set including lowercase letters, uppercase letters, decimal digits, special characters and escape sequences. A character is usually stored in the computer as an 8-bits (1 byte) unsigned integer. The integer value stored for a character depends on the character set used by the computer on which the program is running.
There are two commonly used character sets: ASCII (American Standard Code for Information Interchange) EBCDIC (Extended Binary Coded Decimal Interchange Code) Fundamentals of Characters and Strings
There are two commonly used character sets: ASCII (American Standard Code for Information Interchange) EBCDIC (Extended Binary Coded Decimal Interchange Code) Fundamentals of Characters and Strings
Example: ASCII character #include // 1.c int main(void) { char demo_A = 'A'; char demo_Z = 'Z'; char demo_a = 'a'; char demo_z = 'z'; printf("\n ASCII integer value for A is %d", demo_A ) ; printf("\n ASCII integer value for Z is %d", demo_Z ) ; printf("\n ASCII integer value for a is %d", demo_a ) ; printf("\n ASCII integer value for z is %d", demo_z ) ; printf("\n\n\n"); printf("\n 65 in ASCII represents %c", 65 ); printf("\n 90 in ASCII represents %c", 90 ); printf("\n 97 in ASCII represents %c", 97 ); printf("\n 122 in ASCII represents %c \n\n", 122 ); return 0 ; }
Example (continued) #include //2a.c int main(void) { char ch = ' '; printf("\n\nEnter a character: "); scanf("%c", &ch); if ( ch >= 'A' && ch <= 'Z' ) { printf("\nCapital letter.\n"); } return 0 ; } #include //2b.c int main(void) { char ch = ' '; printf("\n\nEnter a character: "); scanf("%c", &ch); if ( ch >= 65 && ch <= 90 ) { printf("\nCapital letter.\n"); } return 0 ; } equivalent to
Character Type: char In C, characters are indicated by single quotes: char input_char = 'P'; printf( "input_char is %c \n ", input_char );
Strings In C a string is really an array of characters that ends with a special character: the null character ( '\0' ) … we use double quotes: "this is a string" // " " means the \0 is added But you can't use an assignment operator to assign a string to a character array after it has been declared (need to use the string copy function) char color[ 15 ] = "green"; // Acceptable assignment demo = "purple"; // Unacceptable assignment
Strings A null ( '\0' ) character is placed to mark the end of each string String functions use '\0' to locate end of string (so you don't need to pass a string's length as argument to a string function) tsisihas\0gnirt
In C Strings are Character Arrays (logically) Strings in C, in a logical sense, are arrays of characters which terminate with a delimiter (\0 or ASCII NULL character). char str_1 [ ] = {'H', 'e', 'l', 'l', 'o', '\0'}; char str_2 [10] = {'\0'}; str_2 is a ten-element array that can hold a up to nine characters + \0 Strings in C need the delimeter to determine where the string ends (remember: the length of a string is dynamic… it isn't determined before runtime) It's the delimiter position (not the size of the array) that determines the length of the string
Accessing String Characters Like any array, the first element of a string in C is at index 0. The second is at index 1, and so on … char str_2 [10] ; str_2[0] = 'P'; str_2[1] = 'u'; str_2[2] = 'l'; str_2[3] = 'p'; str_2[4] = '\0'; str_2 now contains the string "Pulp" + \0 + 5 unused (at this time) "blanks"
String Literals String literals are given as a string inside double quotes. You've used string literals many times already printf("Enter an inter value:"); String literals are often used to initialize a string array/pointer variable char str_1[10] = "Roswell"; char str_1 [ ] = "Roswell"; Remember: the NULL is added automatically to the end (if there is space available)
Entering Strings with scanf ( ) Use %s format specifier: %s scans up to but does not include next white space %ns scans the next n characters or up to the next white space, whichever is first You only need to provide the starting address of the string with %s Example: scanf ("%s", str_1); scanf ("%2s", str_1); No address-of operator (&) is necessary when inputting strings (%s) into character arrays! But you an use the & if you like.
Reading and Printing a String #include /* 3a.c */ int main ( void ) { char name [ 15 ] = {'\0'}; printf( " \n Enter your first name: " ); scanf( " %s ", name); printf( " \n Your first name is: %s \n\n ", name); printf( " \n Enter your whole name: " ); scanf( " %s ", name); printf( " \n Your whole name is: %s \n\n ", name); return (0); }
Reading and Printing a String #include /* 3b.c … it's safer to limit the characters input*/ int main ( void ) { char name [ 15 ] = {'\0'}; printf( " \n Enter your first name: " ); scanf( " %14s ", name); printf( " \n Your first name is: %s \n\n ", name); printf( " \n Enter your whole name: " ); scanf( " %14s ", name); printf( " \n Your whole name is: %s \n\n ", name); return (0); }
Strings in C We can change parts of a string variable char str_1[6] = "hello"; str_1[3] = 'p'; /* str_1 now contains "helpo" */ str_1[4] = '\0'; /* str_1 now contains "help" */ We must retain the delimiter… by replacing str_1[5] in the original string with a character other than '\0', this makes a string that has no end, which means it is not a string (it is an array of characters) We must stay within limits of array char str_1[6] = "Hello"; /* this is fine */ char str_2[5] = "Hello"; /* this is not fine… no space for the \0)
Strings in C %s format specifier is used to read a string in a scanf( ) call %s ignores all leading white space %s reads all characters until next white space is found %s stores \0 (NULL) after last character %s reads into an array (no & necessary because an array is a pointer constant) Example: char str_1[15]; scanf("%s", str_1); Remember: too many characters for array causes problems
Strings in C Use a width value in with the format specifier to limit the number of characters read: char str_1[15]; scanf("%14s", str_1); Important Point: you always need one space for the \0 so the "effective" width is always one less than the size of the array Strings shorter than the field specification are read normally (as The Terminator might say, "no problemo")
Strings in C %s format specifier used to print a string in printf( ) call: characters in a string printed until \0 encountered char str_1[15] = "Santa"; printf("%s", str_1); Output: Santa Use width value to print string with spaces: printf("%14s", str_1); Output: Santa Use - flag to print string as "left justified": printf("%-14s", str_1); Output: Santa
scanf and Strings: Safer Approach 1 Use %widths to copy only up to some number number of characters. char demo[10]; printf("Enter a string: "); scanf("%9s", demo); printf("You entered %s\n\n", demo)
scanf and Strings: Safer Approach 2 #include //4.c #include int main(void) { char user_input[11]; int size = 0, index = 0; printf("\n\nEnter a word: ") ; scanf("%10s", user_input ); printf("%s backwards is ", user_input ); size = strlen(user_input) ; for( index = size - 1 ; index >= 0 ; index = index - 1) putchar( user_input [ index ] ) ; printf("\n\n") ; return(0); }
getchar getchar ( ) will fetch one (1) character from the input stream char demo ; printf("Enter a character: "); demo = getchar( ); printf("You entered %c \n\n", demo);
fgets char * fgets( charArray, lengthLimit, file_pointer of stdin ) fetches a whole line, up to the size limit or when it reads a new line character '\0' added at the end of string Example: char demo[80]; fgets( demo, 79, stdin ) ; // fetch from keyboard Returns a NULL if something went wrong, otherwise a pointer to the array
#include //5.c #include int main(void) { char user_input[100]; int size = 0, index = 0; printf("\n\nEnter a word: ") ; fgets(user_input, 99, stdin ); printf("%s backwards is ", user_input ); size = strlen(user_input) ; for( index = size - 1 ; index >= 0 ; index = index - 1) putchar( user_input [ index ] ) ; printf("\n\n") ; return(0); }
String Functions Pretty straightforward Both texts are pretty clear Practice questions at the end of the chapter are useful as are the e-Book challenge questions Play with your food Let's move on to the next topic: Programmer-Created Functions
Functions – A Little Review and A Little New What is a function? Why are functions useful? What are the characteristics of a function? What is a programmer-created function? How do we create programmer-created functions?
What is a function? Function can be thought of as a module or a subprogram A named block that is designed to perform a specific task within a program Examples of functions with which we’ve worked: main( ), printf ( ), and scanf( )
Functions Are Very Flexible Tools Many useful functions are found in libraries See Table 3.1 and Appendix B in the textbook Some functions are general while others are very specific in nature and use Some functions have parameters and some do not Some functions return a single value and some do not Some functions have side-effect(s) and some do not effect+%28computer+science%29 Function libraries are not panaceas: we need ability to create our own functions (programmer-created functions)
Why are functions useful? They facilitate the use of structured programming - Top-down design - Code reusability - Information hiding - Abstraction
Structured Programming Structured Programming is a problem-solving strategy and a programming methodology that has the following two goals: The flow of control in a program should be as simple as possible The construction of a program should embody top-down design
Top-down Design Top-down design, also referred to as stepwise refinement, it consists of repeatedly decomposing a problem into smaller problems. Smaller problems solved via smaller solutions (programs, sub-programs or modules) Each piece is more manageable than the original program Requires integration of smaller programs (programs, sub- programs or modules) into a mosaic that satisfies the larger/overarching goal
Code Reusability Code reusability addresses the ease with which software programs/modules/functions) can be used in other programs. Goals include: Allowing programs to take advantage of other programmers’ knowledge/expertise Saving time and resources Making a programmer’s life easier
Information Hiding Information hiding is a concept in which the data structure and the implementation of its operations are not known by the user. C language examples with which we are familiar: printf( ) and scanf( ) Practical examples of a “black box” might include: picture-taking machine at an amusement park car engine or transmission
Function Characteristics Functions are composed of three elements/pieces: - Prototype (e-Book does not use prototypes… working with publisher to add them) - Declaration - Call Functions found in libraries will have their prototypes and declarations inside the library… therefore, we do not include prototypes and declarations for library functions in the source- code that we write
Function Characteristics When we write functions in our C code these functions will be known as programmer-created functions In our programs we must provide all three components of a function for all programmer-created functions - Prototype - Declaration - Call Library functions vs. programmer-created functions
Programmer-created Function Prototype Always located before main( ) function… provides a "hint" to compiler of what is to come that isn't standard C or in a library General syntax: ([ ]) ; Return type may be void or a single data type only Parameters may be void or parameters may be numerous and of various (mixed) data types Parameters may be named but are not usefully named in the function prototype… only data type(s) are required in prototypes Prototype examples: int add_two_integers ( int, int ) ; same as int add_two_integers ( int perch, int trout ) ;
Programmer-created Function Declaration Always located after main( ) function Contains all the source code for that function ( [ ] ) { C programming code ; return ; } Parameters (aka formal parameter or formal arguments) must be named in the function declaration Parameters are memory objects Local variables (variables inside the function) may be used
Programmer-created Function Declaration Example: int add_two_integers ( int first, int second ) { return (first + second) ; }
Programmer-created Function Call Located inside main( ) function or inside another function = ([ ]) ; or ([ ]) ; Examples: sum = add_two_integers (12, 34) ; display_greeting ( ); programmer-created functions calls arguments list
Another example (the whole picture in segments): int cuber ( int ) ; // Function Prototype ******************************************************* int cuber ( int num1 ) // Function Declaration Begins { int answer; answer = num1 * num1 * num1 ; return answer; } // Function Declaration Ends ******************************************************* n = cuber(5) ; // Function Call
The next slide puts everything together.
# include // file 6.c in my DogNet home directory int cuber ( int ) ; // Programmer-created function cuber prototype int main (void) { int input = 0, result = 0 ; // Local variables for main( ) declared printf("\n\n Enter an integer value to be cubed: "); scanf ("%d", &input) ; result = cuber ( input ) ; // Programmer-defined function cuber call printf("\n\n\n The value of %d cubed is %d.\n\n\n", input, result ); return (0); } int cuber ( int num1 ) // Programmer-created function cuber declaration start { int answer; // Programmer-created function cuber local variable answer = num1 * num1 * num1 ; return answer; } // Programmer-created function cuber declaration end
Another example on the next slide… this example demonstrates a side-effect and an empty parameters list.
# include // My file 7.c void display_message (void) ; // PCF Prototype int main ( void ) { display_message ( ) ; // PCF Call return (0); } void display_message (void) // PCF Definition… shows one type of // “side effect” { printf(" \n\n What do you want for nothing? \n") ; printf(" Rubber Biscuit! \n\n\n " ) ; return ; } never place void in a function call
/* An example demonstrating local variables and side-effects … my file 8.c */ # include // make sure to use a symbol table/memory map void function_1 (void); // PCF Prototype int main (void ) { int num_1 = 22; // num_1 used as variable in main() printf("%d \n", num_1); function_1( ); // PCF Call printf("%d \n", num_1); return (0); } void function_1 (void) // PCF Declaration { int num_1 = 55; // num_1 used as variable in function_1 printf("%d\n", num_1); num_1= num_ ; printf("%d\n", num_1) ; return ; }
/* An example demonstrating local variables, scoping, and side-effects … 8.c */ # include // make sure to use a symbol table/memory map void function_1 (void); // PCF Prototype int main (void ) { int num_1 = 22; // num_1 used as variable in main() printf("%d \n", num_1); function_1( ); // PCF Call printf("%d \n", num_1); return (0); } void function_1 (void) // PCF Declaration { int num_1 = 55; // num_1 used as variable in function_1 printf("%d\n", num_1); num_1= num_ ; printf("%d\n", num_1) ; return ; } Output
The Return Statement When a return statement is executed, program control is immediately passed back to the calling environment/function. If an expression follows the keyword return, the value of the expression is returned to the calling environment as well. A return statement has one of the following two forms: return; return expression;
The Return Statement return; return answer ; // Assuming answer is a variable return first + second ; // Assuming first and second are variables return (a+b+c); // Assuming a, b, and c are variables
Pico Shortcuts (one more time) ctrl-w followed by ctrl-t produces a prompt that asks you on which line you like the cursor to be positioned ctrl-c produces the number of the line on which the cursor is currently positioned ctrl-y moves the cursor up one page ctrl-v moves the cursor down one page ctrl-k deletes an entire line