Docsity

Arrays and spring in C programming, Study notes of Distributed Programming and Computing

Toggle sidebar
bg1
UNIT-III ARRAYS AND STRINGS
Contents
Single and Multidimensional Arrays: Array Declaration and Initialization of arrays – Arrays as
function arguments. Strings: Initialization and String handling functions. Structure and Union:
Definition and Declaration - Nested Structures, Array of Structures, Structure as function
arguments, Function that return structure – Union.
ARRAYS
Introduction:
So far we have used only single variable name for storing one data item. If we need to store
multiple copies of the same data then it is very difficult for the user. To overcome the difficulty a
new data structure is used called arrays.
An array is a linear and homogeneous data structure
An array permits homogeneous data. It means that similar types of elements are stored
contiguously in the memory under one variable name.
An array can be declared of any standard or custom data type.
Example of an Array:
Suppose we have to store the roll numbers of the 100 students the we have to declare 100
variables named as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C
programming arrays is introduced in C which gives the capability to store the 100 roll numbers
in the contiguous memory which has 100 blocks and which can be accessed by single variable
name.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Programming Arrays
The above array is declared as int a [5];
a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1;
In the above figure 4, 5, 33, 13, 1 are actual data items. 0, 1, 2, 3, 4 are index variables.
Index or Subscript Variable:
1. Individual data items can be accessed by the name of the array and an integer enclosed
in square bracket called subscript variable / index
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c

Partial preview of the text

Download Arrays and spring in C programming and more Study notes Distributed Programming and Computing in PDF only on Docsity!

UNIT-III ARRAYS AND STRINGS

Contents

Single and Multidimensional Arrays: Array Declaration and Initialization of arrays – Arrays as function arguments. Strings: Initialization and String handling functions. Structure and Union: Definition and Declaration - Nested Structures, Array of Structures, Structure as function arguments, Function that return structure – Union.

ARRAYS Introduction: So far we have used only single variable name for storing one data item. If we need to store multiple copies of the same data then it is very difficult for the user. To overcome the difficulty a new data structure is used called arrays. An array is a linear and homogeneous data structure An array permits homogeneous data. It means that similar types of elements are stored contiguously in the memory under one variable name. An array can be declared of any standard or custom data type. Example of an Array: Suppose we have to store the roll numbers of the 100 students the we have to declare 100 variables named as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C programming arrays is introduced in C which gives the capability to store the 100 roll numbers in the contiguous memory which has 100 blocks and which can be accessed by single variable name.

  1. C Programming Arrays is the Collection of Elements
  2. C Programming Arrays is collection of the Elements of the same data type.
  3. All Elements are stored in the Contiguous memory
  4. All elements in the array are accessed using the subscript variable (index). Pictorial representation of C Programming Arrays

The above array is declared as int a [5]; a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1; In the above figure 4, 5, 33, 13, 1 are actual data items. 0 , 1, 2, 3, 4 are index variables. Index or Subscript Variable:

  1. Individual data items can be accessed by the name of the array and an integer enclosed in square bracket called subscript variable / index
  1. Subscript Variables helps us to identify the item number to be accessed in the contiguous memory. What is Contiguous Memory?
  2. When Big Block of memory is reserved or allocated then that memory block is called as Contiguous Memory Block.
  3. Alternate meaning of Contiguous Memory is continuous memory.
  4. Suppose inside memory we have reserved 1000-1200 memory addresses for special purposes then we can say that these 200 blocks are going to reserve contiguous memory. Contiguous Memory Allocation
  5. Two registers are used while implementing the contiguous memory scheme. These registers are base register and limit register.
  6. When OS is executing a process inside the main memory then content of each register are as Register Content of register

Base register Starting address of the memory location where process execution is happening

Limit register Total amount of memory in bytes consumed by process

Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non- contiguous allocation of memory.

  1. When process try to refer a part of the memory then it will firstly refer the base address from base register and then it will refer relative address of memory location with respect to base address. How to allocate contiguous memory?
  2. Using static array declaration.
  3. Using alloc ( ) / malloc ( ) function to allocate big chunk of memory dynamically. Array Terminologies:

Size Dimensions of the Array Array declaration requirements Requirement Explanation Data Type Data Type specifies the type of the array. We can compute the size required for storing the single cell of array.

Valid Identifier Valid identifier is any valid variable or name given to the array. Using this identifier name array can be accessed.

Size of Array It is maximum size that array can have.

What does Array Declaration tell to Compiler?

  1. Type of the Array
  2. Name of the Array
  3. Number of Dimension
  4. Number of Elements in Each Dimension

Types of Array

**1. Single Dimensional Array / One Dimensional Array

  1. Multi Dimensional Array**

