0% found this document useful (0 votes)
24 views21 pages

UNIT III C Final

Uploaded by

Kandula Anusha
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)
24 views21 pages

UNIT III C Final

Uploaded by

Kandula Anusha
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/ 21

UNIT-III

ARRAYS AND STRINGS

1.ARRAYS INDEXING
Definition:
An array is a variable that can store multiple values. An array is defined as finite ordered collection of
homogenous data, stored in contiguous memory locations. Here the words,
 finite means data range must be defined.
 ordered means data must be stored in continuous memory addresses.
 homogenous means data must be of similar data type.
Syntax / Declaring arrays
dataType arrayName[arraySize];
 Data_type: It will decide the type of elements the array will accept. For example, If we want to store
integers, then we declare the Data Type as int. If we want to store floating-point values, then we declare
the Data Type as float, etc
 ArrName: This is the name you want to give to it. For example, students, age, marks, employees, etc
 Arr_Size: Number of elements an array can hold or store. For example, if Arr_Size =10, it will hold
10 values.
Example
float mark[5];
Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it can hold 5 floating-
point values.
It's important to note that the size and type of an array cannot be changed once it is declared.
Initialization of Array in C
After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value).
An array can be initialized at either compile time or at runtime. That means, either we can provide values to
the array in the code itself, or we can add user input value into the array.
Compile time Array initialization in C
Compile time initialization of array means we provide the value for the array in the code, when we create the
array,
data-type array-name[size] = { list of values };
For example: int mark[5] = {19, 10, 8, 17, 9};
You can also initialize an array like this.
int mark[] = {19, 10, 8, 17, 9};
Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5
elements.

#include<stdio.h> Output
void main()
{ 2 3 4
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}

Runtime Array initialization in C


An array can also be initialized at runtime using scanf() function. This approach is usually used for initializing
large arrays, or to initialize arrays with user specified values.
To input elements in an array, we can use a for loop or insert elements at a specific index.
// Program to take 5 values from the user Output
and store them in an array
// Print the elements stored in the array Enter 5 integers: 1
-3
#include <stdio.h> 34
0
int main() { 3
Displaying integers: 1
int values[5]; -3
34
printf("Enter 5 integers: "); 0
3
// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
Here, we have used a for loop to take 5 inputs from the user and store them in an array. Then, using another
for loop, these elements are displayed on the screen.
Access Array Elements
To access a specific element of an array, you use the array subscript operator [] followed by the index value of
the element you want to access. The index value represents the position of the element in the array, and it starts
from 0 for the first element.
array_name [index];
In C, array indexing always starts with 0. This means that the first element of an array is at index 0, and the
last element is at index N – 1, where N is the total number of elements in the array.
For example, if you have an array with 5 elements, the indices of the elements will be 0, 1, 2, 3, and 4.
Example
#include <stdio.h> Output
int main() Element at arr[2]: 35
{ Element at arr[4]: 55
Element at arr[0]: 15
// array declaration and initialization
int arr[5] = { 15, 25, 35, 45, 55 };

// accessing element at index 2 i.e 3rd element


printf("Element at arr[2]: %d\n", arr[2]);

// accessing element at index 4 i.e last element


printf("Element at arr[4]: %d\n", arr[4]);

// accessing element at index 0 i.e first element


printf("Element at arr[0]: %d", arr[0]);
return 0;
}
Update Array Element
To update the value of an element at a specific index in an array in C, you use the array subscript operator []
to access the element, and then you can use the assignment operator = to assign a new value to it.
// C Program to demonstrate the use of array Output
#include <stdio.h> Elements in Array: 10 20 100 40 50

int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };

// modifying element at index 2


arr[2] = 100;

// traversing array using for loop


printf("Elements in Array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}

return 0;
}

2.MEMORY MODEL
When we execute a C program, the executable code of the file loads into RAM in an organized manner.
Computers do not access program instructions directly from secondary storage because the access time of
secondary storage is longer when compared to that of RAM. RAM is faster than secondary storage but has a
limited storage capacity, so it is necessary for programmers to utilize this limited storage efficiently.
Knowledge of memory layout in C is helpful to programmers because they can decide the amount of memory
utilized by the program for its execution.
C program memory layout in C mainly comprises six components these are heap, stack, code segment,
command-line arguments, uninitialized and initialized data segments.
Diagram for memory structure of C
The diagram mentioned below shows a visual representation of how RAM loads a program written in C into
several segments.
Code segment
The code segment, also known as the text segment, is where the compiled machine instructions of the program
are stored. It contains the executable code, including functions, statements, and instructions that make up the
program's logic. This segment is typically read-only and shared among multiple instances of the same program.
Data Segment:
 The data which we use in our program will be stored in data section.
 Since the variables declared inside the main () function are stored in the stack, but the variables declared
