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

Unit 3

Uploaded by

pavanbeemeneni
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 views32 pages

Unit 3

Uploaded by

pavanbeemeneni
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/ 32

UNIT 3

Arrays and Strings

Arrays indexing, memory model, programs with array of integers, two dimensional arrays, Introduction to
Strings.

ARRAYS
Def: - 1. An array is a special type of variable used to store multiple values of same data type at a
time.

2. An array is a collection of similar data items stored in continuous memory locations with single

name.

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.
When we work with a large number of data values, we need that any number of different variables.
As the number of variables increases, the complexity of the program also increases and so the programmers
get confused with the variable names. There may be situations where we need to work with a large number
of similar data values. To make this work easier, C programming language provides a concept called
"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 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.

P BHANU PRAKASH 9676288008 [email protected] 1


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 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.
TYPES OF ARRAYS
➢ Single Dimensional Array / One Dimensional Array
➢ Multi-Dimensional Array
SINGLE DIMENSIONAL ARRAY / ONE DIMENSIONAL ARRAY
Syntax of an Array
In C programming language, when we want to create an array, we must know the datatype of values
to be stored in that array and also the number of values to be stored in that array.
General syntax to create an array...
datatype arrayName [ size ] ;
Syntax for creating an array with size and initial values
datatype arrayName [ size ] = {value1, value2, ...} ;
Syntax for creating an array without size and with initial values
datatype arrayName [ ] = {value1, value2, ...} ;
In the above syntax, the datatype specifies the type of values we store in that array and size specifies the
maximum number of values that can be stored in that array.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and
the highest address to the last element.

Index or Subscript Variable:


1. Individual data items can be accessed by the name of the array and an integer enclosed in square bracket
called subscript variable / index
2. Subscript Variables helps us to identify the item number to be accessed in the contiguous memory.
What is Contiguous Memory?
1. When Big Block of memory is reserved or allocated then that memory block is called as Contiguous
Memory Block.
2. Alternate meaning of Contiguous Memory is continuous memory.

P BHANU PRAKASH 9676288008 [email protected] 2


3. Suppose inside memory we have reserved 1000-1200 memory addresses for special purposes then we
can say that these 200 blocks are going to reserve contiguous memory.
Contiguous Memory Allocation:
1. Two registers are used while implementing the contiguous memory scheme. These registers are base
register and limit register.
2. When OS is executing a process inside the main memory then contents of each register are as,
Registers Content of registers
1. Base register Starting address of the memory location where process execution is happening
2. Limit register Total amount of memory in bytes consumed by process

Here, Diagram 1: represents the contiguous allocation of memory


and
Diagram 2: represents non-contiguous allocation of memory.
3. When process try to refer a part of the memory then it will firstly refer the base address from base
register and then it will refer relative address of memory location with respect to base address.
How to allocate contiguous memory?
1. Using static array declaration.
2. Using calloc( ) / malloc( ) function to allocate big chunk of memory dynamically.

Array Terminologies:
1) Size : Number of elements to store in an array. It is always mentioned in square brackets [ ]
2) Type : Refers to data type. It decides which type of element is stored in the array. It is also
instructing the compiler to reserve memory according to the data type.
3) Base : The address of the first element is a base address. The array name itself stores address of
the first element.
4) Index : The array name is used to refer to the array element. For example int num[x], num is array
and x is index. The value of x begins from 0. The index value is always an integer value.
5) Range : Value of index of an array varies from lower bound to upper bound. For example, int
num[100]; the range of index is 0 to 99.

P BHANU PRAKASH 9676288008 [email protected] 3


Characteristics of an array:
1. The declaration int a[5] is creation of five variables of integer types in memory instead of declaring five
variables for five values.
2. All the elements of an array share the same name and they are distinguished from one another with the
help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the other elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or array variable of
its type.
6. Array elements are stored in contiguous memory locations.
Declaration of Array
data_type array_name[array_size]; // Syntax
int a [3] ; //Declaration of array
Here, the compiler allocates 6 bytes of contiguous memory locations with a single name 'a' and tells the
compiler to store three different integer values (each in 2 bytes of memory) into that 6 bytes of memory.

In the above memory allocation, all the three memory locations have a common name 'a'. So accessing
individual memory location is not possible directly. Hence compiler not only allocates the memory but also
assigns a numerical reference value to every individual memory location of an array. This reference number
is called "Index" or "subscript" or "indices".

Accessing Individual Elements of an Array


The individual elements of an array are identified using the combination of 'arrayName' and 'indexValue'.
arrayName [ indexValue ] ;
For the above example the individual elements can be denoted as.

P BHANU PRAKASH 9676288008 [email protected] 4


For example, if we want to assign a value to the second memory location of above array 'a'.
a [1] = 100 ;

Using for loops for sequential access


In order to read elements into the array sequentially or to access elements of an array sequentially we make
use of looping constructs.
For reading elements into the array sequentially:
int number[10]; /* array declaration */
/* reading elements into the array sequentially */
for ( i=0; i < 10 ; i++ )
scanf( “ %d ”, & number[ i ] );
Explanation:
For loop is used to vary the index of the array from 0 to its size-1. The variable used in for loop is
used in the scanf statement along with the array name enclosed in square brackets. This variable is called as
subscript variable.
For printing elements of the array sequentially:
For e.g. if we suppose assume that the array is declared and the elements are already initialized, then we
will see how elements are accessed sequentially from the array.
/* accessing elements from the array sequentially */
for( i=0; i<10 ;i++ )
{
Printf(“ %d ”, number[i]);
}
Explanation:
➢ for loop is used to vary the index of the array from 0 to its size-1.
➢ The variable used in the for loop is used in any of the executable statement along with the array
name enclosed in square brackets.
➢ In the above example each and every element of the array is accessed and assigned to the variable
num and that value is immediately printed.

P BHANU PRAKASH 9676288008 [email protected] 5


Initialization of 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.
int marks[5]; // Declaration of the array
marks[0]=80; //initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

ARRAY EXAMPLE
#include<stdio.h> OUTPUT
int main(){ 80
int i=0; 60
int marks[5]; //declaration of array 70
marks[0]=80; //initialization of array 85
marks[1]=60; 75
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;
}

