Programming Fundamentals

Size: px
Start display at page:

Download "Programming Fundamentals"

Transcription

1 Programming Fundamentals 1

2 Session Plan Introduction to Data Structures Introduction to Arrays Arrays and Functions Introduction to Strings Strings and Functions Handling Multidimensional Arrays 2 Today's session we will be discussing the various data structures 2

3 Data structure Data Struture is the logical or mathematical model of a particular organization of data mirror the actual relationships of the data Examples of data structures: Arrays linked lists Stacks Queues trees c 3 Data structures are "an organization of information, usually in memory, for better algorithm efficiency." 1 Examples of data structures are arrays, queues, dictionaries, hash tables, and collections. The key component of this definition is related to "algorithm efficiency." What does a data structure have to do with algorithm efficiency? As you will see in this set of articles, plenty. Arrays serve as a good starting point for demonstrating how data structure choice affects algorithm choice, and vice versa The logical or mathematical model of a particular organization of data is called a data structure. While solving a programming problem, once the algorithm has been developed, the next step is to determine the data structures to be used to implement the algorithm. Two things should be considered in selecting a data structure. 1. The structure should mirror the actual relationships of the data in the real world. 2. The structure should be simple so that processing data is effective. Data structure are classified as either linear or nonlinear. A data structure is said to be linear if its data have a linear relationship. One way of achieving the linear relationship in a data structure is to represent the data in sequential memory locations. These linear structures are called arrays. 3

4 Data structure.. contd... A data structure is linear if elements are accessed in a single direction Example: Arrays Lists Stacks strings A data structure is nonlinear if its elements are accessed through different directions Example: Trees : Are used to represent data containing a hierarchical relationship between elements 4 4

5 How to select a data structure? Two things should be considered in selecting a data structure The structure should mirror the actual relationships of the data in the real world. The structure should be simple so that processing data is effective. 5 5

6 Arrays Arrays are linear data structures The linear relationships between the elements is represented by means of sequential memory locations. 6 A very familiar concept to most any programmer is that of an array, and they are a common part of our everyday programming lives. We use them so often that we probably forget what they really are. Arrays are a data structure that is used to store a group of objects of the same type sequentially in memory. All the elements of an array must be the same data type. Arrays are "a set of items which are randomly accessible by numeric index." Arrays are typically laid out in memory as a contiguous chunk of blocks, where each block is of the same data type. Because the memory is laid out as a contiguous set of memory chunks, arrays are very fast for accessing items by index. Arrays are a great choice of data structure when the number of elements it contains is known ahead of time. An array is a fixed collection of same data-type that are stored contiguously and are accessible by an index. What this means is that an array consists of a set of physically contiguous memory locations. These memory locations can all be addressed with one name the name of the array. Each location in the array is referred to by the subscript of the array. In C, the syntax to declare an array is as follows. int aiarrayofintegers[10]; This statement declares an integer array named aiarrayofintegers, consisting of 10 elements. Each of these 10 elements can only contain an integer value. The index of the first element of an array in C is 0. That is, the ten elements of the array can be referenced as aiarrayofintegers[0], aiarrayofintegers[1], aiarrayofintegers[2],..., aiarrayofintegers[9]. These values may be accessed as shown below. ivar1 = aiarrayofintegers[0]; Note that in the declaration statement, aiarrayofintegers[10]means that there are 10 elements in the array; but in an assignment statement, aiarrayofintegers[10]refers to the 11th element of a 10-element array. That is, if there are ten elements in an array, the subscript of the last element of the array is 9, and not 10. This is a common programming mistake and results in some indeterminate value being returned by aiarrayofintegers[10], which is very likely to cause program failure. In the declaration statement, the subscript can be a named constant; however, it cannot be a variable. 6

7 Example Read the marks of 2 subjects; find their average; print the marks of that subject as queried by user. 7 write the program. #include <stdio.h> int main() int imark1, imark2, inumber; float faveragemarks; printf("\nenter marks for the subject1 : "); scanf("%d", &imark1); printf("\nenter marks for the subject2 : "); scanf("%d", &imark2); faveragemarks = (imark1 + imark2) / 2.0; printf("\naverage is: %f", faveragemarks); printf("\nenter subject number whose marks you want"); scanf("%d", &inumber); if (inumber == 1) printf("\nmarks of subject 1 is: %d", imark1); else if (inumber == 2) printf("\nmarks of subject 2 is: %d", imark2); else printf("\ninvalid Number"); 7

8 Array Sequence of elements A R R A Y In d iv id u al d ata o b jects o f id entical n atu re : : : : : : : : Indexing Store an element Retrieve an element 8 Now lets try and extend the previous problem to accepts marks in five subjects for a student and display the average. It should then be able to display marks for any subject that the user wants. Consider solving this problem without the use of arrays. #include <stdio.h> main() int imark1;int imark2;int imark3;int imark4;int ichoice; float faverage; printf("\n Enter the four marks"); scanf("%d%d%d%d",&imark1,&imark2,&imark3,&imark4); faverage = (imark1 + imark2 + imark3 +imark4)/4.0; printf("\n Average mark is %f", faverage); printf("\n Do you want to see the Mark? ); printf("\n 1. Mark1"); printf("\n 2. Mark2"); printf("\n 3. Mark3"); printf("\n 4. Mark4"); printf("\n scanf("%d", &ichoice); switch (ichoice) Enter your choice"); case 1: printf("\n Mark1 = %d", imark1); break; case 2: printf("\n Mark2 = %d", imark2); break; case 3: printf("\n Mark3 = %d", imark3); break; case 4: printf("\n Mark4 = %d", imark4); break; default: printf( \n Invalid choice. Please enter your choice again ); break; 8

9 Array -Contd..) Please refer to Notes page for more explanation on previous slide 9 Consider the Previous program written using array. An array is defined with this syntax. datatype arrayname[size]; int ID[30]; /* Could be used to store the ID numbers of students in a class */ float temperatures[31]; /* Could be used to store the daily temperatures in a month */ unsigned short int[52]; /* Holds 52 unsigned short integer values */ #include <stdio.h> main() int aimarksarray[4]; int ichoice; int Counter; int isum; isum = 0; ichoice = 0; printf("\n Enter the five marks"); fflush(stdin); for (Counter = 0; Counter < 4; Counter = Counter + 1) scanf("%d ", &aimarksarray[counter]); isum = isum + aimarksarray[counter]; printf("\naverage mark is %f", isum/4.0); do printf("\n Do you want to see the Mark? ); printf("\n 1. Mark1"); printf("\n 2. Mark2"); printf("\n 3. Mark3"); printf("\n 4. Mark4"); printf("\n Enter your choice"); fflush(stdin); scanf("%d", &ichoice); while (ichoice < 1 ichoice > 4); printf("\n Mark%d = %d",ichoice, aimarksarray[ichoice-1]); 9

10 Array-(Contd..) Please refer to Notes page for more explanation on previous slide 10 Note how the use of an array makes input, processing and output easier. Since an array consists of physically contiguous elements that can all be addressed using the name of the array and a subscript, manipulating the values in an array is not only more efficient, it is also more intuitive compared to working with a number of independent variables. When you declare an array, you declare the type of data it will hold and the size of the array. Once the memory for the array is allocated, it cannot be changed. If you want to set the value for an item in the array, you reference a pre-existing index in the array and specify its contents.if you want to increase the size of the array, you must create a new array with size n+1 and copy the contents of the old array into the new one 10

