0% found this document useful (0 votes)
2 views60 pages

Unit 3 R22

The document provides an overview of arrays in programming, including their declaration, initialization, and types such as one-dimensional and multi-dimensional arrays. It covers operations like accessing elements, searching, sorting, and performing mathematical operations on arrays, along with examples in C programming. Additionally, it discusses the use of 2D arrays for storing data in a structured format and includes code snippets for various array manipulations.

Uploaded by

subikshajagan164
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)
2 views60 pages

Unit 3 R22

The document provides an overview of arrays in programming, including their declaration, initialization, and types such as one-dimensional and multi-dimensional arrays. It covers operations like accessing elements, searching, sorting, and performing mathematical operations on arrays, along with examples in C programming. Additionally, it discusses the use of 2D arrays for storing data in a structured format and includes code snippets for various array manipulations.

Uploaded by

subikshajagan164
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

UNIT III-Arrays

Arrays - Declaration, Initialization, Multi dimensional arrays – String and Character


arrays, String Operations on arrays.

1
Arrays Introduction
• An Array is a derived data type that can store a fixed-size sequential
collection of elements of the same type.

• An array is a collection of variables of the same type.

Example:
int a; // store single value in the variable a
int a[20]; // store 20 values in a single variable

Types of arrays:
a) One Dimensional Array (one row only)
b) Two Dimensional Array (rows and columns)
c) Multi Dimensional Array
2
Arrays Introduction
Need :
 To store multiple values in a single variable

Characters:
The elements of the array should be in same type.
The array index starts from zero.
The elements are stored in consecutive memory locations.
The size of the array is fixed

3
Array Declaration
Syntax:
type arrayName[ ArraySize ];
int rollno[10]; // user can store 10 rollno 1 2 3 4 5 6 7 8 9 10

float gpa[25]; // user can store 25 gpa values

Array size must be an integer constant greater than zero.


Array can have any datatypes that are used in C programming.

4
Array Initialization
1. Compile time initialization
int a[5]={1,2,3,4,5}
int a[]={1,2,3,4,5} - though size is not mentioned, the system will calculate it
int a[5]={1,2,3,4}- system will take zero for the last value
int a[5]={0}-first value is 0, system will take 0 for remaining 4 values too.
int a[5]={}-error array should not be empty
int a[5]={1,2,3,4,5,6,7,8,9,10}-error-size of array is more than no. of values
int a[5]={‘a’, ‘b’} - error character values stored in int array

2. Run time initialization


Get input from the user 5
Accessing the array
int a[5]={10,20,30,40,50} with base address is 1000

0 1 2 3 4  Index
10 20 30 40 50

1000 1004 1008 1012 1016  Address


To access any element in the array, use the formula:
Base address + ( index number * size of datatype)
1000+(1*4) = 1004 to access the element stored in 2nd position of index

6
Get the input of 10 integer elements and print the array elements
#include <stdio.h>
void main()
{
int arr[10], i ;
printf("Input 10 elements in the array :\n");
for(i=0; i<10; i++)
{ Output
printf("element - %d : ", i); Input 10 elements in the array :
scanf("%d", &arr[i]); element - 0 : 4
} element - 1 : 5
element - 2 : 6
printf("\n Elements in array are: "); element - 3 : 8
element - 4 : 9
for(i=0; i<10; i++)
element - 5 : 11
{ element - 6 : 21
printf("%d ", arr[i]); element - 7 : 2
} element - 8 : 3
} element - 9 : 4
Elements in array are: 4 5 6 8 9 11 21 2 3 4
7
Print the sum of the odd and even numbers present in the array
#include<stdio.h>
void main( )
{
int size, i, a[10], Even_Sum = 0, Odd_Sum = 0;
printf("\n Enter the Size of an Array : ");
scanf("%d", &size);
Output
printf("\n Enter the Array Elements\n"); Enter the Size of an Array : 5
for(i = 0; i<size; i++)
{ Enter the Array Elements
1
scanf("%d", &a[i]);
2
} 3
4
for(i=0; i<size; i++) 5
{
if(a[i]%2==0) Sum of Even Numbers in Array = 6
{ Sum of Odd Numbers in Array = 9
Even_Sum = Even_Sum + a[i];
8
}
else
{
Odd_Sum = Odd_Sum + a[i];
}
}
printf("\n Sum of Even Numbers in Array = %d ", Even_Sum);
printf("\n Sum of Odd Numbers in Array = %d ", Odd_Sum);
}