P BHANU PRAKASH 9676288008 [email protected] 6


Declaration with Initialization
We can initialize the c array at the time of declaration.
int marks [5] = {20,30,40,50,60};
In such case, there is no requirement to define the size.
int marks [] = {20,30,40,50,60};
ARRAY EXAMPLE
#include<stdio.h> OUTPUT
int main(){ 20
int i=0; 30
int marks[5]={20,30,40,50,60}; //declaration and 40
initialization of array 50
//traversal of array 60
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
EXAMPLE
Sorting an array largest and second largest element
#include<stdio.h> #include<stdio.h>
void main () void main ()
{ {
int i, j,temp; int arr[100],i,n,largest,sec_largest;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23}; printf("Enter the size of the array?");
for(i = 0; i<10; i++) scanf("%d",&n);
{ printf("Enter the elements of the array?");
for(j = i+1; j<10; j++) for(i = 0; i<n; i++)
{ {
if(a[j] > a[i]) scanf("%d",&arr[i]);
{ }
temp = a[i]; largest = arr[0];
a[i] = a[j]; sec_largest = arr[1];
a[j] = temp; for(i=0;i<n;i++)
} {

P BHANU PRAKASH 9676288008 [email protected] 7


} if(arr[i]>largest)
} {
printf("Printing Sorted Element List ...\n"); sec_largest = largest;
for(i = 0; i<10; i++) largest = arr[i];
{ }
printf("%d\n",a[i]); else if (arr[i]>sec_largest && arr[i]!=largest)
} {
} sec_largest=arr[i];
}
}
printf("largest = %d, second largest =
%d",largest,sec_largest);
}

Different Methods of Initializing of 1-D Array:


1. Declare & Initialize an array by its subscripts / index positions,
int num[5];
num[0] = 2; // by index positions
num[1] = 8;
num[2] = 7;
num[3] = 6;
num[4] = 0;

2. Two ways are there to Declare an array at Compile Time,


i) initialize array size Directly int num[5] = { 2, 8, 7, 6, 0 }; // by list / comma separated values
ii) initialize array size Indirectly int num[ ] = { 2, 8, 7, 6, 0 };
Array elements initialize by its subscripts / index Array elements initialize by list / comma separated
positions values
#include<stdio.h> // Simple Sequential program method #include<stdio.h> // Simple Sequential program method

int main() int main()


{ {
int num[5]; int num[5] = { 1, 2, 3, 4, 5 };
num[0]=1; num[1]=2; num[2]=3; num[3]=4; num[4]=5; printf(" %d ", num[0] );
printf(" %d ", num[0] ); printf(" %d ", num[1] );
printf(" %d ", num[1] ); printf(" %d ", num[2] );
printf(" %d ", num[2] ); printf(" %d ", num[3] );
printf(" %d ", num[3] ); printf(" %d ", num[4] );
printf(" %d ", num[4] ); return 0;

P BHANU PRAKASH 9676288008 [email protected] 8


return 0; }
}
O/p: 1 2 3 4 5
O/p: 1 2 3 4 5

MEMORY MODEL of 1-D ARRAY:


➢ The subscript of a column or row index will be used to access this type of array. A single subscript, in this
case, represents each element. The items are saved in memory in sequential order.
➢ Array elements are stored at contiguous memory locations only. For example, A[1], A[2], …, A[n]
➢ Representing 1-D array, int a[5] = { 10, 20, 30, 40, 50 };
memory array array
address elements index
. .
. .
.
.
1000 }
1001
1002 } can’t store a[5]
1003 } because, 5 free
1004 } mem. locations
1005 not in contiguous
1006 }
1007
1008 10  a[0];
1009 20 a[1];
1010 30 a[2];
1011 40 a[3];
1012 50 a[4];
1013
1014 .
.
. .
. .
Operations on One Dimensional Array:
1. Traversing - It a process to visit each and every element of an array from first to last at least once
without skipping any element.
2. Insertion - Used to insert an element at a specified position in an array.
3. Deletion - Involves deleting specified elements form an array.
4. Searching - An array element can be searched. The process of seeking specific elements in an array is
called searching.
5. Merging - The elements of two arrays are merged into a single one.
6. Sorting - Arranging elements in a specific order either in ascending or in descending order.

P BHANU PRAKASH 9676288008 [email protected] 9


Applications of Arrays in C
• Arrays are used to Store List of values
In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single dimensional
array data is stored in linear form.
• 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.
• Arrays are used to implement Search Algorithms
We use single dimensional arrays to implement search algorihtms like ...
1. Linear Search
2. Binary Search
• Arrays are used to implement Sorting Algorithms
We use single dimensional arrays to implement sorting algorithms like ...
1. Insertion Sort
2. Bubble Sort
3. Selection Sort
4. Quick Sort
5. Merge Sort, etc.,
• Arrays are used to implement Data structures
We use single dimensional arrays to implement data structures like...
1. Stack Using Arrays
2. Queue Using Arrays
• Arrays are also used to implement CPU Scheduling Algorithms
PROGRAMS WITH 1-D ARRAY OF INTEGERS:
List of Programs using 1-D array

1. Initialize and print 1-D array with 5 data elements.


2. Insert a new element at the last position in an array.
3. Delete an element at the last position in an array.
4. Remove the duplicate elements from an array.
5. Search an element in an array.
6. Copy all elements of an array into another array.
7. Merge two arrays into one array.
8. Sum of all elements & Avg. in an array.

P BHANU PRAKASH 9676288008 [email protected] 10


9. Find Smallest element in an array.
10. Find Biggest element in an array.
11. Reverse an array element in an array.

1: Write a C program to Initialize and Print 1-D array 2: Write a C Program to Insert a new element at the
with 5 data elements. last position in an array.

#include <stdio.h> #include<stdio.h>


int main() int main()
{ {
int n[ ] = { 2, 8, 7, 6, 0 }; int arr[30], num, element, i;
int i; printf("\nEnter no of elements: ");
for (i=0; i<5; i++) scanf("%d", &num);
{ for (i = 0; i < num; i++)
printf(“\nArray Element n[%d] = %d”, i, n[i]); {
} scanf("%d", &arr[i]);
return 0; }
} printf("\nEnter the element to be inserted: ");
scanf("%d", &element);
Output: arr[num] = element;
Array Element n[0] = 2 num=num+1;
Array Element n[1] = 8 for (i = 0; i < num; i++)
Array Element n[2] = 7 {
Array Element n[3] = 6 printf("%d ", arr[i]);
Array Element n[4] = 0 }
return(0);
}