11 Example Read the marks of students in a class and then print the number of students for each possible total marks. marks are in the range Using Arrays Arrays in C are zero based. Suppose an array named myexample contains N elements. This array is indexed from 0 to (N-1). The first element of myexample is at index 0 and is accessed as myexample[0]. The second element is at index 1 and is accessed as myexample[1]. The last element is at index (N-1) and is accessed as myexample[n-1]. As a concrete example, suppose N equals 5 and that myexample will store integer data. int myexample[5]; /* Defines myexample to be of length 5 and to contain integer data */ myexample[0] /* First element of myexample */ myexample[1] /* Second element of myexample */ myexample[2] /* Third element of myexample */ myexample[3] /* Fourth element of myexample */ myexample[4] /* Fifth and final element of myexample */ Here is a sample program that calculates and stores the squares of the first one hundred positive integers. #include <stdio.h> int main() int square[100]; int i; /* loop index */; int k; /* the integer */ /* Calculate the squares */ for (i = 0; i < 100; i++) k = i + 1; /* i runs from 0 to 99, k runs from 1 to 100 */ square[i] = k*k; printf("the square of %d is %d\n",k,square[i]); return 0; 11

12 Solution #include <stdio.h> int main( ) int aiarrhist[101]; int isize; int icount; int imarks; printf("how many students are there?"); scanf("%d", &isize); for(icount = 0; icount < 101; icount++) iarrhist[icount] = 0; 12 You cannot initialize an array using a variable. For example: int x = 5; int ia[x]; This above example is illegal. C restricts the array initialization size to be constant. So is this legal? int ia[]; No. The array size is not known at compile time. How can we get around this? By using macros we can also make our program more readable! #define MAX_ARRAY_SIZE 5 /*... code... */ int ia[max_array_size]; Now if we wanted to change the array size, all we'd have to do is change the define statement! We can initialize the contents of the array int ia[5] = 0, 1, 3, 4; int ia[ ] = 0, 2, 1; Both of these work. The first one, ia is 20 bytes long with 16 bytes initialized to 0, 1, 3, 4. The second one is also valid, 12 bytes initialized to 0, 2, 1. Arrays are static memory allocated data structures. 12

13 Solution (contd ) for(icount = 0; icount < isize; icount++) scanf("%d", &imarks); aiarrhist[imarks] = aiarrhist[imarks] + 1; for(icount = 0; icount < 101; icount++) printf("\nthe no. of students with marks %d are %d", icount, aiarrhist[icount]); 13 13

14 Example Insert a element in the array 14 #include <stdio.h> void fvacceptarrvalues(int [],int); void fvinsarrelement(int aiarrdata[],int ipos,int inoofelements,int inewnumber); void fvdisparr(int aiarrdata[],int inoofelenents); int icount; int main( ) int aiarrdata[100]; int inoofelementsinarray; int inewnumber; int ipos; printf("how many numbers are there "); scanf("%d", &inoofelementsinarray); fvacceptarrvalues(aiarrdata,inoofelementsinarray); printf("enter the new number "); scanf("%d", &inewnumber); printf("where do you want to insert"); scanf("%d", &ipos); fvinsarrelement(aiarrdata,ipos,inoofelementsinarray,inewnumber) printf("the new data is:"); fvdisparr(aiarrdata,inoofelementsinarray); 14

15 Inserting Elements - Solution printf("how many numbers are there "); scanf("%d", &inoofelementsinarray); fvacceptarrvalues(aiarrdata,inoofelementsinarray); printf("enter the new number "); scanf("%d", &inewnumber); printf("where do you want to insert"); scanf("%d", &ipos); fvinsarrelement(aiarrdata,ipos,inoofelementsinarray,inewnumber); printf("the new data is:"); fvdisparr(aiarrdata,inoofelementsinarray); 15 Like simple value and variable, it is also possible to pass the value of an array element and even an entire array as an argument to a function. To pass an array element to a function, the array element is specified as an argument to the function in the normal fashion. Let us revisit our earlier example of finding average marks for student. We rewrite the example using the array variable. #include <stdio.h> float fgetaverage (int inum1, int inum2, int inum3); void main() int i; int aiarray[3]; float faverage; for (i = 0; i < 3; i++) scanf("%d", &aiarray[i]); faverage = fgetaverage(aiarray[0], aiarray[1], aiarray[2]); printf("average is %f", faverage); float fgetaverage (int inum1, int inum2, int inum3) float favg; favg = (inum1 +inum2 +inum3) /(3.0); return favg; 15

16 Inserting Elements Solution-(Contd..) Please refer to Notes page for more explanation on previous slide 16 In the above example, we have passed the array elements in the same fashions as we did for simple variables in our earlier example However, the above example can also be written more succinctly as shown below by passing the whole array to the function fgetaverage instead of passing each element of the array separately. #include <stdio.h> #define SIZE 3 float fgetaverage (int aiarr[], const int N); void main() int i; float faverage; int aiarray[size]; printf(" Please enter %d numbers",size); fflush(stdin); for (i = 0; i < SIZE; i++) scanf("%d", &aiarray[i]); faverage = fgetaverage(aiarray,size); printf("average is %f", faverage); float fgetaverage (int aiarr[], const int N) int isum; int i; float favg; isum = 0; for (i = 0; i < N; i++) isum = isum + aiarr[i]; favg = isum /(3.0); return favg; 16

17 Inserting Elements Solution-(Contd..) Please refer to Notes page for more explanation on previous slide 17 Observe the prototype declaration, function definition and function call for fgetaverage in the above program. For passing an entire array to a function, it is only required to list the name of the array, without any subscript, in the function call. In the function prototype and definition there is no mention about the size of the array. 17

18 Inserting Elements Solution-(Contd..) Please refer to Notes page for more explanation on previous slide 18 However, there is a major distinction that must always be kept in mind while dealing with array arguments. Before discussing further let us look at the following simple example. Consider an array of integers of size 10. We initialize all the elements of the array to 0. Then we change the value of those array elements to 1 who are occupying the even position in the array, i.e., with index 1, 3 5, 7, 9. Finally, print all the elements of the array after reinitialization. The program can be written as below. #include <stdio.h> # define SIZE 10 main( ) int i; int aiarray[size]; for (i = 0; i < SIZE; i++) aiarray[i] = 0; //initialization for (i = 0; i < SIZE; i++) if ( i %2!= 0) aiarray[i] = 1; //re-initialization for (i = 0; i < SIZE; i++) printf( array[%d] = %d \n, i, aiarray[i] ); 18

19 Inserting Elements Solution-(Contd..) Please refer to Notes page for more explanation on previous slide 19 Let us rewrite the above example using a self-explanatory function where the entire array has been passed in the argument. #include <stdio.h> # define SIZE 10 void vre_initialize( int aiarr[], int n) int i; for (i = 0; i < n; i++) if ( i %2!= 0) aiarr[i] = 1; main( ) int i; int aiarray[size]; for (i = 0; i < SIZE; i++) aiarray[i] = 0; //initialization vre_initialize(aiarray, SIZE); for (i = 0; i < SIZE; i++) printf( array[%d] = %d \n, i, aiarray[i]); The output of the above program after its execution demonstrates one major deviation from what we have been seeing so far. That is, the function vre_initialize changes the value of the original array aiarray that has been passed to it as argument. This change remains in effect even after the function vre_initialize has completed its execution and has returned to the calling routine (i.e., main( )) The following points have to be kept in mind when dealing with array arguments. In a function call (in C language), the values that are passed as arguments to the function are copied (known as Pass by value) into the formal parameters. 19

20 Inserting Elements Solution-(Contd..) Please refer to Notes page for more explanation on previous slide 20 However, when the entire array is passed as arguments, the entire contents of the array are NOT copied into the formal parameter array of the function. Instead, the formal parameter array holds the information describing WHERE in the computer s memory the actual array is located (known as Pass by Reference). Thus, any changes made to the formal parameter array by the function are reflected on the actual array passed to the function. Hence, when the function returns, the changes still remain in effect. Note: The preceding discussion applies only to the entire arrays that are passed as arguments, and not to the individual elements, whose values are copied into the corresponding formal parameters and therefore cannot be changed by the function. 20