Single / One Dimensional Array:

  1. Single or One Dimensional array is used to represent and store data in a linear form.
  2. Array having only one subscript variable is called One-Dimensional array
  3. It is also called as Single Dimensional Array or Linear Array Single Dimensional Array Declaration and initialization: Syntax for declaration: [size]; Examples for declaration: int iarr[3]; char carr[20]; float farr[3]; Syntax for initialization: [size] = {val1, val2, …, valn}; Examples for initialization: int iarr[3] = {2, 3, 4}; char carr[20] = “program”; float farr[3] = {12.5, 13.5, 14.5}; Different Methods of Initializing 1-D Array Whenever we declare an array, we initialize that array directly at compile time.

Initializing 1-D Array is called as compiler time initialization if and only if we assign certain set of values to array element before executing program. i.e. at compilation time.

Here we are learning the different ways of compile time initialization of an array. Ways of Array Initializing 1-D Array:

  1. Size is Specified Directly
  2. Size is Specified Indirectly Method 1: Array Size Specified Directly In this method, we try to specify the Array Size directly. int num [5] = {2,8,7,6,0}; In the above example we have specified the size of array as 5 directly in the initialization statement. Compiler will assign the set of values to particular element of the array. num[0] = 2; num[1] = 8; num[2] = 7; num[3] = 6; num[4] = 0; As at the time of compilation all the elements are at specified position So This initialization scheme is Called as “ Compile Time Initialization “. Graphical Representation:

Method 2: Size Specified Indirectly In this scheme of compile time Initialization, We do not provide size to an array but instead we provide set of values to the array.

arr[5] = Sixth Element of Array whereas elements are assigned to an array using below way arr[0] = 51; arr[1] = 32; arr[2] = 43; arr[3] = 24; arr[4] = 5; arr[5] =26; Example Program 1 : Accessing array

#include<stdio.h>

#include<conio.h>

void main()

int arr[] = {51,32,43,24,5,26};

int i;

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

printf("\nElement at arr[%d] is %d",i,arr[i]);

getch();

Output:

Element at arr[0] is 51

Element at arr[1] is 32

Element at arr[2] is 43

Element at arr[3] is 24

Element at arr[4] is 5

Element at arr[5] is 26

How a[i] Works? We have following array which is declared like int arr[] = { 51,32,43,24,5,26}; As we have elements in an array, so we have track of base address of an array. Below things are important to access an array.

Expression Description Example

arr It returns the base address of an array Consider 2000

*arr It gives zeroth element of an array 51

Expression Description Example

*(arr+0) It also gives zeroth element of an array 51

*(arr+1) It gives first element of an array 32

So whenever we tried accessing array using arr[i] then it returns an element at the location*(arr

  • i) Accessing array a[i] means retrieving element from address (a + i). Example Program 2 : Accessing array

#include<stdio.h>

#include<conio.h>

void main()

int arr[] = {51,32,43,24,5,26};

int i;

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

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

getch();

Output:

Operations with One Dimensional Array

  1. Deletion – Involves deleting specified elements form an array.
  2. Insertion – Used to insert an element at a specified position in an array.
  3. Searching – An array element can be searched. The process of seeking specific elements in an array is called searching.

Location of the element to be deleted: 3

2. C Program to delete duplicate elements from an array

int main() {

int arr[20], i, j, k, size;

printf("\nEnter array size: ");

scanf("%d", &size);

printf("\nAccept Numbers: ");

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

scanf("%d", &arr[i]);

printf("\nArray with Unique list: ");

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

for (j = i + 1; j < size;) {

if (arr[j] == arr[i]) {

for (k = j; k < size; k++) {

arr[k] = arr[k + 1]; }

size--; }

else

j++; }

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

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

return (0);

Output:

Enter array size: 5

Accept Numbers: 1 3 4 5 3

Array with Unique list: 1 3 4 5

3. C Program to insert an element in an array

#include<stdio.h>

int main() {

int arr[30], element, num, i, location;

printf("\nEnter no of elements:");

scanf("%d", &num);

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

scanf("%d", &arr[i]); }

printf("\nEnter the element to be inserted:");

scanf("%d", &element);

printf("\nEnter the location");

scanf("%d", &location);

//Create space at the specified location

for (i = num; i >= location; i--) {

arr[i] = arr[i - 1]; }

num++;

arr[location - 1] = element;

//Print out the result of insertion

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

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

return (0);

Output:

Enter no of elements: 5

Enter the element to be inserted: 6

Enter the location: 2

4. C Program to search an element in an array

#include<stdio.h>

int main() {

int a[30], ele, num, i;

printf("\nEnter no of elements:");

scanf("%d", &num);

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

scanf("%d", &arr1[i]); }

/* Copying data from array 'a' to array 'b */

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

arr2[i] = arr1[i]; }

