Unit 3 R22
Unit 3 R22
1
Arrays Introduction
• An Array is a derived data type that can store a fixed-size sequential
collection of elements 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
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
0 1 2 3 4 Index
10 20 30 40 50
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];
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
}
}
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]);
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}
};
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];
}}
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);
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);
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];
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");
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
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.
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;
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);
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