Download presentation
Presentation is loading. Please wait.
Published byHelena Ward Modified over 9 years ago
1
CGS 3460 Unix Commands n man – manual (man gcc) n ls – list directory contents (ls) n pwd – prints working directory (pwd) n cd – change directory (cd ) n mkdir – create directory (mkdir n rm – remove a file (rm ) lUse –r if removing a directory
2
CGS 3460 Unix Commands(cont) n cp–copy a file (cp ) lUse –r if copying a directory n mv–move or rename files (mv ) n jpico – text editor (jpico ) n gcc – compiler (gcc sourceFile.c) l-o option n Directory shortcuts l~ home directory l.. parent directory l. sub directory
3
CGS 3460 Declaration of Variables type name = initial_value; type name1 = initial_value1, name2 = initial_value2, …; { int v1, v2, sum; v1 = 50; v2 = 30; sum = v1 + v2; } { int v1= 50, v2 = 30, sum; sum = v1 + v2; }
4
CGS 3460 Summary of Data Type TypeExamplesPrintf char‘a’, ‘\n’%c _Bool0, 1%i, %u short int1,100, -5%hi, %hx, %ho unsigned short int1, 39, 100%hu, %hx, %ho int -1, 5, 0XAF, 0177 %i, %x, %o unsigned int 5u, 0XAFu, 0177U %u, %x, %o long int0xffffL, 12l%li, %lx, %lo unsigned long int0xffffUL, 12ul%lu, %lx, %lo
5
CGS 3460 Summary of Data Type – cont. TypeExamplesPrintf long long int0xffffLL, 12ll%lli, %llx, %llo unsigned long long int0xffffULL, 12ull%llu, %llx, %llo float12.3f, 3.1e-5f, 0x1.5p10 %f, %e, %g %a double12.3, 3.1e-5, 0x1.5p10 %f, %e, %g %a long double12.3l, 3.1e-5l%Lf, %Le, %Lg
6
CGS 3460 Operations for int type n Declaration int x, y, z; n Assignment ly = 10; lz = 6; n Calculation lPlus: + x = y + z; lMinus: - x = y – z; lMultiply: * x = y * z; lDivide: / x = y / z; lModulus x = y % z; result of y/z will be truncated
7
CGS 3460 Operations for float type n Declaration float x, y, z; n Assignment ly = 10.00; lz = 5.8; n Calculation lPlus: + x = y + z; lMinus: - x = y – z; lMultiply: * x = y * z; lDivide: / x = y / z; result of y/z will NOT be truncated
8
CGS 3460 Assignment Operators n Join the arithmetic operators lFormat: op= n Examples: count = count + 10; count += 10; count = count - 5; count -= 5; a /= b + c; a = a / (b + c);
9
CGS 3460 Unary Operators n Unary plus / minus l+ / - lExample: -a n Unary increment/decrement l++ / -- M = M + 1; M += 1; ++M; M++;
10
CGS 3460 Precedence FIRST ()(3 + 5) * 8 ++, --x++ (Unary) +, --x * 7 *, /, %5 * 8 (Binary) +, -3 + 5 =x = 4 LAST
11
CGS 3460 Operator Return Types (z = x ? y) xyz int float intfloat intfloat
12
CGS 3460 Getting Input n Need input from user lscanf Same format as printf, except put “&” in front of variable names scanf(“%i”, &count); “&” means the "address of“ to store whatever the user enters into the memory address where number is stored Leaving out the & will cause your program to work incorrectly! Exception: double uses %lf in scanf and %f in printf
13
CGS 3460 If statement n Consists of keyword if lFollowed by condition in parenthesis lFollowed by the body of the if statement This is what is executed if the condition evaluates to true Body can consist of multiple statements if they are enclosed with { } OperatorMeaningExample ==Equal tovar == 10 !=Not equal tovar != 10 <Less thanvar < 10 <=Less than or equal tovar <= 10 >Greater thanvar > 10 >=Greater than or equal tovar >= 10
14
CGS 3460 The if Statement n Format if ( condition ) program statement; or if ( condition ) { program statement(s); } Condition satisfied? Program statement Yes No
15
CGS 3460 The if-else Statement n Format if ( condition ) program statement 1; else program statement 2; n Or if ( condition ) { program statement(s) 1; } else { program statement(s) 2; } Condition satisfied? Program statement 1 Yes No Program statement 2
16
CGS 3460 The else if Statement n Format if ( condition1 ) program statement 1; else if (condition2) program statement 2; n Flow Condition 1 satisfied? Program statement 1 Yes No Condition 2 satisfied? No Program statement 2 Yes
17
CGS 3460 Logical Operators n Why lMake a decision based on multiple conditions n What are they OperatorExampleDescription ||x widthlogical OR &&x >= 0 && x <= widthlogical AND !!(x < 0)Logical NOT
18
CGS 3460 Logical OR n Returns false only if both expressions are false n Example: n (4 > 5 || 6 <= 10) n (4 <= 5 || 6 == 10) n (4 >= 5 || 6 > 10) n (4 < 5 || 6 != 10) ABA || B True FalseTrue FalseTrue False 1 1 0 1
19
CGS 3460 Logical AND n Returns true only if both expressions are true n Examples: n (4 > 5 && 6 <= 10) n (4 <= 5 && 6 == 10) n (4 >= 5 && 6 > 10) n (4 < 5 && 6 != 10) ABA && B True False TrueFalse 0 0 0 1
20
CGS 3460 Logical NOT n Inverts the Boolean value of an expression n Example: _Bool a = 0; if (!a) { printf(“a is a false value (0)\n”); } a = 1; if (a) { printf(“a is a true value (1)\n”); } A!A TrueFalse True
21
CGS 3460 The switch Statement n When to use lThe value of a variable successively compared against different values n Format switch( expression ) { case value 1: program statement 1; break; case value 2: program statement 2; break; ׃ case value n: program statement n; break; default : program statement n+1; break; } == value 1 evaluate expression statement 1 Y N == value 2 == value n N N statement n+1 Y statement 2 Y statement n
22
CGS 3460 More on switch Statement case value 1: program statement 1; case value 2: program statement 2; break ; == value 1 statement 1 Y N == value 2 N Y statement 2
23
CGS 3460 for loop n Format: for( init_expression; loop_condition; loop_expression ) { program statement; } n Flow: Condition satisfied? No Initial Expression Yes Program statement loop expression
24
CGS 3460 Example n If we want to print following pattern * ** *** **** ***** ****** ******* ******** ********* ********** Print n stars at the nth line Print 1 star at the 1st line Print 2 stars at the 2nd line Print 3 stars at the 3rd line
25
CGS 3460 Code #include int main(void) { int row, col; for (row = 1; row <= 5; row++) { for (col = 1; col <= row; col++) { printf("*"); } printf("\n");
26
CGS 3460 while loop n Format while (loop_condition) { program statement; } n Flow Condition satisfied? Program statement Yes No
27
CGS 3460 for loop vs while loop Condition satisfied? No Initial Expression Yes Program statement loop expression Condition satisfied? Program statement Yes No for loopwhile loop
28
CGS 3460 Convert for loop to while loop while (loop_condition) { program statement; } for( init_expression; loop_condition; loop_expression ) { program statement; } program statement; loop_expression; init_expression; while(loop_condition) { }
29
CGS 3460 do-while loop n Format do { program statement } while (loop_condition); Condition satisfied? Program statement Yes No
30
CGS 3460 while and do-while loop n In while loop, program statement may never be evaluated. While in do-while loop, it is evaluated at least once Condition satisfied? Program statement Yes No while (loop_condition) { program statement; } do { program statement } while (loop_condition); Condition satisfied? Program statement Yes No
31
CGS 3460 break n Used to break out of a loop immediately lPossibly due to detection of an error int i; for(i=0; i < 3; i++) { printf(“here\n”); break; printf(“there\n”); } here
32
CGS 3460 continue n Used to continue at the next point lPossibly due to detection of an error int i = 0; for(i=0; i < 3; i++) { printf(“here\n”); continue; printf(“there\n”); } here
33
CGS 3460 Array n What is an array lData structure that holds a group (list) of homogenous elements of a specific type Associate a set of values with a single variable name All of these values must be of the same data type Think grades for example n Why? lProcess a group of values using a loop lConsider dealing with grades of 50 students Without arrays you would declare 50 variables for each student
34
CGS 3460 How to Define n Declaration type [size]; n Example lTo define an integer array called numbers of size 5 int numbers[5]; Compare to normal integer declaration Each number is called an element Indexed from 0 to N-1 (4) numbers 0 1 2 3 4
35
CGS 3460 How to Use n How to refer to an individual element of an array lAccessed by their position in the array, e.g. numbers[1] = 2; Set the element at index 1 of numbers to 2 lDo this for any element (0 – 4) n Operation on element in an array lSame as normal variable numbers[0] numbers[1] numbers[2] numbers[3] numbers[4] 2
36
CGS 3460 22 Array Manipulation numbers[0] numbers[1] numbers[2] numbers[3] numbers[4] 12 int first, i; int numbers[5]; numbers[0] = 12; numbers[1] = 14; numbers[2] = 6; numbers[3] = 8; numbers[4] = 7; first = numbers[0]; //first becomes 12 numbers[1] = numbers[0] + 10; numbers[3] = numbers[0] + numbers[1] + numbers[2]; i = 2; numbers[i] = 50; numbers[i-1] = numbers[i]; numbers[i] = numbers[i] + numbers[i+1]; 14 6 8 7 40 50 90
37
CGS 3460 Initializing Arrays n Initializing an array using a comma-separated list of values in { } lint number[ ] = { 5, 7, 2 }; Size of an array is automatically set as the number of elements within { } numbers[0] numbers[1] numbers[2] 5 7 2
38
CGS 3460 Initializing Arrays n Initializing part of an array, and other numbers will set to 0 lint numbers[5] = { 3, 1}; 3 1 0 numbers[0] numbers[1] numbers[2] numbers[3] numbers[4] 0 0
39
CGS 3460 Initializing Arrays n Initializing part of an array, and other numbers will set to 0 lint numbers[5] = { [0] = 3, [2] = 1}; 3 1 0 numbers[0] numbers[1] numbers[2] numbers[3] numbers[4] 0 0
40
CGS 3460 Character Arrays n You can have an array of characters lchar word[ ] = {‘H’,’e’,’l’,’l’,’o’,’!’} Hello! word[0]
41
CGS 3460 Strings n A sequence of characters delimited by “ “ (not part of the string) l“hello” l“Neko” l“This is some random sentence that I typed!” n C does not have a string type n It uses an array of characters lArray contains a null character (‘\0’) to denote the end of the string n Uses %s to print
42
CGS 3460 Getting String Input n Several ways – scanf is simplest but most dangerous n Example take input and print it // demonstrates string input #include main () { // variables declaration char name[11]; // get input from user printf ("Your name (10 letters max):\n"); scanf ("%s", &name); printf ("Hello %s \n", name); } Your name (10 letters max): Neko Hello Neko
43
CGS 3460 Declaring and Defining n Declaring a function – must be done before main if used return_value_type function_name( parameter-list); n How to define a function lIf you declare the function, you can define it after main lIf you don’t declare the function you must define it before main return_value_type function_name( parameter-list) { Declarations & Definitions; Statements; } n Parameter-list format type1 variable_name1, type2 variable_name2,…typeN variable_nameN
44
CGS 3460 Examples n Definitions int main() { …;} double calcMax(double a, double b) {…;} n Special cases lUse void for return_value_type if no value is needed to be returned. lDon’t need to put anything for parameter-list if no parameters are needed to pass to the function (you can add void if you like)
45
CGS 3460 Arguments n Arguments: lSpecific values for a particular function call lParameters – variables passed in to a function n Example double CalcMax(double a[10]); lThe values assigned to the array a are passed to the function at runtime lIncrease usefulness and flexibility
46
CGS 3460 Function – III n How to return a value in a function lreturn; // for void return type lreturn expression; // to return the value to expression to the caller n How to call/invoke a function lfunction_name(…); // for function with no return value lvariable_name = function_name(…); // for function with return value
47
CGS 3460 Calculating Area - Example n Create a function to calculate the area of a rectangle given its length and width lWhat does it need to calculate the area? Length floating point type Width floating point type lWhat will it give back Area floating point type CalcArea( ); length,width double
48
CGS 3460 Example: Area Calculation - 1 double CalcArea(double height, double width) { return height * width; } int main() { double h, w, area; printf(“Please input height and width\n”); scanf(“%f, %f”, &h, &w); area = CalcArea(h, w); printf(“The area is %f”, area); return 0; }
49
CGS 3460 Example: Area Calculation - 2 double CalcArea(double height, double width) ; int main() { double h, w, area; printf(“Please input height and width\n”); scanf(“%f, %f”, &h, &w); area = CalcArea(h, w); printf(“The area is %f”, area); return 0; } double CalcArea(double height, double width) { return height * width; }
50
CGS 3460 Pass by Value n Passing a copy of the value as an argument lParameters receive a distinct copy of the caller's arguments, as if the parameters were assigned from the arguments lChanges made to parameters have no effect on the caller’s arguments n Examples: h = 3; w = 4; area = CalcArea(h, w); double CalcArea(double height, double width) { …; } height = 3, width = 4 3, 4
51
CGS 3460 Local Variables – I n What is local variables lVariables declared within a function n Example: double CalcMax(double a[10]) { int i; double maxValue; …; } int main() { int i; double a[10] double maxValue; maxValue = CalcMax(a) ; } Local variables
52
CGS 3460 Local Variables - 3 #include void foo(int x); int main() { int x = 3, y = 2; printf("x1: %i\t\ty1: %i\n", x, y); foo(x); printf("x4: %i\t\ty4: %i\n", x, y); printf("z: %i\n", z); return 0; } void foo(int x) { int y = 8, z = 12; printf("x2: %i\t\ty2: %i\t\tz2: %i\n", x, y, z); x = 7; printf("x3: %i\t\ty3: %i\t\tz3: %i\n", x, y, z); } x1: 3 y1: 2 x2: 3 y2: 8 z2: 12 x3: 7 y3: 8 z3: 12 x4: 3 y4: 2 Syntax Error
53
CGS 3460 Array as Parameters – Example 1 #include void foo(int x[10]); int main() { int x[10] = {[4] = 5, [3]= 4,[2] = 2}; printf("x1: %i\n", x[0]); foo(x); printf("x4: %i\n", x[0]); return 0; } void foo(int x[10]) { printf("x2: %i\n", x[0]); x[0] = 7; printf("x3: %i\n", x[0]); } x1: 0 x2: 0 x3: 7 x4: 7
54
CGS 3460 Pass by Reference n Passing the address itself rather than the value lChanges to parameters will affect the caller's arguments as well, for they are the same variable lUsed for array, variable address Use ‘&’ to get the location of a particular variable n Example int values[100], minVal; minVal = minimum(values); double minimum(int a[100]) { …; } values a int b, c; swap(&b, &c); void swap(int *v1, int *v2) { …; }
55
CGS 3460 Automatic and static variables n By default, all variables defined within function are automatic local variables n Static variables lUsing keyword static lDoes not disappear after function call lInitialized only once
56
CGS 3460 Example void auto_static(void) { int autoVar = 1; static int staticVar = 1; printf("automatic = %i, static = %i\n", autoVar, staticVar); autoVar++; staticVar++; } int main() { int i; for(i = 0; i < 5; i++) auto_static(); return 0; } automatic = 1, static = 1 automatic = 1, static = 2 automatic = 1, static = 3 automatic = 1, static = 4 automatic = 1, static = 5
57
CGS 3460 Formatting Output n Sometimes you would like your output to have nice tabular output n Conversion specification (%i, %f, etc) allows for formatting text n Format : %[flags][width][.prec][hlL]type l[] mean its optional lOnly % and type are mandatory
58
CGS 3460 Flags FlagMeaning -Left – justify value +Precede value with + or - (space)Precede positive value with space character 0Zero fill numbers #Precede octal value with 0, hexadecimal value with 0x; display decimal point for floats; leave trailing zeroes for g or G format
59
CGS 3460 Width and Precision SpecifierMeaning numberMinimum size of field *Take next argument to printf as size of field.numberMinimum number of digits to display for integers; number of decimal places for e or f formats; maximum number of significant digits to display for g; maximum number of characters for s format.*Take next argument to printf as precision
60
CGS 3460 Declarations n Three ways struct date{ int day; char month[10]; int year; }; struct date today; typedef struct { int day; char month[10]; int year; } date; date today; struct { int day; char month[10]; int year; } today;
61
CGS 3460 Initialization struct { int day; char month[10]; int year; } today = {15, “ June ”, 2007}; typedef struct { int day; char month[10]; int year; } date; date today = {15, “June”, 2007}; struct date{ int day; char month[10]; int year; }; struct date today = {15, “June”, 2007};
62
CGS 3460 How to use n To access the members in the structure lspecify the variable name, followed by a period and the member name today.day = 15; today.year = 2007; today.month[0]=‘J’; today.month[1]=‘u’; today.month[2]=‘n’; today.month[3]=‘e’; today.month[4]=‘\0’; lOR today.day = 15; today.year = 2007; today.month=“June”; 15 ‘J’ ‘u’ ‘n’ ‘e’ ‘\0’ 2007.month.day.year today
63
CGS 3460 Main Memory n Main memory of computers (also called RAM or Random Access Memory) is made up of bytes. n The number of bytes in a computer with 512 MB of RAM is: 512 * 1024 * 1024 = 5,3687,0912 bytes n Each byte in the main memory has a unique binary address that can be used to refer to it. n Earlier computers used to have a 16-bit address. Nowadays, most computers have a 32-bit (or even 64-bit) addressing system. n The range of integers that can be stored in 32 bit address is 0 through 4,294,967,295. Thus, in a 32-bit machine, we can have only 4 GB of addressable main memory (since we can only represent that many bytes with unique addresses)
64
CGS 3460 Addresses in a 4 bit Computer Byte NumberBinary AddressHex Equivalent 000000x0 100010x1 200100x2 300110x3 401000x4 501010x5 601100x6 701110x7 810000x8 910010x9 1010100xA 1110110xB 1211000xC 1311010xD 1411100xE 1511110xF
65
CGS 3460 Pointer variable n A pointer variable is simply a variable that can be used to hold memory addresses (location) of another variable. n An integer pointer variable can be used to store the memory address of an integer variable. n A char pointer variable can be used to store the memory address of a character variable. n A float pointer variable can be used to store the memory address of a float type variable.
66
CGS 3460 Declaring a pointer variable n A pointer variable should be declared before usage. Declaring an integer pointer variable p: lint *p; n * informs the compilier that variable p is a pointer variable. n int tells the compiler that variable p will be used to store memory address of integer variables (i.e. a pointer to an int).
67
CGS 3460 Initializing a pointer variable n Before we can use a pointer, we should initialize it using the assignment operator. n For an integer pointer, we can only assign the address of some other integer variable. n The example below assigns the address of integer variable a to the pointer p main () { int a = 10; // integer variable initialized to value 10 int *p; // integer pointer p = &a; // store address of a in p }
68
CGS 3460 What this does main () { int a = 10; // integer variable initialized to value 10 int *p; // integer pointer p = &a; // store address of a in p } a p 10
69
CGS 3460 Dereferencing n Pointers store memory addresses. n Can access the contents of the memory address stored in a pointer. (access the value a pointer points to) n This is called dereferencing a pointer n Done using the operator *
70
CGS 3460 * Operator n Returns the value stored at an address n Place in front of a pointer to return the value stored at the pointers address int a = 7; int *p = &a; n p 0x7e473d (the location of a) n *p 7(the value stored at the location of a) n Note that if p is a pointer variable, then *p is an alias for the object to which p currently points to.
71
CGS 3460 Demonstration main () { int a = 10; // integer variable initialized to value 10 int *p1, *p2, *p3; // 3 integer pointers p1 = &a; // store address of a in p1 p2 = p1; // copy value in p1 (address of a) to p2 p3 = p2; // copy value in p2 (address of a) to p3 int c = *p3; // dereference p2 (value of a) and assign it to c printf (" %d %d %d \n", *p1, *p2, c); // output will be 10 10 10 } 133613371335 10 a p2p3 15571843 p1 1445 1336 203220332031 10 c 10 10 10
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.