//Printing of all elements of array

printf("The copied array is:");

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

printf("\narr2[%d] = %d", i, arr2[i]);

return (0);

Output:

Enter no of elements: 5

Enter the values: 11 22 33 44 55

The copied array is: 11 22 33 44 55

6. C program to merge two arrays in C Programming

#include<stdio.h>

int main() {

int arr1[30], arr2[30], res[60];

int i, j, k, n1, n2;

printf("\nEnter no of elements in 1st array:");

scanf("%d", &n1);

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

scanf("%d", &arr1[i]); }

printf("\nEnter no of elements in 2nd array:");

scanf("%d", &n2);

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

scanf("%d", &arr2[i]); }

i = 0;

j = 0;

k = 0;

// Merging starts

while (i < n1 && j < n2) {

if (arr1[i] <= arr2[j]) {

res[k] = arr1[i];

i++;

k++; }

else {

res[k] = arr2[j];

k++;

j++; }

/*Some elements in array 'arr1' are still remaining where as the array

'arr2' is exhausted*/

while (i < n1) {

res[k] = arr1[i];

i++;

k++; }

/*Some elements in array 'arr2' are still remaining where as the array

'arr1' is exhausted */

while (j < n2) {

res[k] = arr2[j];

k++;

j++; }

//Displaying elements of array 'res'

printf("\nMerged array is:");

for (i = 0; i < n1 + n2; i++)

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

return (0);

Enter no of elements in 1st array: 4

int i, arr[50], num;

printf("\nEnter no of elements :");

scanf("%d", &num);

//Reading values into Array

printf("\nEnter the values :");

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

scanf("%d", &arr[i]); }

//Printing of all elements of array

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

printf("\narr[%d] = %d", i, arr[i]); }

return (0);

Output:

Enter no of elements : 5

Enter the values : 10 20 30 40 50

arr[0] = 10

arr[1] = 20

arr[2] = 30

arr[3] = 40

arr[4] = 50

3. C Program to calculate addition of all elements in an array

#include<stdio.h>

int main() {

int i, arr[50], sum, num;

printf("\nEnter no of elements :");

scanf("%d", &num);

//Reading values into Array

printf("\nEnter the values :");

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

scanf("%d", &arr[i]);

//Computation of total

sum = 0;

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

sum = sum + arr[i];

//Printing of all elements of array

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

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

//Printing of total

printf("\nSum=%d", sum);

return (0);

Output:

Enter no of elements : 3

Enter the values : 11 22 33

a[0]=

a[1]=

a[2]=

Sum=

4. C Program to find smallest element in an array

#include<stdio.h>

int main() {

int a[30], i, num, smallest;

printf("\nEnter no of elements :");

scanf("%d", &num);

//Read n elements in an array

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

scanf("%d", &a[i]);

//Consider first element as smallest

smallest = a[0];

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

if (a[i] < smallest) {

smallest = a[i]; } }

#include<stdio.h>

int main() {

int arr[30], i, j, num, temp;

printf("\nEnter no of elements : ");

scanf("%d", &num);

//Read elements in an array

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

scanf("%d", &arr[i]); }

j = i - 1; // j will Point to last Element

i = 0; // i will be pointing to first element

while (i < j) {

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

i++; // increment i

j--; // decrement j

//Print out the Result of Insertion

printf("\nResult after reversal : ");

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

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

return (0);

Output:

Enter no of elements : 5

Result after reversal : 55 44 33 22 11

Multi Dimensional Array:

  1. Array having more than one subscript variable is called Multi-Dimensional array.
  2. Multi Dimensional Array is also called as Matrix.

Syntax: [row subscript][column subscript];

Example: Two Dimensional Arrays Declaration: Char name[50][20]; Initialization:

int a[3][3] = { 1, 2, 3

In the above example we are declaring 2D array which has 2 dimensions. First dimension will refer the row and 2nd dimension will refer the column. Example: Three Dimensional Arrays Declaration: Char name[80][20][40]; The following information are given by the compiler after the declaration

Example Type (^) NameArray^ Dimension No.^ No. Each Dimension^ of Elements in

1 integer roll 1 10

2 character name 2 80 and 20

3 character name 3 80 and 20 and 40

Two Dimensional Arrays:

  1. Two Dimensional Array requires Two Subscript Variables
  2. Two Dimensional Array stores the values in the form of matrix.
  3. One Subscript Variable denotes the “ Row ” of a matrix.
  4. Another Subscript Variable denotes the “ Column ” of a matrix.

Declaration and use of 2D Arrays:

int a[3][4];