dipalinaglot.files.wordpress.com  · web viewprogramming arrays introduction. in the previous...

22
Array Programming Arrays Introduction In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables are the one of the building block in C Programming. So far we were using the single variable name for storing one data item. If we need to store the multiple copies of the same data then it is very difficult for the user. Thoughtful Example of 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. Pictorial Look of C Programming Arrays

Upload: others

Post on 21-Sep-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

Array

Programming Arrays Introduction

In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables are the one of the building block in C Programming.

So far we were using the single variable name for storing one data item. If we need to store the multiple copies of the same data then it is very difficult for the user.

Thoughtful Example of 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.

Pictorial Look 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;

Page 2: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

4,5,33,13,1 are actual data items … ( in our case Roll numbers )0,1,2,3,4 are index variables ..( similar to ‘i’ in for loop / Subscript variable )

Term : C Programming Arrays

Array is collection of the data items having same data type

Term : 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

2. Subscript Variables helps us to identify the item number to be accessed in the contiguous

memory.

C Array Types

1.Single Dimensional Array :

1. Single or One Dimensional array is used to represent and store data in a linear form.

Page 3: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

2. Array having only one subscript variable is called One-Dimensional array

3. It is also called as Single Dimensional Array or Linear Array

Syntax :

<data-type> <array_name> [size];

Example of Single Dimensional Array :

int iarr[3] = {2, 3, 4};

char carr[20] = "c4learn" ;

float farr[3] = {12.5,13.5,14.5} ;

2. 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 :

<data-type> <array_name> [row_subscript][column-subscript];

Example : Two Dimensional Array

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

5,6,7

8,9,0 };

Page 4: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

One Dimensional Array

How to declare Array in Cint num[35];  /* An integer array of 35 elements */char ch[10];  /* An array of characters for 10 elements */Similarly an array can be of any data type such as double, float, short etc.

How to access element of an array in C

You can use array subscript (or index) to access any element stored in array. Subscript starts with 0, which means arr[0] represents the first element in the array arr.

In general arr[n-1] can be used to access nth element of an array. where n is any integer number.

For example:

int mydata[20];mydata[0] /* first element of array mydata*/mydata[19] /* last (20th) element of array mydata*/

Example of Array In C programming to find out the average of 4 integers#include <stdio.h>int main(){ int avg = 0; int sum =0; int x=0;

/* Array- declaration – length 4*/ int num[4];

/* We are using a for loop to traverse through the array * while storing the entered values in the array */ for (x=0; x<4;x++) { printf("Enter number %d \n", (x+1)); scanf("%d", &num[x]); } for (x=0; x<4;x++) {

Page 5: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

sum = sum+num[x]; }

avg = sum/4; printf("Average of entered number is: %d", avg); return 0;}Output:

Enter number 1 10Enter number 2 10Enter number 3 20Enter number 4 40Average of entered number is: 20Lets discuss the important parts of the above program:

Input data into the array

Here we are iterating the array from 0 to 3 because the size of the array is 4. Inside the loop we are displaying a message to the user to enter the values. All the input values are stored in the corresponding array elements using scanf function.

for (x=0; x<4;x++){ printf("Enter number %d \n", (x+1)); scanf("%d", &num[x]);}Reading out data from an array

Suppose, if we want to display the elements of the array then we can use the for loop in C like this.

for (x=0; x<4;x++){ printf("num[%d]\n", num[x]);}Various ways to initialize an array

Page 6: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

In the above example, we have just declared the array and later we initialized it with the values input by user. However you can also initialize the array during declaration like this:

int arr[5] = {1, 2, 3, 4 ,5};OR (both are same)

int arr[] = {1, 2, 3, 4, 5};Un-initialized array always contain garbage values.

Two dimensional(2D) Array

An array of arrays is known as 2D array. The two dimensional (2D) array in C programming is also known as matrix. A matrix can be represented as a table of rows and columns. Before we discuss more about two Dimensional array lets have a look at the following C program.

Simple Two dimensional(2D) Array ExampleFor now don’t worry how to initialize a two dimensional array, we will discuss that part later. This program demonstrates how to store the elements entered by user in a 2d array and how to display the elements of a two dimensional array.

#include<stdio.h>int main(){ /* 2D array declaration*/ int disp[2][3]; /*Counter variables for the loop*/ int i, j; for(i=0; i<2; i++) { for(j=0;j<3;j++) { printf("Enter value for disp[%d][%d]:", i, j); scanf("%d", &disp[i][j]); } } //Displaying array elements printf("Two Dimensional array elements:\n"); for(i=0; i<2; i++) { for(j=0;j<3;j++) { printf("%d ", disp[i][j]); if(j==2){ printf("\n");

Page 7: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

} } } return 0;}Output:

Enter value for disp[0][0]:1Enter value for disp[0][1]:2Enter value for disp[0][2]:3Enter value for disp[1][0]:4Enter value for disp[1][1]:5Enter value for disp[1][2]:6Two Dimensional array elements:1 2 3 4 5 6

Initialization of 2D ArrayThere are two ways to initialize a two Dimensional arrays during declaration.

int disp[2][4] = { {10, 11, 12, 13}, {14, 15, 16, 17}};OR

int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};Although both the above declarations are valid, I recommend you to use the first method as it is more readable, because you can visualize the rows and columns of 2d array in this method.

Things that you must consider while initializing a 2D array

We already know, when we initialize a normal array (or you can say one dimensional array) during declaration, we need not to specify the size of it. However that’s not the case with 2D array, you must always specify the second dimension even if you are specifying elements during the declaration. Let’s understand this with the help of few examples –

