lab 3: c programming continued - site.uottawa.ca

27
1 Lab 3: C programming Lab 3: C programming continued continued CSI 3130 CSI 3130

Upload: others

Post on 22-Dec-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

1

Lab 3: C programming Lab 3: C programming continuedcontinued

CSI 3130CSI 3130

2

Types, Operators and Types, Operators and ExpressionsExpressions

•• Data typeData typechar, int, float, double, short int, long int

•• ConstantsConstants#define PI 3.1415926

•• TypedefTypedef: assigning alternative names to existing: assigning alternative names to existingtypedef int myInteger;

•• Relational and logical operatorsRelational and logical operators> >= < <= == !=

•• Increment and decrement operatorsIncrement and decrement operatorsb = a++; b = ++a; b = a--; b = --a;

3

Control FlowControl Flow•• The semicolon is a statement terminatorThe semicolon is a statement terminator•• IfIf--Else, ElseElse, Else--IfIf

if (expression) if (expression) statement1 statement1

else else if (expression)statement2 statement2

elsestatement3

•• For loopFor loopyou need to define the counter variable before the loop

for(expr1; expr2; expr3)statement

4

Control Flow (ContControl Flow (Cont’’d)d)•• The semicolon is a statement terminatorThe semicolon is a statement terminator•• WhileWhile--DoDo

expr1;While(expr2)

statementexpr3;

•• DoDo--WhileWhiledo

statementWhile(expression);

5

Control Flow (ContControl Flow (Cont’’d)d)•• SwitchSwitch

switch (expression){switch (expression){case constcase const--exprexpr : statements: statementscase constcase const--exprexpr : statements: statementsdefault: statementsdefault: statements

}}

•• Conditional expressions Conditional expressions (expr1 ? expr2 : expr3)(expr1 ? expr2 : expr3)if(aif(a>b)>b)

z=a;z=a; z = (a > b) ? a : b ;z = (a > b) ? a : b ;elseelse

z=b;z=b;

6

Input and OutputInput and Output

•• printfprintf– printf(“the int value is %d”, var);– printf(“the string value is %s”, var);– printf(“the character and double values are %c and %e”, var);– printf(“the double value is %e”, var);

•• scanfscanf– scanf(“enter an int: %d”, &var);– scanf(“enter a string: %s”, &var);– scanf(“enter a character and a double: %c %e”, &var);– scanf(“enter a string: %s”, &var);

•• Do not forget including Do not forget including <<stdio.hstdio.h>>

7

Function declarationFunction declaration•• Return valueReturn value

–– Default return value of a function in C is Default return value of a function in C is intint•• JavaJava

–– The use of function may appear earlier than its definitionThe use of function may appear earlier than its definition•• C programC program

–– Should be Should be declareddeclared somewhere earlier than their invocationssomewhere earlier than their invocationsintint power(intpower(int b, b, intint e); e); main()main(){{....../* call power() here *//* call power() here */} } intint power(intpower(int b, b, intint e) e) {{intint r = 1;r = 1;while (ewhile (e---- > 0) r *= b; > 0) r *= b; return r;return r;

}}

intint power(intpower(int b, b, intint e) e) {{intint r = 1;r = 1;while (ewhile (e---- > 0) r *= b; > 0) r *= b; return r;return r;

}}main()main(){{....../* call power() here *//* call power() here */}}

8

Variable scopeVariable scope

intint globalVarglobalVar = 34;= 34;

myFunmyFun()(){{

intint x =1;x =1;}}

Global; outside of the function

Local

9

Some details about CSome details about C•• No No booleanboolean type in Ctype in C

–– No explicit No explicit booleanboolean typetype#define TRUE 1 #define TRUE 1 #define FALSE 0#define FALSE 0if (a){ if (a){

……} }

•• No function overloading in CNo function overloading in C– Two functions cannot have the same name

•• Variables must be declared at the top of a basic Variables must be declared at the top of a basic block (for some c systems)block (for some c systems)– The following may not pass the compiler

{{ intint a;a;printf("Helloprintf("Hello worldworld\\n");n");char b;char b;

} }

10

Some details about C Some details about C (Cont(Cont’’d)d)

•• Lack of exceptionsLack of exceptions– Illegal activity may not be told (e.g. access memory

that hasn’t been allocated in some way)

•• No automated garbage collection in CNo automated garbage collection in C– you must free the memory

11

File inclusionFile inclusion•• Header files: Header files: how to interface to a library codehow to interface to a library code

•• Standard librariesStandard libraries#include <stdio.h>

•• UserUser--defined header filesdefined header files (usually put all declarations here)(usually put all declarations here)

#include “myheaderfile.h”

– Do not put definitions of functions or variables in header files

– Header files should normally only contain types, function prototypes, variable declarations, and macro definitions

