100% found this document useful (1 vote)
901 views30 pages

UNIT II Arrays and Strings

The document discusses arrays and functions in C programming. It covers: 1) Initialization, declaration, and accessing of one-dimensional arrays. Properties include elements being of the same type and stored at contiguous memory locations. 2) Declaration and initialization of two-dimensional arrays. Traversing 2D arrays with nested for loops. Examples of storing elements in a matrix and printing it. 3) Examples of sorting an array, finding the largest/second largest element, and matrix multiplication. 4) Brief introduction to strings as character arrays terminated by a null character.

Uploaded by

Sivasathiya G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (1 vote)
901 views30 pages

UNIT II Arrays and Strings

The document discusses arrays and functions in C programming. It covers: 1) Initialization, declaration, and accessing of one-dimensional arrays. Properties include elements being of the same type and stored at contiguous memory locations. 2) Declaration and initialization of two-dimensional arrays. Traversing 2D arrays with nested for loops. Examples of storing elements in a matrix and printing it. 3) Examples of sorting an array, finding the largest/second largest element, and matrix multiplication. 4) Brief introduction to strings as character arrays terminated by a null character.

Uploaded by

Sivasathiya G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 30

EASWARI ENGINEERING COLLEGE

(AUTONOMOUS)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND
DATA SCIENCE

191GES204T – PROGRAMMING IN C

Unit II –Notes

(Arrays and Functions in C)

PREPARED BY APPROVED BY

G.SIVASATHIYA, AP/AIADS HOD/AIADS


Arrays: Initialization – Declaration – Accessing the array elements – Operations on
array - One dimensional array - two dimensional arrays

Strings: String operations – String Arrays - Simple programs : sorting- searching–


matrix operations.

ARRAYS: INTRODUCTION

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.

It also has the capability to store the collection of derived data types, such as
pointers, structure, etc. The array is the simplest data structure where each data element
can be randomly accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different variables
for the marks in the different subject. Instead of that, we can define an array which can
store the marks in each subject at the contiguous memory locations.

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.

Properties of Array
 Each element of an array is of same data type and carries the same size
i.e., int = 4 bytes.
 Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
 Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of
the data element.

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 LinkedList which we will
learn later.

INITIALIZATION OF 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;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

DECLARATION OF C ARRAY

We can declare an array in the c language in the following way.

data_type array_name[array_size];

Now, let us see the example to declare the array.

int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

C array example
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}

Output

80
60
70
85
75

ACCESSING THE ARRAY ELEMENTS

We can access any array element using array name and subscript/index written
inside pair of square brackets [ ].

Example:

Suppose we have an integer array of length 5 whose name is marks.

int marks[5] = {5,2,9,1,1};

Now we can access elements of array marks using subscript followed by array name.

marks[0] = First element of array marks = 5


marks[1] = Second element of array marks = 2
marks[2] = Third element of array marks = 9
marks[3] = Fourth element of array marks = 1
marks[4] = Last element of array marks = 1

C Array: 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;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}

Output

20
30
40
50
60

C Array Example: Sorting an array

In the following program, we are using bubble sort method to sort the array in ascending
order.

#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}

Output

Printing Sorted Element List ...


101
78
44
34
23
23
12
10
9
7