/* Valid declaration*/int abc[2][2] = {1, 2, 3 ,4 }  /* Valid declaration*/ int abc[][2] = {1, 2, 3 ,4 }  /* Invalid declaration – you must specify second dimension*/

Page 8: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

int abc[][] = {1, 2, 3 ,4 }   /* Invalid because of the same reason  mentioned above*/int abc[2][] = {1, 2, 3 ,4 }

How to store user input data into 2D arrayWe can calculate how many elements a two dimensional array can have by using this formula:The array arr[n1][n2] can have n1*n2 elements. The array that we have in the example below is having the dimensions 5 and 4. These dimensions are known as subscripts. So this array has first subscript value as 5 and second subscript value as 4.So the array abc[5][4] can have 5*4 = 20 elements.

To store the elements entered by user we are using two for loops, one of them is a nested loop. The outer loop runs from 0 to the (first subscript -1) and the inner for loops runs from 0 to the (second subscript -1). This way the the order in which user enters the elements would be abc[0][0], abc[0][1], abc[0][2]…so on.

#include<stdio.h>int main(){ /* 2D array declaration*/ int abc[5][4]; /*Counter variables for the loop*/ int i, j; for(i=0; i<5; i++) { for(j=0;j<4;j++) { printf("Enter value for abc[%d][%d]:", i, j); scanf("%d", &abc[i][j]); } } return 0;}

Page 9: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

In above example, I have a 2D array abc of integer type. Conceptually you can visualize the above array like this:

However the actual representation of this array in memory would be something like this:

Program on Array

Page 10: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

#include <stdio.h>

int main () {

int n[ 10 ]; /* n is an array of 10 integers */

int i,j;

/* initialize elements of array n to 0 */

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

n[ i ] = i + 100; /* set element at location i to i + 100 */

}

/* output each array element's value */

for (j = 0; j < 10; j++ ) {

printf("Element[%d] = %d\n", j, n[j] );

} return 0;

}Output:

Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109

A. Write C program to find minimum and maximum from n entered numbers.

/** * C program to find maximum and minimum element in array */

#include <stdio.h>

#define MAX_SIZE 100 // Maximum array size

int main(){

Page 11: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

int arr[MAX_SIZE]; int i, max, min, size;

/* Input size of the array */ printf("Enter size of the array: "); scanf("%d", &size);

/* Input array elements */ printf("Enter elements in the array: "); for(i=0; i<size; i++) { scanf("%d", &arr[i]); }

/* Assume first element as maximum and minimum */ max = arr[0]; min = arr[0];

/* * Find maximum and minimum in all array elements. */ for(i=1; i<size; i++) { /* If current element is greater than max */ if(arr[i] > max) { max = arr[i]; }

/* If current element is smaller than min */ if(arr[i] < min) { min = arr[i]; } }

/* Print maximum and minimum element */ printf("Maximum element = %d\n", max); printf("Minimum element = %d", min);

return 0;}

Output:

Page 12: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

Enter size of the array: 10

Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10

Maximum element = 100

Minimum element = -10

B. Write C program to print alternate numbers from n entered numbers

/*  * C Program to Print the Alternate Elements in an Array  */  #include <stdio.h> void main() {  int array[10]; int i; printf("enter the element of an array \n"); for (i = 0; i < 10; i++) scanf("%d", &array[i]);  printf("Alternate elements of a given array \n"); for (i = 0; i < 10; i += 2) printf( "%d\n", array[i]) ; }

Output:

1223455768738497120125Alternate elements of a given array12

Page 13: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

456884120

C. Write C program to search an element in an array using linear.

Linear search:

#include <stdio.h>

int main()

{

int array[100], search, c, n;

printf("Enter the number of elements in array\n");

scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

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

scanf("%d", &array[c]);

printf("Enter a number to search\n");

scanf("%d", &search);

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

{

if (array[c] == search) /* If required element is found */

{

printf("%d is present at location %d.\n", search, c+1);

break;

} }

if (c == n)

printf("%d isn't present in the array.\n", search);

return 0;

}

Page 14: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

Output:

C Program – Selection sort

#include<stdio.h>int main(){ /* Here i & j for loop counters, temp for swapping, * count for total number of elements, number[] to * store the input numbers in array. You can increase * or decrease the size of number array as per requirement */ int i, j, count, temp, number[25];

printf("How many numbers u are going to enter?: "); scanf("%d",&count);

printf("Enter %d elements: ", count); // Loop to get the elements stored in array for(i=0;i<count;i++) scanf("%d",&number[i]); // Logic of selection sort algorithm for(i=0;i<count;i++){ for(j=i+1;j<count;j++){ if(number[i]>number[j]){ temp=number[i]; number[i]=number[j]; number[j]=temp; } } }

printf("Sorted elements: "); for(i=0;i<count;i++)

Page 15: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

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

return 0;}

Output:

As you can see that we have entered 6 elements in random order and the program sorted them in ascending order by using selection sort algorithm which we have implemented in the program. You can also modify this same program to sort the elements in descending order as well.

Page 16: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

String (Character Array)

Strings are actually one-dimensional array of characters terminated by a nullcharacter '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as follows −

char greeting[] = "Hello";

Following is the memory presentation of the above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array

A. Write C program to find length of string (with and without using library function).

#include<stdio.h>

int main() {

char str[100];

int length;

printf("\nEnter the String : ");

gets(str);

Page 17: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables

length = 0; // Initial Length

while (str[length] != '\0')

length++;

printf("\nLength of the String is : %d", length);

return(0);

}

Page 18: dipalinaglot.files.wordpress.com  · Web viewProgramming Arrays Introduction. In the previous chapter’s we have learn’t variables are used for the storage of the data. Variables