Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Arrays in C Language, Study Guides, Projects, Research of Computer Programming

This document introduces the concept of arrays in C language. It explains the definition, declaration, and initialization of arrays, including one-dimensional and two-dimensional arrays. The document also covers the memory mapping of two-dimensional arrays and provides examples of performing addition, subtraction, and multiplication of matrices using arrays. The drawbacks of initializing a large number of array elements are also discussed.

Typology: Study Guides, Projects, Research

2021/2022

Available from 01/02/2024

dheeraj-kumar-karne
dheeraj-kumar-karne 🇮🇳

6 documents

1 / 23

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
UNIT-IV
ARRAYS
Introduction:-
#include<stdio.h>
#include<conio.h>
void main()
{
int a=2;
a=4;
printf(“%d”,a);
}
Output:- 4
a=2 is assigned before assigning 4 to it. When we assign 4 to ‘a’ then the value stored in
‘a’ is replaced with the new value. Hence, ordinary variables can capable of storing one value at
a time. This fact is same for all data types. But in application the variables must be assigned to
more than one value. This can be obtained with the help of “Arrays”.
Definition:-
Array is a collection of similar data types in which each element is located in separate
memory locations.
Array is a Derived data type.
Declaration of an Array:-
Syntax:-
<datatype><arrayname>[size];
1. The data type specifies the type of elements that will be contained in the array such as
int, float & char.
2. Array name specifies all elements of an the array share the same name and they are
distinguished from one another with the help of an element number (or) index number.
3. Size indicates the maximum number of elements that can be stored inside the array.
Ex:- int group[10];
declares the group as an array to contain a maximum of 10 integer constants
Individual values are called elements.
Initializing Array:-
Syntax:-
<datatype>< arrayname>[size]={list of values};
Ex:- int a[5]={1,2,3,4,8};
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17

Partial preview of the text

Download Arrays in C Language and more Study Guides, Projects, Research Computer Programming in PDF only on Docsity!

UNIT-IV

ARRAYS

Introduction:- #include<stdio.h> #include<conio.h> void main() { int a=2; a=4; printf(“%d”,a); } Output:- 4 a=2 is assigned before assigning 4 to it. When we assign 4 to ‘a’ then the value stored in ‘a’ is replaced with the new value. Hence, ordinary variables can capable of storing one value at a time. This fact is same for all data types. But in application the variables must be assigned to more than one value. This can be obtained with the help of “Arrays”. Definition:- Array is a collection of similar data types in which each element is located in separate memory locations. Array is a Derived data type. Declaration of an Array:- Syntax:- [size];

  1. The data type specifies the type of elements that will be contained in the array such as int, float & char.
  2. Array name specifies all elements of an the array share the same name and they are distinguished from one another with the help of an element number (or) index number.
  3. Size indicates the maximum number of elements that can be stored inside the array. Ex :- int group[10]; declares the group as an array to contain a maximum of 10 integer constants Individual values are called elements. Initializing Array:- Syntax :- < arrayname>[size]={list of values}; Ex :- int a[5]={1,2,3,4,8};

Here 5 elements are stored in an array ‘a’. The array elements are stored sequentially in separate locations. Array in ‘c’ language indexing starting at ‘0’.Reading of array elements begins from ‘0’. a[0]= a[1]= a[2]= a[3]= a[4]=

  1. If the number of values in the list is less than the number of elements, then only that remaining elements will be set to zero automatically. Ex :- float total[5]={0.0,15.75,-10} The remaining two elements to zero.
  2. The size may be omitted. In such cases the compiler allocates enough space for all initialized elements. Ex :- int counter[]={1,10,18,20};
  3. Character arrays may be initialized. Ex :- char name[]={‘L’,‘U’,‘C’,‘K’,’Y’,‘\0’}; 6 characters initialized with string “LUCKY” ending with the NULL character.
  4. If the number of values in the list is greater than the number of elements, then produce an error. Ex :- int num[3]={10,20,30,40}; NOTE :-Compile time initialization may be partial i.e.., the number of initializers may be less than the declared size. In such cases, the remaining elements are initialized to zero, if array type is numeric & NULL if the type is char. The smallest possible value of array index is LOWER BOUND. The highest possible value of array index is UPPER BOUND. Drawback :- There is no short cut method for initializing a large number of array elements. An Array can be explicitly initialized at run time. Ex :- for(i=0;i<100;i++) { if(i<50) sum[i]=0.0; else sum[i]=1.0; } The first 50 elements of the array sum are initialized to ‘0’ while the remaining 50 elements are initialized to 1.0 at run time. We can also use a read function such as scanf to initialize an array. Ex :- int x[3]; scanf(“%d%d%d”, &x[10],&x[1],&x[2])

