[go: up one dir, main page]

0% found this document useful (0 votes)
10 views17 pages

Unit Ii

This document provides an overview of arrays and strings in C programming, covering topics such as declaration, initialization, and operations on one-dimensional and two-dimensional arrays. It includes example programs for computing mean, median, and mode, as well as matrix operations. Key concepts such as array indexing, out-of-bounds access, and initialization are also discussed.

Uploaded by

thirunavukkarasu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views17 pages

Unit Ii

This document provides an overview of arrays and strings in C programming, covering topics such as declaration, initialization, and operations on one-dimensional and two-dimensional arrays. It includes example programs for computing mean, median, and mode, as well as matrix operations. Key concepts such as array indexing, out-of-bounds access, and initialization are also discussed.

Uploaded by

thirunavukkarasu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CS8251 Dept of CSE Programming in C

UNIT - II
ARRAYS AND STRINGS Introduction to Arrays: Declaration, Initialization – One
dimensional array – Example Program: Computing Mean, Median and Mode - Two
dimensional arrays – Example Program: Matrix Operations (Addition, Scaling,
Determinant and Transpose) - String operations: length, compare, concatenate, copy –
Selection sort, linear and binary search
2.1 Introduction to Arrays
An array is a collection of data that holds fixed number of values of same type. For
example: if you want to store marks of 100 students, you can create an array for it.

float marks[100];

The size and type of arrays cannot be changed after its declaration.
2.1.1 Declaration
How to declare an array in C?

data_type array_name[array_size];

For example,

float mark[5];

Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can
hold 5 floating-point values.
Elements of an Array and How to access them?
You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element is mark[0], second
element is mark[1] and so on.

Few key notes:


 Arrays have 0 as the first index not 1. In this example, mark[0]
 If the size of an array is n, to access the last element, (n-1)index is used. In this
example, mark[4]
 Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1],
will be 2124d, address of a[2] will be 2128d and so on. It's because the size of a
float is 4 bytes.
2.1.2 Initialization
How to initialize an array in C programming?
It's possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

TPGIT/CSE 1
CS8251 Dept of CSE Programming in C

int mark[] = {19, 10, 8, 17, 9};

Here,

mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9

How to insert and print array elements?

int mark[5] = {19, 10, 8, 17, 9}

// insert different value to third element


mark[3] = 9;

// take input from the user and insert in third element


scanf("%d", &mark[2]);

// take input from the user and insert in (i+1)th element


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

// print first element of an array


printf("%d", mark[0]);

// print ith element of an array


printf("%d", mark[i-1]);

Example: C Arrays
// Program to find the average of n (n < 10) numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);

TPGIT/CSE 2
CS8251 Dept of CSE Programming in C
sum += marks[i];
}
average = sum/n;

printf("Average = %d", average);

return 0;
}
Output

Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

Important thing to remember when working with C arrays


Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can use the array members from testArray[0] to testArray[9].


If you try to access array elements outside of its bound, let's say testArray[12], the
compiler may not show any error. However, this may cause unexpected output
(undefined behavior).
2.2 One dimensional array in c programming language :
ID array
The declaration form of one dimensional array is
Data_type array_name [size];
The following declares an array called ‘numbers’ to hold 5 integers and sets the first and
last elements. C arrays are always indexed from 0. So the first integer in ‘numbers’ array
is numbers[0] and the last is numbers[4].
int numbers [5];
numbers [0] = 1; // set first element
numbers [4] = 5; // set last element
This array contains 5 elements. Any one of these elements may be referred to by giving
the name of the array followed by the position number of the particular element in
square brackets ([]). The first element in every array is the zeroth element.Thus, the first
element of array ‘numbers’is referred to asnumbers[ 0 ], the second element of array
‘numbers’is referred to as numbers[ 1 ], the fifth element of array ‘numbers’is referred
to as numbers[ 4 ], and, in general, the n-th element of array ‘numbers’is referred to as
numbers[ n – 1 ].
Example:
1 #include<stdio.h>
2 #include<conio.h>
3 int main()

TPGIT/CSE 3
CS8251 Dept of CSE Programming in C
4 {
5 int i,number[5];
6 clrscr();
7 printf(“Enter 5 number \n”);
8 for(i=0;i<5;i++)
9 scanf(“%d”,&numbers[i]);
10 printf(“Array elements are \n”);
11 for(i=0;i<5;i++)
12 printf(“%d\n”,numbers[i]);
13 getch();
14 return 0;
15 }
Output :
4
6
7
3
2
Array elements are
4
6
7
3
2
It’s a very common error to try to refer to non-existent numbers[ 5], element. C does not
do much hand holding. It is invariably up to the programmer to make sure that
programs are free from errors. This is especially true with arrays. C does not complain if
you try to write to elements of an array which do not exist!
For example: If you wrote:
numbers[ 5 ], = 6;
C would happily try to write 6 at the location which would have corresponded to the
sixth element, had it been declared that way. Unfortunately this would probably be
memory taken up by some other variable or perhaps even by the operating system. The
result would be either:
 The value in the incorrect memory location would be corrupted with