•• Inline functionsInline functions– indicate to the compiler that a function's speed is critical by

making it inline: inline int square(int x) { return x * x; }

12

Standard libraryStandard library•• <<stdio.hstdio.h>>

–– Input/outputInput/output•• <<string.hstring.h>>

–– String handlingString handling•• <<math.hmath.h>>

–– Mathematical functionsMathematical functions•• <<ctype.hctype.h>>

–– CharactersCharacters•• <<stdlib.hstdlib.h>>

–– dynamic memory allocation dynamic memory allocation •• <<float.hfloat.h>>

–– expand the standard floatingexpand the standard floating--point typespoint types•• <<time.htime.h>>

–– declare time and date functions declare time and date functions •• <<errno.herrno.h>>

–– report error code report error code

• http://www.utas.edu.au/infosys/info/documentation/C/CStdLib.html

13

C CompilerC Compiler•• CompilerCompiler

–– PrePre--processing: processing: •• includes #define and includes #define and

#include tags in the C++ #include tags in the C++ file. file.

–– Lexical analyzerLexical analyzer–– Compiling: Compiling:

•• Converts C code to Converts C code to machine language. machine language.

–– Output: Output: •• Writes the machine Writes the machine

language to an object file. language to an object file.

•• LinkerLinker–– takes object files and the takes object files and the

precompiled library files and precompiled library files and puts them all togetherputs them all together

14

Some common errorsSome common errors

•• if (a=1){if (a=1){some stuff some stuff }}

== Boolean evaluation= Variable assignment operator

•• void void myfunc(intmyfunc(int a) { /* ... */ } a) { /* ... */ } void void myfunc(floatmyfunc(float b) { /* ... */ } b) { /* ... */ }

error: myfunc already defined

15

StructuresStructures

•• No class declaration in CNo class declaration in C•• From From ObjectObject--oriented languageoriented language to to Structure languageStructure language•• A collection of one or more variablesA collection of one or more variables

StructStruct point {point {intint X, Y;X, Y;}}

structstruct point location; point location; location.xlocation.x = 10; = 10; location.ylocation.y = 13;= 13;

structstruct point point addpoint(structaddpoint(struct point p1, point p1, structstruct point p2)point p2){{

p1.x += p2.x;p1.x += p2.x;p1.y += p2.y;p1.y += p2.y;return p1;return p1;

}}

16

ExerciseExercise

•• Write a program that Write a program that –– Accepts an input Accepts an input ““xx”” (A value to progress up to) (A value to progress up to) –– Starting at 0 and 1, outputs the Fibonacci sequence up to Starting at 0 and 1, outputs the Fibonacci sequence up to

““xx”” permutations. permutations.

•• There should be two functions, for clarity. There should be two functions, for clarity. –– ((mainmain) Accepts the input and calls the ) Accepts the input and calls the fibonaccifibonacci function. function. –– ((fibonaccifibonacci) One that accepts the value of x and outputs the ) One that accepts the value of x and outputs the

sequence. sequence.

17

Fibonacci in JavaFibonacci in Javaimport java.ioclass Fibonacci { public static void main(String args[]) {

System.out.println("How many numbers of the sequence would you like?"); InputStreamReader sr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(sr); try {

String input = br.readLine(); int n = Integer.valueOf(input).intValue(); fibonacci(n);

} catch (NumberFormatException e){System.out.println("That is not an integer. Please enter an integer value"); } catch (IOException e) { System.out.println("I did not recieve an input"); }

} public static void fibonacci(int n){

int a=0,b=1; for (int i=0;i<n;i++){

System.out.println(a); a=a+b; b=a-b;

} } }

18

Fibonacci in CFibonacci in C#include <stdio.h> int main () {

int n; printf("\nHow many numbers of the sequence would you like?\n"); scanf("%d",&n); fibonacci(n); return 0;

} int fibonacci(int n) {

int a = 0; int b = 1; int sum; int i; for (i=0;i<n;i++) {

printf("%d\n",a); sum = a + b; a = b; b = sum;

} return 0;

}

19

PointersPointers

A pointer is a variable that contains the address of a A pointer is a variable that contains the address of a variablevariable–– a variable may be of pointer type ( it holds the a variable may be of pointer type ( it holds the

address of some data in memory)address of some data in memory)–– & operator obtains the address of a variable& operator obtains the address of a variable–– * operator dereferences the pointer* operator dereferences the pointer–– If a pointer variable has been neither initialized nor If a pointer variable has been neither initialized nor

assigned the address of a real object, it could be assigned the address of a real object, it could be pointing anywhere, or be null. pointing anywhere, or be null.

double *f1;double *f1;

20

Pointers (ContPointers (Cont’’d)d)•• An example of using pointers:An example of using pointers:

