Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
12 views17 pages

12 Arrays

The document is a lab manual for a Computer Programming Lab focused on Arrays and String Functions in C programming. It covers topics such as creating, accessing, modifying, and looping through arrays and strings, including multidimensional arrays and string manipulation functions. The document also provides practical examples and explanations of concepts related to arrays and strings.

Uploaded by

eishaahmed17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views17 pages

12 Arrays

The document is a lab manual for a Computer Programming Lab focused on Arrays and String Functions in C programming. It covers topics such as creating, accessing, modifying, and looping through arrays and strings, including multidimensional arrays and string manipulation functions. The document also provides practical examples and explanations of concepts related to arrays and strings.

Uploaded by

eishaahmed17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

DEPARTMENT OF AVIONICS

ENGINEERING

SUBJECT : Computer Programming Lab

LAB NO : 12

TITLE : Arrays & String Functions


SUBMITTED TO : Ms. Maha Intakhab Alam
SUBMITTED BY :
BATCH : Avionics 09
SECTION :
Marks Obtained :

Remarks:

DEADLINE:

DATE OF SUBMISSION:

Table of Contents
1 Arrays.........................................................................................................3
2 Access the Elements of an Array...............................................................3
3 Change an Array Element..........................................................................3
4 Loop Through an Array..............................................................................4
5 Set Array Size............................................................................................4
6 Get Array Size or Length............................................................................4
7 Making Better Loops..................................................................................5
8 Real-Life Example......................................................................................6
9 Multidimensional Arrays.............................................................................7
10 Two-Dimensional Arrays.........................................................................8
11 Access the Elements of a 2D Array........................................................8
12 Change Elements in a 2D Array.............................................................9
13 Loop Through a 2D Array.......................................................................9
14 Strings....................................................................................................9
15 Access Strings......................................................................................10
16 Modify Strings......................................................................................10
17 Loop Through a String..........................................................................11
18 Another Way Of Creating Strings.........................................................11
19 Differences...........................................................................................12
20 Strings - Special Characters.................................................................12
21 String Functions...................................................................................14
22 String Length........................................................................................14
23 Concatenate Strings.............................................................................15
24 Copy Strings.........................................................................................15
25 Compare Strings...................................................................................16
1 ARRAYS
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value. To create an array, define the data type
(like int) and specify the name of the array followed by square brackets [].

To insert values to it, use a comma-separated list, inside curly braces:

int myNumbers[] = {25, 50, 75, 100};

We have now created a variable that holds an array of four integers.

2 ACCESS THE ELEMENTS OF AN ARRAY


To access an array element, refer to its index number. Array indexes start
with 0: [0] is the first element. [1] is the second element, etc.

This statement accesses the value of the first element [0] in myNumbers:

Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
// Outputs 25

3 CHANGE AN ARRAY ELEMENT


To change the value of a specific element, refer to the index number:

Example
myNumbers[0] = 33;

Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
// Now outputs 33 instead of 25
4 LOOP THROUGH AN ARRAY
You can loop through the array elements with the for loop. The following
example outputs all elements in the myNumbers array:

Example
int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) // array index starts at 0


{
printf("%d\n", myNumbers[i]);
}

5 SET ARRAY SIZE


Another common way to create arrays, is to specify the size of the array, and
add elements later:

Example
// Declare an array of four integers:
int myNumbers[4];

// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;

Using this method, you should know the number of array elements in
advance, in order for the program to store enough memory. You are not able to
change the size of the array after creation.

6 GET ARRAY SIZE OR LENGTH


To get the size of an array, you can use the sizeof operator:
Example
int myNumbers[] = {10, 25, 50, 75, 100};
printf("%lu", sizeof(myNumbers)); // Prints 20
Why did the result show 20 instead of 5, when the array contains 5 elements?

- It is because the sizeof operator returns the size of a type in bytes.

You learned from the Data Types chapter that an int type is usually 4 bytes, so
from the example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.

Knowing the memory size of an array is great when you are working with larger
programs that require good memory management.

But when you just want to find out how many elements an array has, you can
use the following formula (which divides the size of the array by the size of one
array element):

Example
int myNumbers[] = {10, 25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);

printf("%d", length); // Prints 5

7 MAKING BETTER LOOPS


In the array loops section in the previous chapter, we wrote the size of the array
in the loop condition (i < 4). This is not ideal, since it will only work for arrays of
a specified size.

However, by using the sizeof formula from the example above, we can now
make loops that work for arrays of any size, which is more sustainable.

Instead of writing:

Example
int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", myNumbers[i]);
}

It is better to write:

Example
int myNumbers[] = {25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
int i;

for (i = 0; i < length; i++) {


printf("%d\n", myNumbers[i]);
}

8 REAL-LIFE EXAMPLE
To demonstrate a practical example of using arrays, let's create a program that
calculates the average of different ages:

// An array storing different ages


int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;


int i;

// Get the length of the array


int length = sizeof(ages) / sizeof(ages[0]);

// Loop through the elements of the array


for (i = 0; i < length; i++) {
sum += ages[i];
}

// Calculate the average by dividing the sum by the


length
avg = sum / length;
// Print the average
printf("The average age is: %.2f", avg);

Example
And in this example, we create a program that finds the lowest age among
different ages:

// An array storing different ages


int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

int i;

// Get the length of the array


int length = sizeof(ages) / sizeof(ages[0]);

// Create a variable and assign the first array element


of ages to it
int lowestAge = ages[0];

// Loop through the elements of the ages array to find


the lowest age
for (i = 0; i < length; i++) {
if (lowestAge > ages[i]) {
lowestAge = ages[i];
}
}

9 MULTIDIMENSIONAL ARRAYS
In the previous chapter, you learned about arrays, which is also known
as single dimension arrays. These are great, and something you will use a lot
while programming in C. However, if you want to store data as a tabular form,
like a table with rows and columns, you need to get familiar
with multidimensional arrays.

A multidimensional array is basically an array of arrays.

Arrays can have any number of dimensions. In this chapter, we will introduce
the most common; two-dimensional arrays (2D).
10 TWO-DIMENSIONAL ARRAYS
A 2D array is also known as a matrix (a table of rows and columns). To create a
2D array of integers, take a look at the following example:

int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

The first dimension represents the number of rows [2], while the second
dimension represents the number of columns [3]. The values are placed in row-
order, and can be visualized like this:

11 ACCESS THE ELEMENTS OF A 2D ARRAY


To access an element of a two-dimensional array, you must specify the index
number of both the row and column.

This statement accesses the value of the element in the first row (0) and third
column (2) of the matrix array.

Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

printf("%d", matrix[0][2]); // Outputs 2


Remember that: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.

12 CHANGE ELEMENTS IN A 2D ARRAY


To change the value of an element, refer to the index number of the element in
each of the dimensions:
The following example will change the value of the element in the first row
(0) and first column (0):

Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf("%d", matrix[0][0]); // Now outputs 9 instead


of 1

13 LOOP THROUGH A 2D ARRAY


To loop through a multi-dimensional array, you need one loop for each of the
array's dimensions.

The following example outputs all elements in the matrix array:

Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}

14 STRINGS
Strings are used for storing text/characters.

For example, "Hello World" is a string of characters.

Unlike many other programming languages, C does not have a String type to
easily create string variables. Instead, you must use the char type and create
an array of characters to make a string in C:

char greetings[] = "Hello World!";


Note that you have to use double quotes ( "").
To output the string, you can use the printf() function together with the
format specifier %s to tell C that we are now working with strings:

Example
char greetings[] = "Hello World!";
printf("%s", greetings);

15 ACCESS STRINGS
Since strings are actually arrays in C, you can access a string by referring to its
index number inside square brackets [].

This example prints the first character (0) in greetings:

Example
char greetings[] = "Hello World!";
printf("%c", greetings[0]);

Note that we have to use the %c format specifier to print a single


character.

16 MODIFY STRINGS
To change the value of a specific character in a string, refer to the index
number, and use single quotes:

Example
char greetings[] = "Hello World!";
greetings[0] = 'J';
printf("%s", greetings);
// Outputs Jello World! instead of Hello World!

17 LOOP THROUGH A STRING


You can also loop through the characters of a string, using a for loop:
Example
char carName[] = "Volvo";
int i;

for (i = 0; i < 5; ++i) {


printf("%c\n", carName[i]);
}

And like we specified in the arrays chapter, you can also use the sizeof
formula (instead of manually write the size of the array in the loop condition (i
< 5)) to make the loop more sustainable:

Example
char carName[] = "Volvo";
int length = sizeof(carName) / sizeof(carName[0]);
int i;

for (i = 0; i < length; ++i) {


printf("%c\n", carName[i]);
}

18 ANOTHER WAY OF CREATING STRINGS


In the examples above, we used a "string literal" to create a string variable. This
is the easiest way to create a string in C.

You should also note that you can create a string with a set of characters. This
example will produce the same result as the example in the beginning of this
page:

Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
printf("%s", greetings);