21 Inserting Elements Solution-(Contd ) void fvacceptarrvalues(int aiarrdata[],int inoofelementsinarray) for(icount = 0; icount < inoofelementsinarray; icount++) scanf("%d", &aiarrdata[icount]); void fvinsarrelement(int aiarrdata[],int ipos,int inoofelementsinarray,int inewnumber) for(icount = inoofelementsinarray - 1; icount >= ipos-1; icount--) aiarrdata[icount+1] = aiarrdata[icount]; aiarrdata[ipos -1] = inewnumber;inoofelementsinarray = inoofelementsinarray +1; void fvdisparr(int aiarrdata[],int inoofelementsinarray) for(icount = 0; icount < inoofelementsinarray; icount++) printf("%d",aiarrdata[icount]); 21 When an array is passed into a function, the function receives not a copy the array, but instead the address of the first element of the array. The function receives a pointer to the start of the array. Any modifications made via this pointer will be seen in the calling program. Let's see how this works. Suppose the main program has an array of 10 integers and that a function has been written to double each of these. void doublethem(int a[], int size); int main() int myints[10] = 1,2,3,4,5,6,7,8,9,10; doublethem(myints, 10); return 0; void doublethem(int a[], int size) int i; for (i = 0; i < size; i++) a[i] = 2 * a[i]; Hence entire Arrays are passed by reference by default. But when individual array elements are passed as argument they could be passed by ref / by argument. 21

22 Inserting Elements Solution-(Contd ) Please refer to Notes page for more explanation on previous slide 22 Consider another example #include <stdio.h> #include <stdio.h> void fvchange(int aiarr1[],int aiarr20,int *aiarr21); main() int aiarr1[2],aiarr2[2]; aiarr1[0]=1; aiarr1[1]=2; aiarr2[0]=3; aiarr2[1]=4; printf("arr1 Elements %d-%d",aiarr1[0],aiarr1[1]); printf("\narr2 Elements %d-%d",aiarr2[0],aiarr2[1]); printf("\n"); fvchange(aiarr1,aiarr2[0],&aiarr2[1]); printf("arr1 Elements %d-%d",aiarr1[0],aiarr1[1]); printf("\narr2 Elements %d-%d",aiarr2[0],aiarr2[1]); void fvchange(int aiarr1[],int aiarr20,int *aiarr21) aiarr1[0]=5; aiarr1[1]=6; aiarr20=7; *aiarr21=8; In the example aiarr1 array is passed by reference,aiarr2[0] element is passed by value and aiarr2[1] element is passed by reference. 22

23 Arrays and Pointers int ia[6] = 0, 1, 2, 3, 4, 5; int *ip; ip = ia; /* equivalent to ip = &ia[0]; */ ip[3] = 32; ia 100 ia[0] ia[1] ia[2] ia[3] ia[4] ia[5] ip An array name is just a pointer to the beginning of the allocated memory space. Let's take this example and analyze it: int ia[6] = 0, 1, 2, 3, 4, 5; /* 1 */ int *ip; /* 2 */ ip = ia; /* equivalent to ip = &ia[0]; */ /* 3 */ ip[3] = 32; /* equivalent to ia[3] = 32; */ /* 4 */ ip++; /* ip now points to ia[1] */ /* 5 */ printf("%d ", *ip); /* prints 1 to the screen */ /* 6 */ ip[3] = 52; /* equivalent to ia[4] = 52 */ /* 7 */ Ok, so what's happening here? Let's break this down one line at a time. Refer to the line numbers on the side: 1.Initialize ia 2.Create ip: a pointer to an int 3.Assign ip pointer to ia. This is effectively assigning the pointer to point to the first position of the array. 4.Assign the fourth position in the array to 32. But how? ip is just a pointer?!?! But what is ia? Just a pointer! 5.Use pointer arithmetic to move the pointer over in memory to the next block. Using pointer arithmetic automatically calls sizeof(). 6.Prints ia[1] to the screen, which is 1 7.Sets ia[4] to 52. Why the fifth position? Because ip points to ia[1] from the ip++ line. Now it should be clear. Pointers and arrays have a special relationship because arrays are actually just a pointer to a block of memory! Point to be noted here is that Arrays are constant pointers. 23

24 Coping with inflexibilities of Arrays define constant for size recompile define a very big array wastage of space 24 Because names of arrays represents just a pointer to the beginning of the array, we have some limitations or "problems." 1.No Array Out of Bounds Checking. For example: int ia[2] = 0, 1; printf("%d ", ia[2]); The above code would result in runtime error, because you are trying to look at an area of memory not inside the array memory allocation. 2.Array Size Must be Constant or Known at Compile-time 3.Arrays Cannot be Copied or Compared. Why? Because they are pointers. 4.Array Index Type must be Integral. Another limitation comes with arrays being passed into functions. Take for example: void func(int ia[]) void func(int *ia) Both are the same declaration (you should know why by now). But why would this cause problems? Because only the pointer to the array is passed in, not the whole array. So what if you mistakenly did a sizeof(ia) inside func? Instead of returning the sizeof the whole array, it would only return the size of a single element in the array. 24

25 Array as a data structure very fast at storing and getting from a particular index Slow in inserting and deleting elements Alternatives are there linked lists trees a a a NULL Address of third node 2 nd data element 25 Although arrays are extremely useful, one of the major disadvantages of using an array is insertion (deletion) of an element to (from) the array. Consider inserting an element in the beginning of an array (assume that enough memory is available for insertion). For achieving this, the value in every element must be moved to its subsequent element. Then the new value is inserted into the first position. Imagine such situation when the array size is large enough! Similar is the case for deleting an element from an array. An alternative is to use linked lists. A linked list(a linear data structure) consists of a series of nodes such that, each node has a data element and the address of the next node in the list. The following figure gives a schematic view of a link list with 5 nodes. The first node contains the information of element 1 and address of element 2, the second node contains the information of element 2 and address of node 3 and so on. To insert or delete a new node, only two nodes at most (the ones just before in case it is inserted after the first node and just after in case it is inserted before the last node) have to be modified suitably. 25

26 Strings Text processing word processors Searching databases Input/output 26 String (in C) is referred to a variable-length array of characters, defined by a starting point and by a string-termination character ( \0 ) marking the end. In computing applications where processing of textual data are involved, strings are useful in representing these textual data and hence, are valuable in low-level data structure. The difference between an array of characters and a string revolves around length. Both represents a contiguous area of memory, but the length of the array is set at the time that array is created, whereas the length of a string may change during the execution of a program. We need to reserve memory for a string, either during compile time by declaring an array of characters (will be followed in this course) or at execution time by invoking dynamic memory allocation function (beyond the scope of the course). Once the array is allocated, we can fill it with characters, starting at the beginning and ending with the string termination character ( \0 )or popularly known as the NULL character(i.e., having value 0). Without a string termination character, the string is same as an array of characters. Only with the string terminating character, we can consider the portion of the array from the beginning to the string termination character to contain meaningful information. 26

27 Definitions of strings char name[4] = xy ; Will create a string consisting of 4 memory locations. 1 st element stores x 2 nd element stores y 3 rd element stores \0 ; 4 th element is unused char n1[] = xy ; Will create a string consisting of 3 memory locations. 1 st element stores x 2 nd element stores y 3 rd element stores \0 ; char a[5]='h','e','l','l','o'; Will create a character array consisting of 5 memory locations. 27 Stings in C are stored as null character, '\0', terminated character arrays. This means that the length of a string is the number of characters it contains plus one to store the null character. Common string operations include finding lengths, copying, searching, replacing and counting the occurrences of specific characters and words. A string is just a character array with the convention that the end of the valid data is marked by a null '\0'. Now you should be able to see why you can read in a character string using scanf("%s", name) rather than scanf("%s",&name) - name is already a pointer variable. Manipulating strings is very much a matter of pointers and special string functions. For example, the strlen(str) function returns the number of characters in the string str. It does this simply by counting the number of characters up to the first null in the character array - so it is important that you are using a valid null-terminated string. Indeed this is important with all of the C string functions 27

