0% found this document useful (0 votes)
48 views

Unit 6 Arrays

The document discusses arrays and strings in C programming language. Arrays can store multiple values of the same type and can be accessed using indexes. The document describes different ways to declare, initialize and access single and multi-dimensional arrays. It also explains strings in C which are arrays of characters terminated by a null character. Functions like scanf(), printf(), gets() and puts() are discussed for input/output of arrays and strings.

Uploaded by

Sakar Sapkota
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Unit 6 Arrays

The document discusses arrays and strings in C programming language. Arrays can store multiple values of the same type and can be accessed using indexes. The document describes different ways to declare, initialize and access single and multi-dimensional arrays. It also explains strings in C which are arrays of characters terminated by a null character. Functions like scanf(), printf(), gets() and puts() are discussed for input/output of arrays and strings.

Uploaded by

Sakar Sapkota
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Array

An array is defined as the collection of similar type of data items stored at contiguous
memory locations.
Arrays are the derived data type in C programming language which can store the primitive
type of data such as int, char, double, float, etc.
By using the array, we can access the elements easily. Only a few lines of code are required
to access the elements of the array.

The index of array always starts from 0 to n-1.

Advantage of C Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like Linked List.

Types of Array in C

 Single Dimensional Array / 1D-Array


 Multi-Dimensional Array / 2D-Array

Single Dimensional Array


A 1D array is a simple data type that stores a collection of similar type data in a contiguous
block of memory.
Declaration of 1D C Array
We can declare an array in the c language in the following way.

Data_type array_name[array_size];

Example:-

int marks[5];

Initialization of 1D C Array
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.

marks[0]=80;
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Declaration with Initialization


We can initialize the C array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define the size. So it may also be written as the
following code.

int marks[]={20,30,40,50,60};
#include<stdio.h>
int main()
{
int i=0, marks[5], marks1[5]={20,30,40,50,60};
marks[0]=80;
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

for(i=0; i<5;i++)
{
printf("%d ",marks[i]);
}
printf(“\n”);
for(i=0; i<5;i++)
{
printf("%d ",marks1[i]);
}
return 0;
}
Output

0 60 70 85 75

20 30 40 50 60

Taking user input and printing it


#include<stdio.h>
int main()  Sum of all element in the array
{
 Average of all element in the array
int i, n , a[5]
printf("Enter Array Element\n");  Copy element of one array into another array
for(i=0; i<5; i++)  Print the element of array in reverse order
{  Print & count even and odd number present in the array
Scanf("a[%d] \n ", &a[i]);  Sorting the element in ascending order
}
 Sorting the element in descending order
for(i=0;i<5;i++)
{
printf("a[%d] ",a[i]);
}

return 0;
}

Two-Dimensional / 2D-Array
The two-dimensional array can be defined as an array of arrays. It is a type of array that
stores multiple data elements of the same type in matrix or table format with a number
of rows and columns.

Declaration of two dimensional Array in C


The syntax to declare the 2D array is given below.

data_type array_name[rows][columns];

Example:-

int a[3][4];
Initialization of 2D-Array
int a[3][4];

a[0][0]=5;
a[0][1]=7;
a[0][2]=9;
a[0][3]=5;
a[1][0]=1;
a[1][1]=6;
a[1][2]=3;
a[1][3]=2;
a[2][0]=10;
a[2][1]=8;
a[2][2]=4;
a[2][3]=11;

Initialization with Declaration of 2D Array in C


In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D arrays.
We will have to define the dimension of the array.

The two-dimensional array can be declared and defined in the following way.

int a[3][4]={{5,7,9,5},{1,6,3,2},{10,8,4,11}};

#include<stdio.h>
int main()
{
int i=0,j=0;
int a[3][4]= {{5,7,9,5},{1,6,3,2},{10,8,4,11}};
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("a[%d] [%d] = %d \n", i, j ,a[i][j]);
}
printf("\n");
}
return 0;
}
Output
a[0] [0] = 5
a[0] [1] = 7
a[0] [2] = 9
a[0] [3] = 5

a[1] [0] = 1
a[1] [1] = 6
a[1] [2] = 3
a[1] [3] = 2