Output:
Enter no of elements: 5
10 20 30 40 50

Enter element insert at last: 60


10 20 30 40 50 60

3: Write a C Program to Delete an element at the last 4: Write a C Program to delete / Remove the duplicate
position in an array. elements from an array.

#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int arr[30], num, element, i; int arr[20], i, j, k, size;
char ch; printf("\nEnter array size: ");
printf("\nEnter no of elements: "); scanf("%d", &size);
scanf("%d", &num); printf("\nEnter array elements: ");
for (i = 0; i < num; i++) for (i = 0; i < size; i++)
{ scanf("%d", &arr[i]);
scanf("%d", &arr[i]); printf("\nArray with Unique list: ");
} for (i = 0; i < size; i++)
printf("\n Delete the last element (y/n): "); {
scanf("%c", &ch); for (j = i + 1; j < size;)
if(ch==’y’ || ch==’Y’) {
{ if (arr[j] == arr[i])

P BHANU PRAKASH 9676288008 [email protected] 11


num=num-1; {
printf(“ \n Last element is Deleted! ”); for (k = j; k < size; k++)
} {
else arr[k] = arr[k + 1];
printf(“ \n Last element is NOT Deleted! ”); }
for (i = 0; i < num; i++) size--;
{ }
printf("%d ", arr[i]); else
} j++;
return(0); }
} }
for (i = 0; i < size; i++)
Output: printf("%d ", arr[i]);
Enter no of elements: 6 return (0);
10 20 30 40 50 60 }

Delete the last element (y/n): y Output:


10 20 30 40 50
Enter array size: 10
Enter array elements: 10 20 30 40 50 60 20 30 70 90

Array with Unique list: 10 20 30 40 50 60 70 90

5: Write a C Program to Search an element in an array. 6: Write a C Program to Copy all elements of an array
into another array.
#include<stdio.h>
int main() #include<stdio.h>
{ int main()
int a[30], key, num, i, flag=0; {
printf("\n Enter array size: "); int arr1[30], arr2[30], i, num;
scanf("%d", &num); printf("\nEnter no of elements:");
printf("\n Enter array elements: "); scanf("%d", &num);
for (i = 0; i < num; i++) printf("\nEnter the values:");
scanf("%d", &a[i]); for (i = 0; i < num; i++) {
printf("\n Enter search key: "); scanf("%d", &arr1[i]); }
scanf("%d", &key); for (i = 0; i < num; i++) // Copying array 'a' to 'b’
for(i=0; i<num; i++) {
{ arr2[i] = arr1[i];
if (key == a[i]) }
{ printf("The copied array is: ");
flag=1; for (i = 0; i < num; i++)
break; printf("\n arr2[%d] = %d", i, arr2[i]);
} return (0);
} }
if (flag=1)
printf("Search key found at location = %d", i+1); Output:
else
printf("Search key not found"); Enter no of elements: 5
return (0); Enter the values: 11 22 33 44 55
} The copied array is:
arr2[0] = 11
Output: arr2[1] = 22
arr2[2] = 33
Enter array size: 10 arr2[3] = 44
Enter array elements: 10 20 30 40 50 60 70 80 90 99 arr2[4] = 55

P BHANU PRAKASH 9676288008 [email protected] 12


Enter search key: 50
Search key found at location = 5
------- ---
Enter search key: 100
Search key not found

7: Write a C Program to Merge two arrays into new. 8: Write a C Program to find Sum of all array
elements.
#include<stdio.h>
int main() #include<stdio.h>
{ int main()
int arr1[30], arr2[30], mrg[60]; {
int i, j, n1, n2, n3; int i, arr[50], sum, num;
printf("\nEnter no of elements in 1st array:"); printf("\nEnter no of elements: ");
scanf("%d", &n1); scanf("%d", &num);
for (i = 0; i < n1; i++) { printf("\nEnter the values: ");
scanf("%d", &arr1[i]); } for (i = 0; i < num; i++)
printf("\nEnter no of elements in 2nd array:"); scanf("%d", &arr[i]);
scanf("%d", &n2); for (i = 0; i < num; i++)
for (i = 0; i < n2; i++) sum = sum + arr[i];
{ for (i = 0; i < num; i++)
scanf("%d", &arr2[i]); printf("\na[%d]=%d", i, arr[i]);
} printf("\nSum=%d", sum);
for (i=0; i<n1; i++) // Merging starts return (0);
{ }
mrg[i] = arr1[i]; // copy arr1[ ] into mrg[ ]
j=i; Output:
}
for (i=0; i<n2; i++) Enter no of elements: 3
{ Enter the values: 11 22 33
j++; a[0]=11
mrg[j] = arr2[i]; // copy arr2[ ] into mrg[ ] a[1]=22
} a[2]=33
n3=n1+n2; Sum=66
printf("Merged array is: ");
for (i = 0; i < n3; i++) 8.1: Write a C Program to find Sum of all array
{ elements & average of them.
printf("%d", mrg[i]);
} #include<stdio.h>
return(0); int main()
} {
int i, n=10, sum; float avg=0.0;
Output: int arr[n] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 10 };
for (i = 0; i < n; i++)
Enter no of elements in 1st array: 5 sum = sum + arr[i];
11 22 33 44 55 avg = (float) sum / 10;
Enter no of elements in 2nd array: 5 printf("\nSum = %d", sum);
66 77 88 99 100 printf("\nAverage = %f", avg);
return(0);
Merged array is: 10 11 22 33 44 55 66 77 88 99 100 }
Output: Sum = 55
Avg = 5.5

P BHANU PRAKASH 9676288008 [email protected] 13