unpredictable consequences.
 The value would corrupt the memory and crash the program completely!
The second of these tends to be the result on operating systems with proper memory
protection. Writing over the bounds of an array is a common source of error. Remember
that the array limits run from zero to the size of the array minus one.
Out of bounds access :
I would be doing well, that really shows the range of valid indices, please check often.
10 When the number of elements, all the indices of 10 or more is illegal. Also, whether
any size of negative indices is also illegal.
These errors are detected at compile time is not. It is an error at run time. However,
there is no guarantee that the error reliably. Sometimes works correctly (seems to be
moving.) This is the “luck ran” instead of “bad luck worked” so, please, as no doubt.

TPGIT/CSE 4
CS8251 Dept of CSE Programming in C
The best way to see these principles is by use of an example, so load the program and
display it on your monitor.
The elements of an array can also be initialized in the array declaration by following the
declaration with an equal sign and a comma-separated list (enclosed in braces)
of initializers.
Example:
1 #include <stdio.h>
2 #include <conio.h>
3 int main( )
4{
5 char name[7]; /* define a string of characters */
6 name[0] = 'A';
7 name[1] = 's';
8 name[2] = 'h';
9 name[3] = 'r';
10 name[4] = 'a';
11 name[5] = 'f';
12 name[6] = '\0'; /* Null character - end of text */
13 name[7] = ‘X’;
14 clrscr();
15 printf("My name is %s\n",name);
16 printf("First letter is %c\n",name[0]);
17 printf("Fifth letter is %c\n",name[4]);
18 printf("Sixth letter is %c\n",name[5]);
19 printf("Seventh letter is %c\n",name[6]);
20 printf("Eight letter is %c\n",name[7]);
21 getch();
22 return 0;
23 }
The following program initializes an integer array with five values and prints the array.
1 #include <stdio.h>
2 #include <conio.h>
3 int main()
4{
5 int numbers[]={1,2,3,4,5};
6 int i;
7 clrscr();
8 printf("Array elements are\n");
9 for(i=0;i<=4;i++)
10 printf("%d\n",numbers[i]);
11 getch();
12 return 0;
13 }
If there are fewer initializers than elements in the array, the remaining elements are
initialized to zero. For example, the elements of the array n could have been initialized
to zero with the declaration
int n[ 10 ] = { 0 };
which explicitly initializes the first element to zero and initializes the remaining nine

TPGIT/CSE 5
CS8251 Dept of CSE Programming in C
elements to zero because there are fewer initializers than there are elements in the array.
It is important to remember that arrays are not automatically initialized to zero. The
programmer must at least initialize the first element to zero for the remaining elements
to be automatically zeroed. This method of initializing the array elements to 0 is
performed at compile time for static arrays and at run time for automatic arrays.
2.3: Example
Computing mean, median and mode
What is mean ?
Mean is same as average. The mean is found by adding up all of the given data
and dividing by the number of elements.
Example: Mean of 1,2,3,4,5 is
(1+2+3+4+5 )/5 = 15/3 = 3
What is Median ?
The median is the middle number in an ordered list (ascending or descending). First
you arrange the numbers in orders in ascending order, then you find the middle
number and save it as median
Example:
12345
Median is 3

What is Mode ?
Mode is the element which happens most number of time in the list. If no element
happens more than once, all elements are considered as mode.