9
#include<stdio.h> Reverse the elements of the array without using another array
void main( )
{
int i, j, a[5], temp, length=5;
printf("Enter the array elements");
for(i=0; i<5; i++)
scanf("%d", &a[i]);

i=0; Output
j=length-1; Enter the array elements1
while(i<j) 2
{ 3
temp = a[i]; 4
a[i] = a[j]; 5
Reverse of array: 5 4 3 2 1
a[j] = temp;
i++;
j--;
}
printf("Reverse of array: ");
for(i=0; i<5; i++) 10
Largest and smallest element in an array
#include<stdio.h>
void main( )
{
int a[50], i, n, large, small;
printf("\n Enter the number of elements : ");
scanf("%d", &n); Output
printf("\n Input the array elements : "); Enter the number of elements : 5
for(i=0; i<n; ++i)
scanf("%d", &a[i]);
Input the array elements : 1
large=small=a[0]; 5
15
for(i=1; i<n; i++) 2
{
if(a[i]>large) 6
large=a[i];
The smallest element is 1
if(a[i]<small) The largest element is 15
small=a[i];
}
printf("\n The smallest element is %d", small);
printf("\n The largest element is %d", large);
} 11
Searching an element in an array
Used to check whether an element is present in an array or not and also
print its position, if found.
Two types of searching is done
i) Sequential search (Linear search):
Array is traversed sequentially and every element is checked,
ex: linear Search.
ii) Interval search (Binary search):
Array is divided into two by taking the center element into
consideration and searching is done in both the sub arrays, ex: Binary search

12
Count number of times the given number N is present in the array
#include<stdio.h> (Linear Search)
void main( ) Output
{ Enter the array elements4
int a[5], i, key, count = 0; 5
printf("Enter the array elements"); 2
2
for(i=0; i<5; i++)
3
scanf("%d", &a[i]); Enter the number to be searched ...
printf("Enter the number to be searched ...\n"); 3
scanf("%d \n", &key);
3 appeared at position 5 in the array.
for(i=0; i<5; i++)
{ 3 appeared 1 times in the array
if(a[i] == key)
{
printf("%d appeared at position %d in the array \n", key, i + 1);
count++;
}
}
printf("\n %d appeared %d times in the array", key, count); } 13
Count number of times the given number N is present in the array
#include <stdio.h> (Binary Search)
int main() {
int n, i, key, low, high, mid;
int arr[100];

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter %d elements (in sorted order):\n", n);


for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the element to search: ");
scanf("%d", &key);
low = 0;
high = n - 1;

14
while (low <= high) {
mid = (low + high) / 2;

if (arr[mid] == key) {
printf("Element %d found at position %d\n", key, mid + 1);
return 0;
}
else if (arr[mid] < key) {
low = mid + 1; // Search right half
}
else {
high = mid - 1; // Search left half
}
}

printf("Element %d not found in the array.\n", key);


return 0;
}
15
Sorting an array
Sorting is the technique used to re-arrange the elements in an array in
ascending or descending order.
There are different types of sorting with different time and space
complexity.
1. Bubble sort
2. Insertion sort
3. Quick sort
4. Merge sort
5. Selection sort
16
Bubble sort
• Each element is compared with next element
• If array has n elements, n-1 iterations are required to sort the array
• In each iteration, the number of comparisons will be reduced by 1,
compared to the previous iteration.