The array number to store the values number[0] number[1] number[2] number[3] number[4] Memory Map With One-Dimensional Array:- 4002 4004 4006 4008 4010 35 40 20 57 19 a[0] a[1] a[2] a[3] a[4] “[ ]” Specifies indication dealing with an arrays. / C program to create a ono-dimensional array and find sum of the elements / #include<stdio.h> #include<conio.h> void main { int a[10], i, n, sum; clrscr(); printf(“enter size:”); scanf(“%d”, &n) ; sum=0; printf(“enter array elements \n”) ; for( i=0; i<n; i++) { scanf(“%d”, &a[i]); sum = sum+a[i]; } printf(“the sum = %d \n”,sum); getch(); }

2. Two-dimensional arrays:- So far we have discussed the array variables that can store a list of values. There could be situation where a table of values will have to be stored. Consider the following data table, which shows the value of sales of 3 items by 4 sales girls

Item1 Item2 Item Salesgirl 1 310 275 365 Salesgirl 2 210 190 325 Salesgirl 3 405 235 240 Salesgirl 4 260 300 380

The table contains a total of 12 values, 3 in each line. This table as a matrix consisting of 4 rows and 3 columns. Two-dimensional arrays are declared as follows: [row-size][column-size]; Two-dimensional arrays are stored in memory, as shown in fig. As with the single dimensional arrays, each dimension of the array is indexed from zero to its maximum size minus one; the index selects the row and second index selects the column within that row. [0][0] [0][1] [0][2] 310 275 365

Initializing Two-Dimensional Arrays:- Like the one-dimensional arrays, two dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex :- int table[2] [3]={0,0,0,1,1,1}; Initialize the elements of the first row to zero and second row to one. Ex :- int table [2][3]={{0,0,0},{1,1,1}};

Initialize a 2-D array in the form of a matrix Ex :- int table [2][3]= { {0, 0, 0}, {1, 1, 1} }; When the array is completely initialized with all the values explicitly, we need not specify the size of the first dimension. Ex :- int table [][3]= { {0, 0, 0}, {1, 1, 1} }; If the values are missing in the initializer, they are automatically set to zero. Ex :- int table[2][3]={ {1,1}, {2} }; When all the elements are to be initialized to zero, the following short-cut method may be used. Ex :- int m[3][5]= {{0},{0},{0} }; Memory Mapping For Two Dimensional Arrays:-

for(j=0;j<c1;j++) scanf("%d", &b[i][j]); } printf("\n Matrix Addition \n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) printf("%5d", a[i][j] + b[i][j]); printf("\n"); } printf("\n Matrix subtraction \n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) printf("%5d", a[i][j] - b[i][j]); printf("\n"); } getch(); } Ex:-Write a C program to perform multiplication of two matrices. #include<stdio.h> #include<conio.h> void main() { int i, j, k, a[3][3], b[3][3], c[3][3]; clrscr(); printf("enter the first 3*3 matrix: \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("a[%d][%d]=", i, j); scanf("%d", &a[i][j]); } }