Algorithm
1. Start
2. Declare an array a[20], sum =0,i=0,j=0,z=0
3. Read number of terms n
4. Repeat step 5 & 6 while (i<n)
5. sum=sum+a[i]
6. next i
7. mean=sum/n
8. if(n%2=0)
median=(a[n/2]+a[n/2-1])/2
else
median=a[n/2]
9. print mean and median
10. repeat step 11 & 12 when i=0 to n, j=0 to i
11. if a[i]=a[j], then b[i]++
12. if b[i]>z, then z=b[i]
13. For i=0 to n if b[i]=z, print b[i]
14. end
Program:
#include <stdio.h>
main()
{ int i,j,x,k=0,n,a[20],z=0,b[20];
float sum=0, t,mean,medn,mod;
printf(“\n Enter the no. of elements (Max 20)\n”);

TPGIT/CSE 6
CS8251 Dept of CSE Programming in C
scanf(“%d”,&n);
printf(“Enter the elements\n”);
for(i=0;i
{scan (“%d”,&a[i]);}
for(i=0;i
{sum=sum+a[i];}
printf(“Sum: %f”,sum);
mean=sum/n;
}
for(i=0;i
{ for (j=i+1;j
{ if (a[i]>a[j])
{ t=a[i];a[i]=a[j];a[j]=t; }
}
}
if (n%2==0)
medn=(a[n/2]+a[(n/2)-1])/2;
else
medn=a[n/2];
for(i=0;i
{ for ( j=0; j<i; j++ )
{ if (a[i]==a[j])
b[i]++;
}
}
for(i=0;i<n;i++)
{ if (b[i]>z)
z=b[i];
}
printf(“Mean :%f \n Median : %f \n Mean : “, mean, medn);
for I i=0; i<n; i++)
{ if (b[i]==z)
printf(“%d\t”, a[i]);
}
}

2.4 Dimensional Array


 Two-dimensional array are those type of array, which has finite number of rows
and finite number of columns. The declaration form of 2-dimensional array is
Data_type Array_name [row size][column size];
 The type may be any valid type supported by C.
 The rule for giving the array name is same as the ordinary variable.
 The row size and column size should be an individual constant.
The following declares a two-dimensional 3 by 3 array of integers and sets the first and
last elements to be 10.
int matrix [3][3];
matrix[0][0] = 10;
matrix[2][2] = 10;

TPGIT/CSE 7
CS8251 Dept of CSE Programming in C
The following Figure illustrates a two dimensional array, matrix. The array contains
three rows and tree columns, so it is said to be a 3-by-3 array. In general, an array
with m rows and n columns is called an m-by-n array.
[0] [1] [2]
[0] 10
[1]
[2] 10
Every element in array matrix is identified by an element name of the form matrix[ i ][ j
]; matrix is the name of the array, and i and j are the subscripts that uniquely identify
each element in matrix . Notice that the names of the elements in the first row all have a
first subscript of 0; the names of the elements in the third column all have a second
subscript of 2.
In the case of Two-dimensional array, during declaration the maximum number of rows
and maximum number of column should be specified for processing all array elements.
The implementation of the array stores all the elements in a single contiguous block of
memory. The other possible implementation would be a combination of several distinct
one-dimensional arrays. That’s not how C does it. In memory, the array is arranged
with the elements of the rightmost index next to each other. In other words, matrix[1][1]
comes right before matrix[1][2] in memory.
The following array:
[0] [1] [2]
[0] 1 2 3
[1] 4 5 6
[2] 7 8 9
would be stored:
123456789
EXAMPLE :
1 #include<stdio.h>
2 #include<conio.h>
3 int main()
4{
5 int matrix [3][3],i,j,r,c;
6 clrscr();
7 printf(“Enter the order of matrix\n”);
8 scanf(“%d%d”,&r,&c);
9 printf(“Enter elements of %d * %d matrix \n”,r,c);
10 for(i=0;i<r;i++)
11 for(j=0;j<c;j++)
12 scanf(“%d”,&matrix[i][j]);
13 printf(“Given matrix:\n”);
14 for(i=0;i<r;i++)
15 {
16 for(j=0;j<c;j++)
17 printf(“%d\t”,matrix[i][j]);
18 printf(“\n”);
19 }
20 printf(“%d\t”,matrix[2][2]);

TPGIT/CSE 8
CS8251 Dept of CSE Programming in C
21 getch();
22 return 0;
23 }
Output :
Enter the order of matrix
2
2
Enter elements of 2*2 matrix
1
2
3
4
Given matrix :
1 2
3 4
2.5 Example
Matrix Operations (Addition, Scaling, Determinant and Transpose)
/* Write a Program to implement the following operations on the matrices :
1. Addition
2. Subtraction
3. Multiplication
4. Transpose */

#include<stdio.h>
#include<conio.h>
int main()
{
int m,n,a[20][20],b[20][20],i,j,sum[20][20],sub[20][20],opt,tr[20][20],opt1,ch,e,f;
printf("Note : For Addition or Subtraction , no. of rows and columns should be same
and for transpose of matrices , your first matrices entered should be the desired
matrices .\n");
printf("Enter the no. of rows: ");
scanf("%d",&m);
printf("Enter the no. of columns: ");
scanf("%d",&n);
printf("Enter the Data Elements of first matrices\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
} printf("Enter the no. of rows for second matrices: ");
scanf("%d",&e);
printf("Enter the no. of columns: ");
scanf("%d",&f);
printf("Enter the Data Elements of second matrices\n");

TPGIT/CSE 9
CS8251 Common to CSE & IT Programming in C
for(i=0;i<e;i++)
{
for(j=0;j<f;j++)
{
scanf("%d",&b[i][j]);
}
}
do
{
if(m==e&&n==f)
{
printf("Enter 1 for addtion or subtraction of matrices\n");
if(n==e){printf("Enter 2 for multiplication of matrices\n");}
printf("Enter 3 for transpose of first matrices\n");
}
else if(m!=n&&n==e)
{
printf("Enter 2 for multiplication of matrices\n");
printf("Enter 3 for transpose of first matrices\n");
}
else
{
printf("Enter 3 for transpose of first matrices\n");
}
scanf("%d",&ch);
switch(ch)
{
case 1 :
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sum[i][j]=a[i][j]+b[i][j];
sub[i][j]=a[i][j]-b[i][j];
}
}
printf("Enter 1 for Addition or 2 for Subtraction: ");
scanf("%d",&opt);
switch(opt)
{
case 1 :
printf("The resultant matrices is :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",sum[i][j]);
}

St.Joseph’s College of Engineering/St. Joseph’s Institute of Technology


10
CS8251 Common to CSE & IT Programming in C
printf("\n");
}
break;
case 2 :
printf("The resultant matrices is :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",sub[i][j]);
}
printf("\n");
}
}
break;
case 2 :
printf("The resultant matrices is : \n");
int k;
for(i=0;i<m;i++)
{
for(j=0;j<f;j++)
{ sum[i][j]=0;
for(k=0;k<m;k++)
{
sum[i][j]+=a[i][k]*b[k][j];
}
printf("%d\t",sum[i][j]);
}
printf("\n");
}
break;
case 3 :
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
tr[j][i]=a[i][j];
}
}
printf("The resultant matrices is :\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%3d",tr[i][j]);
}
printf("\n");
}

