180 likes | 199 Views
This introduction provides a brief overview of the C programming language, including its history, key features, and differences from Java. It covers topics such as arrays, pointers, function calling, I/O, data types, naming conventions, constants, arrays, control flow, and functions.
E N D
Introduction to C • C dates back to 1968 • It is a relatively small language although can be difficult, particularly when it comes to • Arrays of characters (strings) • Pointers • Function calling • You will find that C and Java look very similar about 50% of the time, but they differ because • C has no objects • C uses explicit pointers and all parameters are pass by copy • to achieve pass by reference, you must pass a pointer • I/O differs greatly from Java • Functions can be compiled separately which leads to a completely different treatment in defining structures, global variables, etc
Types • All types in C are primitive (unlike Java) • The types are (in order from smallest to largest): • char, short int (or just short), int, unsigned int, long int (or just long), unsigned long int, float, double, long double • Notice that there is no boolean, we will instead use int values of 0 and non-zero (anything other than 0) for booleans • Declaring variables is just as in Java • float a, b; // declare multiple variables if desired • int c = 5, d = 10; // declare and initialize • long int a = 10000000000; // int can be omitted • Literal values default to int or double unless otherwise indicated by L/l for long, U/u for unsigned, F/f for float • You can specify a double or float using a decimal or scientific notation (e.g., 123.4 or 1.234e2) • You can also provide values in Octal by preceding the number with a 0, or Hexadecimal by preceding the number with a X/x
Legal names are much like in Java Must start with letter or _ Must consist of letters, digits, _ no $ unlike Java Must not be a reserved word Can be any length desired in some versions of C, only the first 31 characters are used so identifiers that are 32 characters and only the last character differs would be thought of as the same identifier As with Java, C is case sensitive, so x and X are different identifiers and Void is a legal identifier since it is not the reserved word void Naming Conventions Much like Java – variables start with lower case characters and each new word in the variable starts with an upper case character or is separated by _ Constants are usually fully capitalized No objects, so no classes Naming Identifiers
Constants can be defined in two ways using #define compiler directive #define NAME value using the const qualifier const double PI = 3.14159; We will discuss the #define directive later, for now, you can declare constants either way Declaring arrays: type variable[size]; or type variable[ ] = {values}; unlike Java, there is no instantiation of the array You can define enumerable types using enum enum days = {sun = 1, mon, tue, wed, thu, fri, sat}; These are not strings! And they cannot be input or output Instead, you can reference them like you might int values But these provide the programmer with an idea what they are used for example: for(a = sun; a <= sat; a++) first value defaults to 0 unless you override as above: sun = 1, sat = 7 Constants and enum definitions are usually placed at the top of the program, prior to any functions Other Forms of Declaration
Assignment Statements • C is the same as Java when it comes to • Assignment statements • Reassignment statements • Relational operators and expressions • Boolean operators and expressions • except that in C, there is no true or false, it is 0 and non-0 • Prefix/Postfix increment/decrement • Casting and coercion • Conditional expression • x = (x < y ? 1 : 0); is the same as • if(x < y) x = 1; else x = 0; • In addition, C allows for bit-wise operations: • & (AND), | (OR), ^ (XOR), << (left shift), >> (right shift), ~ (NOT)
All of the following are the same as in Java: if if-else Nested if-else switch for while do continue break C offers a goto statement goto label label must follow the same rules as other identifiers labels are placed in your program as label: The goto statement is not necessary as the same effort can be achieved using the other control statements Control Flow Example: if(x < 0) goto error; value = sqrt(x); goto next; error: value = 0; next: printf(…);
Functions • In C, there are no methods, instead everything is a function • the function is very much like a Java method except that there are no visibility modifiers, anyone can call any function • As with Java, your program must include a main function • this will be the first set of code executed • it may call other functions • Functions may be written in the same file or in separate files • the C compiler will seek out functions that are referenced but not in the current file, however to be successful, these functions must be defined in files in the same directory • C also permits separate compilation of files so that you can compile a file that calls functions that haven’t been written yet • this makes C easier to develop software in than Java, at least in some cases • We will cover writing functions separately, but for now we will use some of the functions available in standard C libraries • to use any function, you must either provide its definitions in the file that calls it, and have the definition appear prior to the function that calls it, or you must use function prototypes • prototypes are usually placed prior to your function’s definition, but can also be placed in library files…
Importing Library Files • Unlike Java, a C library file is just a collection of declarations rather than definitions • that is, instead of having methods, we use the library file for declaring constants, enums, function prototypes, other import statements, and perhaps declaration of global variables • For now, just plan on importing the library files needed for your C programs • later in the semester we will write our own library files but for now, we will merely use the built-in ones: • stdio – loads the definitions and prototypes for the I/O operations • time – if we need to deal with the clock • stdlib – standard library that includes functions like random • To import a library of functions use #include • #include <stdio.h> // standard I/O functions • #include “myfunctions.h” // use “” if header file is yours
Random Numbers • There are two functions used to generate random numbers, both part of the <stdlib.h> library • srand(value) is used to initialize the random number generator seed at position value • You can specify a location via an input number or a constant (which would mean that you always get the same random numbers) or by using the current time • To use time, you need to include <time.h> • srand(time(NULL)); • To generate a random number, use rand( ) which generates any int value, so you will want to mod it • x = rand( ) % SIZE + 1; // generates a number from 1..SIZE
Basics on Input & Output • C offers three standard ways to get input and three standard ways to get output • Single character I/O • Input and output of multiple variables from keyboard and to monitor • Input and output from and to disk file • Single character input uses the getchar( ) function • this returns an int value that is interpreted as a char • the function is in the stdio library, so you need #include <stdio.h> • ex: c = getchar( ); • or more complicated: while((c = getchar( )) != ‘\n’) {…} • Single character output uses putchar(c) where c is the char (or an int storing an ascii value, e.g., 65 for ‘A’) • also part of stdio library • putchar returns a value that can be used for error detection – the value -1 denotes an error
Characters, Ints and Escape Sequences • In C, chars and ints are related to each other • the char is actually stored as an int, but what it stores is the int’s ascii value • this allows us to treat the char as an int for doing such things as ++, --, or using them in for-loops, etc • some functions that deal with chars actually return int values (e.g., getchar) • casting is necessary when converting an char to an int, but not when we want to use an int as a char as long as the int is a legal ascii value • as with Java, character values can be single characters or escape sequences, all escape sequences all begin with \, examples include: • \\ -- backslash \b – backspace • \? – question mark \’ – single quote mark • \n – new line \” – quote mark • \t – horizontal tab \0 – null character (this is slash zero) • <ctype.h> is the header file for a built-in library of char functions, including: • isalnum(c), isalpha(c), iscntrl(c), isdigit(c), islower(c), isupper(c), isspace(c), ispunct(c) – these return non-zero if true and 0 if false (alnum means alphanumeric) • tolower(c)/toupper(c) – returns c in lower/upper case if c is a letter
printf • This is more useful than putchar as • printf allows you to output multiple things in one instruction and allows you to format your output • putchar just outputs one character at the next location in the output stream • the actual command will look like this: • printf(“specificiation”, var1, var2, …); • where specification denotes the formatting for each of the variables, followed by the list of variables • As an example, printf(“%d%s%c”, x, y, z); would output the int value x followed by the string value y followed by the char z
The specification is a string that includes for each variable to be output % Special indicator (optional) Conversion character Special indicators are – (left justified) number (minimum field width) .number (precision indicator for float/double and string) h or l for short or long int values Conversion characters are d, i – int, decimal number o – int, unsigned octal x, X – int, unsigned hex u – int, unsigned decimal c – int, single char s – char *, a char array (more precisely, a pointer to a char array) or string f – double with the number of decimal digits indicated by using the special indicator .x e, E – double in scientific notation g, G – double in scientific notation without trailing zeros p – pointer % – no argument, print a % printf Specifications
scanf var1 scanf • The primary input instruction is scanf • It permits any type of input, not just chars as with getchar and you can input multiple variables with one scanf instruction • The general form is • scanf(“specification”, var1, var2, …); • However, in C, parameters are passed by copy • this means that any parameter passed to the function is actual a copy of the original and any changes made to this variable stay inside the function, that is, the value is returned • in the above example, var1 and var2 are passed as an uninitialized variables to scanf, scanf then gets values from the keyboard and stores them in the local parameters, but are not returned, so var1 and var2 remain unchanged! • we need to pass pointers instead of variables • if var1 is a pointer to a memory location, then scanf takes the input value and places into that memory location directly so that var1 receives the value (var1)
More on scanf • The basic form of scanf is: • scanf(specification, &var1, &var2, …) or • var = scanf(specification, &var…) • scanf returns an int value equal to the number of successful items input • specification, as with printf, is a string that describes the expected values • This format for the specification is of the form “%x %y” where the letters represent formatting information • the specification options are the same as with printf except that there is no %p (pointer) and you don’t use the special indicators like – or . • The specification string may also include blanks (ignored), ordinary characters (which are expected to match the next non-white space char in the input stream), * (suppress the next char), a number (expected width of the next input) or a letter representing a size (h, l, L) • All variables must be specified as the address to that variable, thus the &
scanf is tricky because it is easy to forget to pass an address instead of the variable itself Consider: scanf(“%d”, n); scanf(“%d”, &n); Both of these instructions compile but only the second instruction sets n to the appropriate value the first of these could (and probably will) result in run-time or logical errors Arrays are treated differently than other variables, they are already referenced by pointer Strings are actually arrays of chars, so we have to slightly alter how to input strings, we do not pass a pointer to the string (the variable is already a pointer): if s is a string, then to input s you would do scanf(“%s”, s); not scanf(“%s”, &s); A Word of Caution
File I/O • To handle interactions with a file, we need to use the file functions, part of the stdio library • C offers the type FILE (notice that it’s spelling is all upper case, but it is a type like int) • Interaction will be through a variable of type FILE, however the interactions will require a pointer, so you want to make a pointer of type FILE as in • FILE *fp; // fp is a file pointer • You must first open the file using fopen • fopen takes two arguments, the file’s name (a string) and a mode which is a string that indicates how the file is to be used (“r” for read, “w” for write, “a” for append, “b” for binary – otherwise it defaults to a text file) • If a file to be written to does not exist, it is created when opened
Using Files • Read/write 1 char from/to a file, use putc and getc • similar to putchar/getchar except these include the file pointer as a parameter • char c = getc(fp); • putc(c, fp); • For formatted I/O to disk file we use fscanf and fprintf • these are variants on scanf/printf but include the file pointer • fprintf(fp, “%s”, s); • Files need to be closed after they have been used, using fclose(fp); • Some miscellaneous file functions include: • ungetc – takes the char just retrieved from a file and adds it back to the file • x = ungetc(c, fp); // returns EOF if error • ferror returns an error condition regarding the file, 0 if no error • e = ferror(fp); // e is 0 if no error, an error code otherwise • feof determines if the file is at the end yet • e = feof(fp); // non-zero means end of file reached • fgets and fputs gets or puts an entire line of some max chars from or to a file • fgets(line, max, fp); // line is a string • fputs(line, fp); // line is a string