outside the main () method will be stored in data section.
 The variables declared in the data section could be stored in the form of initialized, uninitialized, and
it could be global or local.
 Therefore, the data section is divided into four categories i.e., initialized, uninitialized, global or local.
Example
int var1;  Here var1 and var2 variables are declared outside the main()
int var2=10; function where var1 is the uninitialized variable, whereas the
void function1() var2 is an initialized variable.
{  These variables can be accessed anywhere in the program
printf(“i am function1”); Because these variables are not a part of the main() in the stack.
}
int main()
{
function1();
return 0;
}
The data segment is divided into two segments:
1. Uninitialized Data Segment
The uninitialized data segment is also known as a .bss segment that stores all the uninitialized global, local
and extern variables. The .bss segment stands for Block Started by a symbol.
char a; // uninitialized global variable.
int main()
{
static int a; // uninitialized static variable.
return 0;
}
2. Initialized data segment
An initialized data segment is also known as the data segment. A data segment is a virtual address space of a
program that contains all the global and static variables which are explicitly initialized by the programmer.
char string[]=”memory”; // global variable stored in initialized data segment in read-write area
int main()
{
static int i=90; // static variable stored in initialized data segment
return 0;
}
Stack
 The stack area traditionally adjoined the heap area and grew in the opposite direction; when the stack
pointer met the heap pointer, free memory was exhausted.
 When we define a function and call that function then we use the stack frame.
 The stack section plays a very important role in the memory because whenever the function is called,
a new stack frame is created.
 Stack is also used for recursive functions.
Heap
 Heap memory is used for the dynamic memory allocation.
 Heap memory begins from the end of uninitialized data segment and grows upwards to the higher
addresses.
 The malloc() and calloc() functions are used to allocate the memory in the heap.
 The heap memory can be used by all the shared libraries and dynamically loaded modules.
 The free() function is used to deallocate the memory from the heap.

3.PROGRAMS WITH ARRAY OF INTEGERS