Why do we include the \0 character at the end? This is known as the "null
terminating character", and must be included when creating strings using this
method. It tells C that this is the end of the string.
19 DIFFERENCES
The difference between the two ways of creating strings, is that the first method
is easier to write, and you do not have to include the \0 character, as C will do it
for you.

You should note that the size of both arrays is the same: They both have 13
characters (space also counts as a character by the way), including the \
0 character:

Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
char greetings2[] = "Hello World!";

printf("%lu\n", sizeof(greetings)); // Outputs 13


printf("%lu\n", sizeof(greetings2)); // Outputs 13

Real-Life Example

Use strings to create a simple welcome message:

char message[] = "Good to see you,";


char fname[] = "John";

printf("%s %s!", message, fname);

20 STRINGS - SPECIAL CHARACTERS


Because strings must be written within quotes, C will misunderstand this string,
and generate an error:

char txt[] = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string
characters:
Escape Result Description
character

\' ' Single quote

\" " Double quote

\\ \ Backslash

The sequence \" inserts a double quote in a string:

Example
char txt[] = "We are the so-called \"Vikings\" from the
north.";

The sequence \' inserts a single quote in a string:

Example
char txt[] = "It\'s alright.";

The sequence \\ inserts a single backslash in a string:

Example
char txt[] = "The character \\ is called backslash.";
Other popular escape characters in C are:

Escape Result Try


Character it

\n New Line Try it »


\t Tab Try it »

\0 Null Try it »

21 STRING FUNCTIONS
C also has many useful string functions, which can be used to perform certain
operations on strings.

To use them, you must include the <string.h> header file in your program:

#include <string.h>

22 STRING LENGTH
For example, to get the length of a string, you can use the strlen() function:

Example
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));

In the Strings chapter, we used sizeof to get the size of a string/array. Note
that sizeof and strlen behaves differently, as sizeof also includes the \
0 character when counting:

Example
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet)); // 26
printf("%d", sizeof(alphabet)); // 27
It is also important that you know that sizeof will always return the memory
size (in bytes), and not the actual string length:

Example
char alphabet[50] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet)); // 26
printf("%d", sizeof(alphabet)); // 50

23 CONCATENATE STRINGS
To concatenate (combine) two strings, you can use the strcat() function:

Example
char str1[20] = "Hello ";
char str2[] = "World!";

// Concatenate str2 to str1 (result is stored in str1)


strcat(str1, str2);

// Print str1
printf("%s", str1);

Note that the size of str1 should be large enough to store the result of the two
strings combined (20 in our example).

24 COPY STRINGS
To copy the value of one string to another, you can use the strcpy() function:

Example
char str1[20] = "Hello World!";
char str2[20];

// Copy str1 to str2


strcpy(str2, str1);

// Print str2
printf("%s", str2);

Note that the size of str2 should be large enough to store the copied string (20
in our example).

25 COMPARE STRINGS
To compare two strings, you can use the strcmp() function.

It returns 0 if the two strings are equal, otherwise a value that is not 0:

Example
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";

// Compare str1 and str2, and print the result


printf("%d\n", strcmp(str1, str2)); // Returns 0 (the
strings are equal)

// Compare str1 and str3, and print the result


printf("%d\n", strcmp(str1, str3)); // Returns -4 (the
strings are not equal)
TASKS
Array Tasks
1. Write a program that calculates the sum of all elements in an integer
array.
2. Write a program that finds the maximum element in an integer array.
3. Write a program that reverses the elements of an integer array in
place.
4. Write a program that counts the number of even elements in an
integer array.
5. Write a program that checks if an array is a palindrome (reads the
same forwards and backwards).

String Tasks
6. Write a program that counts the occurrences of a specific character in
a string.
7. Write a program that counts the number of vowels in a given string.
8. Write a program that removes all consonants from a given string.
9. Write a program that finds the first occurrence of the word “of” within
the given string below:
"The beauty of the landscape, with its lush greenery and towering mountains,
spoke of the wonders of nature. The sound of birds chirping and the rustle of
leaves reminded me of the tranquility of the forest. The scent of flowers in
bloom and the freshness of the air filled my senses, evoking memories of
past adventures. The taste of ripe fruit and the sweetness of honey brought a
sense of pleasure, reminding me of the simple joys of life. The warmth of the
sun on my skin and the gentle breeze brushing against my face whispered of
the promise of a new day.
10. Write a program that replaces all occurrences of “of” substring
with your name in the above paragraph.

You might also like