28 Input/output of strings char yourname[20] scanf("%s",yourname); scanf( %s,&yourname[0]); /* yourname is a character array. yourname[0] specifies the first element of the array. &yourname[0] specifies the address of the first element of the array. In C, an array name by itself is shorthand for the address of the first element. So, yourname is equivalent to &yourname[0], which is what must be passed into scanf. */ 28 scanf will skip over white space such as blanks, tabs and newlines in the input stream. The exception is when trying to read single characters with the conversion specifier %c. In this case, white space is read in. So, it is more difficult to use scanf for single characters. Some more input functions getchar getchar reads a single character from standard input. Its prototype is: int getchar(); It returns int rather than char because the "end of file", EOF, character must be handled. EOF is an int and is too large to fit in a char variable. A newline character in C is '\n'. This designates the end of a line. gets gets reads a line of input into a character array. Its prototype is: char *gets(char *buffer); It returns a pointer to the character string if successful, or NULL if end of file is reached or if an error has occurred. The string is also read into the character array specified as an argument. The character string will be terminated be a "\0", which is standard for C. 28

29 Input/output of strings printf("hello World\n"); /* The format string contains only ordinary characters. Ordinary characters are output unmodified. A character string in C is of type "char *". */ printf("my name is %s\n",myname); printf("my first initial is %c\n",initial); /* The %s specifies that a character string will be output. */ /* The %c specifies that a character will be output. */ printf("hello %s or should I say %c\n",myname,initial); /* Multiple arguments of different types may be output. */ 29 putchar putchar writes a single character to standard output. Its prototype is: int putchar(int value); puts puts writes a line of output to standard output. Its prototype is: int puts(const char *buffer); Here is a simple program which echoes back everything that is typed in. Note that depending on which operating system you are using, EOF is entered by typing control-z or control-d. So, if you try running this code, type control-z or control-d to end execution #include <stdio.h> int main() int c; while ((c = getchar())!= EOF) putchar(c); return(0); It terminates the line with a newline, '\n'. It will return EOF is an error occurred. It will return a positive number on success. 29

30 Input/output of strings-(contd ) Please refer to Notes page for more explanation on previous slide 30 Here is the "echo" program implemented using the functions gets and puts. If you run this, remember to type control-z or control-d to end execution. #include <stdio.h> int main() char buffer[120]; /* Holds input and output strings */ char *pt; /* A pointer to datatype char */ int returncode; while ((pt = gets(buffer))!= NULL) returncode = puts(buffer); if (returncode == EOF) printf("error on output\n"); return(0); There are some very important things to note in the this example. First, gets returns a NULL pointer when EOF is reached. This is the condition that must be checked in while loop. Second, puts returns EOF on failure. A check is made on this, and an appropriate error message is output if an error has occurred. Finally, the character array buffer is declared to be of length 120. The function gets makes no check on the array size to see if it is large enough to hold the string entered. It is up to the programmer to create a character array that is large enough. If the entered string is larger than the array, gets will still put the string in memory starting at the location of the first byte of the designated array. Since the string is longer than the array, the result is that memory past the end of the array will be overwritten with the entered string. This will cause either erratic behavior or failure (core dump) of the program. 30

31 String Handling functions There is no basic data type for a string in C. Instead, strings in C are implemented as an array of characters. There is an extensive set of library functions for manipulating strings available in string.h Length of string strlen function Concatenate two strings strcat function Compare two strings strcmp function Copy a string to another strcpy function Next Token of string strtok function Replace/substitute a string Find substring in string 31 The strlen function takes as parameter the string whose length has to be calculated and return the number of characters (excluding \0 ) The strcmp function takes 2 strings, to be compared.as parameters and does a character by character comparison. It returns a integer value which is 0 if the strings are equal >0 if the string 1 is greater than string 2 (ascii difference of the chars where mismatch is found) <0 if the string 1 is less than string 2 (ascii difference of the chars where mismatch is found) The strcpy function takes 2 string arguments. The first parameter is the destination string and the second parameter is the source string. Care need to be taken that the destination string needs to be large enough to store the source string. The function does not validate this while copying Some more String handling functions are listed in the slide. 31

32 String Handling functions-(contd..) Please refer to Notes page for more explanation on previous slide 32 Functions Function Signature Description strchr() char* strchr(const char* s, int c) Returns a pointer to the first occurrence of c in string s. Returns NULL if c is not found in s. strncat() char* strncat(char* s1, const char* s2, size_t n) Tacks on the first n characters of s2 onto s1. A pointer to s1 is returned. strncmp() int strncmp(const char* s1, const char* s2, size_t n) Compares s1 with the first n characters of s2. Returns a negative, zero, or positive integer (just like strcmp). strncpy() char* strncpy(char* s1, const char*s2, size_t n) Copies the first n characters of s2 into the first n characters of s1. strrchr() char* strrchr(const char*s, int c) Returns a pointer to the last occurrence of c in string s. (Compare with strchr().) strstr() char* strstr(const char* s1, const char* s2) Returns the address of the first occurence of string s2 that is also in string s1. Returns NULL if s2 is not found in s1. 32

33 String Length Function strlen() - Returns the number of characters in the string s, starting at s[0] and ending before the first NULL. Prototype declaration - size_t strlen(const char* s) #include <stdio.h> #include <string.h> int main() char name[80],int length; printf("enter your name: "); gets(name); length = strlen(name); printf("your name has %d characters\n", length); return 0; 33 User defined function equivalent to strlen is :- int istr_len(char acstring[]) int iindex ; iindex = 0; while(acstring[iindex]!= \0 ) return iindex; iindex++; 33

34 String Compare Function strcmp() - Compares s1 and s2 alphabetically. Returns a negative, zero, or positive number depending on whether s1 is before, the same as, or after s2 if you were alphabetizing s1 and s2. Prototype declaration - int strcmp(const char* s1, const char* s2) #include <stdio.h> #include <string.h> void main() char first[80], second[80]; printf("enter a string: "); gets(first); printf("enter another string: "); gets(second) ; if (strcmp(first, second) == 0) /* comparison of the form if(first==second) is not valid*/ puts("the two strings are equal"); else puts("the two strings are not equal"); return 0; 34 The strcmp Function The strcmp function is used to compare two strings together. The variable name of an array points to the base address of that array. Therefore, if we try to compare two strings using the condition if (first == second) We would be comparing two addresses, which would obviously never be the same as it's not possible to store two values in the same location. Code the user defined version of the same function. 34

35 String Copy Function strcpy() - Copies s2 into s1, and returns a point to s1. Prototype declaration - char* strcpy(char* s1, const char* s2) #include <stdio.h> #include <string.h> void main() char first[80], second[80]; printf("enter a string: "); gets(first); strcpy(second, first); /* an assignment of the form second=first is invalid */ printf("first: %s, and second: %s\n", first, second); return 0; 35 The strcpy Function The strcpy function is used to copy one string to another. Examples firstname= "Arnold"; /* Illegal */ strcpy(firstname, Arnold ) ; /* valid */ lastname= "Schwarznegger"; /* Illegal */ strcpy(lastname, Schwarznegger ) ; /* valid */ 35