Program 1
Write a program in C to read n number of values in an array and display them in reverse order.
#include <stdio.h>
void main()
{
int i,n,a[100];

printf("\n\nRead n number of values in an array and display it in reverse


order:\n");
printf("------------------------------------------------------------------------\n");

printf("Input the number of elements to store in the array :");


scanf("%d",&n);

printf("Input %d number of elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&a[i]);
}

printf("\nThe values store into the array are : \n");


for(i=0;i<n;i++)
{
printf("% 5d",a[i]);
}

printf("\n\nThe values store into the array in reverse are :\n");


for(i=n-1;i>=0;i--)
{
printf("% 5d",a[i]);
}
printf("\n\n");
}
Output
Read n number of values in an array and display it in reverse order:
------------------------------------------------------------------------
Input the number of elements to store in the array :3
Input 3 number of elements in the array :
element - 0 : 2
element - 1 : 5
element - 2 : 7

The values store into the array are :


2 5 7

The values store into the array in reverse are :


7 5 2
In the above code -
 The first printf statement prompts the user to input the number of elements they want to store in the
array and stores it in the variable n using scanf.
 The second printf statement asks the user to input n number of elements into the array using a for loop,
and stores each input in the corresponding index of the array a[i].
 The third printf statement then prints out the contents of the array in order using another for loop.
 The fourth printf statement then prints out the contents of the array in reverse order using yet another
for loop, which iterates over the elements of a starting from the last element and printing each element
out in reverse order.
Program 2
Write a program in C to find the sum of all elements of an array.
#include <stdio.h>
void main()
{
int a[100];
int i, n, sum=0;
printf("\n\nFind sum of all elements of array:\n");
printf("--------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&a[i]);
}

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


{
sum += a[i];
}

printf("Sum of all elements stored in the array is : %d\n\n", sum);


}
Output
Find sum of all elements of array:
--------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 2
element - 1 : 5
element - 2 : 8
Sum of all elements stored in the array is : 15
In the above code -
 The first printf statement prompts the user to input the number of elements they want to store in the
array and stores it in the variable n using scanf.
 The second printf statement asks the user to input n number of elements into the array using a for loop,
and stores each input in the corresponding index of the array a[i].
 The third for loop calculates the sum of all the elements in the array by iterating over each element of
the array and adding its value to the variable sum.
 The final printf statement then prints out the sum of all the elements in the array using the value stored
in the variable sum.
Program 3
Write a program in C to copy the elements of one array into another array.
#include <stdio.h>

void main()
{
int arr1[100], arr2[100];
int i, n;
printf("\n\nCopy the elements one array into another array :\n");
printf("----------------------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
/* Copy elements of first array into second array.*/
for(i=0; i<n; i++)
{
arr2[i] = arr1[i];
}

/* Prints the elements of first array */


printf("\nThe elements stored in the first array are :\n");
for(i=0; i<n; i++)
{
printf("% 5d", arr1[i]);
}

/* Prints the elements copied into the second array. */


printf("\n\nThe elements copied into the second array are :\n");
for(i=0; i<n; i++)
{
printf("% 5d", arr2[i]);
}
printf("\n\n");
}
Output
Copy the elements one array into another array :
----------------------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 15
element - 1 : 10
element - 2 : 12

The elements stored in the first array are :


15 10 12

The elements copied into the second array are :


15 10 12
In the above code -
 The first printf statement prompts the user to input the number of elements they want to store in the
array and stores it in the variable n using scanf.
 The second printf statement asks the user to input n number of elements into the first array arr1 using
a for loop, and stores each input in the corresponding index of the array arr1[i].
 The third for loop then copies the elements of arr1 into a second array arr2 by iterating over each
element of arr1 and assigning it to the corresponding index of arr2.
 The next two printf statements then print out the contents of the first array arr1 and the second array
arr2 respectively, using separate for loops to iterate over the elements of each array and print them out
using printf.
Program 4
Write a program in C to find the maximum and minimum elements in an array.
#include <stdio.h>
void main()
{
int arr1[100];
int i, mx, mn, n;

printf("\n\nFind maximum and minimum element in an array :\n");


printf("--------------------------------------------------\n");

printf("Input the number of elements to be stored in the array :");


scanf("%d",&n);

printf("Input %d elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
mx = arr1[0];
mn = arr1[0];

for(i=1; i<n; i++)


{
if(arr1[i]>mx)
{
mx = arr1[i];
}
if(arr1[i]<mn)
{
mn = arr1[i];
}
}
printf("Maximum element is : %d\n", mx);
printf("Minimum element is : %d\n\n", mn);
}
Output
Find maximum and minimum element in an array :
--------------------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 45
element - 1 : 25
element - 2 : 21
Maximum element is : 45
Minimum element is : 21
In the above code -
 The first printf statement prompts the user to input the number of elements they want to store in the
array and stores it in the variable n using scanf.
 The second printf statement asks the user to input n number of elements into the array arr1 using a for
loop, and stores each input in the corresponding index of the array arr1[i].
 The next for loop then iterates over each element in arr1 and finds the maximum and minimum
elements in the array by comparing it to every other element in the array using if statements. The
variables mx and mn are used to store the maximum and minimum elements, respectively.
 Finally, the last printf statement prints out the maximum and minimum elements found.
Program 5
Write a C program to read an array of length 6 and find the smallest element and its position.
#include <stdio.h>
int main() {
int e, i, sval, position;
// Prompt user to input the length of the array
printf("\nInput the length of the array: ");
scanf("%d", &e);
// Declare an array of length 'e'
int v[e];
// Prompt user to input the array elements
printf("\nInput the array elements:\n ");
for(i = 0; i < e; i++) {
scanf("%d", &v[i]);
}
// Initialize 'sval' and 'position' with the first element of the array
sval = v[0];
position = 0;
// Find the smallest value and its position in the array
for(i = 0; i < e; i++) {
if(sval > v[i]) {
sval = v[i];
position = i;
}
}
// Print the smallest value and its position
printf("Smallest Value: %d\n", sval);
printf("Position of the element: %d\n", position);
return 0;
}
Output
Input the length of the array: 5
Input the array elements:
25
35
20
14
45
Smallest Value: 14
Position of the element: 3
Program 6
Write a program in C to sort elements of an array in ascending order.
#include <stdio.h>
void main()
{
int arr1[100];
int n, i, j, tmp;

printf("\n\nsort elements of array in ascending order :\n ");


printf("----------------------------------------------\n");

printf("Input the size of array : ");


scanf("%d", &n);

printf("Input %d elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(arr1[j] <arr1[i])
{
tmp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = tmp;
}
}
}
printf("\nElements of array in sorted ascending order:\n");
for(i=0; i<n; i++)
{
printf("%d ", arr1[i]);
}
printf("\n\n");
}
Output
sort elements of array in ascending order :
----------------------------------------------
Input the size of array : 5
Input 5 elements in the array :
element - 0 : 2
element - 1 : 7
element - 2 : 4
element - 3 : 5
element - 4 : 9
Elements of array in sorted ascending order:
2 4 5 7 9
Program 7
Write a program in C to sort the elements of the array in descending order.
#include <stdio.h>
void main()
{
int arr1[100];
int n, i, j, tmp;
printf("\n\nsort elements of array in descending order :\n");
printf("----------------------------------------------\n");
printf("Input the size of array : ");
scanf("%d", &n);

printf("Input %d elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(arr1[i] < arr1[j])
{
tmp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = tmp;
}
}
}
printf("\nElements of array is sorted in descending order:\n");
for(i=0; i<n; i++)
{
printf("%d ", arr1[i]);
}
printf("\n\n");
}
Output
sort elements of array in descending order :
----------------------------------------------
Input the size of array : 3
Input 3 elements in the array :
element - 0 : 5
element - 1 : 9
element - 2 : 1
Elements of array is sorted in descending order:
9 5 1
4, TWO-DIMENSIONAL ARRAYS
Two Dimensional Arrays can be thought of as an array of arrays, or as a matrix consisting of rows and columns.
Declaration of two-dimensional Array in C
data_type array_name[i][j];
 data_type: It will tell the type of data that has to be stored in each element.
 array_name: It will tell the name of the array with which it will be referenced in the whole program.
 i: It is the number of rows.
 j: It is the number of columns.
A two-dimensional array is an array of several one-dimensional arrays. Following is an array with five rows,
each row has three columns:
int my_array[5][3];
The code above declares a one-dimensional array that has five elements. Each of these five elements is
themselves, an array of three integers. The following diagram shows a simple way to visualize this:

Initialization of 2D Array in C
We can initialize the 2D array in c by using two methods.
 Using Initializer List
 Using Loops
Initializing using Initializer List
In the initializer list we have two methods to declare the two dimensional array in C.
First Method
In the first method we can write all the elements together.
int a[4][3] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
Here the array contains 4 rows and 3 columns. We read the elements in the matrix from left to right so in this
also the elements are read from left to right so after every 3 elements we go to the new row, and the new row
starts to be filled.
Second Method
This method is comparatively better as we have clearly specified the elements in each row.
int a[4][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}};
In the above example we have nested brackets which shows the element of each row individually.
Accessing elements in two-dimensional arrays
Just like one-dimensional arrays, two-dimensional arrays also require indices to access the required elements.
A row and a column index are needed to access a particular element; for nested loops, two indices (one to
traverse the rows and the other to traverse the columns in each row) are required to print a two-dimensional
array.
array_name[x][y]
Where;
x: is the row index.
y: is the column index
Looping Through a 2D Array
#include <stdio.h> Output
int main() { 123
int grid[3][3] = {{1, 2, 3},{4, 5, 6}, {7, 8, 9}}; 456
// Loop through the 2D array and print its elements 789
for (int i = 0; i < 3; i++) { // Iterate over rows
for (int j = 0; j < 3; j++) { // Iterate over columns
printf("%d ", grid[i][j]); // Print the current element
}
printf("\n"); // Move to the next row
}
return 0;
}
Example 1: Matrix addition in c
To perform matrix addition in C programming, we can use multi-dimensional arrays. A multi-dimensional
array is an array that can store an array within an array, allowing us to represent matrices. For instance, a two-
dimensional array with int matrix[row][column] can store a matrix with the specified number of rows and
columns.
#include <stdio.h> Output

