31
Programming DVA103, VT15 Lecture 4 Stefan Bygde

Lecture4- ENG.pdf

Embed Size (px)

Citation preview

Page 1: Lecture4- ENG.pdf

ProgrammingDVA103, VT15

Lecture 4

Stefan Bygde

Page 2: Lecture4- ENG.pdf

Content

●Functions repetition

●Arrays

●Macros

●Matrices

●Strings

2

Page 3: Lecture4- ENG.pdf

Functioner - repetition

3

Funktion 1:

Funktion 2:

main():

call function 1

Call function 2

arguments

argumentsReturn value

Return value

Page 4: Lecture4- ENG.pdf

Functions - repetition

● Function definition:

Return_type Name(Arguments)

{

statements..

return value/expression;

}

● Function call:

variable = Name(Values);

4

If the return type is not void

If the return type is not void

void if no return valuevoid if no return value

One value for eachargument.

One value for eachargument.

The call has to match the definition!

Arbitrary number of arguments. Each

argument is a variable declaration.

Arbitrary number of arguments. Each

argument is a variable declaration.

Page 5: Lecture4- ENG.pdf

Arrays

● Very often a program needs to process multiple data

● So far we have proccessed all data incrementaly(example: sum all numbers between x and y).

● Some times all data has to be stored

● Example, what if we want to store 100 numbers and print them on the screen?int a1,a2,a3,a4,a5,..., a100;

scanf(”%d”,&a1);

scanf(”%d”,&a2);

...

● And then…printf(”%d”,a1);

printf(”%d”,a2);

printf(”%d”,a3);

…5

Page 6: Lecture4- ENG.pdf

Arrays

● It would be better to store these 100 numbers usingonly one name.

● An array is a collection of variables that are stored as one name.

● The individual values are accessed via indecies.

● An array is declared as:

type name[size];

6

Page 7: Lecture4- ENG.pdf

Arrays

● Exempel

float nr[10];

●Creates ten floats.

●To assign one value: nr[2] = 6.0;

●Used as normal variables: sum = nr[1] + nr[8];

7

nr[0] nr[1] nr[2] nr[3] nr[4] nr[5] nr[6] nr[7] nr[8] nr[9]

nr: 16.1 12.0 6.0 -25.1 -5.0 10.5 0 0 8.0 41.8

Page 8: Lecture4- ENG.pdf

Arrays

●Mind the difference of usage and declaration:

●Declaration: int temperature[25];

Here 25 is the size of the array.

●Usage: x = temperature[6];

Here 6 is an index.

● Normal operations are not possible on arrays:

●Example: you assign an array to copy it:

double arr1[45];

double arr2[45];

arr2 = arr1;

8

Page 9: Lecture4- ENG.pdf

Arrays -initialisation

● An array can be initialised while declared using {, , , ...} (but only when declared!)

int x[5] = {12,5,7,8,10};

● Omitted numbers are set to 0

int x[5] = {12,5};

● To initialise all elements to 0

int x[5] = {};

● Initialisation can determine size, then size can be omitted:

int x[] = {12,5,7};9

x[0] x[1] x[2] x[3] x[4]

x: 12 5 7 8 10

x[0] x[1] x[2] x[3] x[4]

x: 12 5 0 0 0

x[0] x[1] x[2] x[3] x[4]

x: 0 0 0 0 0

x[0] x[1] x[2]

x: 12 5 7

Page 10: Lecture4- ENG.pdf

Arrays -index

● Accessing elements:

name[value/expression];

● As long as they are integers, any type of indexing canbe done:

x=nr[5]; x=nr[y]; x=nr[++y];

x=nr[nr[3]] x=nr[max-3+i]; x=nr[f(y)];

● If you use an index outside the array anything canhappen. The compiler does not check it.

float nr[5];

nr[8] = … <- error!

10

Page 11: Lecture4- ENG.pdf

Arrays -index

● Arrays works especially well with loops!

int main(void) {

float sum=0, pressure[10];

int i;

printf(”Enter 10 numbers: ”);

for (i=0; i<10; i=i+1)

scanf(”%f”, &pressure[i]);

for (i=0; i<10; i=i+1)

sum = sum + pressure[i];

printf(”%f\n”, sum);

return 0;

}

