How to shrink your stomach

How to shrink your stomach created by jack federbroke helpd me to loss weight so i want to feedback him for that thank you jack! How to shrink your stomach

Friday, March 2, 2012

C LANGUAGE TUTORIAL 7.Strings and Arrays

7 Strings and Arrays

7.1 What Is A String?

A string is a group of characters, usually letters of the alphabet. In order to format your printout
in such a way that it looks nice, has meaningful titles and names, and is esthetically pleasing to
you and the people using the output of your program, you need the ability to output text data.

Actually you have already been using strings, because the second program in this tutorial, way
back in Chapter 2, output a message that was handled internally as a string. A complete definition
is a series of "char" type data terminated by a NULL character, which is a zero.

When C is going to use a string of data in some way, either to compare it with another, output
it, copy it to another string, or whatever, the functions are set up to do what they are called to
do until a NULL, which is a zero, is detected.

7.2 What Is An Array?

An array is a series of homogeneous pieces of data that are all identical in type, but the type can
be quite complex as we will see when we get to the chapter of this tutorial discussing structures.
A string is simply a special case of an array.

The best way to see these principles is by use of an example, so load the program chrstrg.c
and display it on your monitor.

main( )
char name[5];      /* define a string of characters */
name[0] = ’D’;
name[1] = ’a’;
name[2] = ’v’;
name[3] = ’e’;
name[4] = 0;     /* Null character - end of text  */
printf("The name is %s\n",name);
printf("One letter is %c\n",name[2]);
printf("Part of the name is %s\n",&name[1]);

The first thing new is the line that defined a "char" type of data entity. The square brackets
define an array subscript in C, and in the case of the data definition statement, the 5 in the
brackets defines 5 data fields of type "char" all defined as the variable "name". In the C language,
all subscripts start at 0 and increase by 1 each step up to the maximum which in this case is 4.

We therefore have 5 "char" type variables named, "name[0]", "name[1]", "name[2]", "name[3]",
and "name[4]". You must keep in mind that in C, the subscripts actually go from 0 to one less
than the number defined in the definition statement.

7.3 How Do We Use The String?