int main() Number of rows of matrices to be


{ added : 2
int rowCount, columnCount, i, j; Number of columns matrices to be
int firstMatrix[10][10], secondMatrix[10][10], resultMatrix[10][10]; added : 2
Elements of first matrix :
printf("Number of rows of matrices to be added : "); 5
scanf("%d", &rowCount); 5
5
printf("Number of columns matrices to be added : "); 5
scanf("%d", &columnCount); Elements of second matrix :
1
printf("Elements of first matrix : \n"); 1
1
for (i = 0; i < rowCount; i++) 1
for (j = 0; j < columnCount; j++) Difference of entered matrices :
scanf("%d", &firstMatrix[i][j]); 6 6
6 6
printf("Elements of second matrix : \n");

for (i = 0; i < rowCount; i++)


for (j = 0; j < columnCount; j++)
scanf("%d", &secondMatrix[i][j]);

printf("Sum of entered matrices : \n");


for (i = 0; i < rowCount; i++)
{
for (j = 0; j < columnCount; j++)
{
resultMatrix[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
printf("%d\t",resultMatrix[i][j]);
}
printf("\n");
}

return 0;
}

Example 2:Multiplication of two Matrices


#include <stdio.h> Output
void main()
{ Multiplication of
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,k,r1,c1,r2,c2,sum=0; two Matrices:
------------------------
printf("\n\nMultiplication of two Matrices :\n"); ----------
printf("----------------------------------\n");
printf("\nInput the rows and columns of first matrix : "); Input the rows and
scanf("%d %d",&r1,&c1); columns of first
printf("\nInput the rows and columns of second matrix : "); matrix: 2
scanf("%d %d",&r2,&c2); 2
if(c1!=r2){
printf("Mutiplication of Matrix is not possible."); Input the rows and
printf("\nColumn of first matrix and row of second matrix must be same."); columns of second
} matrix: 2
else 2
{ Input elements in
printf("Input elements in the first matrix :\n"); the first matrix:
for(i=0;i<r1;i++) element - [0],[0]: 1
{ element - [0],[1]: 2
for(j=0;j<c1;j++) element - [1],[0]: 3
{ element - [1],[1]: 4
printf("element - [%d],[%d] : ",i,j); Input elements in
scanf("%d",&arr1[i][j]); the second matrix:
} element - [0],[0]: 5
} element - [0],[1]: 6
printf("Input elements in the second matrix :\n"); element - [1],[0]: 7
for(i=0;i<r2;i++) element - [1],[1]: 8
{ The First matrix is:
for(j=0;j<c2;j++) 1 2
{ 3 4
printf("element - [%d],[%d] : ",i,j); The Second matrix
scanf("%d",&brr1[i][j]); is:
} 5 6
} 7 8
printf("\nThe First matrix is :\n"); The multiplication
for(i=0;i<r1;i++) of two matrices is:
{
printf("\n"); 19 22
for(j=0;j<c1;j++) 43 50
printf("%d\t",arr1[i][j]);
}

printf("\nThe Second matrix is :\n");


for(i=0;i<r2;i++)
{
printf("\n");
for(j=0;j<c2;j++)
printf("%d\t",brr1[i][j]);
}
//multiplication of matrix
for(i=0;i<r1;i++)
for(j=0;j<c2;j++)
crr1[i][j]=0;
for(i=0;i<r1;i++) //row of first matrix
{
for(j=0;j<c2;j++) //column of second matrix
{
sum=0;
for(k=0;k<c1;k++)
sum=sum+arr1[i][k]*brr1[k][j];
crr1[i][j]=sum;
}
}
printf("\nThe multiplication of two matrices is : \n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
printf("%d\t",crr1[i][j]);
}
}
}
printf("\n\n");
}