17
#include <stdio.h> Bubble Sort
void main( )
{
int array[50], n, c, d, swap;
printf("Enter number of elements \n");
scanf("%d", &n);
printf("Enter the array elements");
for (c=0; c<n; c++)
scanf("%d", &array[c]);

for (c=0; c<n - 1; c++)


{
for (d = 0 ; d<n-c-1; d++)
{
if (array[d] > array[d+1])
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
} 18
}

printf("Sorted list in ascending order:\n");


for (c = 0; c < n; c++)
printf("%d\n", array[c]); Output
} Enter number of elements
5
Enter the array elements
3
2
5
1
4
Sorted list in ascending order:
1
2
3
4
5
19
Pattern
#include <stdio.h>
void main( )
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows); Output
for (i = 1; i <= rows; ++i) Enter the number of rows: 5
*
{ **
for (j = 1; j <= i; ++j) ***
{ ****
*****
printf("* ");
}
printf("\n");
}
}
20
Pattern
#include <stdio.h>
void main( )
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows); Output
for (i = 1; i <= rows; ++i) Enter the number of rows: 5
1
{ 22
for (j = 1; j <= i; ++j) 333
{ 4444
printf("%d", i); 55555
}
printf("\n");
}
}
21
2D Arrays
Need
Store more data
Ex: In single dimensional array, marks of CPP of all 57 students can be stored in a
separate array pps[57], similarly for physics, chemistry as phy[57], che[57].
Whereas using 2D array, we can store the marks of all 6 subjects of 57 students in a
single array as chem[6][57]
Syntax: datatype array_name [row_size][column_size]
2D array is used to reduce the [Link].
Similary if we want to store marks of all 1st year students we can store it in an array as
svce[8][6][60]

22
2D Arrays Introduction
 A 2D array is a collection of multiple or many 1D arrays.
 2D array are used to solve problems related to matrices
 Access the data in 2D array using the array index.
 [Link] elements stored in a 2D array = row_size*column_size, ie. If the array has
5 rows and 3 columns, then we can store max of 15 elements in the array.

23
2D Arrays Initialization – Compile time
Consider a 2D array to store CAT marks of first 3 students of Chem branch.
int marks[3][6]={
{42,44,46,48,50,50},
{45,46,47,48,49,50},
{50,49,48,47,46,45}
};

2D Arrays Initialization – Run time


int marks[3][6];
for(int i=0;i<3;i++)
{
for(int j=0;j<6;j++)
{
scanf(“%d”, &marks[i][j]);
}
} 24
Matrix Addition
#include <stdio.h>
void main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows: ");
scanf("%d", &r);
printf("Enter the number of columns: ");
scanf("%d", &c); Output
Enter the number of rows (between 1 and 100): 2
printf("\n Enter elements of 1st matrix:\n"); Enter the number of columns (between 1 and 100): 2
for (i = 0; i < r; ++i) { Enter elements of 1st matrix:
for (j = 0; j < c; ++j) { Enter element a11: 1
Enter element a12: 2
printf("Enter element a%d%d: ", i + 1, j + 1);
Enter element a21: 3
scanf("%d", &a[i][j]);
Enter element a22: 4
}} Enter elements of 2nd matrix:
Enter element b11: 1
printf("Enter elements of 2nd matrix:\n"); Enter element b12: 2
for (i = 0; i < r; ++i) { Enter element b21: 3
for (j = 0; j < c; ++j) { Enter element b22: 4
printf("Enter element b%d%d: ", i + 1, j + 1); Sum of two matrices:
scanf("%d", &b[i][j]); 2 4 25
}} 6 8
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}}

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


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

26
Matrix Subtraction
#include <stdio.h>
void main() {
int r, c, a[100][100], b[100][100], sub[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c); Output
Enter the number of rows (between 1 and 100): 2
printf("\n Enter elements of 1st matrix:\n"); Enter the number of columns (between 1 and 100): 2
for (i = 0; i < r; ++i) { Enter elements of 1st matrix:
for (j = 0; j < c; ++j) { Enter element a11: 1
printf("Enter element a%d%d: ", i + 1, j + 1); Enter element a12: 2
scanf("%d", &a[i][j]); Enter element a21: 3
}} Enter element a22: 4
Enter elements of 2nd matrix:
Enter element b11: 1
printf("Enter elements of 2nd matrix:\n");
Enter element b12: 2
for (i = 0; i < r; ++i) { Enter element b21: 3
for (j = 0; j < c; ++j) { Enter element b22: 4
printf("Enter element b%d%d: ", i + 1, j + 1); Subtraction of two matrices:
scanf("%d", &b[i][j]); 0 0 27
}} 0 0
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
sub[i][j] = a[i][j] - b[i][j];
}}

printf("\n Subtraction of two matrices: \n");


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

28
Transpose of the matrix:
#include <stdio.h>
void main( ) {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);

printf("\nEnter matrix elements:\n");