9: Write a C program to find smallest element in an array 10: Write a C program to find biggest element in an
array
#include<stdio.h>
int main() #include<stdio.h>
{ int main()
int a[30], i, num, smallest; {
printf("\nEnter no. of elements: "); int a[30], i, num, biggest;
scanf("%d", &num); printf("\nEnter no. of elements: ");
for (i = 0; i < num; i++) scanf("%d", &num);
scanf("%d", &a[i]); for (i = 0; i < num; i++)
smallest = a[0]; scanf("%d", &a[i]);
for (i = 0; i < num; i++) biggest = a[0];
{ for (i = 0; i < num; i++)
if (a[i] < smallest) {
{ if (a[i] > biggest)
smallest = a[i]; {
} biggest = a[i];
} }
printf("\nSmallest Element is: %d", smallest); }
return (0); printf("\nBiggest Element is: %d", biggest);
} return (0);
}
Output:
Output:
Enter no of elements: 5
55 44 99 11 22 Enter no of elements: 5
Smallest Element: 11 55 44 99 11 22
Biggest Element: 99

11: Write a C program to reverse an array element in 11.1: Write a C program to reverse an array element
an array. in an array.

#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int arr[30], i, j, num, temp; int arr[30], i, j, num, temp;
printf("\nEnter no of elements: "); printf("\nEnter no of elements: ");
scanf("%d", &num); scanf("%d", &num);
for (i = 0; i < num; i++) for (i = 0; i < num; i++)
{ scanf("%d", &arr[i]); } {
j = i - 1; // j will Point to last Element scanf("%d", &arr[i]);
i = 0; // i will be pointing to first element }
while (i < j) printf("\nResult after reversal : ");
{ for (i=num-1; i <= 0; i--)
temp = arr[i]; {
arr[i] = arr[j]; printf("%d \t", arr[i]);
arr[j] = temp; }
i++; // increment i return (0);
j--; // decrement j }
}
printf("\nResult after reversal : "); Output:
for (i = 0; i < num; i++) Enter no of elements: 5
{ printf("%d \t", arr[i]); } 11 22 33 44 55
return (0); Result after reversal: 55 44 33 22 11

P BHANU PRAKASH 9676288008 [email protected] 14


}
Output:
Enter no of elements: 5
11 22 33 44 55
Result after reversal: 55 44 33 22 11

MULTI-DIMENSIONAL ARRAY
An array of arrays is called as multi-dimensional array. In simple words, an array created with more
than one dimension (size) is called as multi-dimensional array. Multi-dimensional array can be of two-
dimensional array or three-dimensional array or four-dimensional array or more...
Most popular and commonly used multi-dimensional array is two-dimensional array. The 2-D
arrays are used to store data in the form of table. We also use 2-D arrays to create mathematical matrices.
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
data_type array_name [rows] [columns];
int twodimen [4] [3];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array
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 at least the
second dimension of the array.
datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
(or)
int matrix_A [2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Example:

1. int a[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // initialize all array elements as list / comma separated values

2. int a[3][3] = { 1, , , , 1, , , , 1 }; // initialize some array elements as list / comma separated values

3. int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // array elements in row-wise

P BHANU PRAKASH 9676288008 [email protected] 15


4. int a[3][3] = { { 1, 2, 3 }, // like matrix / grid of array elements in row-wise
{ 4, 5, 6 },
{ 7, 8, 9 } };

5. int a[3][3] = { 0 }; // to initialize 0 to all coordinates

6. char grid[3][4] = { { 'a', 'b', 'c', 'd' },// 3 rows & 4 columns as single char comma separated value in row-wise
{ 'e', 'f', 'g', 'h' },
{ 'i', 'j', 'k', 'l' }
};

7. char name[5][10] = { "tree", // 5 rows & 10 columns as string in row-wise


"bowl",
"hat",
"mice",
"toon"
};

ACCESSING INDIVIDUAL ELEMENTS OF TWO-DIMENSIONAL ARRAY


In a c programming language, to access elements of a two-dimensional array we use array name
followed by row index value and column index value of the element that to be accessed. Here the row and
column index values must be enclosed in separate square braces. In case of the two-dimensional array the
compiler assigns separate index values for rows and columns.
General syntax to access the individual elements of a two-dimensional array
arrayName [ rowIndex ] [ columnIndex ]
matrix_A [0][1] = 10 ;
In the above statement, the element with row index 0 and column index 1 of matrix_A array is
assigned with value 10.
EXAMPLE OUTPUT
#include<stdio.h> arr[0][0] = 1
int main(){ arr[0][1] = 2
int i=0,j=0; arr[0][2] = 3
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; arr[1][0] = 2
//traversing 2D array arr[1][1] = 3
for(i=0;i<4;i++){ arr[1][2] = 4
for(j=0;j<3;j++){ arr[2][0] = 3
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]); arr[2][1] = 4
} //end of j arr[2][2] = 5
} //end of i arr[3][0] = 4
return 0; arr[3][1] = 5
} arr[3][2] = 6

P BHANU PRAKASH 9676288008 [email protected] 16


EXAMPLE 1 OUTPUT
Storing elements in a matrix and printing it Enter a[0][0]: 56
#include <stdio.h> Enter a[0][1]: 10
void main ()
Enter a[0][2]: 30
{
int arr[3][3],i,j; Enter a[1][0]: 34
for (i=0;i<3;i++)
Enter a[1][1]: 21
{
for (j=0;j<3;j++) Enter a[1][2]: 34
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]); Enter a[2][0]: 45
}
Enter a[2][1]: 56
}
printf("\n printing the elements ....\n"); Enter a[2][2]: 78
for(i=0;i<3;i++)
{
printf("\n"); printing the elements ....
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]); 56 10 30
}
34 21 34
}
} 45 56 78

Ex: 2-D Array elements initialize by its subscripts / Ex: 2-D Array elements initialize by list / comma
index positions separated values

#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int mat_a[3][3]; int mat_a[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
mat_a[0][0]=1; /* int mat_a[ ][ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; */
mat_a[0][1]=2; printf(" %d ", mat_a[0][0] );
mat_a[0][2]=3; printf(" %d ", mat_a[0][1] );
mat_a[1][0]=4; printf(" %d ", mat_a[0][2] );
mat_a[1][1]=5; printf("\n");
mat_a[1][2]=6; printf(" %d ", mat_a[1][0] );
mat_a[2][0]=7; printf(" %d ", mat_a[1][1] );
mat_a[2][1]=8; printf(" %d ", mat_a[1][2] );
mat_a[2][2]=9; printf("\n");

