ARRAY
Introduction
An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number. For instance, if we want to store the marks scored by a student in 5 subjects, then there’s no need to define individual variables for each subject. Rather, we can define an array that will store the data elements at contiguous memory locations. Array marks[5] define the marks scored by a student in 5 different subjects where each subject’s marks are located at a particular location in the array, i.e., marks[0] denote the marks scored in the first subject, marks[1] denotes the marks scored in 2nd subject and so on.
Advantages of Array
1. Arrays represent multiple data elements of the same type using a single name.
2. Accessing or searching an element in an array is easy by using the index number.
3. An array can be traversed easily just by incrementing the index by 1.
4. Arrays allocate memory in contiguous memory locations for all its data elements.
Disadvantages of Array
Accessing an array out of bounds:
➢The first disadvantage of arrays is that they are statically allocated.
➢This means that once their size is initialized, it can not be increased or decreased.
➢Homogeneity:
➢We can store only a single type of element in the array i.e., arrays are homogeneous.
➢We can not use it as a template. For example, if the array data type is char, then only characters can be stored in the array.
➢If you try to store integers or any other element of a different data type, it will throw an error.
One Dimension Array Declaration
➢There are various ways in which an array can be declared and initialized in various ways. You can declare an array of any data type (i.e.int, float, double, char)
in C.
➢The following ways can be used to declare and initialize an array in C.
➢Array Declaration by Specifying the Size
➢Arrays can be declared by specifying the size or the number of array elements.
➢The size of the array specifies the maximum number of elements that the array can hold.
➢you can either declare an array by simply specifying the size at the time of the declaration or you can provide a user-specified size.
➢When an array is declared without allocating any value, then it stores a garbage value. If you access any uninitialized array value, then just like any uninitialized variable, it will give you a garbage value.
➢Array Declaration by Initializing Elements
➢An array can be initialized at the time of its declaration.
➢In this method of array declaration, the compiler will allocate an array of size equal to the number of the array elements.
➢The following syntax can be used to declare and initialize an array at the same time.
// initialize an array at the time of declaration.
int my_array[] = {100, 200, 300, 400, 500}
➢In the above syntax, an array of 5 elements is created and even though the array size has not been specified here, the compiler will allocate a size of 5 integer elements.
➢Array Declaration by Specifying the Size and Initializing Elements
➢An array can also be created by specifying the size and assigning array elements at the time of declaration.
➢This method of array creation is different from the previous one.
➢Here, if the number of initialized elements is less than the size of the array specified, then the rest of the elements will automatically be initialized to 0 by the compiler.
//declare an array by specifying size and // initializing at the time of declaration int my_array1[5] = {100, 200, 300, 400, 500}; // my_array1 = {100, 200, 300, 400, 500} // int my_array2[5] = {100, 200, 300}; // my_array2 = {100, 200, 300, 0, 0}
➢Array Initialization Using a Loop
Ø An array can also be initialized using a loop.
Ø The loop iterates from 0 to (size - 1) for accessing all indices of the array starting from 0.
Ø The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C.
Ø In the given syntax, an array of size 5 is declared first. The array is then initialized using a for loop that iterates over the array starting from index 0 to (size - 1).
// declare an array.
int my_array[5];
// initialize array using a "for" loop.
int i;
for(i = 0; i < 5; i++)
{
my_array[i] = 2 * i;
}
// my_array = {0, 2, 4, 6, 8}
Access Array Elements
➢Since an array is stored contiguously in the memory, it has indices starting from ”0” to “array_size - 1”, also known as zero-based indexing.
➢This indexing represents the position in the array.
➢The array indices are used to access any element of the array in the following way:
array_name[index]
➢The index of the element to be accessed is specified within square brackets “[]”. The range of the index is- integers in the range [0, size]. Example:
Input Array Elements
➢Array values can be stored by taking input from the user and storing them in the array. The following example illustrates this:
// input an integer element and store it
// in 1st position of the array
scanf("%d", &my_array[0]);
// input a float element and store
it // in ith position of the array
Scanf("%f",&my_array[i-1]);
Output Array Elements
➢array elements can also be displayed in the output using the printf() method.
➢The index is specified indicating the position of the element to be printed.
➢The following example illustrates this:
// print the element stored at 1st position or 0th index
printf("%d", my_array[0]);
// print the element stored at ith position or (i - 1)th index
printf("%d", my_array[i-1]);
WAP to store marks of 5 subjets and display them.
#include <stdio.h>
int main(){
int marks[5];
int i;
for (i = 0; i < 5; i++) {
printf("Enter marks for subject %d:",i+1);
scanf("%d", &marks[i]);
}
for (i = 0; i < 5; i++) {
printf("The marks for subject %d:",i+1);
printf("%d\n", marks[i]);
}
return 0;
}
WAP to store marks of 5 subjects and find sum and average
#include <stdio.h>
int main(){
int marks[5];
int i,sum=0;
float average;
for (i = 0; i < 5; i++) {
printf("Enter marks for subject %d:",i+1);
scanf("%d", &marks[i]);
}
for (i = 0; i < 5; i++) {
sum = sum + marks[i];
}
printf("The total marks obtained is %d\n",sum);
average = sum/5.0;
printf("Average = %f\n",average);
return 0;
}
WAP to find the smallest and largest elements in the array
#include <stdio.h>
#define N 5
int main(){
int a[N];
int i,small, large;
for (i = 0; i < 5; i++) {
printf("Enter the %d element of an array:",i+1);
scanf("%d", &a[i]);
}
small = a[0];
large = a[0];
for (i = 0; i < 5; i++) {
if(small>a[i])
small = a[i];
if(large < a[i])
large = a[i];
}
printf("The smallest element is %d and largest is %d",small,large);
return 0;
}
WAP to insert an element in an array
#include <stdio.h>
int main() {
int i;
int arr[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
int pos;
printf("Enter the position: ");
scanf("%d", &pos);
int element;
printf("Enter the element: ");
scanf("%d", &element);
if (pos > 10) {
printf("Input is invalid !");
}
else {
for (i = 9; i >= pos - 1; i--)
arr[i + 1] = arr[i];
arr[pos - 1] = element;
printf("Array after insertion is:\n");
for (i = 0; i < 10; i++)
printf("% d ", my_array[i]);
}
return 0;
}
Sorting
➢Sorting refers to ordering data in an increasing or decreasing
manner according to some linear
relationship among the data items.
➢Ordering:
arranging items in a sequence ordered by some criterion;
➢A Sorting Algorithm is used to rearrange a given array or list of
elements according to a comparison operator on the elements. The
comparison operator is used to decide the new order of elements
in the
respective data structure.
➢Different types of sorting
algorithms:
➢Selection Sort
➢Insertion Sort
➢Exchange Sort
➢Bubble Sort
➢Merge
Sort
Selection Sort
➢Selection sort is a sorting algorithm that selects the smallest
element from an unsorted list in each iteration and places that
element at the beginning of the unsorted list and then forget the
leftmost component. Do this
repeatedly.
➢Let a[n] be a linear array
of n elements.
➢The selection sort works as
follows:
➢pass 1: Find the location loc of the smallest element in the list of n
elements a[0], a[1], a[2], a[3], …......,a[n-1] and then interchange
a[loc] and a[0].
➢Pass 2: Find the location loc of the smallest element in the sub-list
of n-1 elements a[1], a[2], a[3], …......,a[n-1] and then interchange
a[loc] and a[1] such that a[0], a[1] are sorted.
➢Then we will get the sorted list a[0]<=a[1]<=
a[2]<=a[3]<= …......<=a[n-1].
WAP to perform a selection sort in an array.
#include <stdio.h>
int main() {
int data[] = {20, 18, 10, 15, 2};
int temp,i,j;
int size = sizeof(data) / sizeof(data[0]);
for (i = 0; i< size - 1; i++) {
int min_idx = i;
for (j = i+ 1; j < size; j++) {
if (data[j] < data[min_idx])
min_idx = j;
}
temp = data[min_idx];
data[min_idx] = data[i];
data[i] = temp;
}
printf("Sorted array in Acsending Order:\n");
for (int i = 0; i < size; ++i) {
printf("%d ", data[i]);
}
}
Bubble Sort
Ø Bubble Sort is a simple sorting algorithm commonly used to sort elements in a list or array.
Ø It works by repeatedly comparing adjacent elements and swapping them if they are in the wrong order.
Ø The algorithm iterates through the list multiple times until no more swaps are needed, resulting in a sorted sequence.
Ø Just like the movement of air bubbles in the water that rise up to the surface, each element of the array move to the end in each iteration.
Ø Therefore, it is called a bubble sort.
WAP to perform a bubble sort in an array.
#include <stdio.h>
int main() {
int data[] = {-2, 45, 0, 11, -9};
int i,j;
int size = sizeof(data) / sizeof(data[0]);
for (i = 0; i < size - 1; ++i) {
for (j = 0; j < size - i - 1; ++j) {
if (data[j] > data[j + 1]) {
int temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
printf("Sorted Array in Ascending Order:\n");
for (int i = 0; i < size; ++i) {
printf("%d ", data[i]);
}
}
WAP to input age of 30 employees into array and find out the second largest age from array.
#include<stdio.h>
#define size 5
void main(){
int i,j,temp,age[size];
printf ("Enter the numbers\n");
for (i=0; i<size; ++i)
scanf ("%d",&age[i]);
for (i = 0; i< size - 1; i++) {
int min_idx = i;
for (j = i+ 1; j < size; j++) {
if (age[j] < age[min_idx])
min_idx = j;
}
temp = age[min_idx];
age[min_idx] = age[i];
age[i] = temp;
}
printf ("The numbers arranged in assending order are given below\n");
for (i=0; i<size; ++i)
printf ("%d ",age[i]);
printf ("The 2nd largest age is = %d", age[size-2]);
}
Searching (Sequential)
Searching refers to the process of finding the required information from a collection of items stored as elements in the computer memory.
Sequential Search
Sequentially checks each element of the list until the key element is found or the entire list has been traversed.
It uses conditional statements and relational operators to find whether the given element is present in the list or not.
WAP to implement a sequential search in an array.
#include <stdio.h>
int main() {
int array[100], search, i, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (i = 0; i < n; i++) {
if (array[i] == search) {
printf("%d is present at location %d.\n", search, i+1);
break;
}
}
if (i == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
WAP to input any 10 integers and count the number of even and odd elements in an array.
#include <stdio.h>
#define size 10
int main() {
int array[size], counteven = 0, countodd = 0,i;
printf("Enter any 10 integer(s)\n");
for (i = 0; i < size; i++)
scanf("%d", &array[i]);
for (i = 0; i < size; i++) {
if (array[i]%2 == 0) {
counteven++;
}
else{
countodd++;
}
}
printf("The number of even numbers = %d",counteven);
printf("The number of odd numbers = %d",countodd);
return 0;
}
Multi-Dimensional
Array
Ø A multi-dimensional array can be termed as
an array of arrays that stores homogeneous data in tabular form.
Ø Data in multidimensional arrays is
generally stored in row-major order in the memory.
Ø The general form of declaring N-dimensional arrays is
shown below.
Ø data_type array_name[size1][size2]....[sizeN];
Ø data_type: Type of data to be stored in the array.
Ø array_name: Name of the array.
Ø size1,
size2,…, sizeN: Size of each
dimension.
Ø Examples:
Ø Two dimensional array: int two_d[10][20];
Ø Three dimensional array: int three_d[10][20][30];
Size of Multidimensional Arrays:
Ø The total number of elements that can be
stored in a multidimensional array can be calculated by multiplying the size of
all the dimensions. For example:
Ø The array int x[10][20] can store total (10*20) = 200 elements.
Ø Similarly array int x[5][10][20] can store total
(5*10*20) = 1000 elements.
Ø To get the size of the array in bytes, we
multiply the size of a single element with the total number of elements in the
array. For example:
Ø Size of array int x[10][20] = 10 * 20 * 4 = 800 bytes.
(where int = 4 bytes)
Ø Similarly, size of int x[5][10][20] = 5 * 10 * 20 *
4 = 4000 bytes. (where int = 4 bytes)
Ø The most commonly used forms of the
multidimensional array are:
Ø Two
Dimensional Array
Ø Three
Dimensional Array
Initialization of
Multi-Dimensional Array
Ø Initialization
of a 2d array
Ø int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
Ø int c[2][3] = {1, 3, 0, -1, 5, 9};
Ø Initialization
of a 3d array
Ø int
test[2][3][4] = {{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},{{13, 4, 56,
3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Two Dimensional Array
Ø A two-dimensional array or 2D array in C is the simplest form of the multidimensional
array.
Ø We can visualize a two-dimensional array as
an array of one-dimensional arrays arranged one over another forming a table
with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and
the column number ranges from 0 to (y-1).
Declaration of Two-Dimensional Array in C
Syntax:
data_type
array_name[x][y];
where,
◦
data_type: Type
of data to be stored in each element.
◦
array_name: name
of the array
◦
x: Number of
rows.
◦
y: Number of
columns.
Ø We can declare a two-dimensional integer
array say ‘x’ with 10 rows and 20 columns as:
Ø Example:
Ø int x[10][20];
Initialization of Two-Dimensional Arrays
Ø The various ways in which a 2D array can
be initialized are as follows:
Ø Using
Initializer List
Ø Using
Loops
Ø Initialization
of 2D array using Initializer List
Ø int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7
, 8 , 9 , 10 , 11};
Or
Ø int x[3][4] = {{0,1,2,3}, {4,5,6,7},
{8,9,10,11}};
Or
Ø int x[][3] = {{1, 3, 0}, {-1, 5, 9}};
Initialization of 2D array using Loops
int x[3][4];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 4; j++){
x[i][j] = i + j;
}
}
Accessing Elements of Two-Dimensional Arrays
Ø Elements in 2D arrays are accessed using row indexes and column indexes. Each element in a 2D array can be referred to by:
Ø Syntax:
Ø array_name[i][j];
Ø where,
◦ i: The row index.
◦ j: The column index.
Ø Example:
Ø int x[2][1];
#include <stdio.h>
int main(){
int x[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("Element at x[%i][%i]: ", i, j);
printf("%d\n", x[i][j]);
}
}
return 0;
}
WAP to store temperature of two cities of a week and display it.
#include <stdio.h>
const int CITY = 2;
const int WEEK = 7;
int main() {
int temperature[CITY][WEEK];
for (int i = 0; i < CITY; ++i) {
for (int j = 0; j < WEEK; ++j) {
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &temperature[i][j]);
}
}
printf("\nDisplaying values: \n\n");
for (int i = 0; i < CITY; ++i) {
for (int j = 0; j < WEEK; ++j) {
printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]);
}
}
return 0;
}
WAP to find the sum of two matrices of order m x n.
#include <stdio.h>
int main() {
int i,j,row,col;
printf("Enter the number of rows");
scanf("%d",&row);
printf("Enter the number of column");
scanf("%d",&col);
float a[row][col], b[row][col], result[row][col];
//
printf("Enter elements of 1st matrix\n");
for (i = 0; i < row; ++i)
for (j = 0; j < col; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}
printf("Enter elements of 2nd matrix\n");
for (i = 0; i < row; ++i)
for (j = 0; j < col; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}
for (i = 0; i < row; ++i)
for (j = 0; j < col; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}
printf("\nSum Of Matrix:\n");
for (i = 0; i < row; ++i)
for (j = 0; j < col; ++j)
{
printf("%.1f\t", result[i][j]);
if (j == col-1)
printf("\n");
}
return 0;
}
WAP to find the product of two matrices.
#include<stdio.h>
int main() {
int r1, c1, r2, c2, i, j, k;
int a[10][10], b[10][10], res[10][10];
printf("Enter the order of first matrix\n");
scanf("%d%d", &r1, &c1);
printf("Enter the order of second matrix\n");
scanf("%d%d", &r2, &c2);
if (c1 != r2) {
printf("matrix is incompatible for multiplication\n");
}
else {
printf("Enter the elements of matrix-A:\n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
scanf("%d", & a[i][j]);
}
}
printf("Enter the elements of matrix-B:\n");
for (i = 0; i < r2; i++) {
for (j = 0; j < c2; j++) {
scanf("%d", & b[i][j]);
}
}
/* loop to multiply two matrices */
for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++) {
res[i][j] = 0;
for (k = 0; k < r2; k++) {
res[i][j] += a[i][k] * b[k][j];
}
}
}
printf("The product of the two matrices is:-\n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++) {
printf("%d\t", res[i][j]);
}
printf("\n");
}
}
return 0;
}
WAP to Find the
Transpose of a Matrix
#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
printf("\nEnter matrix elements:\n");
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
}
printf("\nEntered matrix: \n");
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
}
printf("\n");
}
// computing the transpose
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}
}
WAP to find the sum
of diagonal elements of a square matrix
#include<stdio.h>
void main() {
int mat[12][12];
int i,j,row,col,sum=0;
printf("Enter the number of rows and columns for matrix\n");
scanf("%d%d",&row,&col);
if(row != col){
printf("It is not a square matrix");
}
else {
printf("Enter the elements of the matrix\n");
for(i=0;i<row;i++) {
for(j=0;j<col;j++) {
scanf("%d",&mat[i][j]);
}
}
printf("The matrix\n");
for(i=0;i<row;i++) {
for(j=0;j<col;j++) {
printf("%d\t",mat[i][j]);
}
printf("\n");
}
//To add diagonal elements
for(i=0;i<row;i++) {
for(j=0;j<col;j++) {
if(i==j) {
sum=sum+mat[i][j];
}
}
}
printf("The sum of diagonal elements of a square matrix = %d\n",sum);
}
}
WAP to display the upper triangular matrix.
#include<stdio.h>
int main() {
int rows, cols, array[10][10],i,j;
printf("Enter the rows and cols value:");
scanf("%d%d", &rows, &cols);
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("array[%d][%d] = ", i, j);
scanf("%d", &array[i][j]);
}
}
printf("matrix is\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
if(rows != cols) {
printf("Matrix should be a square matrix\n");
}
else{
printf("Upper triangular matrix: \n");
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
if(i > j)
printf("0 ");
else
printf("%d ", array[i][j]);
}
printf("\n");
}
}
return 0;
}
Three-Dimensional Array in C
Ø A Three Dimensional Array or 3D array in C is a collection of two-dimensional arrays. It can be visualized as multiple 2D arrays stacked on top of each other.
Fig: Graphical Representation of Three-Dimensional Array of Size 3 x 3 x 3
Declaration of Three-Dimensional Array
Syntax:
◦ data_type array_name[x][y][z];
◦ Where,
◦ data_type: Type of data to be stored in each element.
◦ array_name: name of the array
◦ x: Number of 2D arrays.
◦ y: Number of rows in each 2D array.
◦ z: Number of columns in each 2D array.
Ø Example:
Ø int array[3][3][3];
Initialization of Three-Dimensional Array
Ø
A 3D array in C can be initialized by using:
Ø
Initializer List
Ø
Loops
Ø
Initialization of 3D Array using Initializer
List
Ø
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23};
Or
Ø
int x[2][3][4] = { {{0,1,2,3}, {4,5,6,7},
{8,9,10,11}}, {{12,13,14,15}, {16,17,18,19}, {20,21,22,23}} };
Initialization of 3D
Array using Loops
Ø
It is
also similar to that of 2D array with one more nested loop for accessing one
more dimension.
int x[2][3][4];
for (int i=0;
i<2; i++) {
for (int j=0; j<3; j++) {
for (int k=0; k<4; k++) {
x[i][j][k] = (some_value);
}
}
}
Accessing elements
in Three-Dimensional Array
Ø
Accessing
elements in 3D Arrays is also similar to that of 3D Arrays.
Ø
The
difference is we have to use three loops instead of two loops for one
additional dimension in 3D Arrays.
Ø
Syntax:
Ø
array_name[x][y][z]
where,
Ø
x: Index
of 2D array.
Ø
y: Index
of that 2D array row.
Ø
z: Index
of that 2D array column.
#include
<stdio.h>
int
main(){
int x[2][3][2] = { { { 0, 1 }, { 2, 3 }, {
4, 5 } }, { { 6, 7 }, { 8, 9 }, { 10, 11 } } };
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
printf("Element at
x[%d][%d][%d] = %d\n", i, j, k, x[i][j][k]);
}
}
}
return 0;
}
WAP to print 3D
array elements and their indexes
#include<stdio.h>
#include<conio.h>
int
main() {
int i, j, k;
int arr[3][4][2] = {
{ {2, 4}, {7, 8}, {3, 4}, {5, 6} },
{ {7, 6}, {3, 4}, {5, 3}, {2, 3} },
{ {8, 9}, {7, 2}, {3, 4}, {5, 1} }
};
for(i=0; i<3;
i++) {
for(j=0; j<4; j++) {
for(k=0; k<2; k++) {
printf("arr[%d][%d][%d] = %d
", i, j, k, arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
getch();
return 0;
}
String in C
Ø
A String
in C programming is a sequence of characters terminated with a null character
‘\0’.
Ø
The C
String is stored as an array of characters.
Ø
The
difference between a character array and a C string is the string is terminated
with a unique character ‘\0’.
Ø
Operations
performed on character strings include:
Ø Reading and writing strings.
Ø
Copying
one string to another.
Ø
Combining
strings together.
Ø
Comparing
strings for equality
Ø Extracting a portion of a string.
C String
Declaration
Ø
Declaring
a string in C is as simple as declaring a one-dimensional array.
Ø
Below is
the basic syntax for declaring a string.
Ø
char string_name[size];
Ø
Where,
Ø
str_name is any name given to the string variable and size is used to define
the length of the string, i.e the number of characters strings will store.
Ø
There is
an extra terminating character which is the Null character (‘\0’)
used to indicate the termination of a string that differs strings from normal
character arrays.
C String
Initialization
Ø
We can
initialize a C string in 4 different ways which are as follows:
Ø
Assigning a string literal without size
Ø
String
literals can be assigned without size. Here, the name of the string str acts as
a pointer because it is an array.
Ø
char
str[] = “Programming";
Ø
Assigning a string literal with a predefined
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.
Ø
char
str[50] = “Programming";
Ø
Assigning character by character with size
Ø
We can
also assign a string character by character. But we should remember to set the
end character as ‘\0’ which is a null character.
Ø
char
str[14] = { ‘P',‘r',‘o',‘g',’r’,‘a',‘m',‘m',‘i',‘n',‘g','\0'};
Ø
Assigning character by character without size
Ø
We can
assign character by character without size with the NULL character at the end.
Ø
The size
of the string is determined by the compiler automatically.
Ø
char
str[] = { ‘P',‘r',‘o',‘g',’r’,‘a',‘m',‘m',‘i',‘n',‘g','\0'};
Reading string from
user
Ø
The
input function scanf can be used with %s format specification to read in a
string of characters.
Ø
Eg:
scanf(“%s”,name);
Ø
No
ampersand(&) is required before variable name.
Ø
Scanf()
terminates its input on the first white space it encounters.
#include<stdio.h>
int
main() {
char name[50]
printf("Enter your name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}
Ø
Some
version of scanf() support the following conversion specification for strings:
Ø
%[characters]
Ø
%[^characters]
Ø
The
specification %[characters] means that only the characters specified within the
brackets are allowed in the input of string.
Ø
The
specification %[^characters] means that the characters specified after the
caret(^) are not allowed in the string.
Ø
%[A-Z],
%[^\n]
String handling
function
Ø
The
<string.h> header file defines some string handling function such as
strcpy(), strcat(),strev(),strcmp(), strlen(), etc.
Ø
This
functions are used for:
Ø
Manipulating
string data.
Ø
Determining
the length of strings.
Ø
Copying
a string
Ø
Concatenation
of two strings
Ø
Changing
to upper and lower case
Copy String
Ø
To copy
a string in C programming, you have to ask the user to enter the string to
store it in the first string variable, say str1, and then copy it into the
second string variable, say str2, using the strcpy() function of
the string.h library.
Ø
The
function strcpy() takes two arguments.
Ø
The
value of the second argument gets copied to the first argument.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int
main() {
char str1[20], str2[20];
printf("Enter the string: ");
gets(str1);
printf("\nString 1 = %s", str1);
strcpy(str2, str1);
printf("\nString 2 = %s", str2);
getch();
return 0;
}
Copy String without
using strcpy
#include<stdio.h>
int
main() {
char str1[100], str2[100], i;
printf("Enter string 1: ");
gets(str1);
for (i = 0; str1[i] != '\0'; ++i) {
str2[i] = str1[i];
}
str2[i] = '\0';
printf("String 2: %s", str2);
return 0;
}
Finding length of
string
#include
<stdio.h>
#include
<string.h>
int
main() {
char str[100];
printf("Enter the string: ");
scanf("%s", str);
int length;
length = strlen(str);
printf("The length of the string is
%d", length);
return 0;
}
Finding length of
string without using strlen
#include
<stdio.h>
int
main() {
char s[100];
int i,count = 0;
printf("Enter the string");
gets(s);
for (i = 0; s[i] != '\0'; ++i){
count++;
}
printf("Length of the string:
%d", count);
return 0;
}
Concatenating two
strings
#include
<stdio.h>
#include
<string.h>
int
main() {
char s[] = “C-";
char s1[] = “Programming";
// concatenating the string
strcat(s, s1);
printf("Final string is: %s ",
s);
return 0;
}
Reversing the string
#include
<stdio.h>
#include
<string.h>
int main() {
char s[100];
printf("Enter a string to
reverse\n");
gets(s);
strrev(s);
printf("Reverse of the string:
%s\n", s);
return 0;
}
String Comparison
(strcmp())
Ø
The
strcmp() compares two strings character by character. If the strings are equal,
the function returns 0.
Ø
The
function takes two parameters:
Ø
str1 - a string
Ø
str2 - a string
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
Converting string to Uppercase
#include<stdio.h>
#include<string.h>
int main() {
char str[100];
printf(“Enter any string in lowercase”);
gets(str);
strupr(str);
printf("%s\n", str);
return 0;
}
Converting string to Uppercase without strupr
#include <stdio.h>
#include <string.h>
int main() {
char s[100];
int i;
printf("Enter a string : ");
gets(s);
for (i = 0; s[i]!='\0'; i++) {
if(s[i] >= 'a' && s[i] <= 'z') {
s[i] = s[i] -32;
}
}
printf("String in Upper Case = %s", s);
return 0;
}
Converting string to Lowercase
#include<stdio.h>
#include<string.h>
int main() {
char str[100];
printf("Enter any string");
gets(str);
strlwr(str);
printf("%s\n", str);
return 0;
}
Exercise
Ø WAP to read a string and count the number of vowels and consonant in it.
Ø WAP to convert the string to lowercase without using library function.
Ø WAP to check whether a given string is a palindrome or not.
Ø WAP for combining two strings without using strcat() function.
Ø Write a menu driven program to input a 3x3 matrix and display the menu:
◦ 1. Print the input matrix
◦ 2. Sum of even values of elements.
◦ 3. sum of all diagonal elements.
◦ 4. exit
And perform the task as per user’s choice until the choice is to exit using switch.
Ø WAP to display the lower triangular matrix.
If you want this exercise question solution then contact me on this https://www.facebook.com/profile.php?id=61554209287166
No comments:
Post a Comment