printf("enter the second 3*3 matrix: \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("b[%d][%d]=", i, j); scanf("%d", &b[i][j]); } } for(i=0;i<3;i++) for(j=0;j<3;j++) { c[i][j]=0; for(k=0;k<3;k++) c[i][j]=c[i][j] + a[i][k] * b[k][j]; } printf("\n\n the product of the two matrices is : \n"); for(i=0;i<3;i++) { printf("\n\t\t "); for(j=0;j<3;j++) { printf("%d\t",c[i][j]); } } getch(); }

Ex:-Write a C program to perform the transpose of a 3x3 matrix. #include<stdio.h> #include<conio.h> void main() { int i, j, a[3][3], b[3][3]; clrscr(); printf("enter a 3*3 matrix");

3. Multi-Dimensional arrays:-

C allows arrays of 3 or more dimensions. The exact is determined by the compiler. Syntax :- <array-name >[s1][s2][s3][s4]…….[s (^) n ]; sn is the size of the n th^ dimension. Ex :- int survey [3][5][12]; float table [5][4][5][3]; Survey is a 3-D array declared to contain 180 integer type elements. Similarly table is a 4-D array containing 300 elements of floating- point type. MEMORY MAP:- 2x3x3 array memory mapping Ex :- int a[2][3][3]; a[0][0][0]= a[0][0][1]= a[0][0][2]= a[0][1][0]= a[0][1][1]= a[0][1][2]= a[0][2][0]= a[0][2][1]= a[0][2][2]= a[1][0][0]= a[1][0][1]= a[1][0][2]= a[1][1][0]= a[1][1][1]= a[1][1][2]= a[1][2][0]= a[1][2][1]= a[1][2][2]= Array applications: In c programming language, arrays are used in wide range of applications. Few of them are as follows...

  1. Arrays are used to Store List of values
  1. In c programming language, single dimensional arrays are used to store list of values of same data type. In other words, single dimensional arrays are used to store a row of values. In single dimensional array data is stored in linear form.
  2. Arrays are used to Perform Matrix Operations. We use two dimensional arrays to create matrix. We can perform various operations on matrices using two dimensional arrays.
  3. Arrays are used to implement Search Algorithms. We use single dimensional arrays to implement search algorithms like ...  Linear Search  Binary Search
  4. Arrays are used to implement Sorting Algorithms. We use single dimensional arrays to implement sorting algorithms like ...  Insertion Sort  Bubble Sort  Selection Sort  Quick Sort  Merge Sort, etc.,
  5. Arrays are used to implement Data structures. We use single dimensional arrays to implement data structures like...  Stack Using Arrays  Queue Using Arrays
  6. Arrays are also used to implement CPU Scheduling Algorithms.

Passing Arrays to Functions or Functions and Arrays:

One-dimensional Arrays:- Single dimensional arrays can be passed to functions as follows: Ex : #include<stdio.h> #include<conio.h> void main() { int n,i,a[10]; float g; float findavg(int[],int); clrscr(); printf("enter size"); scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); g= findavg(a,n); printf("average is %f",g); getch(); } float findavg(int a[],int n) { float sum=0,avg; int i; for(i=0;i<n;i++) sum=sum+a[i]; return(sum/n); }

Here float table[][5] tells C compiler that table is an array of dimension N X 5 of float. Note : we must specify the second (and subsequent) dimension of the array BUT not the first dimension.

Strings

A string is a collection of characters. A string constant is a one dimensional array of characters terminated by a null (‘\0’) character. Ex :- char name[ ]={‘A’, ‘K’, ‘S’, ‘H’, ‘A’, ’y’, ‘\0’}; Where ‘\0’ is a null character and specifies end of the string. Terminating the string with null ‘\0’ is important, because it is the only way the functions that work with a string can know where the string ends. A K S H A Y
Each character in the array occupies a memory of one byte (including ‘\0’) We can also declare strings like Ex :- char name[ ]=”AKSHAY”; In these declarations ‘\0’ is not necessary C inserts ‘\0’ automatically at the end of the string. Ex :- Write a c program to print a character array. #include<stdio.h> #include<conio.h> Void main() { char name[20]; printf(“Enter the name”); scanf(“%s”,name); printf(“The name is %s”,name); getch(); } Output: Enter the name AKSHAYA The name is AKSHAYA String Handling Functions or String manipulations:- Character strings are often used to build meaningful and readable programs. The common operations performed on character strings include: Reading & writing strings Combining strings together Copying one string to another

Comparing strings for equality Extracting a portion of a string Every C compiler provides a large set of string handling function which are contained in header file <string.h> The C library supports a large number of string-handling functions that can be used to carry out many of the string manipulations.

Functions (^) Description strlen() Determines length of a string strcpy() Copies a string from source to destination strncpy() Copies characters of a string to another string up to the specified length strcmp() Compares characters of two strings(function discriminates b/w small & capital letters) stricmp() Compares two strings(function does not discriminate b/w small & capital letters) strncmp() Compares characters of two strings up to the specified length strnicmp() Compares characters of two strings up to the specified length. Ignores case. strstr() Determines first occurance of a given string in another string strcat() Appends source string to destination string strncat() Appends source string to destination string up to a specified length strrev() Reverses all characters of a string

1.strlen function: This function counts and returns the number of characters in a string. Syntax: n= strlen(string); Where n is a an integer variable, which receives the value of the length of the string. The argument may be a string constant. The counting ends at the first null character. Ex: 1. strlen(“rama rao”) = 8 2.strlen(“7893”)= 4 3.strlen(“+-$”) = 3

strcpy(b,a); String in array a is copied to b. Array b contains “7892” char a[ ]=”hyd”, is valid a=”sec”, is invalid. We can use array name on left hand side of = , only in declaration statement but not in executable statement.

  1. char a[20], b[20]; Strcpy(a,strcpy(b,”hyd”)); “hyd” is stored in arrays b and a. output of inner function is “hyd”.

/ C program to copy the contents of one string to another string by using strcpy()* #include<stdio.h> #include<conio.h> #include<string.h> void main() { char ori[20], dup[20]; clrscr(); printf(“enter ur name”); gets(ori); strcpy(dup,ori); printf(“original string : %s”,ori); printf(“duplicate string: %s”,dup); } 3.strncpy function: This function copies specified length of characters from source to destination string. Syntax : strncpy(destination,source,n); Where n is the number of left most characters of the source string to be copied. Ex : char s1[20]=”london”; char s2[20]; strncpy(s2,s1,5); This statement copies the first 5 characters of the source string s1 into the target string s2.Therefore s2 contains “London”.

/ C program to copy source string to destination string up to a specified length. Length is to be entered through the key board / #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str1[15], str2[15]; int n; clrscr(); printf(“enter source string”); gets(str1); printf(“enter destination string”); gets(str2); printf(“enter no.of characters to replace in destination string”); scanf(“%d”, &n); strncpy(str2,str1,n); printf(“source string : %s”, str1); printf(“destination string : %s”,str2); } 4.strcmp function: This function compares two strings for finding whether they are same or different. This function discriminates between small and capital letters. Ex: char str1[20]=”HELLO”; char str2[20]=”hello”; these two strings are different. Characters of these strings are compared one by one. In case of a mismatch the function returns non-zero value otherwise zero i.e. when the two strings are same strcmp() returns the value zero. If they are different it returns the numeric difference b/w the ASCII values of non- matching characters. Syntax : strcmp(string1,string2); Ex: strcmp(“their”,”there”);

Will return a value of -9 which is the numeric difference between ASCII “i”(105) and ASCII “r”(114) i.e. “i” minus “r” in ASCII code (105-114 ) is -9. If the value is negative, string1 is alphabetically above string2.

char str1[10], str2[10]; int diff; clrscr(); printf(“enter the string1”); gets(str1); printf(“enter the string2”); gets(str2); diff=stricmp(str1,str2); if(diff==0) puts(“the two strings are identical”); else puts(“the two strings are different”); }