P BHANU PRAKASH 9676288008 [email protected] 17


printf(" %d ", mat_a[0][0] ); printf(" %d ", mat_a[2][0] );
printf(" %d ", mat_a[0][1] ); printf(" %d ", mat_a[2][1] );
printf(" %d ", mat_a[0][2] ); printf(" %d ", mat_a[2][2] );
printf("\n"); printf("\n");
return 0;
printf(" %d ", mat_a[1][0] ); }
printf(" %d ", mat_a[1][1] );
printf(" %d ", mat_a[1][2] ); O/p: 1 2 3
printf("\n"); 4 5 6
7 8 9
printf(" %d ", mat_a[2][0] );
printf(" %d ", mat_a[2][1] );
printf(" %d ", mat_a[2][2] );
printf("\n");

return 0;
}

O/p: 1 2 3
4 5 6
7 8 9

STORAGE REPRESENTATION OF TWO-DIMENSIONAL ARRAY:


When speaking of two-dimensional arrays, we are logically saying that, it consists of rows and columns but
when it is stored in memory, the memory is linear. Hence, the actual storage differs from our matrix / grid
representation.
E.g. Logical view of int a[3][4]; as,

Two major types of representation can be used for 2-D array,


1. Row representation (or) Row major order

P BHANU PRAKASH 9676288008 [email protected] 18


2. Column representation (or) Column major order

1. Subscript view of int a[3][3];


by
Row major order as,

= a[0][0]=1;
a[0][1]=2;
a[0][2]=3;
a[1][0]=4; = r0 1 2 3
a[1][1]=5; r1 4 5 6
a[1][2]=6; r2 7 8 9
a[2][0]=7;
a[2][1]=8;
a[2][2]=9;

2. Subscript view of int a[3][3];


by
Column major order as,

= a[0][0]=1;
a[1][0]=4;
a[2][0]=7; c0 c1 c2
a[0][1]=2; = 1 2 3
a[1][1]=5; 4 5 6
a[2][1]=8; 7 8 9
a[0][2]=3;
a[1][2]=6;
a[2][2]=9;

MEMORY MODEL of 2-D ARRAY:


The subscript of a row and column index will be used to access this type of array. Two subscripts, in this
case, represents each element. The items are saved in memory in sequential order. Array elements are stored at
contiguous memory locations only. Ex: A[1], A[2], …, A[n]
Representing 2-D array, int a[3][3] = { 10, 20, 30, 40, 50, 60, 70, 80, 90 }; into memory as,

P BHANU PRAKASH 9676288008 [email protected] 19


memory array array
address elements index
. .
. .
1001 }
1002 }
1003 }
}
1004
1005 } can’t store a[3][3]
1006 } because, 9 free
1007 } mem. locations are
1008 not in contiguous
}
1009
1010
1011 }
1012
1013 10  a[0][0];
1014 20 a[0][1];
1015 30 a[0][2]; // stores elements by
1016 40
a[1][0]; Row major order
1017 50
a[1][1];
1018 60 a[1][2];
1019 70
a[2][0];
1020 80
a[2][1];
1021 90
a[2][2];
1022
. .
. .
Memory stack model

Note 1: ‘C’ compiler represents 2-D array elements in memory default by Row representation or Row major
order. For example, int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // row1, row2, row 3
Note 2: We can tell the ‘C’ compiler to represent 2-D array elements in memory by Column representation or
Column major order using the method of initializing individual subscripts only.
For example, int a[3][3];
a[0][0]=1; // column_0 & all row elements
a[1][0]=4;
a[2][0]=7;
a[0][1]=2; // column_1 & all row elements
a[1][1]=5;
a[2][1]=8;
a[0][2]=3; // column_2 & all row elements
a[1][2]=6;
a[2][2]=9;

P BHANU PRAKASH 9676288008 [email protected] 20


