introduction to computer algorithmics and programming ceng 113 arrays and strings

39
Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Upload: sharlene-dickerson

Post on 13-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Introduction to Computer Algorithmics and Programming

Ceng 113

Arrays and Strings

Page 2: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Arrays

• An array is a collection of variables of the same type that

are referenced by a common name.

• A specific element in an array is accesses by an index.

• All arrays placed a continuous memory areas.

• Arrays may have one to several dimensions.

Page 3: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Single Dimention Arrays

The general decleration form is;type var_name[size];

type ; declares the base type of the array.size ; defines how many elements the array will hold.

The amount of storage required to hold an array is;total bytes = size_of_type * size_of_array

Example;

double balance[100];would be: sizeof(double) * 100, which is usually 8*100 bytes

Page 4: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Single Dimension Arrays

void main(void)

{

int x[10]; /* this reserves 10 integer elements */

int t;

for (t=0; t<10; t++) x[t]=t;

for(t=0; t<10; t++) printf("\n x[%d]= %d", t, x[t]);

}

*

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

Value 0 1 2 3 4 5 6 7 8 9

Array_One_Dim.C

Page 5: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Example #1

Determine the existence of the common elements for two arrays:

found = 0;

for (i = 0; i < n && !found; i++)

for (j = 0; j < m && !found; j++)

if (a[i] == b[j]) found = 1;

if (found)

/* got one: a[i-1] == b[j-1] */

...

else

/* didn't find any common element */

...

Page 6: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Example #2

#include <stdio.h>

// determine the biggest element of an array.

int a[10]={100, 140, 7, 190, 5, 1, 17, 390, 245,112};

void main()

{

int max, i;

max= a[0];

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

if (a[i] > max) max = a[i];

printf(“\n The max element: %d \n”, max);

}

Page 7: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Generating a Pointer to an Array

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

Address 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009

We can generate a pointer to the first element of an array

without any index.

Example;

char x[10];

char *p;

p = x;

How array x appears in memory if it starts at memory location 1000 :

Page 8: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Passing One-Dimension Arrays to Functions

• In C, you cannot pass entire array as an argument to a function.• However, we can pass a pointer to an array to a function by

specifying the array’s name without an index.

void main(void){

int i[10];func1(i);

....}

func1(int *x) /* pointer */{....}

func1(int x[10]) /* sized array */{....}

func1(int x[ ]) /* unsized array */{....}

Page 9: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

String

Most common one dimension array in C is string, which is simply an array of characters terminated by a null. ( ‘\0’ ).

Therefore, we need to declare character arrays to be one character longer than the largest string that they are to hold ‘\0’.

Examples; If we want to hold 10 characters in the string s, we can define this array as:

char s[10];char s[10] = {‘E’, ‘x’, ‘a’, ‘m’, ‘p’, ‘l’, ‘e’, ‘\0’};char s[10] =“Example”;

Page 10: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

String

C does not have a string data type, it allows string constants.

A string constant is a list of characters in double quotes.

Example; “hello there”

Page 11: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Example #3

#include <stdio.h>

// the length of the string?

void main()

{

int i=0;

char s[50];

printf(“\n String: “);

gets(s);

while (s[i]) // means while (s[i] != 0)

++i;

printf(“\n The length of the string: %d”, i);

}

Page 12: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Example #4

include <stdio.h>void main(){

char s[30], temp;int n, j;printf(“\n String:”);gets(s);n=strlen(s);for (j=0; j<n/2; ++j) // reverse the string!{ temp= s[n-j-1];

s[n-j-1]= s[j];s[j] = temp;

}puts(s);}

?

Page 13: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Example #5

#include <math.h>float point_a[2]; /* array of lat/long positions */float point_b[2]; /* array of lat/long positions */float distance; /* distance between point a/b (computed */float sqrt_of_distance; /* square root of distance (computed) */int main() {point_a[0] = 43.0;point_a[1] = 13.0;point_b[0] = 59.0;point_b[1] = 19.0;distance = (point_b[0] + point_b[1]) - (point_a[0] + point_a[1]);sqrt_of_distance = sqrt(distance);

printf("Point A: %f/%f\n", point_a[0], point_a[1]);printf("Point B: %f/%f\n", point_b[0], point_b[1]);printf("Distance: %f\n", distance);printf("Square root of distance: %f\n", sqrt_of_distance);return (0);

}

Page 14: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

String Manipulation Functions

• strcpy(s1, s2) Copies s2 to s1.• strcat(s1, s2) Concatenates s2 to the end of s1.• strlen(s1) Returns the length of s1.• strcmp(s1, s2) if s1 and s2 are same, return 0 (FALSE).

if s1 < s2, return negative value.