Example 3: Write a program in C to find the transpose of a given matrix.


#include <stdio.h> Output

void main()

{
int arr1[50][50],brr1[50][50],i,j,r,c;
printf("\n\nTranspose of a Matrix :\n");
printf("---------------------------\n"); Transpose of a Matrix :
---------------------------

printf("\nInput the rows and columns of the matrix : "); Input the rows and columns of the matrix : 2 2
scanf("%d %d",&r,&c); Input elements in the first matrix :
element - [0],[0] : 1
printf("Input elements in the first matrix :\n"); element - [0],[1] : 2
for(i=0;i<r;i++) element - [1],[0] : 3
{ element - [1],[1] : 4
for(j=0;j<c;j++)
{ The matrix is :
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]); 1 2
} 3 4
}
The transpose of a matrix is :
printf("\nThe matrix is :\n"); 1 3
for(i=0;i<r;i++) 2 4
{
printf("\n");
for(j=0;j<c;j++)
printf("%d\t",arr1[i][j]);
}

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
brr1[j][i]=arr1[i][j];
}
}

printf("\n\nThe transpose of a matrix is : ");


for(i=0;i<c;i++){
printf("\n");
for(j=0;j<r;j++){
printf("%d\t",brr1[i][j]);
}
}
printf("\n\n");
}

