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

Access Array Elements

The document provides an overview of accessing and manipulating arrays in C, including element access, updating values, and array traversal using loops. It also covers one-dimensional and multi-dimensional arrays, string handling, and common string functions. Additionally, it includes examples of copying elements between arrays and displaying them in reverse order.

Uploaded by

malakmahamad376
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 views34 pages

Access Array Elements

The document provides an overview of accessing and manipulating arrays in C, including element access, updating values, and array traversal using loops. It also covers one-dimensional and multi-dimensional arrays, string handling, and common string functions. Additionally, it includes examples of copying elements between arrays and displaying them in reverse order.

Uploaded by

malakmahamad376
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
You are on page 1/ 34

Access Array Elements

We can access any element of an array in C using the array subscript operator [ ] and the index
value i of the element.

array_name [index];

One thing to note is that the indexing in the array always starts with 0, i.e., the first element is at
index 0 and the last element is at N – 1 where N is the number of elements in the array.

Example of Accessing Array Elements using Array Subscript Operator


C

Dr.Eman Haggag Page 1


// C Program to illustrate element access using array

// subscript

#include <stdio.h>

int main()

// array declaration and initialization

int arr[5] = { 15, 25, 35, 45, 55 };

// accessing element at index 2 i.e 3rd element

printf("Element at arr[2]: %d\n", arr[2]);

// accessing element at index 4 i.e last element

Dr.Eman Haggag Page 2


printf("Element at arr[4]: %d\n", arr[4]);

// accessing element at index 0 i.e first element

printf("Element at arr[0]: %d", arr[0]);

return 0;

Output

Element at arr[2]: 35

Element at arr[4]: 55

Element at arr[0]: 15

Dr.Eman Haggag Page 3


Update Array Element

We can update the value of an element at the given index i in a similar way to accessing an element
by using the array subscript operator [ ] and assignment operator =.

array_name[i] = new_value;
arr[2]=40;

printf("Element at arr[2]: %d\n", arr[2]);


output

Element at arr[2]:40

C Array Traversal

Traversal is the process in which we visit every element of the data structure. For C array traversal,
we use loops to iterate through each element of the array.

Dr.Eman Haggag Page 4


Array Traversal using for Loop

for (int i = 0; i < N; i++) {


array_name[i];
}

How to use Array in C?

Dr.Eman Haggag Page 5


The following program demonstrates how to use an array in the C programming language:

// C Program to demonstrate the use of array

#include <stdio.h>

int main()

// array declaration and initialization

int arr[5] = { 10, 20, 30, 40, 50 };

// modifying element at index 2

arr[2] = 100;

// traversing array using for loop

Dr.Eman Haggag Page 6


printf("Elements in Array: ");

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

printf("%d ", arr[i]);

return 0;

Output

Elements in Array: 10 20 100 40 50

Dr.Eman Haggag Page 7


Types of Array in C

There are two types of arrays based on the number of dimensions it has. They are as follows:

One Dimensional Arrays (1D Array)

Multidimensional Arrays

1. One Dimensional Array in C

The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one
dimension.

Syntax of 1D Array in C

array_name [size];

Dr.Eman Haggag Page 8


Example of 1D Array in C

// C Program to illustrate the use of 1D array

#include <stdio.h>

int main()

// 1d array declaration

int arr[5];

// 1d array initialization using for loop

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

arr[i] = i * i - 2 * i + 1;

Dr.Eman Haggag Page 9


}

printf("Elements of Array: ");

// printing 1d array by traversing using for loop

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

printf("%d ", arr[i]);

return 0;

Output

Dr.Eman Haggag Page 10


Elements of Array: 1 0 1 4 9

Array of Characters (Strings)

Dr.Eman Haggag Page 11


In C, we store the words, i.e., a sequence of characters in the form of an array of characters
terminated by a NULL character. These are called strings in C language.

// C Program to illustrate strings

#include <stdio.h>

int main()

// creating array of character

char arr[6] = { 'G', 'e', 'e', 'k', 's', '\0' };

// printing string

int i = 0;

while (arr[i]) {

Dr.Eman Haggag Page 12


printf("%c", arr[i++]);

return 0;

Output

Geeks

Dr.Eman Haggag Page 13


Use strings to create a simple welcome message:

Example

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


char fname[ ] = "John";

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

Good to see you, John!

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>

Dr.Eman Haggag Page 14


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));

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

Dr.Eman Haggag Page 15


printf("%d", sizeof(alphabet)); // 50

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).

Hello World!

Dr.Eman Haggag Page 16


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).

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:

Dr.Eman Haggag Page 17