intint x=1, y=2, z[10]; x=1, y=2, z[10]; intint **ipip;; /*/*ipip is a pointer to is a pointer to intint*/*/ipip = &x;= &x; /*/*ipip now points to x*/now points to x*/y = *ip+2;y = *ip+2; /*y is now 3*//*y is now 3*/**ipip = 0;= 0; /*x is now 0*//*x is now 0*/ipip = &z[10];= &z[10]; /*/*ipip now points to z[0]*/now points to z[0]*/

•• Pointers and Function ArgumentsPointers and Function Arguments–– C passes arguments to functions by valueC passes arguments to functions by value

swap (swap (a,ba,b);); swap (&swap (&a,&ba,&b););voidvoid swap(intswap(int x,x, intint y)y) voidvoid swap(intswap(int *i,*i, intint *j)*j)

{{ {{intint temp;temp; intint temp; temp;

temptemp == x;x; temptemp == *i;*i;xx == y;y; *i*i == *j;*j;yy == temp;temp; *j*j == temp;temp;

}} }}

21

Array:Array: a group of variables of the same type in adjacent memory a group of variables of the same type in adjacent memory intint a[4]; a[4]; a[2] = 3;a[2] = 3;

ororintint a[4] = { 9, 8, 7, 6 }; a[4] = { 9, 8, 7, 6 };

–– the size must be known atthe size must be known at compile timecompile time

•• ArrayArray--pointer relationshippointer relationship–– The address of an array element can be taken, and simple The address of an array element can be taken, and simple

arithmetic can be applied to it.arithmetic can be applied to it.

intint a[4] = { 9, 8, 7, 6 }; a[4] = { 9, 8, 7, 6 }; intint *pa = &a[2]; *pa = &a[2]; intint x, i; x, i; *(pa + 1) = 2; /* set a[3] to 2 */ *(pa + 1) = 2; /* set a[3] to 2 */ *(pa *(pa -- 1) += 11; /* set a[1] to 11 */ 1) += 11; /* set a[1] to 11 */ x = *(pa x = *(pa -- 2); /* set x to 9 */2); /* set x to 9 */

Arrays and PointersArrays and Pointers

22

Multidimensional arrayMultidimensional arraychar a[3][3];a = {“abc”, “def”, “ghi”};

An array of pointersAn array of pointerschar *b[3];b = {“abc”, “defg”, “hijkl”};

Pointer ArraysPointer Arrays

23

PassingPassing Arrays to functionsArrays to functions

Arrays are effectively passed to functions by reference. The Arrays are effectively passed to functions by reference. The array name evaluates to a pointer to the first element array name evaluates to a pointer to the first element

void fill_array_with_square_numbers(int *first, int length) {int i;for (i = 0; i < length; i++)

first[i] = i * i;} /**/int squares[4], moresquares[10]; fill_array_with_square_numbers(squares, 4);fill_array_with_square_numbers(moresquares + 2, 7);

24

StringsStrings

•• An array of char (terminated by a null character An array of char (terminated by a null character ‘‘\\00’’))char word[] = { 'H', 'e', 'l', 'l', 'o', '!', '\0' }; char another[] = "Hello!"; const char *ptr = "Hello!";

•• Utilities for handling character strings are declared in Utilities for handling character strings are declared in <<string.hstring.h>>

char *strcpy(char *to, const char *from);int strlen(char *str);

25

Dynamic memoryDynamic memory

•• Allocating a block of memory: Allocating a block of memory: ptrptr=(cast=(cast--type*)type*)malloc(bytemalloc(byte--size);size);x=(x=(intint*)malloc(100**)malloc(100*sizeof(intsizeof(int));));

•• Allocating multiple blocks of memory: Allocating multiple blocks of memory: ptrptr=(cast=(cast--type*) type*) calloc(n,elemcalloc(n,elem--size);size);

•• Releasing the used space: Releasing the used space: free(ptrfree(ptr););

26

ExerciseExercise

•• Implement quick sort algorithm such that it sorts an Implement quick sort algorithm such that it sorts an array of pointers in place.array of pointers in place.

•• A simple function is provided.A simple function is provided.

27

Quick SortQuick Sort/*qsort: sort v[left] … v[right] into increasing order*/void qsort(int v[], int left, int right){int i, last;void swap(int v[], int I, int);if(left>=right) /*do nothing if arrays contains*/

return; /*fewer than two elements*/swap(v, left, (left+right)/2); /*move partition elem*/last=left; /*to v[0]*/for(i=left+1; i<=right; i++) /*partition*/

if(v[i]<v[left])swap(v, ++last, i);

swap(v, left, last); /*restore partition elem*/qsort(v, left, last-1);qsort(v, last+1, right);

}