PROGRAMS WITH 2-D ARRAY OF INTEGERS:
List of Programs using 2-D array
1. Initialize and print 2-D array elements.
2. Scan and Print 2-D array.
3. Transpose of matrix array.
4. Addition of two matrix array.
5. Multiplication of two matrix array.
1: Write a C program to Initialize and Print 2-D array. 1.1: Write a C program to Initialize and Print 2-D
array.
#include <stdio.h>
int main() #include <stdio.h>
{ int main()
int a[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; {
// int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int a[3][3] = { { 1, 2, 3 },
int i, j; { 4, 5, 6 },
for (i=0; i<3; i++) { 7, 8, 9 }
{ };
for (j=0; j<3; j++) int i, j;
{ for (i=0; i<3; i++)
printf(“\nArray Element a[%d][%d] = %d”, i, j, {
a[i][j] ); for (j=0; j<3; j++)
} {
return 0; printf(“\nArray Element a[%d][%d] = %d”, i, j,
}
a[i][j] );
Output: }
Array Element a[0][0] = 1 return 0;
Array Element a[0][1] = 2 }
Array Element a[0][2] = 3
Array Element a[1][0] = 4 Output:
Array Element a[1][1] = 5 Array Element a[0][0] = 1
Array Element a[1][2] = 6 Array Element a[0][1] = 2
Array Element a[2][0] = 7 Array Element a[0][2] = 3
Array Element a[2][1] = 8 Array Element a[1][0] = 4
Array Element a[2][2] = 9 Array Element a[1][1] = 5
Array Element a[1][2] = 6
Array Element a[2][0] = 7
Array Element a[2][1] = 8
Array Element a[2][2] = 9

2: Write a C program to Scan and Print 2-D array. 3: Write a C program to find Transpose of matrix
array.
#include <stdio.h>
int main() #include <stdio.h>
{ int main()
int a[3][3]; {
int i, j; int i, j, matrix[3][3], transpose[3][3];
for (i=0; i<3; i++) // scan i/p printf("Enter elements of the matrix: \n");
{ for (i= 0; i < 3; i++)
for (j=0; j<3; j++) {
{ for (j = 0; j < 3; j++)
printf(“Enter Element at a[%d][%d] : ”, i, j); {

P BHANU PRAKASH 9676288008 [email protected] 21


scanf(“%d”, &a[i][j] ); scanf("%d", &matrix[i][j]);
} }
} }
for (i = 0; i < 3; i++)
for (i=0; i<3; i++) // print o/p as matrix / grid form {
{ for (j = 0; j < 3; j++)
for (j=0; j<3; j++) {
{ transpose[j][i] = matrix[i][j];
printf(“ %3d ”, a[i][j] ); }
} }
printf(“\n”); printf("Transpose of the matrix: \n");
} for (i = 0; i< 3; i++)
return 0; {
} for (j = 0; j < 3; j++)
{
Output: printf("%4d", transpose[i][j]);
Enter Element at a[0][0] = 1 }
Enter Element at a[0][1] = 2 printf("\n");
Enter Element at a[0][2] = 3 }
Enter Element at a[1][0] = 4 return 0;
Enter Element at a[1][1] = 5 }
Enter Element at a[1][2] = 6
Enter Element at a[3][0] = 7 Outrput:
Enter Element at a[3][1] = 8 Enter elements of the matrix: 1 2 3
Enter Element at a[3][2] = 9 4 5 6
7 8 9
1 2 3
4 5 6 Transpose of the matrix: 1 4 7
7 8 9 2 5 8
3 6 9

4: Write a C program to perform addition of two matrix 5: Write a C program for Multiplication of two
matrix
#include <stdio.h>
int main() #include <stdio.h>
{ int main()
int i, j, a[3][3], b[3][3], c[3][3]; {
printf("Enter elements of the matrix a: \n"); int i, j, a[3][3], b[3][3], c[3][3];
for (i= 0; i < 3; i++) printf("Enter elements of the matrix a: \n");
{ for (i= 0; i < 3; i++)
for (j = 0; j < 3; j++) {
{ for (j = 0; j < 3; j++)
scanf("%d", &a[i][j]); {
} scanf("%d", &a[i][j]);
} }
printf("Enter elements of the matrix b: \n"); }
for (i= 0; i < 3; i++) printf("Enter elements of the matrix b: \n");
{ for (i= 0; i < 3; i++)
for (j = 0; j < 3; j++) {
{ for (j = 0; j < 3; j++)
scanf("%d", &b[i][j]); {
} scanf("%d", &b[i][j]);
} }
}
for (i = 0; i < 3; i++)
{ for (i = 0; i < 3; i++)

P BHANU PRAKASH 9676288008 [email protected] 22


for (j = 0; j < 3; j++) {
{ for (j = 0; j < 3; j++)
c[i][j] = a[i][j] + b[i][j] ; {
} c[i][j]=0;
} for (k = 0; k < 3; k++)
printf("Addition of a & b matrix is: \n"); {
for (i = 0; i< 3; i++) c[i][j] = c[i][j] + a[i][k] * b[k][j];
{ }
for (j = 0; j < 3; j++) }
{ }
printf("%5d", c[i][j]); printf("Multiplication of a & b matrix is: \n");
} for (i = 0; i< 3; i++)
printf("\n"); {
} for (j = 0; j < 3; j++)
return 0; {
} printf("%5d", c[i][j]);
}
Output: printf("\n");
}
Enter elements of the matrix a: 1 2 3 return 0;
4 5 6 }
7 8 9
Output:
Enter elements of the matrix b: 1 2 3 Enter elements of the matrix a: 1 1 1
4 5 6 2 2 2
7 8 9 3 3 3
Enter elements of the matrix b: 1 1 1
Addition of a & b matrix is: 2 4 6 2 2 2
8 10 12 3 3 3
14 16 18 Multiplication of a & b matrix :
(1*1 + 1*2 + 1*3) (1*1 + 1*2 + 1*3) (1*1 + 1*2 + 1*3) 6 6
6
(2*1 + 2*2 + 2*3) (2*1 + 2*2 + 2*3) (2*1 + 2*2 + 2*3) = 12 12
12
(3*1 + 3*2 + 3*3) (3*1 + 3*2 + 3*3) (3*1 + 3*2 + 3*3) 18 18
18

STRINGS
String is a set of characters that are enclosed in double quotes. In the C programming language, strings are
created using one dimension array of character datatype. Every string in C programming language is enclosed within
double quotes and it is terminated with NULL (\0) character. Whenever c compiler encounters a string value it
automatically appends a NULL character (\0) at the end.
Def:1 String is a set of characters enclosed in double quotation marks. In C programming, the string is a character
array of single dimension.
In C programming language, there are two methods to create strings and they are as follows...
➢ Using one dimensional array of character datatype ( static memory allocation )
➢ Using a pointer array of character datatype ( dynamic memory allocation )

P BHANU PRAKASH 9676288008 [email protected] 23


Creating string
In C, strings are created as a one-dimensional array of character datatype. We can use both static and dynamic
memory allocation. When we create a string, the size of the array must be one more than the actual number of
characters to be stored. That extra memory block is used to store string termination character NULL (\0). The
following declaration stores a string of size 5 characters.
char str[6] ;
The following declaration creates a string variable of a specific size at the time of program execution.
char *str = (char *) malloc(15) ;

Declaration of String:
Declaring a string in C is as simple as declaring a one-dimensional array.
syntax: char string_name[size];
string_name - is any name given to the string variable
size - is used to define the length of the string + ‘\0’.
Example: char str[35] = "Welcome to learn ‘C’ programming.";

Initialization of String:
String in C can be initialized in 4 different ways
1. Assigning a String Literal without Size:
It is possible to directly assign a string literal to a character array without any size. The size gets determined
automatically by the compiler at compile time. Here, the name of the string “str” acts as a pointer because it is an
array.
Example: char str[ ] = "Welcome to learn ‘C’ programming.";
2. Assigning a String Literal with Size:
String literals can be assigned with a predefined size. But we should always account for one extra space
which will be assigned to the null character. If we want to store a string of size n then we should always declare a
string with a size equal to or greater than n+1.
Example: char str[35] = "Welcome to learn ‘C’ programming.";
3. Assigning Character by Character without size:
Like assigning directly without size, we also assign character by character with the Null Character at the end.
The compiler will determine the size of the string automatically.
Example: char str[ ] = { ‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘\0’ };
4. Assigning Character by Character with size:
String can be assigned with a predefined size character by character with the Null Character at the end. Total
size / length of the string + one character for ‘\0’.
Example: char str[8] = { ‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘\0’ };

P BHANU PRAKASH 9676288008 [email protected] 24


Assigning string value
String value is assigned using the following two methods...
➢ At the time of declaration (initialization)
➢ After declaration
Examples of assigning string value

int main()
{
char str1[6] = "Hello";
char str2[] = "Hello!";
char name1[] = {'s','m','a','r','t'};
char name2[6] = {'s','m','a','r','t'};

char title[20];
title = "C Programming";
return 0;
}
Reading string value from user
We can read a string value from the user during the program execution. We use the following two methods...
1. Using scanf() method - reads single word
2. Using gets() method - reads a line of text
Using scanf() method we can read only one word of string. We use %s to represent string in scanf() and printf()
methods.
Examples of reading string value using scanf() method
#include<stdio.h>
#include<conio.h>
int main()
{
char name[50];
printf("Please enter your name : ");
scanf("%s", name);
printf("Hello! %s , welcome to btech smart class !!", name);
return 0;
}
When we want to read multiple words or a line of text, we use a pre-defined method gets(). The gets() method
terminates the reading of text with Enter character.

P BHANU PRAKASH 9676288008 [email protected] 25


Examples of reading string value using gets() method
#include<stdio.h>
#include<conio.h>
int main()
{
char name[50];
printf("Please enter your name : ");
gets(name);
printf("Hello! %s , welcome to btech smart class !!", name);
return 0;
}
C Programming language provides a set of pre-definied functions called String Handling Functions to work with
string values. All the string handling functions are defined in a header file called string.h.
C’ programs to Declare, Initialize and Read string from user:

1. String program to Declare, Initialize and print. 2. String program to Declare, Initialize and print.

#include <stdio.h> #include <stdio.h>


int main() int main()
{ {
char str[ ] = "Welcome"; // declare & initialize char str[ ] = { ‘W’, ’e’, ’l’, ’c’, ’o’, ’m’, ’e’, ‘\0’ };
string
// char str[10] = “Welcome”; // char str[10] = { ‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘\0’
printf("%s", str); // print string };
return 0; printf("%s", str); // print string
} return 0;
}
Output:
Welcome Output:
Welcome

4. String program to read str with whitespace and


3. String program to read string and print.
print.

#include <stdio.h> #include <stdio.h>


int main() int main()
{ {
char str[25]; char str[25];
printf(“Enter a String: “); printf(“Enter a String: “);
scanf("%s", str); scanf("%[^\n]s", str);
printf("Entered String: %s", str); printf("Entered String: %s", str);
return 0; return 0;
} }

Output: Output:

Enter a String: Welcome to learn C. Enter a String: Welcome to learn C.


Entered String: Welcome Entered String: Welcome to learn C.

P BHANU PRAKASH 9676288008 [email protected] 26


( Note: Entered string printed up to the first occurrence of ( Note: Entered string printed completely using %[^\n]s
whitespace. ) in scanf(). )

5. String program to read str with gets() and puts(). 6. String program to read str with fgets() and fputs().

#include <stdio.h> #include <stdio.h>


int main() int main()
{ {
char str[25]; char str[25];
printf("\n Enter a String: "); printf("Enter a String: ");
gets(str); fgets(str, 25, stdin);
printf("\n Entered String: "); printf("\n Entered String: ");
puts(str); fputs(str, stdout);
return 0; return 0;
} }

Output: Output:

Enter a String: Welcome to learn C. Enter a String: Welcome to learn C.


Entered String: Welcome to learn C. Entered String: Welcome to learn C.

STRING HANDLING FUNCTIONS:


The standard ‘C’ library provides various functions to manipulate the strings within a program. These functions
are also called as string handlers. All these handlers are present inside <string.h> header file.

Important String handling library functions:


Function Purpose
Used for finding a length of a string. It returns how many characters are
1. strlen()
present in a string excluding the NULL character. Returns in integer type.

2. strcpy(str1, str2) Used to copy one string to another. It copies the contents of str2 to str1.

Used for combining two strings together to form a single string. It Appends
3. strcat(str1, str2)
or concatenates str2 to the end of str1 and returns a pointer to str1.

Used to compare two strings with each other. It returns 0 if str1 is equal
4. strcmp(str1, str2)
to str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2.

5. strrev(str) Used to get reverse of the given String str.

6. strlwr(str) Used to convert the given string into lower case one.

7. strupr(str) Used to convert the given string into upper case one.

Used to find the first occurrence of a specified character (ch) in the given
8. strchr(str1, ch)
string (str1).

Used to find the first occurrence of a specified string (str2) in the given
9. strstr(str1, str2)
string (str1).

P BHANU PRAKASH 9676288008 [email protected] 27


1. Write a C program to find the length of the string. 1.1. Write a C program to find the length of the string.

#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
char str[25]; char str[25];
int strlength; int strlength;
printf(“Enter a String: “); printf(“Enter a String: “);
scanf(“%s”, str); gets(str);
strlength = strlen(str); strlength = strlen(str);
printf(“Given String Length is: %d”, strlength); printf(“Given String Length is: %d”, strlength);
return(0); return(0);
} }