11

What doesthe program

do?

The first element has index 0

The first element has index 0

Page 12: Lecture4- ENG.pdf

Arrays -index

int main(void) {

float sum=0, pressure[50]={};

int i, antal;

printf(”How many (max 50)?”);

scanf(”%d”, &antal);

printf(”Enter numbers: ”);

for (i=0; i<antal; i=i+1)

scanf(”%f”, &pressure[i]);

for (i=0; i<antal; i=i+1)

sum = sum + pressure[i];

printf(”%f\n”, sum);

return 0;

}12

The programmershould make sure that the index never exceeds its

limit…

The programmershould make sure that the index never exceeds its

limit…

Page 13: Lecture4- ENG.pdf

The preprocessor

● Before compiling, C uses a preprocessor. The preproccessor does textual operations before the code is compiled.

● Directives to the preprocessor begins with #

● #include for example, copies and pastes the given

file into your code before compiling.

● #define performs a search/replace on your codebefore compiling.

13

Page 14: Lecture4- ENG.pdf

The preprocessor

● Example:

●#define SIZE 50

●#define PI 3.14159265

●Will replace all occurances of SIZE with 50 and all occurances of PI by 3.14159265

● #defines are usually referred to as macros.

●Why is this useful?

14

Page 15: Lecture4- ENG.pdf

Arrays and macros

Example

#include <stdio.h>

#define MAX 50

int main(void) {

float sum=0, pressure[MAX]={};

int i, antal;

printf(”How many (max %d)?”,MAX);

scanf(”%d”, &antal);

for (i=0; i<antal; i=i+1)

scanf(”%f”, &pressure[i]);

....

return 0;

} 15

Page 16: Lecture4- ENG.pdf

Arrays and macros

Example

#include <stdio.h>

#define MAX 50

int main(void) {

float sum=0, pressure[50]={};

int i, antal;

printf(”Antal tal (max %d)?”,50);

scanf(”%d”, &antal);

for (i=0; i<antal; i=i+1)

scanf(”%f”, &pressure[i]);

....

return 0;

} 16

Replace MAX with 50Replace MAX with 50

Inserts the file stdio.h at this positionInserts the file stdio.h at this position

If we want to changethe max size, we cando it on one placerather than two.

Page 17: Lecture4- ENG.pdf

Macros

● Reasons for using macros:

●Better to have named constants than to use numbers. Better documentation.

●Parameters can be changed on one place.

●Macros are traditionally defined by CAPITALS (although not necessary)

17

Page 18: Lecture4- ENG.pdf

Matrices

● It is possible to make 2-dimensional arrays

● A 2-dimensional array is called a matrix.

Can represent, for instance, a tic-tac-toe board:

char tttboard[3][3] = {{’X',' ',’O'},

{' ',’X',’O'},

{’O',' ',’X'}};

18

0 1 2

0 X O

1 X O

2 O X

tttboard[1][2]

Page 19: Lecture4- ENG.pdf

Matrices

● Exactly the same mechanics as normal arrays.

● It is actually possible to do arrays of any dimension.

●More examples:

tttboard[0][0] = ’X’; // Put x in the top left

Char v = tttboard[1][2]; // Put ’O’ in v.

19

0 1 2

0 X O

1 X O

2 O X

tttboard[1][2]

Page 20: Lecture4- ENG.pdf

Exercise

Write a program that fills a tic-tac-toe board as empty, and then fills it as follows:

● Do we use a loop? Several?

●For which indecies should we assign X?

20

0 1 2

0 X O O

1 O X O

2 O O X

Page 21: Lecture4- ENG.pdf

Exercise

#include <stdio.h>

#define SIZE 3

int main(void)

{

char matrix[SIZE][SIZE];

int row, col;

for (row=0; row<SIZE; row++) {

for (col=0; col<SIZE; col++) {

if (row==col)

matrix[row][col]='X';

else

matrix[row][col]='O';

printf("%c ", matrix[row][col]);

}

printf("\n");

}

return 0;

}21

0 1 2

0 X O O

1 O X O

2 O O X