Program to print the largest and second largest element of the array.
#include<stdio.h>
void main ()
{
int arr[100],i,n,largest,sec_largest;
printf("Enter the size of the array?");
scanf("%d",&n);
printf("Enter the elements of the array?");
for(i = 0; i<n; i++)
{
scanf("%d",&arr[i]);
}
largest = arr[0];
sec_largest = arr[1];
for(i=0;i<n;i++)
{
if(arr[i]>largest)
{
sec_largest = largest;
largest = arr[i];
}
else if (arr[i]>sec_largest && arr[i]!=largest)
{
sec_largest=arr[i];
}
}
printf("largest = %d, second largest = %d",largest,sec_largest);

Output

Enter the size of the array?4


Enter the elements of the array?24
15
42
67
largest = 67, second largest = 42

TWO DIMENSIONAL ARRAY IN C

The two-dimensional array can be defined as an array of arrays. The 2D array is


organized as matrices which can be represented as the collection of rows and columns.
However, 2D arrays are created to implement a relational database lookalike data
structure.

It provides ease of holding the bulk of data at once which can be passed to any
number of functions wherever required.

Declaration of two dimensional Array in C

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

data_type array_name[rows][columns];

Consider the following example.

int twodimen[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.


Initialization of 2D Array in C

initialization are being done simultaneously. However, this will not work with 2D
arrays. We will have to define at least the second dimension of the array. The two-
dimensional array can be declared and defined in the following way.

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Two-dimensional array example in C


#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

C 2D array example: Storing elements in a matrix and printing it.


#include <stdio.h>
void main ()
{
int arr[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",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}

Output

Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34
45 56 78

Matrix multiplication in C
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
Output:

enter the number of row=3


enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18

STRINGS:

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.

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.

 By char array
 By string literal

Let's see the example of declaring string by char array in C language.

char ch[ ]={'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};

As we know, array index starts from 0, so it will be represented as in the figure given
below.

0 1 2 3 4 5 6

w e l c o m e
While declaring string, size is not mandatory. So we can write the above code as given
below:

char ch[ ]={'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};

We can also define the string by the string literal in C language. For example:

char ch[ ]="welcome";

In such case, '\0' will be appended at the end of the string by the compiler.

Difference between char array and string literal

There are two main differences between char array and literal.

 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.
 The string literal cannot be reassigned to another set of characters whereas, we can
reassign the characters of the array.

String Example in C

Let's see a simple example where a string is declared and being printed. The '%s' is used as
a format specifier for the string in c language.

#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
char ch2[11]="welcome";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}

Output

Char Array Value is: welcome


String Literal Value is: welcome
STRING OPERATIONS

Traversing String

Traversing the string is one of the most important aspects in any of the
programming languages. We may need to manipulate a very large text which can be done
by traversing the text.

Traversing string is somewhat different from the traversing an integer array. We


need to know the length of the array to traverse an integer array, whereas we may use the
null character in the case of string to identify the end the string and terminate the loop.

Let's see an example of counting the number of vowels in a string.

#include<stdio.h>
void main ()
{
char s[11] = "welcome";
int i = 0;
int count = 0;
while(i<11)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}

Output

The number of vowels 3

C String Functions

There are many important string functions defined in "string.h" library.


No. Function Description

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, copies the contents of source string to destination string.


source)

3) strcat(first_string, concats or joins first string with second string. The result of
second_string) the string is stored in first string.

4) strcmp(first_string, compares the first string with second string. If both strings are
second_string) same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

C String Length: strlen() function

The strlen() function returns the length of the given string. It doesn't count null character
'\0'.

#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'h', 'e', 'l', 'l', 'o', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}

Output:

Length of string is: 5

C Copy String: strcpy()

The strcpy(destination, source) function copies the source string in destination.

#include<stdio.h>
#include <string.h>
int main( ){
char ch[20]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}

Output:

Value of second string is: hello

C String Concatenation: strcat()

The strcat(first_string, second_string) function concatenates two strings and result is


returned to first_string.

#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}

Output:

Value of first string is: helloc

C Compare String: strcmp()

The strcmp(first_string, second_string) function compares two string and returns 0 if both
strings are equal.

Here, we are using gets() function which reads string from the console.

#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}

Output:

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal

C Reverse String: strrev()

The strrev(string) function returns reverse of the given string. Let's see a simple example of
strrev() function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}

Output:

Enter string: hello


String is: hello
Reverse String is: olleh
C String Lowercase: strlwr()

The strlwr(string) function returns string characters in lowercase. Let's see a simple
example of strlwr() function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}

Output:

Enter string: HELLOstudent


String is: HELLOstudent
Lower String is: hellostudent

C String Uppercase: strupr()

The strupr(string) function returns string characters in uppercase. Let's see a simple
example of strupr() function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
Output:

Enter string: hellostudent


String is: hellostudent
Upper String is: HELLOSTUDENT

C String strstr()

The strstr() function returns pointer to the first occurrence of the matched string in the
given string. It is used to return substring from first match till the last character.

Syntax:

char *strstr(const char *string, const char *match)

String strstr() parameters

string: It represents the full string from where substring will be searched.

match: It represents the substring to be searched in the full string.

String strstr() example


#include<stdio.h>
#include <string.h>
int main(){
char str[100]="this is a c program";
char *sub;
sub=strstr(str,"is");
printf("\nSubstring is: %s",sub);
return 0;
}

Output:

is a c program
STRING ARRAYS

In C programming String is a 1-D array of characters and is defined as an array of


characters. But an array of strings in C is a two-dimensional array of character types.
Each String is terminated with a null character (\0). It is an application of a 2d array.
Syntax:
char variable_name[r] = {list of string};

Here,
var_name is the name of the variable in C.
r is the maximum number of string values that can be stored in a string array.
c is a maximum number of character values that can be stored in each string array.

