0% found this document useful (0 votes)
2 views16 pages

Arrays

The document provides an overview of arrays and strings in C programming, explaining how to create, access, modify, and loop through both single-dimensional and multi-dimensional arrays. It also covers string creation, modification, and various string functions such as concatenation, copying, and comparison. Key examples illustrate the usage of arrays and strings, including their syntax and output results.

Uploaded by

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

Arrays

The document provides an overview of arrays and strings in C programming, explaining how to create, access, modify, and loop through both single-dimensional and multi-dimensional arrays. It also covers string creation, modification, and various string functions such as concatenation, copying, and comparison. Key examples illustrate the usage of arrays and strings, including their syntax and output results.

Uploaded by

jojog5595
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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.

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:
#include <stdio.h>

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

// Outputs 25
Change an Array Element
To change the value of a specific element, refer to the index
number:
Example
myNumbers[0] = 33;

Example
#include <stdio.h>

int main() {
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;

printf("%d", myNumbers[0]);

return 0;
}
// Now outputs 33 instead of 25
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:
#include <stdio.h>

int main() {
int myNumbers[] = {25, 50, 75, 100};
int i;

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


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

return 0;
}
Output
25
50
75
100
Set Array Size
Another common way to create arrays, is to specify the size of
the array, and add elements later:
#include <stdio.h>

int main() {
// Declare an array of four integers:
int myNumbers[4];

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

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

return 0;
}
Output
25
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).

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:
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.
#include <stdio.h>

int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
printf("%d", matrix[0][2]);

return 0;
}

Output
// Outputs 2
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

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:
#include <stdio.h>

int main() {
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]);
}
}

return 0;
}
Output
1
4
2
3
6
8
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:
#include <stdio.h>

int main() {
char greetings[] = "Hello World!";
printf("%s", greetings);
return 0;
}
Output
Hello World!
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:
#include <stdio.h>

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

return 0;
}
Output
H
Note that we have to use the %c format specifier to print
a single character.

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!
Loop Through a String
You can also loop through the characters of a string, using
a for loop:
#include <stdio.h>

int main() {
char carName[] = "Volvo";
int i;

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


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

return 0;
}
Output
V
o
l
v
o
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.
#include <stdio.h>

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

printf("%s\n", greetings);
printf("%s\n", greetings2);

return 0;
}
Output
Hello World!
Hello World!
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>
String Length
For example, to get the length of a string, you can use
the strlen() function:
#include <stdio.h>
#include <string.h>

int main() {
char alphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));
return 0;
}
Output
26
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:
#include <stdio.h>
#include <string.h>

int main() {
char alphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("Length is: %d\n", strlen(alphabet));
printf("Size is: %d\n", sizeof(alphabet));
return 0;
}
Output

Length is: 26
Size is: 27

Concatenate Strings
To concatenate (combine) two strings, you can use
the strcat() function:
#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello ";
char str2[] = "World!";
// Concatenate str2 to str1 (the result is stored in str1)
strcat(str1, str2);

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

return 0;
}
Output
Hello World!
Copy Strings
To copy the value of one string to another, you can use
the strcpy() function:
#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello World!";
char str2[20];

// Copy str1 to str2


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

return 0;
}
Output
Hello World!
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:
#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";

// Compare str1 and str2, and print the result


printf("%d\n", strcmp(str1, str2));
// Compare str1 and str3, and print the result
printf("%d\n", strcmp(str1, str3));

return 0;
}
Output
0
-4

You might also like