for (int i = 0; i < r; ++i) {
for (int 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 (int i = 0; i < r; ++i){
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
}
printf("\n");
} 29
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}} Output
Enter rows and columns: 2 2
printf("\n Transpose of the matrix:\n");
for (int i = 0; i < c; ++i){ Enter matrix elements:
for (int j = 0; j < r; ++j) { Enter element a11: 1
printf("%d ", transpose[i][j]); Enter element a12: 2
} Enter element a21: 3
printf("\n"); Enter element a22: 4
}
} Entered matrix:
1 2
3 4

Transpose of the matrix:


1 3
2 4

30
Sum of all Elements in Matrix
#include<stdio.h>
void main( )
{
int r, c, a[100][100], i, j, sum=0;
printf("Enter the number of rows: ");
scanf("%d", &r);
printf("Enter the number of columns: ");
scanf("%d", &c);

printf("\n Enter elements of matrix:\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]);
}}

31
for(i=0;i<r;i++)
{
for(j=0;j<c;j++) Output
Enter the number of rows: 3
{
Enter the number of columns: 3
sum+=a[i][j];
} Enter elements of matrix:
} Enter element a11: 1
printf("Sum of the matrix element is: %d", sum); Enter element a12: 2
} Enter element a13: 3
Enter element a21: 4
Enter element a22: 5
Enter element a23: 6
Enter element a31: 7
Enter element a32: 8
Enter element a33: 9
Sum of the matrix element is: 45

32
Matrix Multiplication
#include <stdio.h>
void main( )
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];

printf("Enter number of rows and columns of first matrix\n");


scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);

33
printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);

if (n != p)
printf("The multiplication isn't possible.\n");
else
{
printf("Enter elements of second matrix\n");

for (c = 0; c < p; c++)


for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d]; 34
}
multiply[c][d] = sum;
sum = 0;
}
}

printf("Product of the matrices:\n");


for (c = 0; c < m; c++) {
for (d = 0; d < q; d++){
printf("%d\t", multiply[c][d]);
}
printf("\n");
}
}
}

35
Sort the names in alphabetical order
#include <stdio.h>
#include <string.h>
void main( )
{
int n, i, j;
char temp[50];
printf("Enter the number of names: ");
scanf("%d", &n);
char names[n][50]; // Array of strings to store names

printf("Enter %d names:\n", n);


for (i = 0; i < n; i++) {
printf("Name %d: ", i + 1);
scanf(" %[^\n]s", names[i]);
}
36
for (i = 0; i < n - 1; i++) { Output:
for (j = i + 1; j < n; j++) { Enter the number of names: 5
Enter 5 names:
if (strcmp(names[i], names[j]) > 0) { Name 1: Praveenkumar
names[i] and names[j] Name 2: Thiyagarajan
Name 3: Selvaganesh
strcpy(temp, names[i]); Name 4: Kavishree
Name 5: Ranjith
strcpy(names[i], names[j]);
strcpy(names[j], temp); Sorted names in alphabetical order:
Kavishree
} Praveenkumar
} Ranjith
Selvaganesh
} Thiyagarajan
printf("\n Sorted names in alphabetical order:\n");
for (i = 0; i < n; i++)
printf("%s\n", names[i]);
} 37
String - Introduction
 Strings in C are defined as array of characters.
Each string array is terminated with a null character(\0).
%s is the format specifier used here.

Syntax: char array_name[size_of_array];

size of array should be length of the string+1, last space is used to store the null
character.
Ex: If store the string selva, my array should have size of 5 atleast.

38
String - Compile time initialization
 As you know already, alphabets, numbers and special characters are allowed in
strings
char name[10]=“selva” (or) char name[10]={‘s’, ‘e’, ‘l’, ‘v’, ‘a’, ‘/0’}
char class[10]=“CHEM_A”
char roll[15]=“CHEM&01”
char result[100]=“CHEM all clear in CPP”
char names[15]= {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘w ’, ‘o’, ‘r’, ‘l’, ‘d’};

39
String - Run time initialization
Done using scanf and gets;
scanf:
char names[10];
printf("Enter the name:");
scanf("%s", names);
printf("the name is %s", names);

Disadvantage: scanf won’t consider whitespace as character in that string, will put a
null character there automatically and printing will be stopped there.

40
String - Run time initialization
gets:
char names[10];
printf("Enter the name:");
gets(names);
printf("the name is %s", names);
 No disadvantage with whitespace here.