36 String Concatenate Function strcat() - Adds string s2 onto the end of s1 (concatenation). Prototype declaration - char* strcat(char* s1, const char* s2) #include <stdio.h> #include <string.h> void main() char first[80], second[80]; printf("enter a string: "); gets(first); printf("enter another string: "); gets(second); strcat(first, second); /* adding using first=first+second */ is invalid */ printf("the two strings joined together: %s\n", first); return 0; 36 The strcat Function The strcat function is used to join one string to another. Exmaple fullname= "Mr"+firstname +lastname; /* Illegal */ strcat(fullname, Mr ); strcat(fullname,firstname); strcat(fullname,lastname); 36

37 String Tokenizer function strtok() - to find the next token in a string Prototype declaration - char* strcat(char* s1, char* s2) #include <stdio.h> #include <string.h> void main() char line[80], char *delimiters = " ", char *token; gets(line); token = strtok(line, delimiters); while (token!= NULL) puts(token); /* Get the next word */ token = strtok(null, delimiters); 37 The strtok Function The strtok function is used to find the next token in a string. The token is specified by a list of possible delimiters. 37

38 Example: Palindrome Check whether the user entered string is a palindrome or not 38 38

39 Solution #include <stdio.h> int icheck_palindrome(char acstring[], int istringlen); int istr_len(char [ ]); int main ( ) char acstring[100]; int istrlen, iindex, int ipalindrome; printf("enter the string"); gets(acstring); istrlen=istr_len(acstring); ipalindrome=icheck_palindrome(acstring, istrlen); if (ipalindrome == 1) printf("a palindrome"); else printf("not a palindrome"); 39 39

40 Solution (contd ) int icheck_palindrome(char acstring[ ], int istrlen) int ipalindrome; int iindex; ipalindrome = 1; for(iindex=0; iindex<istrlen/2; iindex++) if (acstring[iindex]!= acstring[istrlen - iindex - 1]) ipalindrome = 0; return(ipalindrome); 40 40

41 Example Reverse the user entered string and then print #include <stdio.h> void vreverse_string(char[ ]); int istr_len(char [ ]); int main( ) char acstring[100]; char acreversestring[100]; int istrlen; printf("enter the string"); gets(acstring); istrlen=istr_len(acstring); vreverse_string(acstring,istrlen); printf( The reversed string is %s \n, acstring); 41 41

42 Solution #include <stdio.h> void vreverse_string(char[ ]); int istr_len(char [ ]); int main( ) char acstring[100]; char acreversestring[100]; int istrlen; printf("enter the string"); gets(acstring); istrlen=istr_len(acstring); vreverse_string(acstring,istrlen); printf( The reversed string is %s \n, acstring); 42 42

43 Solution (contd ) void vreverse_string(char acstring[ ], int istrlen) int iindex; char ctemp; for(iindex = 0; iindex < istrlen/2; iindex++) ctemp = acstring[iindex]; acstring[iindex] = sstring[istrlen - iindex - 1]; sstring[istrlen - iindex -1] = ctemp 43 43

44 Multidimensional arrays Declaration int a2[3][2]; -/* a2 is an array of 3 elements, each of which is an array of 2 int reserves memory for 3*2 ~ 6 element / integer values * float temperatures[12][31]; /* Used to store temperature data for a year */ float altitude[100][100]; /* Used to store the altitudes of grid points of a 100 by 100 mile square */ Memory Allocation a2 a2[0][0] a2[0][1] a2[0][2] a2[1][0] a2[1][1] a2[2][2] Accessing elements int i, j; for(i = 0; i < 5; i++) for(j = 0; j < 7; j++) a2[i][j] = 0; 44 C does not have true multidimensional arrays. However, because of the generality of C's type system, you can have arrays of arrays, which are almost as good. (This should not surprise you; you can have arrays of anything, so why not arrays of arrays?) Just as we declared a two-dimensional array using two pairs of brackets, we access its individual elements using two pairs of brackets: Make sure that you remember to put each subscript in its own, correct pair of brackets. Neither int a2[5, 7]; /* XXX WRONG */ nor a2[i, j] = 0; /* XXX WRONG */ nor a2[j][i] = 0; /* XXX WRONG */ would do anything remotely like what you wanted. While declaring arrays, there are times when you don't know the size, so you'd want to use an unsized array. However, you must specify every dimension size except the left one. Like this: int array2d[][5]; 44

45 Multidimensional arrays-(contd ) Please refer to Notes page for more explanation on previous slide 45 Consider an example:- #include <stdio.h> void main() int first[3][4] = 0,1,2,3,4,5,6,7,8,9,10,11; int second[3][4] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11; /* a clearer definition than the first */ int third[][5] = 0,1,2,3,4; /* third[] only has one index of 1 */ int fourth[][6] = 0,1,2,3,4,5, 6,7,8,9,10,11; /* fourth[] has 2 indices - 0 or 1 */ int i,j; int fifth[5][4]; int sixth[2][6]; int seventh[2][3]; for(i=0 ; i<5 ; i++) for(j=0 ; j<4 ; j++) fifth[i][j] = i * 4 + j; for(i=0 ; i<2 ; i++) printf("enter 6 integers separated by spaces: "); for(j=0 ; j<6 ; j++) scanf("%d", &sixth[i][j]); printf("\n"); printf("you entered:\n"); for(i=0 ; i<2 ; i++) for(j=0 ; j<6 ; j++) printf("%d ", sixth[i][j]); printf("\n"); seventh[0][0] = 0; seventh[0][1] = 1; seventh[0][2] = 2; seventh[1][0] = 3; seventh[1][1] = 4; seventh[1][2] = 5; return 0; 45

46 Multidimensional arrays-(contd ) Please refer to Notes page for more explanation on previous slide 46 If you ever wanted to find out how much memory your arrays occupy (1D or multidimensional), you can use the sizeof operator. Example for accessing multidimesional array elements A common way to access the elements of a multidimensional arrays is with nested for loops. #define MAXI 50 #define MAXJ 75 int i; int j; float values[maxi][maxj]; for (i = 0; i < MAXI; i++) for (j = 0; j < MAXJ; j++) values[i][j] = whatever; Important Note About Array Dimensions The C language performs no error checking on array bounds. If you define an array with 50 elements and you attempt to access element 50 (the 51st element), or any out of bounds index, the compiler issues no warnings. It is the programmer's task alone to check that all attempts to access or write to arrays are done only at valid array indexes. Writing or reading past the end of arrays is a common programming bug and can be hard to isolate. 46

47 Multidimensional arrays-(contd ) Please refer to Notes page for more explanation on previous slide 47 What will happen if a program accesses past the end of an array? Suppose a program has the following code. int val; int buffer[10]; val = buffer[10]; /* Bug, remember that the indexes of buffer run from 0 to 9. */ What value will be in val? Whatever happens to be in memory at the location right after the end of the array. This value could be anything. Worse yet, the program may continue to run with the incorrect value and no warnings are issued. What will happen if a program writes past the end of an array? Suppose a program has the following code. int buffer[10]; buffer[593] = 99; The value of 99 will be written at the memory location, buffer "buffer" is a pointer to the beginning of the array. buffer is pointer arithmetic for the address equal to the starting address of the array plus the size of 593 integers. The overwriting of the value at this memory location will change the value of whatever variable is stored there. Some other variable may have its value changed unintentionally. If the program writes unintentionally to memory locations that not valid, the program may crash. 47

48 Multidimensional arrays-(contd ) Please refer to Notes page for more explanation on previous slide 48 The most common cause of writing/reading to invalid array indexes are errors in loop limits. int i; float b[10]; for (i < 0 ; i <= 10; i++) b[i] = 3.14 * i * i; This loop should use "<" rather than "<=" The most straightforward way of passing a multidimensional array to a function is to declare it in exactly the same way in the function as it was declared in the caller. If we were to call func(a2); then we might declare func(int a[5][7])... and it's clear that the array type which the caller passes is the same as the type which the function func accepts. 48