a[2] [0] = 10
a[2] [1] = 8
a[2] [2] = 4
a[2] [3] = 11
Taking input from user and print
#include <stdio.h>
void main ()
{
int a[3][3], i, j;
for (i=0; i<3; i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ", i, j);
scanf("%d", &a[i][j]);
}
}

printf("\n printing the elements ....\n");


for(i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("%d\t" ,a[i][j]);
}
printf("\n");
}
}
Output
Enter a[0][0]: 1  Addition of matrix
Enter a[0][1]: 4  Subtraction of matrix
Enter a[0][2]: 8
 Multiplication of matrix
Enter a[1][0]: 7
 Print the element in tabular form with 4 rows
Enter a[1][1]: 9
and 5 column
Enter a[1][2]: 5
Enter a[2][0]: 4  Print the element in tabular form with 3 rows
Enter a[2][1]: 6 and 2 column
Enter a[2][2]: 3

printing the elements ....

1 4 8
7 9 5
4 6 3

String in C
The string can be defined as the one-dimensional array of characters terminated by a
null ('\0'). The character array or the string is used to manipulate text such as word or
sentences.

Each character in the array occupies one byte of memory, and the last character must
always be 0. The termination character ('\0') is important in a string since it is the only
way to identify where the string ends or not.

When we define a string as char s[10], the character s[10] is implicitly initialized with the
null in the memory.
There are two ways to declare a string in c language.

1. By char array
2. By string literal

By Char array

char s[7]={'b', 'i', 's', 'h', 'a', 'l', '\0'};


char s[]={'b', 'i', 's', 'h', 'a', 'l', '\0'};

By string literal

char ch[10]="bishal";
char ch[]="bishal";

There are two main differences between char array and literal.

o We need to add the null character '\0' at the end of the array by ourself whereas;
it is appended internally by the compiler in the case of the character array.
o The string literal cannot be reassigned to another set of characters whereas, we
can reassign the characters of the array.
#include<stdio.h>
int main()
{
char ch[10]={'b', 'i', 's', 'h', 'a', 'l', '\0'};
char ch2[10]="bishal";

printf("Char Array Value is: %s\n", ch);


printf("String Literal Value is: %s\n", ch2);
return 0;
}

If we want to get character one by one to be print then,

#include<stdio.h>
int main()
{
int i=0;
char ch[10]={'b', 'i', 's', 'h', 'a', 'l', '\0'};
char ch2[10]="bishal";
while (ch[i]!=’\0’)
{
printf("Char Array Value is: %c\n", ch);
i++;
}
return 0;
}

Taking string as input/Reading a String


Till now, we have used scanf to accept the input from the user. However, it can also be
used in the case of strings but with a different scenario. Consider the below code which
stores the string while space is encountered.
#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%s" ,s);
printf("You entered %s" ,s);
}
Output
Enter the string? Bishal Patel
You have entered Bishal
It is clear from the output that, the above code will not work for space separated strings.
To make this code working for the space separated strings, the minor changed required
in the scanf function, i.e., instead of writing scanf("%s",s), we must write:
scanf("%[^\n]s",s) which instructs the compiler to store the string s while the new line
(\n) is encountered.

The output of the program will change


Enter the string? Bishal Patel
You have entered Bishal Patel

C gets() and puts() functions


The gets() and puts() are inbuilt/library functions that are declared in the header file
stdio.h. Both the functions are involved in the input/output operations of the strings.

C gets() function
The gets() function enables the user to enter some characters followed by the enter key.
All the characters entered by the user get stored in a character array.

The null character is added to the array to make it a string. The gets() allows the user to
enter the space-separated strings. It returns the string entered by the user.
Declaration

gets(char variable);

Reading string using gets()


#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
Output
Enter the String ? hello!! My name is bishal
You entered hello!! My name is bishal

