Uploaded by Selvarathinam69

unit 3 notes

advertisement
Introduction to programming inC
UNIT -3 ARRAYS AND STRINGS
One Dimensional Array
A one-dimensional array in C programming is a collection of
elements of the same data type arranged in a linear sequence. You
can think of it as a list of values stored under a single variable name.
Each element in the array is accessed by its index, starting from 0 for
the first element.
Here's how you can declare, initialize, and work with a onedimensional array in C:
1. Declaration and Initialization:
In C, you declare a one-dimensional array using the following syntax:
data_type array_name[array_size];
data_type is the data type of elements you want to store in the
array.
array_name is the name you give to your array.
array_size is the number of elements the array can hold.
You can initialize an array during declaration or separately after
declaration. If you initialize it during declaration, you can provide a
list of values enclosed in curly braces {}.
int numbers[5]; // Declaration of an integer array with size 5 int
numbers[5] = {1, 2, 3, 4, 5}; // Declaration and initialization in one
step int numbers[] = {1, 2, 3, 4, 5}; // Declaration with initialization
(size is inferred)
2. Accessing Elements:
You access elements of an array using their indices. Array indices
start from 0 for the first element and go up to array_size - 1 for the
last element.
int value = numbers[2]; // Access the third element (index 2) and
store it in 'value'
3. Array Elements:
Arrays can store elements of any data type, including integers,
floating-point numbers, characters, and even custom data types
(structures). For example:
float prices[10]; // Array of floating-point numbers char
characters[5]; // Array of characters struct Point points[100]; //
Array of custom data type (structures)
4. Array Size:
The size of an array (i.e., the number of elements it can hold) is fixed
at the time of declaration and cannot be changed during the
program's execution. You can determine the size of an array using
the sizeof operator.
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size
of the array
5. Looping Through an Array:
You can use loops, such as for or while, to iterate through the
elements of an array.
for (int i = 0; i < size; i++) { // Access and work with numbers[i] }
6. Common Operations:
Summing all elements of an array.
Finding the maximum or minimum element.
Searching for a specific element.
Sorting the elements.
Modifying elements in the array.
7. Array Indexing:
Remember that array indices are zero-based. This means the first
element is accessed with index 0, the second element with index 1,
and so on.
8. Memory Allocation:
Arrays allocate contiguous memory locations to store their
elements. The elements are stored next to each other in memory.
9. Strings as 1D Arrays:
In C, strings are often represented as one-dimensional character
arrays. For example:
char greeting[] = "Hello, World!";
10. Arrays and Pointers:
In C, arrays are closely related to pointers. The name of an array can
be used as a pointer to the first element of the array.
These are some fundamental aspects of one-dimensional arrays in C
programming. Arrays are a powerful tool for storing and
manipulating collections of data in a program.
Two Dimensional Array
 Two dimensional arrays are known as matrix.
 The array declaration in two dimensional arrays as two subscripts
to identifies the size of the array.
 Syntax :
Data-type array name [row][column];
 Total no of elements in 2-D array is calculated as row*column
 Example:int a[2][3]
Total no of elements=row*column
2*3 =6
It means the matrix consist of 2 rows and 3 columns For example:20 2 7
8
3 15
Positions of 2-D array elements in an array are as below
00 01 02
10 11 12
a[0][0] a [0][0]
a [0][0]
a [0][0]
a [0][0]
a [0][0]
20
2
7
8
3
15
 Initialization of 2-d array:
• 2-D array can be initialized in a way similar to that of 1-D array.
• for example:int mat[4][3]={11,12,13,14,15,16,17,18,19,20,21,22};
These values are assigned to the elements row wise, so the values
of elements after this initialization are
Mat[0][0]=11, Mat[1][0]=14, Mat[2][0]=17 Mat[3][0]=20
Mat[0][1]=12, Mat[1][1]=15, Mat[2][1]=18 Mat[3][1]=21
Mat[0][2]=13,
Mat[1][2]=16,
Mat[2][2]=19 Mat[3][2]=22
• While initializing we can group the elements row wise using inner
braces.
• for example:Intmat[4][3]={{11,12,13},{14,15,16},{17,18,19},{20,21,22}};
Example program for 2D array:
# include<stdio.h>
Int main()
{
i=0,j=o;
Int a[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}
For(i=0;i<4;i++)
{
For(j=0;j<3;j++)
{
Printf(“a[%d][%d]=%d\n”,i,j,a[i][j]);
}
}
Return 0;
}
Output:
A[0][0]=1
A[0][1]=1
A[0][2]=1
A[1][0]=1
A[1][1]=1
A[1][2]=1
A[2][0]=1
A[2][1]=1
A[2][2]=1
A[3][0]=1
A[3][1]=1
A[3][2]=1
2.MULTIDIMENSIONAL ARRAY
• it allows arrays of three or more dimensions
• The exact limit is determined bythe compiler.
• Syntax:
type array_name[s1][s2][s3]…s[m];
• Eg:
1. int survey[3][5][12];
2. float table[5][4][5][3];
3.STRINGS
• String Array of character is called a string.
• It is always terminated by the NULL character.
• String is a one dimensional array of character
• Initialize the string
• String can be initialize by two methods
• Method-1:
char string name[size];
char name[]={‘j’,’o’,’h’,’n’,’\o’};
• Here each character occupies 1 byte of memory
• last character is always NULL character.
• Where ’\o’ and 0 (zero) are not same,
o ASCII value of ‘\o’ is 0
o ASCII value of 0 is 48.
• Array elements of character array are also stored in contiguous
memory allocation.
J
O
H
N
• terminating NULL is important -string end.
• Method-2 :
• String can also be initialized as;
char name[]=”John”;
• Here the NULL character is not necessary and the compiler will
assume it automatically
• Operations on strings
• The operations that are performed on character strings are
1. Reading and writing strings.
2. Combining strings together.
3. Copying one string to another.
4. Comparing strings for equality.
5. Extracting a portion of a string.
Reading Words
• The familiar input function scanf can be used with %s format
specification to read in a string of characters.
• Eg:
char address[15];
scanf(“%s”,address);
‘\0’
# include <stdio.h>
main()
{
char word1[40],word2[40],word3[40],word4[40];
printf(“Enter text:\n”);
scanf(“%s %s”,word1, word2);
scanf(“%s%s”, word3,word4);
printf(“\n”);
printf(“word1 = %s \n word2 = %s \n”,word1, word2);
printf(“word3 = %s \n word4 = %s \n”,word3, word4);
}
OUTPUT
Enter text: Oxford Road, London M17ED
Word1 = Oxford
Word2 = Road
Word3 = London
Word4 = M17ED
Note: Scanf function terminates its input on the first white space it
finds.
Reading a Line of Text
• It is not possible to use scanf function to read a line containing
more than one word.
• This is because the scanf terminates reading as soon as a space is
encountered in the input.
• We can use the getchar function repeatedly to read single character
from the terminal, using the function getchar.
• Thus an entire line of text can be read and stored in an array.
• Example:
#include<stdio.h>
main()
{
char line[81],character; int c; c= 0; printf(“Enter text. Pressat end \n”);
do
{
character = getchar();
line[c] = character;
c++;
}
while(character != ‘\n’);
c = c-1;
line[c] = ‘\0’;
printf(“\n %s \n”,line);
}
OUTPUT
Enter text. Press at end
Programming in C is interesting
Programming in C is interesting
WRITING STRINGS
• WRITING STRINGS TO SCREEN We have used extensively the
printf function with %s format to print strings to the screen.
• The format %s can be used to display an array of characters that is
terminated by the null character.
•
For eg, the statement
printf(“%s”, name);
can be used to display the entire contents of the array name.
STRING - HANDLING FUNCTIONS
C library supports a large number of string- handling functions that can
be used to carry out many of the string manipulation activities.
Function
strcat( )
strcmp( )
strcpy( )
strlen( )
Action
Concatenates two strings
Compares two strings
Copies one string overanother
Finds the length of the string
strcat( ) Function
• The strcat function joins two strings together.
• syntax
Strcat( string1,string2);
• Eg:
strcat(part1, “GOOD”);
strcat(strcat(string1,string2),string3);
Here three strings are concatenated and the result is stored in string1
strcmp( ) Function
• It is used to compare two strings identified by the arguments and
has a value 0 if theyare equal.
• Syntax
strcmp(string1,string2);
• Eg: 1) strcmp(name1,name2);
2) strcmp(name1,”john”;
3) strcmp(“ram”, “rom”);
strcpy( ) Function
• This function works almost like a string assignment operator.
• Syntax
strcpy(string1,string2);
• This assigns the content of string2 to string1.
• Eg: 1) strcpy(city, “DELHI”);
2) strcpy(city1,city2);
strlen( ) Function
• This function counts and returns the number of characters in a
string.
• Syntax
n= strlen(string);
Example for string handling function:
#include <stdio.h>
main()
{ char s1[20],s2[20],s3[20];
int x, l1, l2, l3;
printf(“Enter two string constants \n”);
printf(“?”);
scanf(“%s %s”, s1, s2);
x= strcmp(s1, s2);
if(x != 0)
printf(“Strings are not equal \n”);
strcat(s1, s2);
else
printf(“Strings are equal \n”);
strcpy(s3,s1);
l1 = strlen(s1);
l2 = strlen(s2);
l3 = strlen(s3);
printf(“\ns1 = %s \t length = %d characters \n”,s1, l1);
printf(“\ns2= %s \t length = %d characters \n”,s2, l2);
printf(“\ns3 = %s \t length = %d characters \n”,s3, l3);
}
OUTPUT
Enter two string constants
? New York
Strings are not equal
s1 = New York
length = 7 characters
s2 = York
length = 4 characters
s3 = New York
length = 7 characters
Enter two string constants ?
London London
Strings are equal
s1 = London
length = 6 characters
s2 = London
length = 6 characters
s3 = London
length= 6character
4.SORTING
• Sorting is the process of arranging elements either in ascending
(or) descending order
• The best example of sorting can be phone numbers in our phones.
If, they are not maintained in an alphabetical order we would not
be able to search any number effectively.
• Many methods are used for sorting, such as:
1. Bubble sort
2. Selection sort
3. Insertion sort
4. Quick sort
5. Merge sort
6. Heap sort
7. Radix sort
8. Shell sort
• Selection Sort• Selection sort is one of the easiest approaches to sorting.
• It is inspired from the way in which we sort things out in day to
day life.
• Selection sort works as1. It finds the first smallest element (2).
2. It swaps it with the first element of the unordered list.
3. It finds the second smallest element (5).
4. It swaps it with the second element of the unordered list.
5. Similarly, it continues to sort the given elements
 Selection Sort ExampleConsider the following elements are to be sorted in ascending