6. Strncmp Function: Comparison of two strings can be made up to certain specified length. Syntax : strncmp (string1, string2, n); This compares the left-most n characters of string1 to string2 and returns, a) 0 if they are equal b) –ve number if string1 sub string is less than string c) +ve number, otherwise

Ex: char str1 [20] =”HELLO”; char str2 [20] =”HE MAN”; strncmp (str1, str2, 2); Returns zero. I.e. the strings are identical up to 2 characters Strncmp () function discriminates between lowercase and uppercase letters. Ex: char str1[20]=”HELLO”; char str2[20]=”he man”; strncmp(str1, str2, 2); Returns non zero value i.e. the strings are different up to 2 characters. / C program to compare two strings up to specified length* #include<stdio.h> #include<conio.h> #include<string.h> void main() {

char str1[10], str2[10]; int n, diff; clrscr(); printf(“enter the string1”); gets(str1); printf(“enter the string2”); gets(str2); printf(“enter the length up to which comparison is to be made:”); scanf(“%d”,&n); diff=strncmp(str1, str2, n); if(diff==0) puts(“the two strings are identical up to %d characters”, n); else puts(“the two strings are different”); } 7.Strnicmp Function: This function compares the characters of the two strings to a specified length. This function does not discriminate between lowercase and uppercase letters. Syntax : strnicmp (string1, string2, n); Ex : char str1[20]=”HELLO”; char str2[20]=”he man”; strnicmp(str1, str2, 2); returns zero. I.e. the two strings are identical up to 2 characters. / C program to compare 2 strings up to specified length using strnicmp () / #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str1[10], str2[10]; int n, diff; clrscr(); printf(“enter the string1”); gets(str1);