if s1 > s2, return positive value.• strchr(s1, ch) Return a pointer to the first occurrence of ch in s1.• strstr(s1, str) Return a pointer to the first occurrence of s2 in

s1.

These functions use the standart header file STRING.H.

Page 15: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

#include <stdio.h>#include <string.h>void main(void){

char s1[80], s2[80];gets(s1); gets(s2);printf(“lenghs: %d %d \n”, strlen(s1), strlen(s2));

if (!strcmp(s1, s2)) printf(“The string are equal \n”);

strcat(s1, s2);printf(“%s \n”, s1);

strcpy(s1, “This is a test. \n”);puts(s1);if(strchr(“hello”, ‘e’)) printf(“e is in hello \n”);if(strstr(“hi there”, “hi”)) printf(“found hi \n”);

}

*

String_Functions.C

Example #5

Page 16: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Two-Dimensional Arrays

C supports multidimensional arrays.

Example; To declare two dimensional integer array d of

size 10 , 20:

int d[10][20];

To access point 1,2 of array d ; d[1][2]

Page 17: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Two-Dimensional ArraysExample; #include <stdio.h>void main(void){ int t, i, num[3][4];

for(t=0; t<3; ++t)for(i=0; i<4; ++i)num[t][i]=t*4+i+1;

/* now print the array */for((t=0; t<3; ++t) {

for(i=0; i<4; ++i)printf(“%3d “, num[t][i]);

printf(“\n”);}}

*

0 1 2 3

0 1 2 3 4

1 5 6 7 8

2 9 10 11 12

First Index

Second Index

The number of bytes of memory to hold this array is;bytes=size of first index * size of second index * size_of_basetype

Array_Two_Dim.C

Page 18: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Two-Dimensional ArraysWhen a two dimentional array is used as an argument to a function,

only a pointer to the first element is passed, and we must define the length of the second dimension. C compiler needs to know the length of each row. If the length of the rows is not known, the compiler cannot determine where the second row begins.

Example;void main(void){ int x[5][10]; func1(x);...}

func1 (int x[ ] [10]){....}

Page 19: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Example #6

#include <stdio.h>

#define ROW 5

#define COL 2

void main()

{ int a[ROW][COL]={10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

int b[ROW][COL]={5, 10, 15, 20, 25, 30, 35, 40, 45, 50};

int c[ROW][COL], i, j;

for (i=0; i<ROW; ++i)

for (j=0; j<COL; ++j) {

c[i][j]=a[i][j] + b[i][j];

printf(“c[%d][%d] = %d\n”, i, j, c[i][j]);

}

}

Page 20: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Sample Program #7

• Use two dimensional array to store the numeric grade for each student in a teacher’s classes.

• The program assumes that the teacher has three classes and a maximum of 10 students per class.

• Write these functions;– Main function to control flow of the program– A function to enter all grades for each class– A function to read a grade from screen – A function to display all grades to screen

Pgm:Array_Two_Dim_Grades.C

*

Page 21: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Sample Program – V.1#include <stdio.h>#include <ctype.h>#include <stdlib.h>/* A simple student grades database */#define CLASSES 2#define GRADES 3int grade[CLASSES][GRADES];void enter_grades(void);int get_grade(int num);void disp_grades(int g[][GRADES]);void main(void){ char ch, str[80];

for( ; ; ){printf("(E)nter grades\n");printf("(R)eport grades\n");printf("(Q)uit\n");gets(str);ch = toupper(str[0]);switch(ch) {case'E': enter_grades();break;

case 'R': disp_grades(grade);break;

case 'Q': exit(0);}

}}

/* Enter the student's grades. */void enter_grades(void){ int t, i;

for(t=0; t<CLASSES; t++) {printf("Class # %d:\n", t+1);for(i=0; i<GRADES; i++)grade[t][i]=get_grade(i);

}}/* Read a grade. */get_grade(int num){ char s[80];

printf("enter grade for student # %d:\n", num+1);

gets(s);return(atoi(s));

}/* Display grades. */void disp_grades(int g[][GRADES]){ int t,i;

for(t=0; t<CLASSES; t++) {printf("Class # %d : \n", t+1);for(i=0; i<GRADES; i++)

printf("Student # %d is %d \n", i+1, g[t][i]);

}}

Page 22: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Sample Program – V.2#include <stdio.h>#include <ctype.h>#include <stdlib.h>#define CLASSES 2#define GRADES 3void enter_grades(int *p);int get_grade(int num);void disp_grades(int g[][GRADES]);void main(void){ char ch, str[80];

int grade[CLASSES][GRADES];for( ; ; ){

printf("(E)nter grades\n");printf("(R)eport grades\n");printf("(Q)uit\n");gets(str);ch = toupper(*str);

switch(ch) {case'E':enter_grades(grade[0]);break;

case 'R':disp_grades(grade);break;

case 'Q':exit(0);

}}

}