49 Multidimensional arrays-(contd ) Please refer to Notes page for more explanation on previous slide 49 While passing single dimensional arrays as parameters to functions, the formal parameters to the function definition were only the array name[]. Size was omitted because it was decided by the parent function which calls this function. But when we look at passing 2-dimensional arrays as parameters to the function the formal parameters to the function definition needs to be array name[][<size>. We can only omit the row dimension and need to specify the column dimension. With multidimensional arrays being passed as parameters to functions, we need to specify all but the first dimension of the array. 49

50 Multidimensional arrays-(contd ) Please refer to Notes page for more explanation on previous slide 50 Another important point to understand here is what is common between arrays and pointers. When we pass arrays as arguments to functions what is actually been passed is the starting address to the array (ie the address of the first element of the array) 50

51 Multidimensional Arrays and functions Passing Arrays as arguments to functions Declaration Definition Invocation func(int arr[][7]) func(int arr[][7]) func(arr) Write a program to accept values into a 2-dimensional array (arr) and display the row totals display the column totals transpose the elements of the array. 51 The most straightforward way of passing a multidimensional array to a function is to declare it in exactly the same way in the function as it was declared in the caller. If we were to call func(a2); then we might declare func(int a[5][7])... and it's clear that the array type which the caller passes is the same as the type which the function func accepts. Concluding, the formal parameters declaration within the function definition must include explicit size specifications in all of the subscript positions except the first 51

52 Array of strings Declarations char caname[5][10]; caname[0] - Creates a 2D array of characters with 5 rows, each row having 10 characters - 1 st single dimensional character array, which can be used to hold 10 characters or a string of 9 characters caname points the 1 st element of the array ie caname[0][0]; caname 52 An array of strings is just a two dimensional array of characters. Consider this: char names[7][6] = "Ryan", "Tom", "Chad", "Jackie", "Tara", "Lori", "Kelly" ; This gives you an array of seven names. The first number in brackets says how many strings there will be, and the second number is the amount of characters any of the strings can have. If you left out the numbers in the brackets, the compiler would figure it out for you using the longest name length as the maximum length (the second number in brackets). To reference a string, only use the first dimension. So the statement printf("%s", names[0]); would print the name Ryan on the screen. Do not reference a string like this names[3][0]. That refers to the character 'J' not the string "Jackie". 52

53 Example #include <stdio.h> #include <string.h> void main() char *mess[] = "Pen", "Pencil", "Scale", "Sharpner", "Scissor" ; printf("%s",mess[0]); printf("%c",mess[3][4]); Consider the declaration above and answer the questions Is it a valid declaration? mess[0] pointer to the string Pen Character at mess[3][4] is? 53 The declaration is valid. Each the string is referred to using mess[0] ->Pen,mess[1]-> Pencil and so on mess[3] -> Sharpner Mess[3][0]->S mess[3][1]->h..hence mess[3][4] -> p 53

54 Summary Definition of strings Input/output of strings String functions Multidimensional Arrays 54 54

55 Thank You! 55 55

Programming in C. Session 2. Seema Sirpal Delhi University Computer Centre

Programming in C. Session 2. Seema Sirpal Delhi University Computer Centre Programming in C Session 2 Seema Sirpal Delhi University Computer Centre Input & Output Input and Output form an important part of any program. To do anything useful your program needs to be able to accept

More information

Pointers, Arrays, and Strings. CS449 Spring 2016

Pointers, Arrays, and Strings. CS449 Spring 2016 Pointers, Arrays, and Strings CS449 Spring 2016 Pointers Pointers are important. Pointers are fun! Pointers Every variable in your program has a memory location. This location can be accessed using & operator.

More information

ARRAYS(II Unit Part II)

ARRAYS(II Unit Part II) ARRAYS(II Unit Part II) Array: An array is a collection of two or more adjacent cells of similar type. Each cell in an array is called as array element. Each array should be identified with a meaningful

More information

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size]; Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

More information

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre Programming in C Session 7 Seema Sirpal Delhi University Computer Centre Relationship between Pointers & Arrays In some cases, a pointer can be used as a convenient way to access or manipulate the data

More information

Array Initialization

Array Initialization Array Initialization Array declarations can specify initializations for the elements of the array: int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; initializes primes[0] to 2, primes[1] to 3, primes[2]

More information

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

CSC209H Lecture 4. Dan Zingaro. January 28, 2015 CSC209H Lecture 4 Dan Zingaro January 28, 2015 Strings (King Ch 13) String literals are enclosed in double quotes A string literal of n characters is represented as a n+1-character char array C adds a

More information

Chapter 8: Character & String. In this chapter, you ll learn about;

Chapter 8: Character & String. In this chapter, you ll learn about; Chapter 8: Character & String Principles of Programming In this chapter, you ll learn about; Fundamentals of Strings and Characters The difference between an integer digit and a character digit Character

More information

Characters and Strings

Characters and Strings Characters and Strings 60-141: Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2013 Instructor: Dr. Asish Mukhopadhyay Character constants A character in single quotes,

More information

Computers Programming Course 11. Iulian Năstac

Computers Programming Course 11. Iulian Năstac Computers Programming Course 11 Iulian Năstac Recap from previous course Cap. Matrices (Arrays) Matrix representation is a method used by a computer language to store matrices of different dimension in

More information

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful

More information

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb CS 201 String Debzani Deb Strings(2) Two interpretations of String Arrays whose elements are characters. Pointer pointing to characters. Strings are always terminated with a NULL characters( \0 ). C needs

More information

ONE DIMENSIONAL ARRAYS

ONE DIMENSIONAL ARRAYS LECTURE 14 ONE DIMENSIONAL ARRAYS Array : An array is a fixed sized sequenced collection of related data items of same data type. In its simplest form an array can be used to represent a list of numbers

More information

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1 Lecture 10 Arrays (2) and Strings UniMAP SEM II - 11/12 DKT121 1 Outline 8.1 Passing Arrays to Function 8.2 Displaying Array in a Function 8.3 How Arrays are passed in a function call 8.4 Introduction

More information

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction. Chapter 9 Scanning Computer Science & Engineering 150A Problem Solving Using Computers Lecture 07 - Strings Stephen Scott (Adapted from Christopher M. Bourke) Scanning 9.1 String 9.2 Functions: Assignment

More information

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings Computer Science & Engineering 150A Problem Solving Using Computers Lecture 07 - Strings Scanning Stephen Scott (Adapted from Christopher M. Bourke) 1 / 51 Fall 2009 cbourke@cse.unl.edu Chapter 9 Scanning

More information

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7 Strings and Clases BIL104E: Introduction to Scientific and Engineering Computing Lecture 7 Manipulating Strings Scope and Storage Classes in C Strings Declaring a string The length of a string Copying

More information

8. Characters, Strings and Files

8. Characters, Strings and Files REGZ9280: Global Education Short Course - Engineering 8. Characters, Strings and Files Reading: Moffat, Chapter 7, 11 REGZ9280 14s2 8. Characters and Arrays 1 ASCII The ASCII table gives a correspondence

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 07 - Strings Stephen Scott (Adapted from Christopher M. Bourke) 1 / 51 Fall 2009 Chapter 9 9.1 String 9.2 Functions: Assignment

More information

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY Strings Arrays of characters Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY 1 Basics Strings A string is a sequence of characters treated as a group We have already

More information

Computer Programming: Skills & Concepts (CP) Strings

Computer Programming: Skills & Concepts (CP) Strings CP 14 slide 1 Tuesday 31 October 2017 Computer Programming: Skills & Concepts (CP) Strings Ajitha Rajan Tuesday 31 October 2017 Last lecture Input handling char CP 14 slide 2 Tuesday 31 October 2017 Today