Output: Output:
Enter a String: Welcome Enter a String: Welcome
Given String Length Is: 7 Given String Length Is: 7

2. Write a C program to Copy one string into another. 2.1. Write a C program to Copy one str. into another.

#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
char str1[25], str2[25]; char str1[25], str2[25];
printf(“Enter a First String: “); printf(“Enter a First String: “);
scanf(“%s”, str1); gets(str1);
printf(“Enter a Second String: “); printf(“Enter a Second String: “);
scanf(“%s”, str2); gets(str2);
printf(“First String is: %s”, str1); printf(“First String is: %s”, str1);
printf(“Second String is: %s”, str2); printf(“Second String is: %s”, str2);
strcpy(str1, str2); strcpy(str1, str2);
printf(“After strcpy(), First String is: %s”, str1); printf(“After strcpy(), First String is: %s”, str1);
return(0); return(0);
} }

Output: Output:

Enter a First String: Enter a First String: Welcome


Enter a Second String: to learn C. Enter a Second String: to learn C.

First String is: Welcome First String is: Welcome


Second String is: to Second String is: to learn C.
After strcpy(), First String is: to After strcpy(), First String is: to learn C.

P BHANU PRAKASH 9676288008 [email protected] 28


3. Write C program to perform String Concatenation. 3.1. Write a C program for String Concatenation.

