COMPUTORIENT HAND-OUTS (June 4-5, 2012) 1.
Introduction to Programming Some terminologies a. Program – Set of instructions – Written to perform a specific task to yield a specific output b. Programming - Art of designing and implementing the operations to be performed by the computer to solve a particular problem or to accomplish a specific task. c. Algorithm – series of steps to be followed to perform a task d. Code – program text e. Pseudocode – intermediary between a language that we understand and a language that can be understood by computers – Most often used to conceptualize the problem before starting to code – Also used to discuss a problem without thinking too much about the programming language that you need to use f. Library – collection of pre-defined functions g. Compiler - Used to convert programs from a source language to a target language h. Bugs – Program errors i. Debugging – process of removing these errors
2.
The C Programming Language Brief History a. Created by Dennis Ritchie b. During the 1970’s c. Created with the Unix Operating System in mind Other facts a. Imperative or a procedural programming language b. It influenced C++ and Java c. It was initially used for Systems programming Program Structure a. Pre-processor directive i. Instructions to the computer before your code is compiled ii. #include<libraryheader> – tells the computer to get code from a certain library iii. #define – usually used to define constants (ex: #define PI 3.14) b. Main function declaration i. Syntax of a normal function declaration: <return value> <name of function> <list of arguments enclosed with parentheses> ii. How a main function is usually declared: int main () c. Function body i. Contains the program proper: executable statements, declarations, etc. ii. The "return 0;" signifies the return value needed by the function. iii. Whole program block is delimited by braces {}
Basic Input-Output a. printf i. Syntax: printf(“insert items to be printed here”); ii. Syntax for use of place holders: printf(“insert items here”, <variables or list of variables to be used in what is to be printed>); iii. Used to print to the standard output stream (console) iv. From the <stdio.h> library v. Common escape sequences: Name Newline \n Tab \t Backslash \\ Question Mark \? Single Quote \’ Double Quote \” vi. Ex: printf(“Hello world!\n”); vii. Ex: printf(“My name is %s.\n”, name); b. scanf i. Syntax:
Symbol
scanf(“placeholder”, &address); ii. Used to get input from the user from the standard input stream (keyboard) iii. From the <stdio.h> library iv. Common placeholders: Name Symbol Whole numbers %d Decimals %f Single Characters %c Multi-character %s v. The "address" in the format above requires the name of the variable to be used. vi. Ex: scanf(“%d”, &age);
Expressions a. Variable Declarations i. Variables – hold the data that your program needs ii. Kinds: 1) Global variables: a) declared outside of the main function b) accessible throughout the whole program 2) Local variables: a) declared inside a specific block b) accessible only in that block iii. Syntax: <variable type> <variable name/s> iv. Variable types (data types): 1) int a) Known as the whole numbers b) Stores negative and non-negative values c) Ex: int myFavoriteNumber = 7; 2) char a) Single characters b) Stores alphanumeric values and symbols c) Ex: char myFavoriteLetter = ‘c’; 3) float a) Stores numbers with fractional parts b) Ex: float pi = 3.14; v. Valid variable names 1) Should start with either an underscore or a letter 2) Can be followed by digits, letters, underscores, or nothing at all 3) Variable names are case-sensitive in C, therefore, abc and ABC stand for two different variables! 4) Ex: myVariable, a, _123, _, XYZ, helloPhowsz1234 b. Operators i. Logical 1) usually used to compare two conditional statements 2) returns either a true expression or a false one 3) AND, OR, and NOT a) AND (&&): evaluates to true if both left hand side and right hand side of the expression evaluates to true. False, otherwise. i. Ex: ( a && b ) b) OR (||): evaluates to true if at least one of the sides evaluates to true. False, otherwise. i. Ex: ( a || b ) c) NOT (!): evaluates to true if the statement it negates is false. False, otherwise. i. Ex: !a d) Note: In C, zero is false and non-zero values are true. ii. Arithmetic 1) Addition (+) 2) Subtraction (-) 3) Multiplication (*) 4) Division (/) 5) Modulo operation (%) a) evaluates to the remainder when two numbers are divided b) Ex: 10 % 3 results to 1 iii. Relational
1) 2) 3) 4)
compares two values or expressions usually used for conditional statements evaluates to true or false Operators a) Greater than (>) b) Less than (<) c) Greater than or equal to (>=) d) Less than or equal to (<=) e) Equal to (==) f) Not equal to (!=) iv. Shortcuts in Operators 1) x = x + y x+=y 2) x = x - y x-=y 3) x = x * y x*=y 4) x = x / y x/=y 5) x = x % y x%=y 6) x = x+1 x++ (postfix) OR ++x (prefix) 7) x = x-1 x—(postfix) OR –x (prefix) v. Additional Notes: 1) Unary operators exist in C. A common example is the negative sign to signify a negative value “-“. Ex: -9 2) Do not confuse "==" with "=". The former is a relational operator. It tests equivalence between two values. The latter is an assignment operator most often used to initialize variables or to change the value they hold. 3) You can add comments to your programs (that is, expressions that are part of your program code but are disregarded by the computer) by using either /* COMMENT HERE*/ or // Comment here. a) The first one is for a multi-liner comment. b) The second one is for a single line comment Control structures a. 3 types: i. Sequential - code is executed in order. From top to bottom. ii. Selection 1) The flow of the program depends on the truth value of conditional statements. 2) Types: a) If Statement i. Syntax: if (condition to be satisfied) { *code block* } ii. Note: if the braces are omitted, the first line in the code block will be the only one to be executed if the condition is satisfied. iii. The form of the condition to be satisfied uses the logical operators and the relational operators. iv. Ex: if ( a > 10 ) { b = a + 3; a++; } b) If-Else Statement i. Just like an ordinary if statement, but has an else with it. ii. Else: 1. requires an if-statement 2. executes when the condition in the if-statement is not satisfied 3. Ex: if ( a > 10 ) { b = a + 3; a++; } else { b = a + 2; a--; } c) Switch Statement i. Used when a lot of cases are possible
ii. Syntax: switch (name of variable to be evaluated) { case 1: *code* break; case 2: *code* break; … default: *code* break; } iii. The break is used so that the statement will only evaluate the codes in the particular case it satisfies. That is, it will not fall through to other cases. iv. The default is used so that there will be a specific code block to be evaluated when none of the cases are satisfied. This can be omitted, in which case, the switch block is disregarded. v. Only the first case to be satisfied will have its code block executed. Unless of course the break is omitted. vi. The cases can also evaluate characters. Only, it should be enclosed by single quotes. vii. Ex: switch (number) { case 1: printf(“One”); break; case 2: printf(“Two”); break; case 3: printf(“Three”); break; case 4: printf(“Four”); break; case 5: printf(“Five”); break; } iii. Repetition 1) A code/block of code is repeated until a specific condition is met 2) Types: a) While Statement i. Usually used when the number of repetition is not known in the beginning. ii. The condition is evaluated in the beginning. iii. Syntax: while (condition to be satisfied) { *code block* } iv. Ex: while ( countdown != 0 ) { printf(“%d”, countdown); countdown--; } b) Do-While Statement i. Like the while statement, however, the condition is evaluated in the end, hence, allowing for at least one execution of the code block. ii. Syntax: do { *code block* } while (condition); iii. Ex: do { printf(“Nothing to do here.”); a--; } while ( a != 0 ); c) For Statement i. Usually used when the number of repetition is known beforehand. ii. Usually, a loop counter is maintained for the loop to terminate. iii. Syntax: for ( initialization of loop counter; condition; updating of the loop counter ) { *code block* } iv. Ex: for ( x = 1; x <= 10; x++ ) { printf(“%d\n”, x); }
Arrays
a. b.
c. d.
e.
f.
g.
Can be thought of as a collection of multiple elements of the same type. Parts: i. Name ii. Index – a number used to access an element in the array iii. Data type Syntax: <data type> <name of the array>[array size]; Example: int arr[10]; this means that you have a collection of integers stored in the array “arr” this array can store up to 10 values to access the first element of the array simply type in arr[0]; it is important to note that accessing the elements of the array start from the 0th index until the n-1th index; n being the size of the array Types: i. One dimensional 1) Ex: int x[5]; [][][][][] (you can imagine it as so) ii. Multi-dimensional 1) “Array of arrays” 2) Ex: int rows = 3; [][][][] int columns = 4; [][][][] // imagine it as so int x[rows][columns]; [][][][] Accessing arrays i. To access individual elements of an array, we use the value of the index that corresponds to the cell that we want to access 1) Ex: char x[10]; strcpy(x,”abcdefg”); char unknown = x[4]; // variable would contain the letter ‘e’ String – an array of characters terminated by a null character i. “\0” – signifies the special character meaning null ii. The last element in a string is always occupied by this special character iii. Example: 1) char str[13] = {‘C’,’o’,’m’,’p’ ‘u’,’t’,’o’,’r’,’i’,’e’,’n’,’t’,’\0’}; o if you print that using the printf function, it would only print the word, “Computorient”. o The ‘\0’ character only terminates the string. Meaning the string is completed. iv. string.h – a library that contains functions used for strings 1) Some functions in string.h: o strcpy() – copies a string into the desired array. Syntax: strcpy(destination, original_string); The first argument contains the destination array where the copied string will be stored. The second argument contains the string or character array to be copied. Ex: char name[20]; strcpy(name,”YourName”); The array “name” will then have the string, “YourName”. o
o
strlen(string) – gives the length of the string minus the null character Ex: name[4] = {‘C’,’a’,’m’,’\0’}; printf(“Length of string: %d\n”, strlen(name)); Output: Length of string: 3 strcmp()- used for comparing strings and returns a value based on the 2 strings Syntax: strcmp(str1, str2); str1 and str2 are the strings that will be compared. The strcmp() function would return 0 if both are equal, returns a nonnegative number if str1>str2 and returns a negative number if str1<str2
Functions a. A function is a block of code that has a name and a property. It can be executed countless of times. b. Conveniently used so that a block of code need not be copied and pasted at different parts in the program. c. Syntax: <return_value> <function_name> (parameters) { <function_body> } d. Parts: i. Return Value – signifies the type of data returned by the function
– if the function does not need to return anything, use “void” ii. Name – used to call a function iii. Body – contains the block of code to be executed whenever the function is called iv. Parameters – data needed in the function body e. Example: int double_the_value (int value) { value = value * 2; return value; } f. Function Prototype – declaration of a function without the body – found before the main function – full function declaration is found after the main function. g. Recursion i. a programming technique that works by calling the function inside its own function body. h. Useful terms: i. Pass by value 1) passing a copy of the variable to the function 2) Example: void funct (int j) { j = 0; } void main() { int k = 100; funct(k); // function call /* does not change the value of k after the function call */ } ii. Pass by reference 1) passing the address of a variable to the function 2) function changes the value of the variable that was passed to it 3) Example: void funct (int *j) { *j = 0; } void main() { int k = 100; funct(&k); // note that the address of k was passed /* k is now equal to 0 after the function call */ } File Handling a. A file is a collection of bytes that is located on a secondary storage device b. Commonly used functions: i. fopen() 1) Opens a file so it can be used. 2) Returns a pointer to the beginning of the file. 3) Usually used modes: o ‘w’ – Opens file for writing. Overwrites anything in the file if file already exists. If not, creates a new file. o ‘r’ – Opens file for reading. o ‘a’ – Opens file for appending. Adds the text at the end of the file. 4) Syntax: fopen(filename,mode_to_be_used); ii. fprintf() – used for writing to a specified stream. It needs an argument for the pointer to a file and the data that would be written to the file. 1) Syntax: fprintf(pointer_to_the_file, text_to_be_written_to_the_file); iii. fscanf() – used for reading data on a stream and stores them to the specified location pointed by the arguments. 1) Syntax: fscanf(pointer_to_the_file, text_to_be_read, variables_for_the_data_to_be_read); iv. fclose() – closes the specified file that is associated with the stream. 1) EOF – the end-of-file marker which can be used to check if the pointer has already reached the ‘\0’ character. 2) Syntax: fclose(pointer_to_the_file); An example code:
#include <stdio.h> main() { FILE *ptr; ptr = fopen(“untitled.txt”,”w”); // opens file for writing fprintf(ptr,”hi everyone!”); // writes to the file fclose(ptr); // closes the file }
Pointers a. A pointer is somehow like a special variable that holds the address of another variable. b. ‘&’ is the reference operator. It can be read as “the address of”. c. ‘*’ is the dereference operator which can be read as “the contents of the variable in this address”. d. Declaring a variable to be a pointer: i. <data_type> *var_name; ii. Ex: char *a; int *b; e. Initializing a pointer: i. Example: char b; char *a = &b; // can be understood as “set the pointer a to the address of b” An example code: #include <stdio.h> main() { int x; int *y; x = 20; printf(“the value of x is %d \n“, x); // prints 20 y = &x; // sets the pointer y to the address of x *y = *y * 2; // set the value of the variable pointed to by y to its original value times 2 printf(“ the value of x is now %d \n “ ,x); // prints 40 }
Structs a. A package of data that lets us combine different data types. b. Somehow like an array but the data types can be different. c. Declaration – usually before the main function i. Syntax: struct struct_name { var_type1 var_name1; var_type2 var_name2; …. } ii. Example: struct student { int gwa; char sex; int age; }; d. Usage: main () { struct student kirong; // makes a “variable” of type struct student named kirong kirong.age = 19; // uses a period and the name of the element to initialize it kirong.gwa = 1; kirong.sex = ’m’; } We could also declare an array of struct by: struct student list[100]; // creates 100 variables of type struct student