Problem in both scanf and gets: Buffer overflow.


ex: name[6];
we give input as Chemical, the program will try to store and print the entire string,
during this process the data in memory after length of 5 may be erased. So it will
prints Chemi. 41
String - Printing using printf & puts
We can print a specific part of string alone using printf.
puts is an alternative of printf, but you can just mention the array name alone in
puts instead of using the array name and the format specifier in printf.

puts(names);
printf("%s", names);

42
Get a String using Scanf
#include<stdio.h>
void main()
{ Output
char name[10]; Enter the name: Chemical dept
I am from Chemical //after space will not be taken in scanf
printf("Enter the name:");
scanf("%s", name);
printf("I am from %s \n", name);
}
Get a String using Gets:
#include<stdio.h> Output
Enter the name: Arun Anand
void main() The name is Arun Anand
{
char names[100];
printf("Enter the name:");
gets(names);
printf("The name is %s", names); } 43
How can we overcome the buffer overflow using scanf?

#include<stdio.h>
void main()
{
char names[5];
Output
printf("Enter the name: "); Enter the name: Arunanand
The name is Aruna
scanf("%5s", names);
printf(“The name is %s", names);
}

44
Read and Print a Line
#include <stdio.h>
void main( )
{
int i;
char str[100]; Output
printf("Input a string\n"); Input a string
scanf("%[^\n]s", str); Hello world
Hello world
Hello world
for(i=0; str[i]!='\0'; i++)
printf("%c", str[i]);

printf("%s", str);
}

45
Use of printf and puts for printing a string

#include<stdio.h>
void main()
{
char names[100]; Output
Enter the name:Arunanand
printf("Enter the name:"); Arun
scanf("%s", names); Arun
Arunanand
printf("%.4s\n", names); Arunanand

printf("%10.4s\n", names);
printf("%s\n", names);
puts(names);
}
46
Count the number of vowels in a string
#include <stdio.h>
void main( )
{ Output
int c = 0, count = 0; Input a string: hello world
char s[100]; Number of vowels in the string: 3
printf("Input a string: \n");
gets(s);
while (s[c] != '\0’)
{
if (s[c] == 'a' || s[c] == 'A' || s[c] == 'e' || s[c] == 'E' || s[c] == 'i' || s[c] == 'I' || s[c] =='o' ||
s[c]=='O' || s[c] == 'u' || s[c] == 'U')
count++;
c++;
}
printf("Number of vowels in the string: %d", count);
}
47
String Library
The string library functions are:
strlen ()
strcmp ()
strcpy ()
strcat ()
strlwr()
strupr()
strncpy ()
strrev ()
strstr ()
strncat ()
strncmp () 48
String Library
strlen() :
i) It returns the number of characters (or) length of the string
syntax: int strlen(string name)
strcmp() :
i)This function compares 2 strings.
ii)It returns the ASCII difference of the first two non – matching characters in both the
strings.
syntax: int strcmp(string1, string2);
*If the difference is equal to zero, then string1 = string2
*If the difference is positive, then string1 > string2
*If the difference is negative, then string1 < string2
49
String Library
strcpy():
i) It is for copying source string into destination string.
ii) The length of the destination string >= source string.
syntax: strcpy (Destination string, Source String);
strcat():
i) It combines two strings.
ii) The length of the destination string must be > than the source string.
strcat (Destination String, Source string);
strlwr() : Returns string characters in lowercase.
syntax: strlwr(string) ;
strupr() : Returns string characters in UPPER CASE.
syntax: strupr(string) ; 50
String Library
strncpy():
i) It copy’s ‘n’ characters of source string into destination string.
ii) The length of the destination string must >= that of the source string.
syntax: strncpy (Destination string, Source String, n);
strrev():
i) The function is used for reversing a string.
ii)The reversed string will be stored in the same string.
syntax: strrev (string) ;
strstr ():
i) It is used to search whether a substring is present in the main string or not.
ii) It returns pointer to first occurrence of s2 in s1.
syntax: strstr(mainsring,substring); 51
String Library
strncat ():
i) This is used for combining or concatenating n characters of one string into another.
ii) The length of the destination string must be greater than the source string
iii) The resultant concatenated string will be in the destination string.
syntax: strncat (Destination String, Source string,n);

