Unit-3 Intro To Prog (AK23)
Unit-3 Intro To Prog (AK23)
Introduction:
So far, we have used only single variable name for storing one data item. If we need to store
multiple copies of the same data then it is very difficult for the user. To overcome the difficulty a new
data structure is used called arrays.
[ So far, we have used only the fundamental data types, namely char, float, int, double and variations of
int and double. A variable of these types can store only one value at any given time. Therefore, they can be
used only to handle limited amounts of data.
To Process such large amounts of data, we need a powerful data type that would facilitate efficient
storing, accessing and manipulation of data items. Array is a secondary or Derived Data type. At some
important areas the concept arrays are used,
• To maintain list of employees in a company.
• In pharmacy to maintain list of Drugs and their cost.
• To maintain test scores of a class of students. ]
Definition of an Array:
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the primitive
type of data such as int, char, double, float, etc. (or)
Array in C can be defined as a method of clubbing multiple entities of similar type into a larger
group in contiguous memory. These entities or elements can be of int, float, char, or double data
type or can be of user-defined data types. (or)
An array is a data structure that stores a collection of similar data type elements, each
identified by an index. The elements in an array are stored in contiguous memory locations, and the
index is used to access a specific element within the array. Arrays are commonly used in computer
programming to organize and manipulate sets of related data. (or)
Array is defined as the set of same data items which are stored in contiguous memory by
sharing same variable name with different index positions. Array permits to declare of any one of
the primitive data types. Array index always starts with zero.
Example:
int a[10]; float a[10]; double a[10]; char str[25];
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 1
[ Suppose we have to store the roll numbers of the 100 students the we have to declare 100 variables
named as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C programming arrays is
introduced in C which gives the capability to store the 100 roll numbers in the contiguous memory which has
100 blocks and which can be accessed by single variable name.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
In the above figure 4, 5, 33, 13, 1 are actual data items. 0, 1, 2, 3, 4 are index variables.
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.
Characteristics of an array:
1. The declaration int a[5] is nothing but 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. ]
Array Declaration:
Array has to be declared before using it in C Program. Array is nothing but the collection of
elements of similar data types.
where as,
Data Type - Data Type specifies the type of the array. We can compute the size required for
storing the single cell of array.
Valid Identifier - Valid identifier is any valid variable or name given to the array. Using this identifier
array_name can be accessed.
Size of Array - It is maximum size that array can have.
Types of an Array:
An array can be of,
1. One-Dimensional array
2. Two-Dimensional array
3. Multi-Dimensional array
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 3
1-D Array Declaration and Initialization:
Syntax for declaration: <data_type> <array_name> [max_size];
Examples: int iarr[10]; char carr[20]; float farr[30];
[ Explanation 1: int y[10] = { 205, 207, 208, 209, 210, 211 }; // values separated by comma
From the above statements the array_name ‘y’ elements are stored in memory as follows,
Compiler will allocate two bytes of space for 10 each integer array elements, totally 20 bytes of space is
allocated for array name y. ]
Compiler will allocate one byte of space for 10 each character array elements, totally 10 bytes of space is
allocated for array name N. ]
#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 }; // int num[ ] = { 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; return 0;
} }
O/p: 1 2 3 4 5 O/p: 1 2 3 4 5
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 4
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 }; into memory as,
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 .
.
. .
. .
memory stack model
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.
3. Searching - An array element can be searched. The process of seeking specific elements in
an array is called searching.
4. 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.
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 5
PROGRAMS WITH 1-D ARRAY OF INTEGERS: .
1. Initialize and print 1-D array with 5 data elements. 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.
Output:
Enter no of elements: 5
10 20 30 40 50
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()
{ {
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 6
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])
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 }
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");
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 7
return (0); Enter no of elements: 5
} Enter the values: 11 22 33 44 55
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> #include<stdio.h>
int main() int main()
{ {
int arr1[30], arr2[30], mrg[60]; int i, arr[50], sum, num;
int i, j, n1, n2, n3; printf("\nEnter no of elements: ");
printf("\nEnter no of elements in 1st array:"); scanf("%d", &num);
scanf("%d", &n1); printf("\nEnter the values: ");
for (i = 0; i < n1; i++) { for (i = 0; i < num; i++)
scanf("%d", &arr1[i]); } scanf("%d", &arr[i]);
printf("\nEnter no of elements in 2nd array:"); for (i = 0; i < num; i++)
scanf("%d", &n2); sum = sum + arr[i];
for (i = 0; i < n2; i++) for (i = 0; i < num; i++)
{ printf("\na[%d]=%d", i, arr[i]);
scanf("%d", &arr2[i]); printf("\nSum=%d", sum);
} return (0);
for (i=0; i<n1; i++) // Merging starts }
{
mrg[i] = arr1[i]; // copy arr1[ ] into mrg[ ] Output:
j=i;
} Enter no of elements: 3
for (i=0; i<n2; i++) Enter the values: 11 22 33
{ a[0]=11
j++; a[1]=22
mrg[j] = arr2[i]; // copy arr2[ ] into mrg[ ] a[2]=33
} Sum=66
n3=n1+n2;
printf("Merged array is: "); 8.1: Write a C Program to find Sum of all array
for (i = 0; i < n3; i++) elements & average of them.
{
printf("%d", mrg[i]); #include<stdio.h>
} int main()
return(0); {
} int i, n=10, sum; float avg=0.0;
int arr[n] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 10 };
Output: for (i = 0; i < n; i++)
sum = sum + arr[i];
Enter no of elements in 1st array: 5 avg = (float) sum / 10;
11 22 33 44 55 printf("\nSum = %d", sum);
Enter no of elements in 2nd array: 5 printf("\nAverage = %f", avg);
66 77 88 99 100 return(0);
}
Merged array is: 10 11 22 33 44 55 66 77 88 99 100 Output: Sum = 55 Avg = 5.5
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 8
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> #include<stdio.h>
int main() int main()
{ {
int a[30], i, num, smallest; int a[30], i, num, biggest;
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", &a[i]); scanf("%d", &a[i]);
smallest = a[0]; biggest = a[0];
for (i = 0; i < num; i++) 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); printf("\nBiggest Element is: %d", biggest);
return (0); return (0);
} }
Output: Output:
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++)
{ printf("%d \t", arr[i]); } Enter no of elements: 5
return (0); 11 22 33 44 55
} Result after reversal: 55 44 33 22 11
Output:
Enter no of elements: 5
11 22 33 44 55
Result after reversal: 55 44 33 22 11
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 9
TWO DIMENSIONAL ARRAYS .
So far, we have discussed the array variables that can store a list of values. There could be
situations where a table of values will have to be stored. In such situations this concept is useful.
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. 2-D arrays are stored
in contiguous memory location row wise. (or)
A matrix is a two-dimensional array that has a size of m-by-n, where m and n are nonnegative
integers. As like one dimensional array, two dimensional arrays are stored in contiguous memory
location row wise. (or)
Example:
int matrix_a[3][3]; float b[5][10]; double a[10][10]; char name[5][25];
Two Dimensional Array requires Two Subscript Variables. It stores the values in the form of
matrix. One Subscript Variable denotes the “Row” of a matrix. Second Subscript Variable denotes
the “Column” of a matrix.
Syntax:
<datatype> array_name [row_size] [column_size];
where, two dimensional array consisting of 3 rows and 3 columns. So the total number of elements
which can be stored in this array are 3 * 3 i.e., 9.
1. Initialize all Array elements but initialization is much straight forward / comma separated values. All values
are assigned sequentially and row-wise.
Syntax:
<data_type> array_name [row_size] [column_size] = { var_1, var_2, ... , var_n };
(or)
<data_type> array_name [row_size] [column_size] = { {row1 list}, {row2 list}, ... {row n list} };
Example:
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 10
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
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' }
};
Ex: 2-D Array elements initialize by its subscripts / index Ex: 2-D 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 mat_a[3][3]; int mat_a[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
/* int mat_a[ ][ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; */
mat_a[0][0]=1;
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;
mat_a[2][0]=7; printf(" %d ", mat_a[1][0] );
mat_a[2][1]=8; printf(" %d ", mat_a[1][1] );
mat_a[2][2]=9; printf(" %d ", mat_a[1][2] );
printf("\n");
printf(" %d ", mat_a[0][0] );
printf(" %d ", mat_a[0][1] ); printf(" %d ", mat_a[2][0] );
printf(" %d ", mat_a[0][2] ); printf(" %d ", mat_a[2][1] );
printf("\n"); printf(" %d ", mat_a[2][2] );
printf("\n");
printf(" %d ", mat_a[1][0] );
printf(" %d ", mat_a[1][1] );
return 0;
printf(" %d ", mat_a[1][2] );
}
printf("\n");
printf(" %d ", mat_a[2][0] ); O/p: 1 2 3
printf(" %d ", mat_a[2][1] ); 4 5 6
printf(" %d ", mat_a[2][2] ); 7 8 9
printf("\n");
return 0;
}
O/p: 1 2 3
4 5 6
7 8 9
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 11
Storage Representation of Two-Dimensional array:
When speaking of two-dimensional arrays, we are logically saying that, it consists of two rows
and columns but when it is stored in memory, the memory is linear. Hence, the actual storage differs
from our matrix / grid representation.
= 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;
= 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;
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 12
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,
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;
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 13
PROGRAMS WITH 2-D ARRAY OF INTEGERS: .
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.
2: Write a C program to Scan and Print 2-D array. 3: Write a C program to find Transpose of matrix array.
4: Write a C program to perform addition of two matrix 5: Write a C program for Multiplication of two matrix
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 15
{ }
for (j = 0; j < 3; j++) }
{ printf("Multiplication of a & b matrix is: \n");
printf("%5d", c[i][j]); for (i = 0; i< 3; i++)
} {
printf("\n"); for (j = 0; j < 3; j++)
} {
return 0; printf("%5d", c[i][j]);
} }
printf("\n");
Outrput: }
return 0;
Enter elements of the matrix a: 1 2 3 }
4 5 6
7 8 9 Outrput:
Enter elements of the matrix a: 1 1 1
Enter elements of the matrix b: 1 2 3 2 2 2
4 5 6 3 3 3
7 8 9 Enter elements of the matrix b: 1 1 1
2 2 2
Addition of a & b matrix is: 2 4 6 3 3 3
8 10 12 Multiplication of a & b matrix :
14 16 18 (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
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 16
INTRODUCTION TO STRINGS: .
Introduction:
The Null Character in C is represented using the escape sequence '\0'. It is essential to
distinguish it from the character '0' to prevent potential bugs in string handling.
Note: ‘C’ does not have a String data type to easily create string variables. So, must use the char type and
create an array of characters to make a string in C: char str[ ] = "Hello World!";
Definition of String:
String is a sequence of character enclosed with in double quotes (“ ”) but ends with ‘\0’. The
compiler puts ‘\0’ at the end of string to specify the end of the string.
Declaration of String:
Initialization of String:
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.
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 17
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.
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’ };
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’ };
Output: Output:
Welcome Welcome
3. String program to read string and print. 4. String program to read str with whitespace and print.
Output: Output:
( Note: Entered string printed up to the first occurrence of whitespace. ) ( Note: Entered string printed completely using %[^\n]s in scanf(). )
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 18
5. String program to read str with gets() and puts(). 6. String program to read str with fgets() and fputs().
Output: Output:
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.
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.
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).
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 19
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:
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);
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 20
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.
#include<stdio.h>
#include<string.h>
int main()
{
char str1[25], str2[25];
int result;
printf(“Enter a First String: “);
gets(str1);
printf(“Enter a Second String: “);
gets(str2);
result = strcmp(str1, str2);
if(result==0)
printf(“Both the strings are Equal.”);
else
printf(“Both the strings are Not Equal.”);
return(0);
}
Output:
5. Write a C program to Reverse the given String. 5.1. Write a C program to find Palindrome or not.
#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(strrev(str1); gets(actual);
return(0); strcpy(reverse, actual);
} strrev(reverse);
result=strcmp(actual, reverse);
Output: if(result == 0)
printf("Given string is a Palindrome.");
Enter a String: Welcome else
emocleW printf("Given strings is Not a Palindrome");
return(0);
}
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 21
Output:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[25];
printf(“Enter a String: “);
gets(str1);
puts(“Actual String: ”);
puts(str1);
Output:
return 0; return 0;
} }
Output: Output:
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 22
STRINGS AND POINTERS: .
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.
output: output:
Hello, World! Enter a String: Hello, World!
Hello, World!
2. ‘C’ program to check palindrome or not 2.1. ‘C’ program to check palindrome or not
using Pointer variable. using 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: “);
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 23
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. ]
[ Courtesy: PROBLEM SOLVING and PROGRAMMING (AK19) by Mr. V.SAMBASIVA, Assistant Professor, Dept. of CSE. ]
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 24