The gets() function is risky to use since it doesn't perform any array bound checking and
keep reading the characters until the new line (enter) is encountered. It suffers from buffer
overflow, which can be avoided by using fgets(). The fgets() makes sure that not more
than the maximum limit of characters are read. Consider the following.
#include<stdio.h>
void main ()
{
char s[10];
printf("Enter the string? ");
fgets(s, 10, stdin);
printf("You entered %s",s);
}
Output
Enter the String ? Bishal patel
You entered Bishal pat
Writing/Printing a String in C
C puts() function

The puts() function is very much similar to printf() function. The puts() function is used
to print the string on the console which is previously read by using gets() or scanf()
function.

Declaration

puts(char_variable)

#include<stdio.h>
#include <string.h>
int main()
{
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}

Output
Enter the String ? hello!! My name is bishal
You entered hello!! My name is bishal
C String library Functions
There are many important string functions defined in "string.h" library.

Strlen()
#include<stdio.h>
#include<string.h>
int main()
{
int i=0;
char ch[10]={'b', 'i', 's', 'h', 'a', 'l', '\0'};
char ch2[10]="bishal";
printf("length of string : %d" ,strlen(ch)) ;
return 0;
}
Output
Length of string is : 6
strcpy()
#include<stdio.h>
#include<string.h>
int main()
{
int i=0;
char ch[10]={'b', 'i', 's', 'h', 'a', 'l', '\0'};
char ch2[10];
strcpy(ch2,ch1);
printf("string of ch2: %s",ch2) ;
return 0;
}

strcat()
#include<stdio.h>
#include<string.h>
int main()
{
int i=0;
char ch[10]={'b', 'i', 's', 'h', 'a', 'l', '\0'};
char ch2[10]= "patel";
strcat(ch,ch2);
printf("string of ch2: %s",ch) ;
return 0;
}

strcmp()
#include<stdio.h>
#include<string.h>
int main()
{
int i=0;
char ch[10]={'b', 'i', 's', 'h', 'a', 'l', '\0'};
char ch2[10]= "patel";
if(strcmp(ch,ch2)==0)
{
printf("Strings are equal");
}
else
{
printf("Strings are not equal");
}
return 0;
}

Rest of the function you do by youself.


And also you should do this function program without using the function.

Array of String
A string is a 1-D array of characters, so an array of strings is a 2-D array of characters. Just
like we can create a 2-D array of int, float etc; we can also create a 2-D array of character
or array of strings.
If we want more than one string at a time then we go for array of string.
Syntax of creating Array of String
Char array_name[size][length];

Declaration
Char name[4][10];

Initialization
Char name[4][10]={“bishal”,”arjun”,”ram”,”shyam”};

b i s h A l \0 \0 \0 \0

a r j u N \0 \0 \0 \0 \0

R a m \0 \0 \0 \0 \0 \0 \0
S h y a M \0 \0 \0 \0 \0

The above table shows some wastage of memory denoted by ‘\0’ null character. This is
not good for programming. To avoid this scenario we have an alternate solution
i.e pointer array.
Char *name[10]={“bishal”,”ram”,”arjun”,”shyam”,”rohan”};
Here no need to give size of string, we can use any number of string but each string has
a fixed length of 10.

Some invalid operation on Array String

char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};

#include<stdio.h>
int main()
{
char a[4][10]={"bishal","ram","arjun","shyam"};
int i;
for(i=0; i<4; i++)
{
printf("%s\t" ,a[i]);
}
return 0;
}
Output
bishal ram arjun shyam

#include<stdio.h>
int main()
{
char *a[10]={"bishal","ram","arjun","shyam"};
int i;
for(i=0;i<4;i++)
{
printf("%s\t" ,a[i]);
}
return 0;
}
Output
bishal ram arjun shyam

Taking input from the user


#include<stdio.h>
int main()
{
char a[10][10];
int i, n;
printf("Enter size of string we want \n");
scanf("%d" ,&n);
printf("Enter List of String\n");
for(i=0; i<n; i++)
{
scanf("%s" ,a[i]);
}
printf("List of Strings are\n");
for(i=0; i<n; i++)
{
printf("%s\t" ,a[i]);
}
return 0;
}
Output
Enter the size of a string we want
5
Enter List of String
Bishal Ram Shyam Arjun
List of the Strings are
Bishal Ram Shyam Arjun

You might also like