Example – 1

#include <stdio.h>

// Driver code
int main()
{
char arr[3][10] = {"Hel", "Hello", "Hellostudents"};
printf("String array Elements are:\n");

for (int i = 0; i < 3; i++)


{
printf("%s\n", arr[i]);
}
return 0;
}

Output:

String array Elements are:


Hel
Hello
Hellostudents

In C, a Character and a String are separate data types, unlike other programming
languages like Python. A String is a collection of Characters. Hence, to define a String, we
use a Character Array:

#include<stdio.h>
int main()
{
char str[8];
printf("Enter a String: ");
scanf("%s", &str);
printf("%s", str);
}

Output:

Enter a String: Hello


Hello

Example – 2
#include<stdio.h>
int main()
{
int i;
char Array[3][6] = {"Black", "Blame", "Block"};
printf("String Array: \n");
for(i = 0; i < 3; i++)
{
printf("%s\n", Array[i]);
}
return 0;
}

Output:

String Array:
Black
Blame
Block

Example – 3

#include<stdio.h>
int main()
{
int i;
char Array[3][6] = {"Black", "Blame", "Block"};
strcpy(Array[0], "Hello");
for(i = 0; i < 3; i++)
{
printf("%s\n", Array[i]);
}

Output:

String Array:
Hello
Blame
Block

SORTING- SEARCHING–MATRIX OPERATIONS.

Implementation of Insertion sort

#include <stdio.h>

void insert(int a[], int n) /* function to sort an aay with insertion sort */
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;

while(j>=0 && temp <= a[j])


/* Move the elements greater than temp to one position ahead from their current position*/
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}

Output:

Implementation of Bubble sort

#include <stdio.h>
int main(){
int arr[50], num, x, y, temp;
printf("Please Enter the Number of Elements you want in the array: ");
scanf("%d", &num);
printf("Please Enter the Value of Elements: ");
for(x = 0; x < num; x++)
scanf("%d", &arr[x]);
for(x = 0; x < num - 1; x++){
for(y = 0; y < num - x - 1; y++){
if(arr[y] > arr[y + 1]){
temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
printf("Array after implementing bubble sort: ");
for(x = 0; x < num; x++)
{
printf("%d ", arr[x]);
}
return 0; }
Output:

Implementing Linear Search in C

#include <stdio.h>
void main()
{
int num;
int i, key, element_found = 0;
printf("Enter number of elements you would like to take as input: ");
scanf("%d", &num);
int arr[num];
printf("\nEnter all the elements of your choice:");
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
printf("\nEnter the key element that you would like to be searched: ");
scanf("%d", &key);
/* Linear search starts */
for (i = 0; i < num ; i++)
{
if (key == arr[i] )
{
element_found = 1;
break;
}
}
if (element_found == 1)
printf("we got the element at index %d",i+1);
else
printf("we haven’t got element at any index in the array\n");
}

Output:
Implementing Binary Search in C
To find the Transpose of a Matrix

#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);

// asssigning elements to the matrix


printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

// printing the matrix a[][]


printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}

// computing the transpose


for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}

// printing the transpose


printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}

Output

Enter rows and columns: 2


3

Enter matrix elements:


Enter element a11: 1
Enter element a12: 4
Enter element a13: 0
Enter element a21: -5
Enter element a22: 2
Enter element a23: 7

Entered matrix:
1 4 0
-5 2 7

Transpose of the matrix:


1 -5
4 2
0 7

To Find the Mean , Median and Mode using C

include<stdio.h>
int main()
{
int a[2500], n, i, t, j, max=0, c=0, mode=0;
float s=0, mean, median;
printf(“Enter how many data you want to input: “);
scanf(“%d”,&n);
printf(“Enter %d Data:\n”, n);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
s+=a[i];
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
// to find mean
mean = s/(float)n;
printf(“mean or average is: %.1f\n”,mean);
//to find median
if(n%2==0)
median=( (a[(n-1)/2] + a[(n-1)/2+1] ) / 2.0);
else
median=( (a[(n-1)/2]) / 2.0);
printf(“median is: %.1f\n”, median);
//to find mode
for(i=0; i<n; i++)
{
t=a[i];
c=0;
for(j=0; j<n; j++) { if(t==a[j]) c++; if(c>max)
{
max=c;
mode=t;
}
}
}
printf(“mode is %d”,mode);
return 0;
}

Output

Enter how many data you want to input:4


Enter 4 Data:
10
10
10
20
mean or average is: 12.5
median is: 10.0
mode is 10

You might also like