More information

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS CHARACTER STRINGS 1. Overview The learning objective of this lab session is to: Understand the internal representation of character strings Acquire skills in manipulating character strings with standard

More information

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17 Grade Distribution Exam 1 Exam 2 Score # of Students Score # of Students 16 4 14 6 12 4 10 2 8 1 Total: 17 Exams 1 & 2 14 2 12 4 10 5 8 5 4 1 Total: 17 Score # of Students 28 2 26 5 24 1 22 4 20 3 18 2

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 6 - Array and String Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Array Generic declaration: typename variablename[size]; typename is

More information

Computers Programming Course 10. Iulian Năstac

Computers Programming Course 10. Iulian Năstac Computers Programming Course 10 Iulian Năstac Recap from previous course 5. Values returned by a function A return statement causes execution to leave the current subroutine and resume at the point in

More information

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Seven: Strings and Files Name: First Name: Tutor: Matriculation-Number: Group-Number:

More information

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013 Lecture07: Strings, Variable Scope, Memory Model 4/8/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C 1 Outline Review pointers New: Strings New: Variable Scope (global vs. local variables)

More information

Write a C program using arrays and structure

Write a C program using arrays and structure 03 Arrays and Structutes 3.1 Arrays Declaration and initialization of one dimensional, two dimensional and character arrays, accessing array elements. (10M) 3.2 Declaration and initialization of string

More information

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen Programming Fundamentals for Engineers - 0702113 6. Arrays Yacoub Sabatin Muntaser Abulafi Omar Qaraeen 1 One-Dimensional Arrays There are times when we need to store a complete list of numbers or other

More information

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

CSCI 6610: Intermediate Programming / C Chapter 12 Strings ... 1/26 CSCI 6610: Intermediate Programming / C Chapter 12 Alice E. Fischer February 10, 2016 ... 2/26 Outline The C String Library String Processing in C Compare and Search in C C++ String Functions

More information

UNIT 6. STRUCTURED DATA TYPES PART 1: ARRAYS

UNIT 6. STRUCTURED DATA TYPES PART 1: ARRAYS UNIT 6. STRUCTURED DATA TYPES PART 1: ARRAYS Programming Year 2017-2018 Industrial Technology Engineering Paula de Toledo Contents 1. Structured data types vs simple data types 2. Arrays (vectors and matrices)

More information

Principles of C and Memory Management

Principles of C and Memory Management COMP281 Lecture 9 Principles of C and Memory Management Dr Lei Shi Last Lecture Today Pointer to Array Pointer Arithmetic Pointer with Functions struct Storage classes typedef union String struct struct

More information

Chapter 8 Character Arrays and Strings

Chapter 8 Character Arrays and Strings Chapter 8 Character Arrays and Strings INTRODUCTION A string is a sequence of characters that is treated as a single data item. String constant: String constant example. \ String constant example.\ \ includes

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 10: Arrays Readings: Chapter 9 Introduction Group of same type of variables that have same

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

Introduction to string

Introduction to string 1 Introduction to string String is a sequence of characters enclosed in double quotes. Normally, it is used for storing data like name, address, city etc. ASCII code is internally used to represent string

More information

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16 Department of Computer Science College of Engineering Boise State University September 11, 2017 1/16 1-dimensional Arrays Arrays can be statically declared in C, such as: int A [100]; The space for this

More information

Chapter 8 - Characters and Strings

Chapter 8 - Characters and Strings 1 Chapter 8 - Characters and Strings Outline 8.1 Introduction 8.2 Fundamentals of Strings and Characters 8.3 Character Handling Library 8.4 String Conversion Functions 8.5 Standard Input/Output Library

More information

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size] (November 10, 2009 2.1 ) Arrays An array is a collection of several elements of the same type. An array variable is declared as type array name[size] I The elements are numbered as 0, 1, 2... size-1 I

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 7 Array and String Department of Computer Engineering Outline Array String Department

More information

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C C strings (Reek, Ch. 9) 1 Review of strings Sequence of zero or more characters, terminated by NUL (literally, the integer value 0) NUL terminates a string, but isn t part of it important for strlen()

More information

https://www.eskimo.com/~scs/cclass/notes/sx8.html

https://www.eskimo.com/~scs/cclass/notes/sx8.html 1 de 6 20-10-2015 10:41 Chapter 8: Strings Strings in C are represented by arrays of characters. The end of the string is marked with a special character, the null character, which is simply the character

More information

CS1100 Introduction to Programming

CS1100 Introduction to Programming CS1100 Introduction to Programming Sorting Strings and Pointers Madhu Mutyam Department of Computer Science and Engineering Indian Institute of Technology Madras Lexicographic (Dictionary) Ordering Badri

More information

Create a Program in C (Last Class)

Create a Program in C (Last Class) Create a Program in C (Last Class) Input: three floating point numbers Output: the average of those three numbers Use: scanf to get the input printf to show the result a function to calculate the average

More information

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14 Reading Assignment Strings char identifier [ size ] ; char * identifier ; K.N. King Chapter 13 K.N. King Sections 23.4, 23.5 Supplementary reading Harbison & Steele Chapter 12, 13, 14 Strings are ultimately

More information

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University SYSC 2006 C Winter 2012 String Processing in C D.L. Bailey, Systems and Computer Engineering, Carleton University References Hanly & Koffman, Chapter 9 Some examples adapted from code in The C Programming

More information

Procedural Programming & Fundamentals of Programming

Procedural Programming & Fundamentals of Programming Procedural Programming & Fundamentals of Programming Exercise 3 (SS 2018) 29.05.2018 What will I learn in the 4. exercise Pointer (and a little bit about memory allocation) Structure Strings and String

More information

ECE551 Midterm Version 1

ECE551 Midterm Version 1 Name: ECE551 Midterm Version 1 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

Chapter 8 C Characters and Strings

Chapter 8 C Characters and Strings Chapter 8 C Characters and Strings Objectives of This Chapter To use the functions of the character handling library (). To use the string conversion functions of the general utilities library

More information

Programming Fundamentals

Programming Fundamentals Programming Fundamentals Day 4 1 Session Plan Searching & Sorting Sorting Selection Sort Insertion Sort Bubble Sort Searching Linear Search Binary Search File Handling Functions Copyright 2004, 2 2 Sorting

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. The string-handling library () provides many useful functions for manipulating string data (copying strings and concatenating strings), comparing strings, searching strings for characters and

More information

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36 Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar

More information

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous

More information

Procedural Programming

Procedural Programming Exercise 5 (SS 2016) 28.06.2016 What will I learn in the 5. exercise Strings (and a little bit about pointer) String functions in strings.h Files Exercise(s) 1 Home exercise 4 (3 points) Write a program

More information

C-LANGUAGE CURRICULAM

C-LANGUAGE CURRICULAM C-LANGUAGE CURRICULAM Duration: 2 Months. 1. Introducing C 1.1 History of C Origin Standardization C-Based Languages 1.2 Strengths and Weaknesses Of C Strengths Weaknesses Effective Use of C 2. C Fundamentals

More information

ECE551 Midterm Version 2

ECE551 Midterm Version 2 Name: ECE551 Midterm Version 2 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa) Looping Forward Through the Characters of a C String A lot of C string algorithms require looping forward through all of the characters of the string. We can use a for loop to do that. The first character

More information

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER: Page 1 of 8 School of Computer Science 60-141-01 Introduction to Algorithms and Programming Winter 2015 Midterm Examination # 2 Wednesday, March 18, 2015 ANSWERS Duration of examination: 75 minutes STUDENT

More information

Procedural programming with C

Procedural programming with C Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical

More information

Arrays and Strings. CS449 Fall 2017