Page 22: Lecture4- ENG.pdf

Strings

● In C, a string is an array of chars

● The end of a string is marked by null-termination’\0’ or 0 (null)

● Example

char name[10] = {’S’,’t’,’e’,’f’,’a’,’n’,’\0’};

22

name[0] name[1] name[2] name[3] name[4] name[5] name[6] name[7] name[8] name[9]

namn: S t e f a n \0 ? ? ?

Page 23: Lecture4- ENG.pdf

Strings

● Simplified notation for strings:

char namn[10] = ”Stefan”;

char name[] = ”Stefan”;

char month[12][4] = {”Jan”,”Feb”,”Mar”,”Apr”,

”May”, ... ,”Dec”};

23

\0 is

automatically

put after.

\0 is

automatically

put after.

No size given, the length of the array willbe the length of the text PLUS one (to

accommodate for \0)

No size given, the length of the array willbe the length of the text PLUS one (to

accommodate for \0)

Three letters + \0Three letters + \0

Array of stringsArray of strings

Page 24: Lecture4- ENG.pdf

Strings

● char text[10] = ”More C!”;

● The array has 10 elements.

● The length of the string is 7

● The string occupies 8 positions in the array.

● To print a text string:

printf(”%s”, text); //%s is the code for

strings

Equivalent to:

for(i=0; text[i]!=’\0’; i++)

printf(”%c”, text[i]); 24

text[0] text[1] text[2] text[3] text[4] text[5] text[6] text[7] text[8] text[9]

text: M o r e C ! \0 ? ?

Page 25: Lecture4- ENG.pdf

Strings -example

#include <stdio.h>

#define FIRST_NAME_SIZE 20

#define LAST_NAME_SIZE 60

int main(void)

{

char first_name[FIRST_NAME_SIZE];

char last_name[LAST_NAME_SIZE];

printf(”First name: ”);

scanf(”%s”,first_name);

printf(”\nLast name: ”);

scanf(”%s”,last_name);

printf(”Hey there %s %s!”,first_name,last_name);

return 0;

}

25

No & for strings! (reasonlater)

No & for strings! (reasonlater)

Page 26: Lecture4- ENG.pdf

Example

Compute the length of a string.

#include <stdio.h>

int main(void)

{

char text[]= ”Some random text”;

int pos= 0;

printf(”Strängen %s\n”,text);

printf(”The length is %d\n”,pos);

return 0;

}

26

for(pos=0; text[pos] != ’\0’; pos++)

;

Page 27: Lecture4- ENG.pdf

String functions

● The library strings.h contains functions for manipulating text strings. (use #include)

● Examples:

●strcat() -Concatenate two strings.

●strcpy() -Copy a string.

●strcmp() -Compare two strings.

●strlen() -Compute the length of a string.

●Etc.. (consult the book or internet for more)

27

Page 28: Lecture4- ENG.pdf

Example

Simpler way of computing length:

#include <stdio.h>

int main(void)

{

char text[]= ”Some random text”;

int length;

printf(”Strängen %s\n”,text);

printf(”The length is %d \n”,length);

return 0;

}

28

length = strlen(text);

#include <string.h>

Page 29: Lecture4- ENG.pdf

Example

Or just:

#include <stdio.h>

#include <string.h>

int main(void)

{

char text[]= ”Some random text”;

printf(”The length is %d\n”,strlen(text));

return 0;

}

29

Page 30: Lecture4- ENG.pdf

String functions

● You can not copy strings by assignment:

char s1[4];

char s2[] = ”Hi!”;

s1 = s2; // Will NOT do what you’d expect

● To copy an array, use strcpy()

char s1[4];

char s2[4] = ”Hi!”;

strcpy(s1,s2); // s1 = ”Hi!”

30

Page 31: Lecture4- ENG.pdf

String functions

● You can not compare strings with ==:

char s1[] = ”Hi!”;

char s2[] = ”Hi!”;

if(s1 == s2) … // will evaluate to FALSE

● To compare two strings, use strcmp()

int s1[] = ”Hi!”;

int s2[] = ”Hi!”;

if(strcmp(s1,s2) == 0) // Will evaluate to TRUE

31