/* Enter the student's grades. */void enter_grades(int *p){ int t, i;

for(t=0; t<CLASSES; t++) {printf("Class # %d:\n", t+1);for(i=0; i<GRADES; i++) *(p + (t*GRADES) + i) =

get_grade(i);}

}/* Read a grade. */get_grade(int num){ char s[80];

printf("enter grade for student # %d:\n", num+1);

gets(s);return(atoi(s));

}/* Display grades. */void disp_grades(int g[ ][GRADES]){ int t,i;

for(t=0; t<CLASSES; t++) {printf("Class # %d : \n", t+1);for(i=0; i<GRADES; i++) printf("Student # %d is %d \n",

i+1, g[t][i]);}

}

Page 23: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Sample Program – V.3#include <stdio.h>#include <ctype.h>#include <stdlib.h>#define CLASSES 2#define GRADES 3void enter_grades(int p[][GRADES]);int get_grade(int num);void disp_grades(int g[][GRADES]);void main(void){ char ch, str[80];

int grade[CLASSES][GRADES];for( ; ; ){

printf("(E)nter grades\n");printf("(R)eport grades\n");printf("(Q)uit\n");gets(str);ch = toupper(*str);

switch(ch) {case'E':enter_grades(grade);break;

case 'R':disp_grades(grade);break;

case 'Q':exit(0);

}}

}

/* Enter the student's grades. */void enter_grades(int p[][GRADES]){ int t, i;

for(t=0; t<CLASSES; t++) {printf("Class # %d:\n", t+1);for(i=0; i<GRADES; i++)

p[t][i]=get_grade(i);}

}/* Read a grade. */get_grade(int num){ char s[80];

printf("enter grade for student # %d:\n", num+1);

gets(s);return(atoi(s));

}/* Display grades. */void disp_grades(int g[][GRADES]){ int t,i;

for(t=0; t<CLASSES; t++) {printf("Class # %d : \n", t+1);for(i=0; i<GRADES; i++)

printf("Student # %d is %d \n", i+1, g[t][i]);

}}

Page 24: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

#include <stdio.h>#define MAX 100#define LEN 80char text[MAX][LEN];

/* A very simple editor */void main(void){

int t, i, j;printf("Enter an empty line to quit. \n");for(t=0; t<MAX; t++) {

printf("%d: ", t);gets(text[t]);if (!*text[t]) break;

}for(i=0; i<t; i++) {

for(j=0; text[i][j]; j++) putchar(text[i][j]);putchar('\n');

}}

Example #8

Pgm:Array_Of_String.C

Page 25: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Multidimensional ArraysC allows arrays of more than two dimensional and the exact limit is

determined by the compiler. Arrays of three or more dimensions are not often used because of the amount of the memory required.

General declaration is;type name[a][b][c]...[z];

Example; int m[4][3][6][5];

Required space is (4*3*6*5*2=720 bytes),A function func1() that receives m, like this:func1(int d[ ][3][6][5]){...}

Page 26: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Indexing Pointers• An array name without an index is a pointer to the first element in

the array.• Any pointer variable can be indexed an array.

Example;

int *p, i[10];

p=i;

i[5] =100; /* assign using index */

*(p+5)=100; /* assign using pointer arithmetic*/

Both assignment place the value 100

in the sixth element of array.

For multidimentional arrays;

a[j][k] = *(a+(j*row_length)+k)p=i

i[0]i[1]i[2]

i[8]i[9]

p+2

p+9

Page 27: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Sample// This program is copied one string to another and use pointers. # include <stdio.h># include <string.h> void string_copy(char *source, char *dest);void main (){ char str_from[80], str_to[80];

gets(str_from);str_to[0]='\0';string_copy(str_from, str_to);puts(str_to);

}

void string_copy(char *source, char *dest){

while ((*dest++ = *source++) != '\0');

}

Page 28: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Array InitializationThe general form is;

type_specifier array_name[size1][size2]..[sizeN]={value_list};

int i[10] = {1,2,3,4,5,6,7,8,9,10};

This means i[0] have the value 1 and i[9] have the value 10.

char array_name[size] = “string”;

char str[9] =“I like C”;

char str[9] = {‘I’,’ ‘,’l’,’i’,’k’,’e’,’ ’,’C’,’\0’};

All strings in C end with a null (‘\0’).

Page 29: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Exercise #1Sample-Array ()Read 5 integers from the standard input and output them in reverse order.Pre define array, constants and local variables and initialize them.Post display the array elements in reverse order.Return null.

Sample-Array()1. size = 5 2. table will be included the numbers of element which is described in size.3. k = 04. loop ( k < size)

1. read table[k]2. k = k + 1