#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
char str1[25], str2[25]; char str1[25], str2[25];
printf(“Enter a First String: “); printf(“Enter a First String: “);
gets(str1); gets(str1);
printf(“Enter a Second String: “); printf(“Enter a Second String: “);
gets(str2); gets(str2);
printf(“First String is: %s”, str1); strcat(str1, str2);
printf(“Second String is: %s”, str2); printf(“After strcat(), First String is:”);
strcat(str1, str2); puts(str1);
printf(“After strcat(), First String is: %s”, str1); return(0);
return(0); }
}
Output:
Output:
Enter a First String: welcome
Enter a First String: Welcome Enter a Second String: to learn c.
Enter a Second String: to learn C.
First String is: welcome
First String is: Welcome Second String is: to learn c.
Second String is: to learn C. After strcat(), First String is: welcome to learn c.
After strcat(), First String is: Welcome to learn C.

4. Write C program to perform String Comparison. 5. Write a C program to Reverse the given String.

#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
char str1[25], str2[25]; char str1[25];
int result; printf(“Enter a String: “);
printf(“Enter a First String: “); gets(str1);
gets(str1); puts(strrev(str1);
printf(“Enter a Second String: “); return(0);
gets(str2); }
result = strcmp(str1, str2);
if(result==0) Output:
printf(“Both the strings are Equal.”);
else Enter a String: Welcome
printf(“Both the strings are Not Equal.”); emocleW
return(0);
}

P BHANU PRAKASH 9676288008 [email protected] 29


Output:

Enter a First String: Welcome


Enter a Second String: Welcome
Both the strings are Equal.

5.1. Write a C program to find Palindrome or not. 6 & 7. C program to convert into lower & upper case.
#include<stdio.h>
#include<stdio.h> #include<string.h>
#include<string.h> int main()
int main() {
{ char str1[25];
char actual[25], reverse[25]; printf(“Enter a String: “);
int result; gets(str1);
printf("Enter a String: "); puts(“Actual String: ”);
gets(actual); puts(str1);
strcpy(reverse, actual);
strrev(reverse); puts(“After strlwr(): ”);
result=strcmp(actual, reverse); puts(strlwr(str1));
if(result == 0)
printf("Given string is a Palindrome."); puts(“After strupr(): ”);
else puts(strupr(str1));
printf("Given strings is Not a Palindrome"); return(0);
}
return(0);
} Output:
Output:
Enter a String: WelCome To Learn c
Enter a String: Malayalam After strlwr(): welcome to learn c
After strupr(): WELCOME TO LEARN C
Given string is a Palindrome.

[ radar, level, civic, madam, refer, noon, rotor, deed,


reviver, rotavator. ]

8. C program to find search character. 9. C program to find search String.

#include <stdio.h> #include <stdio.h>


#include <string.h> #include <string.h>

int main() int main()


{ {
char str1[ ] = "Welcome to learn C"; char str1[ ] = "Welcome to learn C";
char ch = 'm'; char str2[ ] = “co”;
puts(str1); puts(str1);
puts(strchr(str1, ch)); puts(strchr(str1, str2));

P BHANU PRAKASH 9676288008 [email protected] 30


return 0; return 0;
} }

Output: Output:

Welcome to learn C Welcome to learn C


me to learn C come to learn C

STRINGS AND POINTERS:

An efficient String handling concept in ‘C’ language is achieved by implementing two methods. They are,
1. Using character array. example: char str[25] = “Welcome to learn C.”;
2. Using pointer variable. example: char *ptr; ptr = str;
Definition:
In C, Pointers play a crucial role in handling strings efficiently. String is an array of characters terminated by
a null character ('\0'). Pointers can be used to manipulate strings more efficiently. Pointer that points to the beginning
of the string.
Pointer is used to store the String in a Variable. That variable is called as ‘pointer variable’. While using pointer,
no need to go for character data type array.
Pointer is a variable that stores the memory address of another variable. Pointers are widely used in languages
like C to facilitate dynamic memory allocation, array manipulation, and function parameter passing. a pointer is
declared using the * (asterisk) symbol. Dereferencing a pointer means accessing the value stored at the memory address
it points to. The * (asterisk) symbol is used for dereferencing.

1. ‘C’ String program using Pointer variable. 1.1. ‘C’ String program using Pointer variable.
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
char myString[] = "Hello, World!"; char myString[ ];

char *ptr = myString; char *ptr;

while (*ptr != '\0') puts(“Enter a String: “);


{ gets(myString);
printf("%c", *ptr);
ptr++; ptr = myString;
}
puts(ptr);
return 0; return 0;
} }
output:
output: Enter a String: Hello, World!
Hello, World! Hello, World!

P BHANU PRAKASH 9676288008 [email protected] 31


2. ‘C’ program to check palindrome or not using 2.1. ‘C’ program to check palindrome or not using
Pointer variable. Pointer variable.
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
char actual[ ] = ”refer”, *rev; char actual[ ], *rev;
int result; int result;
// rev = actual; printf(“Enter a String: “);
strcpy(rev, actual); gets(actual);
strrev(rev); strcpy(rev, actual);
result=strcmp(actual, rev); strrev(rev);
if(result == 0) result=strcmp(actual, rev);
printf("Given string is a Palindrome."); if(result == 0)
else printf("Given string is a Palindrome.");
printf("Given strings is Not a Palindrome"); else
printf("Given strings is Not a Palindrome");
return(0);
} return(0);
}
Output:
Enter a String: reviver Output:
Given string is a Palindrome. Enter a String: refer
Given string is a Palindrome.
Enter a String: welcome [ radar, level, civic, madam, refer, noon, rotor, deed,
Given string is Not a Palindrome. reviver, rotavator. ]

[ C does not have Boolean data types, and normally uses integers for Boolean testing. Zero is used to
represent false, and One is used to represent true. For interpretation, zero is interpreted as false and
anything non-zero is interpreted as true.]

*****************************End of Third Unit******************************

P BHANU PRAKASH 9676288008 [email protected] 32

You might also like