St.Joseph’s College of Engineering/St. Joseph’s Institute of Technology


11
CS8251 Common to CSE & IT Programming in C

break; }}
while(ch>0);
getch();
}

2.6 Strings Operation

Strings are actually one-dimensional array of characters terminated by a null character


'\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. Let us try to print the above mentioned string −
#include <stdio.h>

int main () {

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


printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings −
Sr.No. Function & Purpose

St.Joseph’s College of Engineering/St. Joseph’s Institute of Technology


12
CS8251 Common to CSE & IT Programming in C
1 strcpy(s1, s2);
Copies string s2 into string s1.

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
greater than 0 if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in
string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in
string s1.
The following example uses some of the above-mentioned functions −
#include <stdio.h>
#include <string.h>

int main () {

char str1[12] = "Hello";


char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */len


= strlen(str1);
printf("strlen(str1) : %d\n", len );

return 0;
}
When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello

St.Joseph’s College of Engineering/St. Joseph’s Institute of Technology


13
CS8251 Common to CSE & IT Programming in C
strcat( str1, str2): HelloWorld
strlen(str1) : 10

2.7 Selection Sort


The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The
algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)from
the unsorted subarray is picked and moved to the sorted subarray.
Following example explains the above steps:arr[]
= 64 25 12 22 11

// Find the minimum element in arr[0...4]


// and place it at beginning
11 25 12 22 64

// Find the minimum element in arr[1...4]


// and place it at beginning of arr[1...4]11
12 25 22 64

// Find the minimum element in arr[2...4]


// and place it at beginning of arr[2...4]11
12 22 25 64

// Find the minimum element in arr[3...4]


// and place it at beginning of arr[3...4]11
12 22 25 64

// C program for implementation of selection sort


#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarrayfor


(i = 0; i < n-1; i++)

St.Joseph’s College of Engineering/St. Joseph’s Institute of Technology


14
CS8251 Common to CSE & IT Programming in C
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Run on IDE

Output:
Sorted array:
11 12 22 25 64
Time Complexity: O(n2) as there are two nested loops.
AuxiliarySpace: O(1)
The good thing about selection sort is it never makes more than O(n) swaps and can be
useful when memory write is a costly operation.
2.8 Binary Search
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");

St.Joseph’s College of Engineering/St. Joseph’s Institute of Technology


15
CS8251 Common to CSE & IT Programming in C
scanf("%d",&n);

printf("Enter %d integers\n", n);

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


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

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {


if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);

return 0;
}
Output of program:

2.9 Linear Search


#include <stdio.h>

int main()
{
int array[100], search, c, n;

St.Joseph’s College of Engineering/St. Joseph’s Institute of Technology


16
CS8251 Common to CSE & IT Programming in C
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 the number to search\n");


scanf("%d", &search);

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


{
if (array[c] == search) /* if required element found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d is not present in array.\n", search);

return 0;
}
Output of program:

St.Joseph’s College of Engineering/St. Joseph’s Institute of Technology


17

You might also like