order6, 2, 11, 7, 5
• The above selection sort algorithm works as illustrated below• Step-01: For i = 0
6
2
11
7
5
• We start here and find the minimum element and swap it with 1st
term of the element
• Step-03: For i = 2
2
6
11
7
5
• We start here and find the minimum element and swap it with 2 nd
term of the element
• Step-03: For i = 2
2
5
11
7
6
• We start here and find the minimum element and swap it with 3 rd
term of the element
• Step-04: For i = 3
2
5
6
7
11
• We start here and find the minimum element and swap it with 4th
term of the element
• Step-05: For i =4
2
5
6
Sorted array
Example:
#include <stdio.h>
int main()
{
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, swap;
7
11
for (i = 0; i < (n - 1); i++)
{
position = i;
for (j = i + 1; j < n; j++)
{
if (arr[position] > arr[j])
position = j;
}
if (position != i)
{
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0;
}
Output
0 2 6 11 12 18 34 45 55 99
Insertion sort
• In insertion sort the element is inserted at an appropriate place
similar to card insertion.
•
Here the list is divided into two parts sorted and unsorted sub-lists.
In each pass, the first element of unsorted sub list is picked up and
moved into the sorted sub list by inserting it in suitable position.
Suppose we have ‘n’ elements, we need n-1 passes to sort the
elements.
• Insertion sort works this way:
122, 17, 93, 3, 36
Step1 :
122 17 93 3 36
Insert before 122
Step2:
17 122
93 3 36
insert between 17 and 122
step3:
17 93 122
3 26
Insert 3 before 17
Step 4:
3
17
93 122
26
Insert 26 before 93
Sorted array 3
17 26
93 122
Example:
#include <stdio.h>
int main()
{
int a[100], number, i, j, temp;
printf("\n Please Enter the total Number of Elements : ");
scanf("%d", &number);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < number; i++)
scanf("%d", &a[i]);
for(i = 1; i <= number - 1; i++)
{
for(j = i; j > 0 && a[j - 1] > a[j]; j--)
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}}
printf("\n Insertion Sort Result : ");
for(i = 0; i < number; i++)
{
printf(" %d \t", a[i]);
}
printf("\n");
return 0;
}
output: please enter the total number of elements
please enter the array elements 10
insertion sort result -20 3 5
5
-20
10
SORTING USING PASS BY REFERENCE
#include <stdio.h>
#include<conio.h>
void main()
{
int n, a[100], i;
void sortarray(int*, int);
printf("\nEnter the Number of Elements in an array:");
scanf("%d",&n);
printf("\nEnter the Array elements\n");
for(i=0;i<n;i++)
15
5 3
15
scanf("%d",&a[i]);
sortarray(a,n);
printf("\nAfter Sorting.............\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}
void sortarray(int *arr, int num)
{
int i,j,temp;
for(i=0;i<num;i++)
for(j=i+1;j<num;j++)
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
OUTPUT
EntertheNumberofElementsinanarray:5
EntertheArrayelements
33
67
21
45
11
AfterSorting....
11
21
33
45
67
5.Searching in C
• Searching is an operation to find whether the given item x is
present in the array or not.
• C language provides two types of searching techniques. They are
as follows −
1. Linear search
2. Binary search
Linear search
• Searching for the key element is done in a linear fashion.
• It is the simplest searching technique.
• It does not expect the list to be sorted.
• Limitation − It consumes more time and reduce the power of
system.
Example:
12 45 13 67 78
Pass 1:
key=67
12 45 13 67 78
67 not matched
Pass 2:
12 45 13 67 78
67 Not matched
Pass 3:
12 45 13 67 78
67 Not matched
Pass 4:
12 45 13 67 78
67 matched
Example: #include<stdio.h>
int main ()
{
int a[50], n, i, key, flag = 0;
printf("enter the no: of elements");
scanf ("%d",&n);
printf("enter the elements:\n");
for (i=0; i<n; i++)
scanf( "%d", &a[i]);
printf("enter a key element:\n");
scanf ("%d", &key);
for (i=0; i<n; i++)
{
if (a[i] == key)
{
flag = 1;
break;
} }
if (flag == 1)
printf("search is successful:");
else
printf("search is unsuccessfull:");
return 0;
}
Output:
enter the no: of elements
enter the elements:
5
12 45
13 67 78
enter a key element: 67
search is successful:
Binary search
• Binary search algorithm can be applied on a sorted array to search
an element.
• Search begins with comparing middle element of array to target
element.
1.If both are equal then position of element is returned.
2.If target element is less than middle element of array then upper half of
array is discarded and again search continued by dividing the lower half.
3.If target element is greater than middle element then lower half is
discarded and search is continued in upper half.
Example
• Let input_array = {12, 18, 23, 25, 29, 32, 35, 40, 58, 66} and key =
18
12
18
23
25
29
32
35
40
58
66
0
1
2
3
4
12
18
23
25
29
0
1
2
3
4
low
5
32
5
6
7
8
9
35
40
58
66
6
7
8
9
mid
high
Low=0 high=9 mid=(0+9)/2=4
Key <mid value
Then high=mid-1
High=3
12
18
23
25
29
0
1
2
3
4
Low
mid
32
5
35
40
58
66
6
7
8
9
35
40
58
66
high
Low=0 high=3 mid=(0+3)/2=1
Key >mid value
Then LOW=mid+1
LOW=2
12
18
23
25
29
32
0
1
2
Low /mid
3
4
high
Low=2 high=3 mid=(2+3)/2=2
Key =mid value
KEY FOUND AT INDEX 2
Example:
#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elementsn");
scanf("%d",&n);
printf("Enter %d integersn", n);
for(i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to findn");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low+high)/2;
while (low <= high) {
5
6
7
8
9
if(array[mid] < key)
low = mid + 1;
else if (array[mid] == key) {
printf("%d found at location %d.n", key, mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list.n", key);
return 0;
}
6.Matrix operation
• Matrix Addition
mat1 = {{1, 2}, {3, 4}}
mat2 = {{1, 2}, {3, 4}}
mat1 + mat2 = {{2, 4}, {6, 8}}
Example:
#include <stdio.h>
int main()
{
int m, n;
scanf(“%d %d”,&m,&n);
int i, j;
int mat1[m][n], mat2[m][n], mat3[m][n];
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
scanf(“%d”,&mat1[i][j]);
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
scanf(“%d”,&mat2[i][j]);
}
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
mat3[i][j] = mat1[i][j] + mat2[i][j];
}}
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
printf(“%d “, mat3[i][j]);
printf(“\n”);
}
return 0;
}
Output:
2 2 (order of the matrix)
1 2 3 4 (matrix 1 elements)
2 3 4 5 (matrix 2 elements)
• Matrix Subtraction
mat1 = {{1, 2}, {3, 4}}
mat2 = {{1, 2}, {3, 4}}
mat1 - mat2 = {{0, 0}, {0, 0}}
Example:
#include <stdio.h>
int main()
{
int m, n;
scanf(“%d %d”,&m,&n);
int i, j;
int mat1[m][n], mat2[m][n], mat3[m][n];
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
scanf(“%d”,&mat1[i][j]);
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
scanf(“%d”,&mat2[i][j]);
}
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
mat3[i][j] = mat1[i][j] – mat2[i][j];
}}
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
printf(“%d “, mat3[i][j]);
printf(“\n”);
}
return 0;
}
OUTPUT
2 2 (order of the matrix)
5 6 7 8 (matrix 1 elements)
1 2 3 4 (matrix 2 elements)
4 4 (resultant matrix)
• Matrix Multiplication
mat1 = {{1, 2}, {3, 4}}
mat2 = {{1, 2}, {3, 4}}
mat1 * mat2 = {{7, 10}, {15, 22}}
Example:
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int mat1[10][10], mat2[10][10], mat3[10][10];
printf(“Enter number of rows and columns of mat1 matrix\n”);
scanf(“%d%d”, &m, &n);
printf(“Enter elements of matrix 1\n”);
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf(“%d”, &mat1[c][d]);
printf(“\nEnter number of rows and columns of mat2 matrix\n”);
scanf(“%d%d”, &p, &q);
if (n != p)
printf(“\nThe matrices can’t be multiplied with each other.\n”);
else
{
printf(“\nEnter elements of mfor (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf(“%d”, &mat2[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + mat1[c][k]*mat2[k][d];
}
mat3[c][d] = sum;
sum = 0;
}
}
printf(“\nProduct of the matrices:\n”);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf(“%d\t”, mat3[c][d]);
printf(“\n”);
}
}
return 0;
}
OUTPUT
Enter number of rows and columns of mat1 matrix
22
Enter elements of matrix 1
2345
Enter number of rows and columns of mat2 matrix
22
Enter elements of matrix 2
1234
Product of the matrices:
11 16
Transpose of a Matrix:
The transpose of a matrix is a new matrix in which the rows of the
original matrix become the columns, and the columns of the original
matrix become the rows, with their order reversed. It is denoted by
adding a superscript "T" or an apostrophe (') to the original matrix.
If you have a matrix A with dimensions m x n, then the transpose of A,
denoted as A^T or A', will have dimensions n x m.
Mathematically, if A = [a_ij] is your original matrix, then the transpose
A^T or A' is defined as:
A^T = [b_ij], where b_ij = a_ji
Program:
#include <stdio.h>
int main() {
int row, col;
printf("Enter the number of rows and columns of the matrix: ");
scanf("%d %d", &row, &col);
int matrix[row][col];
printf("Enter the elements of the matrix:\n");
// Input matrix elements
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Display the original matrix
printf("Original matrix:\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
// Transpose the matrix
int transpose[col][row];
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
transpose[i][j] = matrix[j][i];
}
}
// Display the transposed matrix
printf("Transpose of the matrix:\n");
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
printf("%d\t", transpose[i][j]);
}
printf("\n");
}
return 0;
}}
Sample Output:
Enter the number of rows and columns of the matrix: 3 4
Enter the elements of the matrix:
1234
5678
9 10 11 12
Original matrix:
1234
5678
9 10 11 12
Transpose of the matrix:
1592
6 10 3 7
11 4 8 12
In this example, the program first takes the dimensions of the matrix (3 rows
and 4 columns) and then accepts the elements of the matrix from the user. It
displays the original matrix and its transpose as shown in the sample output.
Download