Dr.Eman Haggag Page 18
Dr.Eman Haggag Page 19
Example
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";

// Compare str1 and str2, and print the result

Dr.Eman Haggag Page 20


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)

Dr.Eman Haggag Page 21


EX: REVERSE NUMBER

#include <stdio.h>

// Main function

int main()

int i, n, a[100];

// Display a message to the user about the program's purpose

printf("\n\nRead n number of values in an array and display it in reverse


order:\n");

printf("------------------------------------------------------------------------
\n");

Dr.Eman Haggag Page 22


// Prompt the user to input the number of elements to store in the array

printf("Input the number of elements to store in the array :");

scanf("%d", &n);

// Prompt the user to input n elements into the array

printf("Input %d number of elements in the array :\n", n);

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

printf("element - %d : ", i);

scanf("%d", &a[i]); // Read the input and store it in the array

Dr.Eman Haggag Page 23


// Display the values stored in the array

printf("\nThe values stored in the array are : \n");

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

printf("% 5d", a[i]); // Print each element in the array

// Display the values stored in the array in reverse order

printf("\n\nThe values stored in the array in reverse are :\n");

for (i = n - 1; i >= 0; i--)

Dr.Eman Haggag Page 24


printf("% 5d", a[i]); // Print each element in reverse order

printf("\n\n");

return 0;

Output:

Read n number of values in an array and display it in reverse order:

------------------------------------------------------------------------

Input the number of elements to store in the array :3

Input 3 number of elements in the array :

Dr.Eman Haggag Page 25


element - 0 : 2

element - 1 : 5

element - 2 : 7

The values store into the array are :

2 5 7

The values store into the array in reverse are :

7 5 2

In the above code -

Dr.Eman Haggag Page 26


The first printf statement prompts the user to input the number of elements they want to store in
the array and stores it in the variable n using scanf.

The second printf statement asks the user to input n number of elements into the array using a
for loop, and stores each input in the corresponding index of the array a[i].

The third printf statement then prints out the contents of the array in order using another for
loop.

The fourth printf statement then prints out the contents of the array in reverse order using yet
another for loop, which iterates over the elements of a starting from the last element and printing
each element out in reverse order.

Dr.Eman Haggag Page 27


Write a program in C to copy the elements of one array into another array.
Test Data :
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 15
element - 1 : 10
element - 2 : 12
Expected Output :
The elements stored in the first array are :
15 10 12
The elements copied into the second array are :
15 10 12

Dr.Eman Haggag Page 28


#include <stdio.h>

// Main function

int main()

int arr1[100], arr2[100]; // Declare two arrays of size 100 to store integer values

int i, n; // Declare variables to store array size and loop counter

// Display a message to the user about the program's purpose

printf("\n\nCopy the elements of one array into another array:\n");

printf("----------------------------------------------------\n");

// Prompt the user to input the number of elements to be stored in the array

Dr.Eman Haggag Page 29


printf("Input the number of elements to be stored in the array :");

scanf("%d", &n);

// Prompt the user to input n elements into the first array

printf("Input %d elements in the array :\n", n);

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

printf("element - %d : ", i);

scanf("%d", &arr1[i]); // Read the input and store it in the first array

/* Copy elements of the first array into the second array. */

Dr.Eman Haggag Page 30


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

arr2[i] = arr1[i]; // Copy each element from the first array to the second array

/* Prints the elements of the first array */

printf("\nThe elements stored in the first array are :\n");

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

printf("% 5d", arr1[i]); // Print each element in the first array

Dr.Eman Haggag Page 31


}

/* Prints the elements copied into the second array. */

printf("\n\nThe elements copied into the second array are :\n");

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

printf("% 5d", arr2[i]); // Print each element in the second array

printf("\n\n"); // Print new lines for better formatting

return 0;

Dr.Eman Haggag Page 32


Output:
Copy the elements one array into another array :
----------------------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 15
element - 1 : 10
element - 2 : 12

The elements stored in the first array are :


15 10 12

The elements copied into the second array are :


15 10 12
}
printf("\n\n");
In the above code -

Dr.Eman Haggag Page 33


The first printf statement prompts the user to input the number of elements they want to store in the
array and stores it in the variable n using scanf.

The second printf statement asks the user to input n number of elements into the first array arr1
using a for loop, and stores each input in the corresponding index of the array arr1[i].

The third for loop then copies the elements of arr1 into a second array arr2 by iterating over each
element of arr1 and assigning it to the corresponding index of arr2.

The next two printf statements then print out the contents of the first array arr1 and the second
array arr2 respectively, using separate for loops to iterate over the elements of each array and print
them out using printf.

Dr.Eman Haggag Page 34

You might also like