Arrays and Strings. CS449 Fall 2017 Arrays and Strings CS449 Fall 2017 Arrays Data type for a sequence of variables of the given element type in consecubve memory Element type can be any data type. E.g. char A[10]; // sequence of chars int

More information

C Programming. Unit 9. Manipulating Strings File Processing.

C Programming. Unit 9. Manipulating Strings File Processing. Introduction to C Programming Unit 9 Manipulating Strings File Processing skong@itt-tech.edu Unit 8 Review Unit 9: Review of Past Material Unit 8 Review Arrays Collection of adjacent memory cells Each

More information

C: How to Program. Week /May/28

C: How to Program. Week /May/28 C: How to Program Week 14 2007/May/28 1 Chapter 8 - Characters and Strings Outline 8.1 Introduction 8.2 Fundamentals of Strings and Characters 8.3 Character Handling Library 8.4 String Conversion Functions

More information

String constants. /* Demo: string constant */ #include <stdio.h> int main() {

String constants. /* Demo: string constant */ #include <stdio.h> int main() { Strings 1 String constants 2 /* Demo: string constant */ #include s1.c int main() { printf("hi\n"); } String constants are in double quotes A backslash \ is used to include 'special' characters,

More information

C Programming Language Review and Dissection III

C Programming Language Review and Dissection III C Programming Language Review and Dissection III Lecture 5 Embedded Systems 5-1 Today Pointers Strings Formatted Text Output Reading Assignment: Patt & Patel Pointers and Arrays Chapter 16 in 2 nd edition

More information

C mini reference. 5 Binary numbers 12

C mini reference. 5 Binary numbers 12 C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char

More information

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Arrays CS10001: Programming & Data Structures Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Array Many applications require multiple data items that have common

More information

Government Polytechnic Muzaffarpur.

Government Polytechnic Muzaffarpur. Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking

More information

Using Character Arrays. What is a String? Using Character Arrays. Using Strings Life is simpler with strings. #include <stdio.

Using Character Arrays. What is a String? Using Character Arrays. Using Strings Life is simpler with strings. #include <stdio. What is a String? A string is actually a character array. You can use it like a regular array of characters. However, it has also some unique features that make string processing easy. Using Character

More information

PDS Class Test 2. Room Sections No of students

PDS Class Test 2. Room Sections No of students PDS Class Test 2 Date: October 27, 2016 Time: 7pm to 8pm Marks: 20 (Weightage 50%) Room Sections No of students V1 Section 8 (All) Section 9 (AE,AG,BT,CE, CH,CS,CY,EC,EE,EX) V2 Section 9 (Rest, if not

More information

Course organization. Course introduction ( Week 1)

Course organization. Course introduction ( Week 1) Course organization Course introduction ( Week 1) Code editor: Emacs Part I: Introduction to C programming language (Week 2-9) Chapter 1: Overall Introduction (Week 1-3) Chapter 2: Types, operators and

More information

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example:

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example: Collecting Elements How to collect elements of the same type? Eg:., marks on assignments: APS105 Arrays Textbook Chapters 6.1-6.3 Assn# 1 2 3 4 5 6 Mark 87 89 77 96 87 79 Eg: a solution in math: x 1, x

More information

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions Announcements Thursday Extras: CS Commons on Thursdays @ 4:00 pm but none next week No office hours next week Monday or Tuesday Reflections: when to use if/switch statements for/while statements Floating-point

More information

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch,

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Dynamic Memory Dynamic Memory Allocation Strings September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Pointer arithmetic If we know the address of the first element of an array, we can compute the addresses

More information

ECE 551D Spring 2018 Midterm Exam

ECE 551D Spring 2018 Midterm Exam Name: ECE 551D Spring 2018 Midterm Exam NetID: There are 6 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

C Characters and Strings

C Characters and Strings CS 2060 Character handling The C Standard Library provides many functions for testing characters in ctype.h. int isdigit(int c); // is c a digit (0-9)? int isalpha(int c); // is c a letter? int isalnum(int

More information

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. Name: ECE551 Midterm NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual work. You

More information

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut dthiebaut@smithedu Outline A Few Words about HW 8 Finish the Input Port Lab! Revisiting Homework

More information

Lecture 05 Pointers ctd..

Lecture 05 Pointers ctd.. Lecture 05 Pointers ctd.. Note: some notes here are the same as ones in lecture 04 1 Introduction A pointer is an address in the memory. One of the unique advantages of using C is that it provides direct

More information

There are functions to handle strings, so we will see the notion of functions itself in little a detail later. (Refer Slide Time: 00:12)

There are functions to handle strings, so we will see the notion of functions itself in little a detail later. (Refer Slide Time: 00:12) Programming Data Structures, Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module - 13b Lecture - 19 Functions to handle strings;

More information

Computers Programming Course 12. Iulian Năstac

Computers Programming Course 12. Iulian Năstac Computers Programming Course 12 Iulian Năstac Recap from previous course Strings in C The character string is one of the most widely used applications that involves vectors. A string in C is an array of

More information

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017 CS 137 Part 6 ASCII, Characters, Strings and Unicode November 3rd, 2017 Characters Syntax char c; We ve already seen this briefly earlier in the term. In C, this is an 8-bit integer. The integer can be

More information

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 5. Iulian Năstac Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction

More information

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world alun@debian:~$ gcc hello.c alun@debian:~$ a.out Hello, world alun@debian:~$ gcc -o hello hello.c alun@debian:~$ hello Hello, world alun@debian:~$ 1 A Quick guide to C for Networks and Operating Systems

More information

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos. UNIT 2 ARRAYS Arrays Structure Page Nos. 2.0 Introduction 23 2.1 Objectives 24 2.2 Arrays and Pointers 24 2.3 Sparse Matrices 25 2.4 Polynomials 28 2.5 Representation of Arrays 30 2.5.1 Row Major Representation

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

Special PRG Lecture No. 2. Professor David Brailsford Special PRG Lecture: Arrays

Special PRG Lecture No. 2. Professor David Brailsford Special PRG Lecture: Arrays Special PRG Lecture No. 2 Professor David Brailsford (dfb@cs.nott.ac.uk) School of Computer Science University of Nottingham Special PRG Lecture: Arrays Page 1 The need for arrays Suppose we want to write

More information

Chapter 9 Strings. With this array declaration: char s[10];

Chapter 9 Strings. With this array declaration: char s[10]; Chapter 9 Strings 9.1 Chapter Overview There is no data type in C called ʻstringʼ; instead, strings are represented by an array of characters. There is an assortment of useful functions for strings that

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #29 Arrays in C (Refer Slide Time: 00:08) This session will learn about arrays in C. Now, what is the word array

More information

Arrays in C C Programming and Software Tools. N.C. State Department of Computer Science

Arrays in C C Programming and Software Tools. N.C. State Department of Computer Science Arrays in C C Programming and Software Tools N.C. State Department of Computer Science Contents Declaration Memory and Bounds Operations Variable Length Arrays Multidimensional Arrays Character Strings

More information

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n Static and Dynamic Memory Allocation In this chapter we review the concepts of array and pointer and the use of the bracket operator for both arrays and pointers. We also review (or introduce) pointer

More information

String can be represented as a single-dimensional character type array. Declaration of strings

String can be represented as a single-dimensional character type array. Declaration of strings String String is the collection of characters. An array of characters. String can be represented as a single-dimensional character type array. Declaration of strings char string-name[size]; char address[25];

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In

More information

Assignment #5 Answers

Assignment #5 Answers Assignment #5 Answers Introductory C Programming UW Experimental College Assignment #5 ANSWERS Question 1. What's wrong with #define N 10;? The semicolon at the end of the line will become part of N's

More information

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/ Pointer Arithmetic and Element

More information