The variable "name" is therefore a string which can hold up to 5 characters, since we need room
for the NULL character, there are actually only four useful characters. To load something useful
into the string, we have 5 statements, each of which assigns one alphabetical character to one
of the string characters. Finally, the last place in the string is filled with the numeral 0 as the
end indicator and the string is complete. (A "define" would allow us to use "NULL" instead of
a zero, and this would add greatly to the clarity of the program. It would be very obvious that
this was a NULL and not simply a zero, we will simply print it out with some other string data
in the output statement. The % is the output definition to output a string and the system will
output characters starting with the first one in "name" until it comes to the NULL character, and
it will quit. Notice that in the "printf" statement, only the variable name "name" needs to be
given, with no subscript since we are interested in starting at the beginning. (There is actually
another reason that only the variable name is given without brackets. The discussion of that
topic will be given in the next chapter.)

7.4 Outputting Part Of A String

The next "printf" illustrates that we can output any single character of the string by using the
"%c" and naming the particular character of "name" we want by including the subscript. The
last "printf" illustrates how we can output part of the string by stating the starting point by using
a subscript. The & specifies the address of "name[1]". We will study this in the next chapter
but I thought you would benefit from a little glimpse ahead.

This example may make you feel that strings are rather cumbersome to use since you have to
set up each character one at a time. That is an incorrect conclusion because strings are very
easy to use as we will see in the next example program.
Compile and run this program.

7.5 Some String Subroutines

Load the example program strings.c for an example of some ways to use strings.

main( )
char name1[12],name2[12],mixed[25];
char title[20];
strcpy(title,"This is the title.");
printf("       %s\n\n"title);
printf("Name 1 is %s\n",name1);
printf(Name 2 is %s\n",name2);
if(strcmp(name1,name2)>0) /* return 1 if name1 > name2 */
printf("The biggest name alphabetically is %s\n",mixed);
strcat(mixed,"  ");
printf("Both names are %s\n",mixed);

First we define four strings. Next we come to a new function that you will find very useful, the
"strcpy" function, or string copy. It copies from one string to another until it comes to the NULL
character. It is easy to remember which one gets copies to which is you think of them like an
assignment statement. Thus if you were to say, for example, "x = 23;", the data is copied from
the right entity to the left one. In the "strcpy" function, the data is also copied from the right
entity to the left, so that after execution of the first statement, name1 will contain the string
"Rosalinda", but without the double quotes, they are the complier’s way of knowing that you
are defining a string.

Likewise, "Zeke" is copied into "name2" by the second statement, then the "title" is copied. The
title and both names are then printed out. Note that it is not necessary for the defined string to
be exactly the same size as the string it will be called upon to store, only that it is at least as long
as the string plus one more character for the NULL.

7.6 Alphabetical Sorting Of Strings

The next function we will look at is the "strcmp" or the string compare function. It will return
a 1 it the first string is larger than the second, zero if they are the same length and have the same
characters, and -1 if the first string is smaller than the second. One of the strings, depending on
the result of the compare is copied into the variable "mixed", and the largest name alphabetically
is printed out. It should come as no surprise to you that "Zeke" wins because it is alphabetically
larger, length doesn’t matter, only the alphabet. It might be wise to mention that the result would
also depend on whether the letters were upper or lower case. There are functions available with
your C compiler to change the case of a string to all upper or all lower case if you desire. These
will be used in an example program later in this tutorial.

7.7 Combining Strings

The last four statements have another new feature, the "strcat", or string concatenation function.
This function simply adds the characters from one string onto the end of another string taking
care to adjust the NULL so everything is still all right. In this case, "name1" is copied into
"mixed", then two blanks are concatenated to "mixed", and finally "name2" is concatenated to
the combination. The result is printed out with both names in the one variable "mixed".

Strings are not difficult and are extremely useful. You should spend some time getting familiar
with them before proceeding on to the next topic.

Compile and run this program and observe the results for compliance with this definition.

7.8 An Array Of Integers

Load the fileintarray.c and display it on your monitor for an example of an array of integers.

main( )
int values[12];
int index;
for (index = 0;index < 12;index++)
values[index] = 2 * (index + 4);
for (index = 0;index < 12;index++)
             printf("The value at index = %2d is %3d\n",index,values[index]);

Notice that the array is defined in much the same way we defined an array of char in order to
do the string manipulations in the last section. We have 12 integer variables to work, with not
counting the one named "index". The names of the variables are "values[0]", "values[1]", ... ,
and "values[11]". Next we have a loop to assign nonsense, but well defined, data to each of the
12 variables, then print all 12 out. You should have no trouble following this program, but be
sure you understand it. Compile and run it to see if it does what you expect it to do.

7.9 An Array Of Floating Point Data

Load and display the program named bigarray.c for an example of a program with an array
of "float" type data.

 This example has been modified to use another integer type variable
 of a float type variable due to the problems in the float library with the
 HI-TECH C Compiler. The compiler returns no fatal errors when the type
 variable is used and the float library included at link time but the Xrel
 produces a address error. The original code is commented out so that you
 still see that was intended in the tutorial.
char name1[ ] = "First Program Title";
int index;
int stuff[12];
/* float weird[12]; */
int weird[12];
static char name2[ ] = "Second Program Title";
    for  (index = 0;index < 12;index++) {
        stuff[index] = index + 10;
  /* weird[index] = 12.0  *  (index  +  7); */
        weird[index] = 12 * (index  +  7);
    for (index = 0;index< 12;index++) {
       printf("%5d %5d   %5d\n",index,stuff[index],weird[index]);
   /*  printf("%5d %5d %10.3f\n",index,stuff[index],weird[index]); */

This program has an extra feature to illustrate how strings can be initialized. The first line of
the program illustrates to you how to initialize a string of characters. Notice that the square
brackets are empty leaving it up to the compiler to count the characters and allocate enough
space for our string. Another string is initialized in the body of the program but it must be
declared "static" here. This prevents it from being allocated as an "automatic" variable and
allows it to retain the string once the program is started. There is nothing else new here, the
variables are assigned nonsense data and the results of all the nonsense are printed out along
with a header. This program should also be easy for you to follow, so study it until you are sure
of what it is doing before going on to the next topic.

7.10 Getting Data Back From A Function

Back in chapter 5 when we studied functions, I hinted to you that there was a way to get data
back from a function by using an array, and that is true. Load the program passback.c for
an example of doing that.

main( )
int index;
int matrix[20];
for (index = 0;index < 20;index++) /* generate data  */
matrix[index] = index + 1;
for (index = 0;index < 5;index++) /* print original data */
printf("Start  matrix[%d] = %d\n",index,matrix[index]);
dosome(matrix); /* go to a function & modify matrix */
for (index = 0;index < 5;index++) /* print modified matrix  */
printf("back matrix[%d] = %d\n",index,matrix[index]);
dosome(list) /* This will illustrate returning data */
int list[];
int i;
for (i = 0;i < 5;i++)
printf("Before marrix[%d] = %d\n",i,list[i]);
for (i = 0;i < 20;i++) /* add 10 to all values */
list[i] +=10;
for (i =0;i < 5;i++) /* print modified matrix */
printf("After  matrix[%d] = %d\n",i,list[i]);

In this program, we define an array of 20 variables named "matrix", then assign some nonsense
data to the variables, and print out the first five. Then we call the function "dosome" taking
along the entire array by putting the name of the array in the parentheses.

The function "dosome" has a name in its parentheses also but it prefers to call the array "list".
The function needs to be told that it is really getting an array passed to it and that the array is
of type "int". The following line, prior to the bracket which starts the program, does that by
defining "list" as an integer type variable and including the square brackets to indicate an array.

It is not necessary to tell the function how many elements are in the array, but you could if you
so desired. Generally a function works with an array until some end-of-data marker is found,
such as a NULL for a string, or some other previously defined data or pattern. Many times,
another piece of data is passed to the function with a count of how many elements to work with.
On our present illustration, we will use a fixed number of elements to keep it simple.

So far nothing is different from the previous functions we have called except that we have passed
more data points to the function this time than we ever have before, having passed 20 integer
values. We print out the first 5 again to see if they did indeed get passed here. Then we add
ten to each of the elements and print out the new values. Finally we return to the main program
and print out the same 5 data points. We find that we have indeed modified the data in the
function, and when we returned to the main program, we brought the changes back. Compile
and run this program to verify this conclusion.

7.11 Arrays Pass Data Both Ways

We stated during our study of functions that when we passed data to a function, the system made
a copy to use in the function which was thrown away when we returned. This is not the case
with arrays. The actual array is passed to the function and the function can modify it any way
it wishes to. The result of the modifications will be available back in the calling program. This
may seem strange to you that arrays are handled differently from single point data, but they are.

It really does make sense, but you will have to wait until we get to pointers to understand it.

7.12 A Hint At A Future Lesson

Another way of getting data back from a function to the calling program is by using pointers
which we will cover in the next chapter. When we get there we will find that an array is in
reality a pointer to a list of values. Don’t let that worry you now, it will make sense when we
get there. In the meantime concentrate on arrays and understand the basics of them because
when we get to the study of structures we will be able to define pretty elaborate arrays.

7.13 Multiply Dimensioned Arrays

Load and display the file named multiary.c for an example of a program with doubly
dimensioned arrays.

main( )
int i,j;
int big[8][8],huge[25][12];
for (i = 0;i < 8;i++)
for (j = 0;j < 8;j++)
big[i][j] = i * j; /* This is a multiplication table */
for (i = 0;i < 25;i++)
for (j = 0;j < 12;j++)
huge[i][j] = i + j; /* This is an addition table */
big[2][6] = huge[24][10] *22;
big[2][2] = 5;
big[big][2][2]...big[2][2]. = 177; /* this is big[5][5] = 177; */
for (i = 0;i < 8;i++) {
for (j = 0;j < 8;j++)
printf("%5d ",big[i][j]);
printf("\n"); /* newline for each increase in i */

The variable "big" is an 8 by 8 array that contains 8 times 8 or 64 elements total. The first
element is "big[0][0]", and the last is "big[7][7]". Another array named "huge" is also defined
which is not square to illustrate that the array need not be square. Both are filled up with data,
one representing a multiplication table and the other being formed into an addition table.

To illustrate that individual elements can be modified at will, one of the elements of "big" is
assigned the value from one of the elements of "huge" after being multiplied by 22. Next
"big[2][2]" is assigned the arbitrary value of 5, and this value is used for the subscripts of the
next assignment statement. The third assignment statement is in reality "big[5][5] = 177"
because each of the subscripts contain the value 5. This is only done to illustrate that any valid
expression can be used for a subscript. It must only meet two conditions, it must be an integer
(although a "char" will work just as well), and it must be within the range of the subscript it is
being used for.

The entire matrix variable "big" is printed out in a square form so you can check the values to
see if they did get set the way you expected them to.

7.14 Programming Exercises

1. Write a program with three short strings, about 6 characters each, and use "strcpy" to copy
"one", "two", and "three" into them. Concatenate the three strings into one string and print the
result out 10 times.

2. Define two integer arrays, each 10 elements long, called "array1" and "array2". Using a
loop, put some kind of nonsense data in each and add them term for term into another 10 element
array named "arrays".

Finally print all results in a table with an index number.
1 2 + 10 = 12
2 4 + 20 = 24
3 6 + 30 = 36 etc.
Hint; The print statement will be similar to:
printf("%4d %4d + %4d = %4d\n",index,array1[index], array2[index],arrays[index]);

next lesson


No comments:

Post a Comment

App creators your key for sucsses

If you can click a mouse, you can
profit from online video!
Recent news articles show how some YouTubers are earning upwards of $100,000 per year from the ads they display on and around their videos...

What if you could earn money from those ads, without actually creating the content?


All you need to know in one place

Small step for huge knowledge
This is the place you learn everything you need to move forward and become the leader in programming and creating mobile apps.

No need to be an expert anyone can start from scratch !

You just need to find the area that interests you and access, from there the way to success is up to you .

Good Luck!

 Click Here App Creators

App creators


i want to know

hello everyone

i wanted to ask from the viewers

if ther any subject thet you read and want continue reading and its not completed yet please let me know by comment or email

or if ther any subject thet you want me to add pls let me know