strncmp ():
i) This function is used for comparing first ‘n’ characters of 2 strings.
syntax: strncmp ( string1, string2, n);

52
Inbuilt String Functions (Length, Compare, Concat, Copy )
#include<stdio.h>
#include <string.h>
void main()
{
char str1[50],str2[50],str3[50];
int length;

printf("Enter string1: ");


gets(str1);
printf("Enter string2: ");
gets(str2);
printf("Enter string3: ");
gets(str3);

length=strlen(str1);
printf("Length of string1 is %d\n", length);

53
int res=strcmp(str1,str2);
if(res==0)
printf("%s is equal to %s\n",str1,str2); Output
Enter string1: chem
else if(res>0)
Enter string2: it
printf("%s is greater than %s\n",str1,str2); Enter string3: hello
else (res<0) Length of string1 is 4
printf("%s is less than %s\n",str1,str2); chem is less than it
The concatenated string is chemit
strcat(str1,str2); copied string is chemit
printf("The concatenated string is %s\n",str1);

strcpy(str3,str1);
printf ("copied string is %s\n",str3);
}

54
Inbuilt String Functions (Uppercase and Lowercase)
#include<stdio.h>
#include<string.h>
void main()
{
char str1[50], str2[50];
printf("\n Enter first string: ");
scanf("%s",str1);
printf("%s \n",strlwr(str1));
printf("\n Enter second string: ");
scanf("%s",str2);
printf("%s \n",strupr(str2));
}
55
String Length without using inbuilt function
#include <stdio.h>
void main()
{
char s[100];
int i=0;
printf("\nEnter a string : ");
Output
gets(s); Enter a string : Welcome
while(s[i]!='\0’) Length of the string is: 7

i++;
printf("Length of the string is: %d", i);
}

56
String Uppercase and Lowercase without using inbuilt function
#include <stdio.h>
void main()
{
char s[100], t[100];
int i;
printf("\nEnter a lower case string : ");
gets(s); Output
printf("\nEnter a UPPER CASE string : "); Enter a lower case string : welcome
gets(t); Enter a UPPER CASE string : HELLO
for (i = 0; s[i]!='\0'; i++)
String in UPPER CASE = WELCOME
if(s[i] >= 'a' && s[i] <= 'z')
String in lower case = hello
s[i] = s[i]-32;
printf("\nString in UPPER CASE = %s", s);

for (i = 0; t[i]!='\0'; i++)


if(t[i] >= 'A' && t[i] <= 'Z')
t[i] = t[i]+32;
printf("\nString in lower case = %s", t);
57
}
String Compare without using inbuilt function
#include <stdio.h>
void main()
{
char Str1[100], Str2[100]; Output
Enter String1:Hello
int result, i; Enter String2:Hai
printf("\n Enter String1:");
gets(Str1); string2 is Less than string1
printf("\n Enter String2:");
gets(Str2);
for(i=0; Str1[i]!='\0' && Str2[i]!='\0'&& Str1[i]==Str2[i]; i++);
if(Str1[i] < Str2[i])
printf("\n string1 is Less than string2");
else if(Str1[i] > Str2[i])
printf("\n string2 is Less than string1");
else
printf("\n string1 is Equal to string2");
} 58
String Copy without using inbuilt function
#include <stdio.h>
void main()
{ Output
char String1[100], String2[100]; Enter String1:Hello
int i; String2 is: Hello
printf("\n Enter String1:");
gets(String1);

//String1 is source and String2 is destination copying character by character


for (i = 0; String1[i] != '\0'; ++i)
String2[i] = String1[i];

printf("String2 is: %s", String2);


}

59
String Concatenation without using inbuilt function
#include<stdio.h>
void main()
{
char str1[50], str2[50];
int i, j;
printf("\n Enter first string: "); Output
scanf("%s",str1); Enter first string: Hello
printf("\n Enter second string: "); Enter second string: Hai
scanf("%s",str2); The concatenated result is: HelloHai
// Loop to count and store the length of a string1
for(i=0; str1[i]!='\0'; ++i);
// Below loop would concatenate the string2 at the end of string1
for(j=0; str2[j]!='\0’; i++, j++)
str1[i]=str2[j];
printf("\n The concatenated result is: %s",str1);
} 60

You might also like