Intro to Programming in C
Motivation for Using C High level, compiler language Efficiency over user-friendliness Allows programmer greater freedom, but chance for is error increased
Functions C includes support for functions Function structure return_type function_name(parameters) { variable declarations; body statements; return return_value; } Example: int add_function(int a, int b) /* Pass values a and b to function */ { int sum; sum = a + b; return sum; /* Returns the integer variable sum */ }
Main Function Each C program contains a main routine, which is itself a function The main routine typically returns no value and contains no parameters, so the default return type is “void” Example: void main(void) { main routine }
Creating Functions Convention is to place function “prototype” above the main routine Prototype includes function name and variables used: int add_function(int, int); /* function prototype */ main routine … Function body defined below main routine: main routine {…} int add_function(int a, int b); { function body};
Calling Functions Call a function by invoking its function name within the main routine or another function and passing parameters Example: void main(void) { int a,b,x; … x = add_function(a, b); /* Passed by value */ /* x is set equal to the return value of add_function */ }
Basic Data Types Int Represents standard integers (usually 32 bits) Float Represents numbers with decimal precision (usually 32 bits) Can use notation: 2.3E10 2.3 * 10^10 Double Represents very large floating point numbers (usually 64 bits) Character (Can also declare “byte” when using Processor Expert) Represents single ASCII characters Characters contained within single quotes: ‘a’ No String types!
Data Type Modifiers Signed Allows the data type to take on negative and positive values Integers, doubles, and floats are signed by default Unsigned Allows the data type to take on only positive values Short Reduces range of values and storage space occupied by the variable (usually 16 bits) Long Increases range of values and storage space occupied by the variable (usually 32 bits)
Declaring Variables Variables are defined using the following format: type name1, …, name5; Name rules: Cannot begin with a number Cannot contain spaces (can contain underscores) Cannot contain any punctuation marks or arithmetic operators Cannot be a reserved keyword C is case sensitive! Examples int a, b, c; short int d; unsigned double e; float f; char g; …
Initializing Variables Possible to initialize variables within declaration: int a = 3; byte x = 0x02; byte y = 0b ; char b = ‘b’; Constants Use keyword “const” Constants cannot be changed after initialization Example: const int b = 5;
Assigning Variables Valid assignments int a,b; int c = 5; a = 10; a = c; a = b = c = 0; Type Casting Possible to convert between several types: (type) variable_name Examples: x = (int) float_variable /* Converts a float to an integer x = (int) char_variable /* Converts a character to ASCII value x = (char) int_variable /* Converts ASCII to appropriate character x = (float) int_variable /* Converts an integer to a float
Variable Scope Global variables Declared above the main routine, normal syntax (convention is to use all caps) Available to all functions Global constants declared using: #define VARIABLE_NAME value Local variables Declared within a function Only available to the function in which declared, able to pass on to other functions
Pointers Used to point to a memory location of a variable Points to the beginning of the memory segment the variable occupies Use the ‘*’ operator in front of variable to declare a pointer float test_var; float *test_var_loc; Use the ‘&’ operator to get the memory location of non-pointer variables test_var_loc = &(test_var)
Pointer Operations Using the ‘*’ in front of an already declared pointer yields contents of memory location pointed to Example: int test_var = 10; int X; int *location; location = &(test_var); X = *location; /* The variable X now contains the value 10
Pointer Operations (cont.) Possible to assign values to memory location using pointer Example: int test_var = 10; int *location; location = &(test_var); *location = 20; /* The variable test_var now contains the value 20
Function Calls Using Pointers Possible to pass “by reference” using pointers Example: void set_zero( int *a) { *a = 0; } void main() { int b = 10; set_zero(&b); /* b is now set to zero */ }
Pointer Notes Not useful to initialize pointers in the declaration: Initially, pointer points to “garbage” location, so assigning a value to this location is useless Useful in debugging Used heavily in string manipulation Make linked-lists possible
Arrays Arrays are defined as follows: type var_name[size] Array index begins at zero Array index ends at size – 1 Example: int array1[3] = {1, 2, 3} /* array1[0] = 1, array1[1] = 2, array1[2] = 3 */
Arrays (cont.) Multidimensional arrays: int multi_array[10][10]; /* 10x10 array */ Possible to use as many dimensions as needed Can initialize entire array at once: multi_array[ ][ ] = 0;
Strings There is no “string” type in C Strings made possible through character arrays Declared as a pointer to a character or an array of characters
Creating Strings Pointer method Creates a pointer to the first location of the string char *test_string = “Hello World”; Strings always terminated with the null character: ‘\0’ Array method Easier to understand char test_string[20] = “Hello World”;
String Manipulation Many useful functions contained within “string.h” strlen(string) returns the length of the string excluding the null character strcpy(string1, string2) copies contents of string2 into string 1 strcmp(string1, string2) compares string 1 to string 2, returns 1 if same and 0 if different strstr(string1, string2) searches string1 for the substring string2, returns the location at which the substring begins or null strcat(string1, string2) concatenates string2 onto the end of string1
Structures Creates a new data type that can hold several data types within one variable Use “struct” keyword typedef struct { char name[30]; char address[50]; int birth_year; int birth_month; int birth_day; } PersonalData; Declare variable of type PersonalData PersonalData record1; Access struct using dot notation record1.name = “Sam Castillo”;
Arithmetic Operations Addition: + a + b Adds a to b Subtraction: - a – b Subtracts b from a Multiplication: * a * b Multiplies a by b Division: \ a \ b Does integer division of a by b Modulus: % a % b Returns remainder of a \ b
Comparison Operators Greater than: >, >= a >= b Tests if a is greater than or equal to b Less than: <, <= a <= b Tests if a is less than or equal to b Equal to: == a == b Tests if a is equal to b Not equal: != a != b Tests if a is not equal to b
Bit Operators Shift Left: << a << b Shifts bits in a left by b bits Shift Right: >> a >> b Shifts bits in a right by b bits And: & a & b Does the bit-wise AND of a and b Or: | a | b Does the bit-wise OR of a and b Exclusive OR: ^ a ^ b Does the bit-wise XOR of a and b
Other Operators One’s compliment: ~ ~a Performs one’s compliment of a Pre-increment: ++ ++a the value of a after incrementing Post-increment: ++ a++ the value of a before incrementing Pre-decrement: -- --a the value of a after decrementing Post-decrement: -- a-- the value of a before decrementing Negation: ! !a does the negation of a
If statements Basic structure: if (test_statement) { do this if test statement is true; } else if (test_statement) { do this if test statement is true; } else { do this if the above conditions were false; }
Alternative If Statement C provides a more concise way to create an If statement The syntax: decision statement ? true statement:false statement Example int X = 4; X == 5 ? X = 6 : X = 7; /* First, the program checks if X is equal to 5 If X was equal to 5, then X would be set equal to 6 Since X wasn’t equal to 5, X is set to equal 7 */
For Loops Basic structure for(control variable; loop condition; increment) { statements; } Example: int count; int a = 1; for(count = 1; count <= 5; count++) { a = a*2; } /* Here a = 32 when the loop completes */ Cannot declare control variable within the for loop! Can exit a for loop at any time with the statement “break”
While Loops While loop: Condition is evaluated each time the loop runs, including the first time it is called while(condition) {statements; } Do While loop: Statements are executed the first time, then execution depends on whether the condition evaluates to 1 do { statements; } while(condition)
Printing to the Screen Output to the screen using “printf” function Structure: printf(“Text…”, variables used); To insert variables, must use “control sequences”
Printf Control Sequences Denoted with a “%” %d integers, doubles %u unsigned integers %c characters %s strings (character arrays) %f fixed floating point values %e scientific notation floating point %x hexadecimal values %o octal values
Inserting Control Sequences Insert the sequences in the Text portion of the printf statement int a = 20; char c = ‘b’; printf(“The value of a is %d.”, a); printf(“The value of c is %c.”, c);
Output Formatting Padding the end of the output printf(“%6d, int_val) /* Pads up to 6 places Padding the start of the output printf(“%-6d, int_val) /* Pads up to 6 places Floating point precision printf(“%.3d, float_val) /* Prints 3 decimal places Truncating strings printf(“%.3s, string_val) /* Prints first 3 characters Truncating and Padding printf(%10.5, string_val) /* Prints first 5 characters, pads last 5
Outputting Special Characters Possible to output with the following codes: \b backspace \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \” double quote \’ single quote \\ backslash \ddd octal ASCII code \xddd hex ASCII code
Receiving Keyboard Input Using the “scanf” function scanf(“String…”, pointers); Must use control sequence, different from printf Must use “&” when referring to input variables Example: scanf(“%d”, &int_var); scanf(“%f”, &float_var); scanf(“%c”, &char_var);
Scanf Control Sequences Denoted with a “%” %d integers %ld long integers %h short integers %c single character %s strings (character arrays) %f fixed floating point values %lf long float type %e scientific notation floating point %x hexadecimal values %o octal values
Dangers of Scanf Scanf can cause many errors if used incorrectly The control sequence used must match the type of variable that is storing the input If types don’t match, scanf quits Input file will hold onto data, which is used in next scanf call
Including Separate Files Start by including all necessary libraries and files before the main routine Use the #include operator to include each header-file as needed Example: #include #include #include Include all function headers before the main routine
Commonly Used Libraries Stdlib.h Contains many of C’s general use functions Stdio.h Contains all input/output functions Math.h Contains many math-related functions String.h Cointains all string manipulation functions
Creating Header Files Create desired functions within a text editor Save with the.h extension Include the header file within the main program using the #include operator
Header File Example Header File: test.h int testfunction1( ) { function body… } int testfunction2() { function body } … Main file #include … Now have access to all functions defined within test.h
Putting it all together Example Program Structure #include … #define … Global variable declarations… function prototypes…. main routine { local variable declarations main body function calls } function definitions… { local variable declarations body statements return }