Unit-1 STRING
Unit-1 STRING
Unit-1
Multi-Dimensional Array and Strings
ARRAY
• Array is a collection of elements having same data type, same name and stored
sequentially in a contiguous memory locations.
• Any element can be accessed by using
→ name of the array and
→ location of element in the array
• Arrays are of two types:
1) Single dimensional array
2) Multi-dimensional array
For ex:
int mat[3][3]; // declares a two dimensional array of size three rows and three columns
The above declaration inside the computer memory can be represented as follows:
• Two dimensional array’s are arranged in rows and columns form in the form of a matrix.
• The elements of the array index start with 0,0.
for ex. in the above figure the first element of integer type is stored at row=0 and col=0 index i.e at
mat[0][0] and the second element is stored at row 0 and col=1 i.e at mat[0][1] & so on.
where, data_type could be any basic types such as int,char or float etc.
array_name: any valid identifier name
size_of_rows: number of rows in 2D array
size_of_cols :number of columns in 2D array
Initialization of Two Dimensional Arrays At Compile Time:
For ex:
int matrix[3][3]= {{1,2,3},{4,5,6},{7,8,9}};
or
int matrix[3][3]= {1,2,3,4,5,6,7,8,9};
Row-1 1 2 3
Row-2 4 5 6
Row-3 7 8 9
Example: Compile Time Initialization:
#include<stdio.h>
int main()
{ int matrix[3][3]={1,2,3,4,5,6,7,8,9};
int i,j;
printf(“\The elements of the matrix are:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d", matrix[i][j]);
}
}
}
Example: Run Time Initialization:
#include<stdio.h>
int main()
{
int matrix[3][3];
scanf("%d", &matrix[0][0]); //reads values entered into matrix at row=0 col=0
scanf("%d", &matrix[0][1]); //reads values entered into row=0 and col=1.
scanf("%d", &matrix[0][2]); //reads values entered into row=0 and col=2
scanf("%d", &matrix[1][0]);
scanf("%d", &matrix[1][1]);
scanf("%d", &matrix[1][2]);
scanf("%d", &matrix[2][0]);
scanf("%d", &matrix[2][1]);
scanf("%d", &matrix[2][2]);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &matrix[i][j]);
}
}
The following loop displays 9 values to the output screen:
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ", matrix[i][j]);
}
}
Example:
#include<stdio.h>
int main()
{
int matrix[3][3];
int i,j;
printf(“\nEnter the elements of the matrix of order [3x3]:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &matrix[i][j]);
}
}
printf(“\nThe elements of the matrix are:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%2d", matrix[i][j]);
}
printf(“\n”);
}
return 0;
}
Output:
Enter the elements of the matrix of order[3x3]: 11 22 33 44 55 66 77 88 99
The elements of the matrix are:
11 22 33
44 55 66
77 88 99
Program : Write a C program to add the elements of square matrices. Display the resultant matrix to the output
screen.
#incude<stdio.h>
int main()
{
int matrix1[3][3], matrix2[3][3], matrix3[3][3];
int rows1, cols1, rows2, cols2;
printf(“Enter the number of rows and columns of first matrix:”);
scanf(“%d%d”,&rows1,&cols1);
printf(“Enter the number of rows and columns of second matrix:”);
scanf(“%d%d”,&rows2,&cols2);
if(rows1!=rows2 && cols1!=cols2)
{
printf(“Not a square matrix. Can’t add elements!!!”);
exit(1);
}
printf(“Enter the elements of first matrix:\n”);
for(i=0;i<rows1;i++)
for(j=0;j<cols1;j++)
{
scanf("%d", &matrix1[i][j]);
}
for(i=0;i< rows;i++)
{
for(j=0;j< cols;j++)
{
printf("%3d", matrix2[i][j]);
}
printf(“\n”);
}
for(i=0;i< rows;i++)
{
for(j=0;j< cols;j++)
{
matrix3[i][j]= matrix1[i][j]+ matrix2[i][j];
}
}
printf(“\nThe elements of resultant matrix:\n”);
for(i=0;i< rows;i++)
{
for(j=0;j< cols;j++)
{
printf("%3d", matrix3[i][j]);
}
printf(“\n”);
}
}
Output:
Enter the number of rows and columns of first matrix: 2 2
Enter the number of rows and columns of second matrix: 2 2
The elements of first matrix: 1 1 1 1
The elements of second matrix: 1 2 3 4
The elements of resultant matrix:
2 3
4 5
ROW- AND COLUMN-MAJOR ORDER REPRESENTATION IN MEMORY
• Row-major order and Column-major order are methods for storing multidimensional arrays in linear
storage such as random access memory.
• In row-major order, the consecutive elements of a row reside next to each other, whereas the same
holds true for consecutive elements of a column in column-major order.
• For example, the array could be stored in two possible ways:
For the Row-wise traversal, we need to print row 1 first, row 2, and row 3, as shown below.
For the Column-wise traversal, you need to print col1 first, then col 2, and then col 3, as shown below.
The 2-dimensional array can be defined as an array of arrays. The 2-Dimensional arrays are
organized as matrices which can be represented as the collection of rows and columns as array[M][N]
where M is the number of rows and N is the number of columns.
To find the address of any element in a 2-Dimensional array there are the following two ways-
For ex:
"HELLO" is a string with 6 characters including the null character stored inside the computer
memory.
0 1 2 3 4 5
Declaration of a String:
Strings are declared in C using the char data type. For ex:
char name[5];
//characters including the NULL character denoted //as ‘\0’
• The above declaration can be represented as:
\0
| Garbage values |
Initialization of a String:
For ex:
char name[]={‘H’,’E’,’L’,’L’,’O’,’\0’};
char s[]="HELLO";
Q1. Can we declare size of string greater than no. of elements that are unitialized?
Ans. YES.
Char str[10]=”HELLO”;
str[0] str[1] str[2] str[3] str[4] str[5] str[6] str[7] str[8] str[9]
‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’ ‘\0’ ‘\0’ ‘\0’ ‘\0’
#include<stdio.h> int
main()
{
char name[5]={ ‘L’,’I’,’O’,’N’}; //or char s[5]="LION";
Output:
Character in the array at First position: L Character
in the array at Second position: I Character in the
array at Third position: O Character in the array at
Fourth position: N
The strings can be accepted from the user using the following formatted functions:
Output 1:
Enter a string: HELLO
You typed the string: HELLO
Output 2:
Enter a string: HELLO WORLD You
typed the string: HELLO
Output:
Type a string: Graphic Era Hill University
gets()--- to read a string from the user until the user enters a newline Character ie
‘\n’ (presses Enter key)
puts()--- to display a string to the screen
Output:
Type a string: Programming in C
You typed: Programming in C
getchar()--- repeatedly string is read by getchar() to read sequence of single characters unless
terminating character is entered.
putchar()--- to display a characters on the screen.
• Whenever strings needs to be manipulated in a program manually it adds the extra lines of
program code and also makes it a very lengthy and difficult to understand.
• To avoid this C supports a large number of string handling functions. There are many functions
defined in <string.h> header file.
11 strrev(s1) Returns the reverse string after reversing the characters of the string s1
strlen(s1)
• The function calculates & returns the length of a string str passed to it as an argument
excluding the null.
• This function copies the content of string s2 into another string s2.
• Putting text into a string:
strcpy(S, "This is String 1.");
#include<string.h>
#include<stdio.h>
int main()
{
char s1[20],s2[20]; printf("Enter A
string: "); scanf("%[^\n]s",s2);
strcpy(s1,s2); //Content of string s2 is copied into string s1
printf("Copied string:");
printf("%s",s1);
return 0;
}
Output:
Enter string: PROGRAMMING IN C
Copied string: PROGRAMMING IN C strncpy(s1,s2,n)
• This function copies first n characters of s2 into another string s1. where n is
an integer
Assume that the following statement has been executed before each of the remaining
code fragments.
• Copying four characters from the beginning of S to D and placing a null at the end:
strncpy(D, S, 4);
D[4] = '\0';
#include<string.h>
#include<stdio.h> int
main()
{
char s1[20],s2[20]; int
n;
printf("Enter a string: "); scanf("%[^\n]s",s2);
printf(“\nHow many characters to be copied:”);
scanf(“%d”,&n);
strncpy(s1,s2,n); //Content of string s2 is copied into string s1
printf("Copied string: %s",s1);
return 0;
}
Output:
Enter a string: PROGRAMMING IN C How
many characters to be copied: 7 Copied string:
PROGRAM
strcat(s1,s2)
Joins two strings by copying the string s2 to the end of s1. strcat() is used to concatenate a
null-terminated string to end of another string variable.
<stdio.h>
#include <string.h>
int main()
{
char s1[10], s2[10]; printf("Enter the
First String:"); gets(s1);
printf("\n Enter the Second String:"); gets(s2);
strcat(s1,s2); //concatenates string s1 and s2 stores the final string in s1
printf("\nConcatenated String: ");
puts(s1); // final concatenated string is stored in s1 return 0;
}
Output:
Enter the First String: Graphic Enter the
Second String: Era Concatenated String:
GraphicEra
strncat(s1,s2,n)
Joins first n characters of s2 joins with string s1 and stores it into s1. Example:
Program to illustrate the use of strcat().
#include <stdio.h>
#include <string.h> int
main()
{
char s1[10], s2[10]; int
n;
printf("Enter the First String:");
gets(s1);
printf("\n Enter the Second String:"); gets(s2);
printf(“\nHow many characters needs to be appended:”); scanf(“%d”,&n);
Output:
Enter the First String: Tic
Enter the Second String: Tac
How many characters needs to be appended: 2
Concatenated String: TicTa
strcmp(s1,s2)
strcmp() is used to compare two strings. The strings are compared character by character starting
at the characters pointed at by the two pointers. If the strings are identical, the integer value zero
(0) is returned. As soon as a difference is found, the comparison is halted and if the ASCII value
at the point of difference in the first string is less than that in the second (e.g. 'a' 0x61 vs. 'e' 0x65)
a negative value is returned; otherwise, a positive value is returned. Examine the following
examples.
diff will have a positive value after the following statement is executed. diff =
strcmp(s2, s1);
diff will have a value of zero (0) after the execution of the following statement, which
compares s1 with itself.
Output 2:
Enter the first string: Pat
Enter the second string: Pet
-1
}
Output:
Enter the first string: program
Enter the second string: Program
First string is greater than second string
strncmp(s1,s2,n)
if(strncmp(s1,s2,n)==0)
printf("Both strings are equal");
else
printf("Strings are unequal");
return 0;
}
Output:
Enter the first string: progRam
Enter the second string: program
How many characters to be compared: 4 Both
strings are equal
strcmpi(s1,s2)
• This function compares two strings s1 with s2 by ignoring the cases (uppercase or lowercase)
and
returns 0 if both the strings are equal i.e s1==s2. returns a
value < 0 if s1<s2
returns a value > 0 if s1>s2
Output:
Enter the first string: program
Enter the second string: PROGRAM Both
strings are equal
strlwr(str):
strupr(str):
#include<stdio.h>
#include<string.h>
int main()
{
char str[]=”HeLLo”;
strupr(str);
printf(“the string is: %s”, str);
return 0;
}
OUTPUT: the string is: HELLO
strrev():
#include<stdio.h>
#include<string.h> int
main()
{
char str[]=”HELLO”;
strrev(str);
printf(“the string after reverse is: %s”, str); return 0;
}
OUTPUT: the string is: OLLEH
1. Program to copy one string into another without using the inbuilt function.
#include<stdio.h>
int main()
{
char s1[100], s2[100]; int i;
printf("Type a string:"); gets(s1);
i = 0;
while (s1[i] != '\0')
{
s2[i] = s1[i];
i++;
}
s2[i] = '\0';
printf("Copied String is: %s ", s2); return
0;
}
Output:
while(s1[i]!='\0')
i++; s1[i++]=‟
„;
while(s2[j]!='\0')
{
s1[i]=s2[j];
j++;
i++;
}
s1[i]='\0';
printf("\n Concatenated String is %s",s1);
return 0;
}
Output:
Enter the First String: Merry
Enter the Second String: goround
Concatenated String is Merry goround
#include<stdio.h>
#include<string.h>
void main()
{
char str[100],str1[100],temp;
int i=0,j=0;
printf("Enter the string 1");
gets(str);
int n=strlen(str);
while(str[i]!='\0')
{
str1[i]=str[i];
i++;
}
str1[i]='\0';
j=strlen(str)-1;
i=0;
while(i<j)
{
temp=str[j];
str[j]=str[i];
str[i]=temp;
i++;
j--;
}
printf("reverse of string is ");
puts(str);
puts(str1);
int num=strcmp(str,str1);
printf("%d",num);
if (num)
{
printf("string is not palindrome ");
}
else
printf("string is palindrome");
}
7. Develop a program to find the number of occurrences of each alphabet in a given string and display
the same to the output screen. Assume that the string contains only alphabets.
#include <string.h>
int stringlength(char s[])
{
int j;
for(j=0;s[j];j++);
return j;
}
void printfrequencyofcharacters(char s[])
{
int i,j,count=0,n;
n=stringlength(s);
for(i=0;i<n;i++)
{
count=1;
if(s[i])
{
for(j=i+1;j<n;j++)
{
if(s[i]==s[j])
{
count++;
s[j]='\0';
}
}
printf(" '%c' = %d \n",s[i],count);
}
}
}
int main()
{
char s[1000];
}
POINTERS AND STRINGS:
Program 1:
#include<stdio.h> int
main()
{
char str[]="HELLO";
char str1[10];
//str=str1; //error
char *p=str; char
*q;
q=p;
while(*q!='\0')
{
printf("%p\t%c\n",(void *)q,*q); q++;
}
}
OUTPUT:
0x7ffe4c12674e H
0x7ffe4c12674f E
0x7ffe4c126750 L
0x7ffe4c126751 L
0x7ffe4c126752 O
#include<stdio.h> int
main()
{
char name1[100] = "GEHU"; char name2[100];
char *ptr1 ;
char *ptr2 ;
ptr1 = name1 ;
ptr2 = name2 ;
OUTPUT:
COPIED String is...
GEHU
#include<stdio.h> void
display(char*); int
main()
{
char str[10];
gets(str);
display(str); //can be &str, &str[0] return
0;
}
void display(char *p)
{
while(*p!='\0')
{
printf("%c",*p); p++;
}
}
main()
{
char org[50] = "Arjun";
char copy[50] ;
// Sample Output
Enter the second String to Compare Arjun
The two Strings are Equal
char *dow[] =
{"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday" };
strtok():
The C library function char *strtok(char *str, const char *delim) breaks string str into a series of
tokens using the delimiter delim.
delim − This is the C string containing the delimiters. These may vary from one call to another.
• Return Value:
This function returns a pointer to the first token found in the string. A null pointer is returned if
there are no tokens left to retrieve.
<string.h>
#include <stdio.h>
int main () {
char str[80] = "Graphic-Era-Hill-University"; const char
s[2] = "-";
char *token;
OUTPUT:
Graphic
Era
Hill
University
atoi():
The C library function int atoi(const char *str) converts the string argument str to an integer (type
int).