5. k = size-16. loop ( k >= 0)

1. display table[k]2. k = k - 1

7. return nullend pgm

Page 30: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Exercise #1#include <stdio.h>

void main(){

const int size = 5;

int table[size];int k;printf("\n Read the table values. \n");for (k=0; k<size; k++){

printf("\n table[%d]=", k);scanf("%d", &table[k]);

}

printf("\n Display the array values in reverse order.\n");

for (k=size-1; k >=0; k--)printf("\n table[%d]= %d",k,table[k]);

}

Page 31: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Exercise #2

• Write a pseudocode algorithm and its function in C which

returns true if the string parameter is a palindrome. A

palindrome is any “word” which is the same forward and

backward, e.g. “radar”, “noon”, “20022002”, .. The function

should return false if the argument is not a palindrome. Assume

the prototype is

bool isPalindrome(char a[ ]);

Assumption:

a. There is no need for temporary arrays. The space in the

arrays passed as parameter is sufficient.

b. These functions can be written in eighter array-style or pointer

style.

Page 32: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Exercise #2Program: bool isPalindrome(char a[ ]);

Pre: Send a string which will be checked the polindrom specification.

Post: Check the string true value if the string is polindrom.

Return: If the string is polindrom, the return value is “True”

otherwise “False”.

1. a_length = Length(a)

2. index_1 = 0, index_2=a_length - 1

3. while (a[index_1] = = a[index_2] AND (index_1 != index_2)

3.1 index_1++

3.2 index_2--

4. if index_1 == index_2 then return(true)

else return(false)

5. end isPolindrome

Page 33: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Exercise #2

bool isPolindrome(char a[ ])

{ int i = 0, j;

j=strlen(a) – 1;

while ((a[i]==a[j]) && (i !=j))

{ i++;

j--;

}

if (i = = j) return True;

else return False;

}

Page 34: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Exercise #3

• Any positive integer i can be expresses as i=2nk, where k is

odd, that is, as a power of 2 times an odd number. We call n the

exponent of 2 in i. For example, the exponent of 2 in 40 is 3

(bacause 40 = 23.5). Write a pseudocode algorithm and the

code in C.

Page 35: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Exercise #3

Program : find_2nk

Pre: Take an odd integer value from user and set i .

Post: Calculate 2nk = i

Return: Print the n and k values.

• Take an integer value and set i.

• division=i and count=0

• Loop until division is odd

– division = division/2

– count = count + 1

• Display i = 2count.division

• End find_2nk

Page 36: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Exercise #3

#include <stdio.h>

#include <math.h>

main() {

int number, i, n=0;

scanf(“%d”, &number);

i=number;

while (!(mod(i,2))

{ n++;

i=i/2;

}

printf (“%d is equal to %d power of 2 and multiply by %d”, number, n, i);

}

Page 37: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Exercise #4/* Vowel Detection - is this letter a vowel */#include <stdio.h>int main() {

char vowels[10] = "AaEeIiOoUu";int is_vowel = 0;char line[100];int counter = 0; int j;printf("Enter a string: ");gets(line); while(line[counter] != '\0') {

for (j=0; j<=10; j++) {if ( line[counter] == vowels[j]) {

is_vowel = 1;break;

}}if(is_vowel == 0)

printf("%c is a consonant\n", line[counter]);

if(is_vowel == 1) {printf("%c is a vowel\n",

line[counter]);is_vowel = 0;

}++counter;

}return (0);

}

Page 38: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

#include <stdio.h>#include <ctype.h> /* includes toupper() *//* Program to compare 2 strings (but NOT case-sensitive) using user-defined function "stricmp()" */

int stricmp(char s1[100], char s2[100]);int main() {

char words[6][20]={"Word","wOrd","box","book","steve","steven"};int test, i;for (i=0; i<6; i+=2) { test=stricmp(words[i],words[i+1]);

printf("\n%s and %s ",words[i],words[i+1]);if (test==0) printf("are the same\n");else { printf("are not the same"); printf("\nThe 1st different letters have int diff of %d\n",test);

} } /* end of for loop */ return 0;}

int stricmp(char s1[100], char s2[100]) {int diff=0, i=0;while(!(s1[i]=='\0' || s2[i]=='\0')) /* stop if one string ends */{if (s1[i]!=s2[i]) diff=toupper(s1[i]) - toupper(s2[i]);/* if letters different set int diff. */ i++; }if (diff==0 && !(s1[i]=='\0' && s2[i]=='\0')) diff=s1[i]-s2[i];

/* If words are the same so far, check one isn't longer than the other */return (diff);

}

Exercise #5

Page 39: Introduction to Computer Algorithmics and Programming Ceng 113 Arrays and Strings

Next Course

• Pointers