5. INTRODUCTION TO STRINGS
In C programming, a string is a sequence of characters terminated with a null character \0.
For example:
char c[] = "c string";
When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a
null character \0 at the end by default.
C String Declaration Syntax
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];
In the above syntax string_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.
C String Initialization
A string in C can be initialized in different ways. We can initialize a C string in 4 different ways which are as
follows:
1. 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 c[] = "abcd";
2. 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 c[50] = "abcd";
3. 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 c[5] = {'a', 'b', 'c', 'd', '\0'};
4. 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 c[] = {'a', 'b', 'c', 'd', '\0'};

Read String from the user


You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until
it encounters whitespace (space, newline, tab, etc.).
#include <stdio.h> Output
int main() Enter name: Dennis Ritchie
{ Your name is Dennis.
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Even though Dennis Ritchie was entered in the above program, only "Dennis" was stored in the name string.
It's because there was a space after Dennis.
Read a String Separated by Whitespaces in C
You can use the fgets() function to read a line of string. And, you can use puts() to display the string.
#include <stdio.h> Output
int main()
{ Enter name: Dennis Ritchie
char name[30]; Name: Dennis Ritchie
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Here, we have used fgets() function to read a string from the user.
The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the size of
the name string.
To print the string, we have used puts(name); .
Note: The gets() function can also be to take input from the user. However, it is removed from the C standard.
It's because gets() allows you to input any length of characters. Hence, there might be a buffer overflow.
Passing Strings to Function
As strings are character arrays, we can pass strings to functions.
// pass string to functions Output
#include <stdio.h> String is : vignan
void printStr(char str[])
{
printf("String is : %s", str);
}

int main()
{
// declare and initialize string
char str[] = "vignan";
// print string by passing string
// to a different function
printStr(str);
return 0;
}
String Handling Functions:
C language supports a large number of string handling functions that can be used to carry out many of the
string manipulations. These functions are packaged in the string.h library. Hence, you must include string.h
header file in your programs to use these functions. The following are the most commonly used string handling
functions.
strcat() function in C
It is used to concatenate(combine) two strings.
Syntax: strcat("hello", "world");
strcat() will add the string "world" to "hello" i.e ouput = helloworld.
#include <stdio.h> Output
#include <string.h>
int main() { Output string after concatenation: HelloWorld
char string1[10] = "Hello";
char string2[10] = "World";
strcat(string1, string2);
printf("Output string after concatenation: %s", string1);
return 0;
}
strlen() function in c
It is used to show the length of a string.
#include <stdio.h> Output
#include <string.h>
int main() { Length of string string1: 7
char string1[20] = "strings";
printf("Length of string string1: %ld", strlen(string1));
return 0;
}
strcpy() function in c
Copies one string into another. It copies the second string argument to the first string argument.
#include <stdio.h> Output
#include <string.h> String s1 is: I'll be copied to string 1.
int main() {

char s1[35] = "string 1"; // string1


char s2[35] = "I'll be copied to string 1."; // string2
strcpy(s1, s2); // copying string2 to string1
printf("String s1 is: %s", s1); // printing string1

}
strcmp() function in c
strcmp() takes two strings as input, then compares them, and returns an integer based on the following
condition:
Expression Returns
string 1 > string 2 Positive integer
string 1 < string 2 Negative
string 1 = string 2 Zero

#include <stdio.h> Output


#include <string.h>
string 1 and 2 are different
int main() {

char s1[20] = "String"; // string1


char s2[20] = "Stringfunction"; // string2
// comparing both the strings
if (strcmp(s1, s2) == 0) {
printf("string 1 and string 2 are equal");
} else {
printf("string 1 and 2 are different");
}
}

strrev() function in c
It is used to show the reverse of a string.
#include <stdio.h> Output
Enter your string: vignan
int main() Your reverse string is: nangiv
{
char s1[50];

printf("Enter your string: ");


gets(s1);
printf("\nYour reverse string is: %s",strrev(s1));
return(0);
}

You might also like