SlideShare a Scribd company logo
Unit - 4
Array and String
01CE1101
Computer Programming
Arrays
• An array is a collection of data items, all of the same type, accessed using a
common name.
• Array is a data structure that hold finite sequential collection of homogeneous
data.
• Array is a collection - Array is a container that can hold a collection of data.
• Array is finite - The collection of data in array is always finite, which is
determined prior to its use.
• Array is sequential - Array stores collection of data sequentially in memory.
• Array contains homogeneous data - The collection of data in array must share
a same data type.
Arrays
• Examples:
- List of customers and their phone numbers
-Table of daily rainfall data
- List of employees in an organization
- Test scores of a class of students and so on….
• Structure of array:
Declaration of Arrays
• Array variables are declared identically to variables of their data type, except that
the variable name is followed by one pair of square [ ] brackets for each dimension
of the array.
• Syntax:
type arrayName [ arraySize ];
• Example:
int group[10];
float height[50];
char name[15];
Initialization of Arrays
• After an array is declared, its elements must be initialized.
• There are two ways to initialize an array.
1.Static array initialization - Initializes all elements of array during its declaration.
2.Dynamic array initialization - The declared array is initialized some time later during
execution of program.
Static initialization of array
• We define value of all array elements within a pair of curly braces { and } during its
declaration.
• Values are separated using comma , and must be of same type.
• Example
int marks[5] = {90, 86, 89, 76, 91};
Dynamic initialization of array
• You can assign values to an array element dynamically during execution of program.
First declare array with a fixed size.
• Then use the following syntax to assign values to an element dynamically.
Syntax:
array_name[index] = some_value;
EX:
scanf("%d",&arr[i]);
Advantages and Disadvantages
• Advantages:
1.Use of less line of code as it creates a single array of multiple elements.
2.Random access of elements using array index.
3.Easy access to all the elements.
4.Traversal through the array becomes easy using a single loop.
5.Sorting becomes easy as it can be accomplished by writing less line of code.
• Disadvantages:
1.Insertion and deletion of elements can be costly since the elements are needed to be
managed in accordance with the new memory allocation.
2.Allows a fixed number of elements to be entered which is decided at the time of
declaration. Unlike a linked list, an array in C is not dynamic.
Types of Arrays
•One-dimensional arrays(single)
•Two-dimensional arrays
•Multidimensional arrays
One – Dimensional Array
• A one-dimensional array as a row, where elements are stored one after another.
• Syntax: datatype array name[size];
Where ….
datatype: It denotes the type of the elements in the array.
array name: Name of the array. It must be a valid identifier.
size: Number of elements an array can hold. here are some example of array
• The elements of an array can be accessed by specifying array name followed
by subscript or index inside square brackets (i.e []).
• Array subscript or index starts at 0. If the size of an array is 10 then the first
element is at index 0, while the last element is at index 9.
• The first valid subscript (i.e 0) is known as the lower bound, while last valid
subscript is known as the upper bound.
Accessing elements of an array
Accessing elements of an array
Example:
int a[5];
then elements of this array are;
First element – a[0]
Second element – a[1]
Third element – a[2]
Fourth element – a[3]
Fifth element – a[4]
Accessing elements of an array
Array subscript or index can be any expression that yields an integer value.
For example:
int a[5];
int i = 0, j = 2;
a[i]; // 1st element
a[i+1]; // 2nd element
a[i+j]; // 3rd element
In the array a, the last element is at a[4],
Example Program
#include<stdio.h>
int main()
{
int a[5], i;
for(i = 0; i < 5; i++)
{
printf("Enter a[%d]: ", i);
scanf("%d", &a[i]);
}
printf("nPrinting elements of the array: nn");
for(i = 0; i < 5; i++)
{
printf("%d ", a[i]);
}
return 0;
}
Example Program
• 1. Write down a program to enter 20 elements in an
array and print the elements in reverse order.
• 2. Write a program to add all the elements in an array.
• 3.Write a program to copy one array to another array.
• 4. Write a program to find out all the even and odd
numbers present in an array.
• 5. Write a program to swap two arrays.
Two Dimensional Array in C
• Two – dimensional array is the simplest form of a multidimensional array.
• The two-dimensional array can be defined as an array of arrays. The 2D
array is organized as matrices which can be represented as the collection
of rows and columns.
• It provides ease of holding the bulk of data at once.
Declaration of two dimensional Array in C
Syntax:
datatype array_name[rows][columns];
Where
datatype: It denotes the type of the elements in the array.
array name: Name of the array. It must be a valid identifier.
Row – size of rows
Column – size of column
Initializing Two – Dimensional Arrays
There are two ways in which a Two-Dimensional array can be initialized.
First Method:
int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}
The above array have 3 rows and 4 columns. The elements in the braces from
left to right are stored in the table also from left to right. The elements will
be filled in the array in the order, first 4 elements from the left in first row,
next 4 elements in second row and so on.
Better Method:
int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
Accessing the 2- D Arrays
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
Example
#include <stdio.h>
int main ()
{
int a[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&a[i][j]);
}
Example
printf("n printing the elements ....n");
for(i=0;i<3;i++)
{
printf("n");
for (j=0;j<3;j++)
{
printf("%dt",a[i][j]);
}
}
return 0;
}
Sorting operation using array
• The process of Sorting can be explained as a technique of rearranging
the elements in any particular order, which can be set ready for further
processing by the program logic.
• We can easily sort a list of elements by means of iterations and
condition check statements.
• We require one outer loop and one inner loop and one swap function to
do the purpose.
Sorting operation using array
• We can do sorting the elements in 2 ways
• Ascending order
• Descending order
Sorting operation –Example
#include <stdio.h>
int main()
{
int a[5],i,j,temp = 0;
printf("Enter the Elements of array: n");
for(i = 0; i < 5; i++)
{
scanf("%d", &a[i]);
}
for (i = 0; i < 5; i++)
{
for (j = i+1; j < 5; j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[j] = temp;
}
}
}
printf("n");
printf("Elements of array sorted in ascending
order: n");
for (i = 0; i <5; i++)
{
printf("%d ", a[i]);
}
return 0;
}
Matrix operation using array
• A matrix is a grid that is used to store data in a structured format.
• It is often used with a table, where the data is represented in horizontal
rows and vertical columns.
• Addition, subtraction and multiplication are the basic operations on the
matrix.
• Matrix multiplication in C language to calculate the product of two
matrices (two-dimensional arrays). A user inputs the orders and
elements of the matrices.
Matrix operation using array
• In programming if the user wants to multiply, add, subtract and divide two
matrices, then the order of the matrix should be declared first.
• A matrix that contains the same number of rows and columns then it is
called a square matrix.
• Matrix is used to store a group of related data. Some of the programming
languages are used to support matrices as a data type that offers more
flexibility than a static array.
• Instead of storing the values in a matrix, it can be stored as an
individual variable, a program can access and perform operations on the
data more efficiently.
Algorithm for Matrix Multiplication
Step 1: Start the Program.
Step 2: Enter the row and column of the first (a) matrix.
Step 3: Enter the row and column of the second (b) matrix.
Step 4: Enter the elements of the first (a) matrix.
Step 5: Enter the elements of the second (b) matrix.
Step 6: Print the elements of the first (a) matrix in matrix form.
Algorithm for Matrix Multiplication
Step 7: Print the elements of the second (b) matrix in matrix form.
Step 8: Set a loop up to row.
Step 9: Set an inner loop up to the column.
Step 10: Set another inner loop up to the column.
Step 11: Multiply the first (a) and second (b) matrix and store the element
in the third matrix (c)
Step 12: Print the final matrix.
Step 13: Stop the Program.
Matrix Multiplication
Matrix Multiplication
#include<stdio.h>
int main()
{
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("multiply of the matrix=n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%dt",mul[i][j]);
}
printf("n");
}
return 0;
}
Matrix addition
Matrix Addition
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10],second[10][10],sum[10][10];
printf("Enter the number of rows and columns of matrixn");
scanf("%d%d",&m,&n);
printf("Enter the elements of first matrixn");
for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
scanf("%d",&first[c][d]);
}
}
printf("Enter the elements of second matrixn");
for (c = 0; c < m; c++)
{
{
scanf("%d", &second[c][d]);
}
}
printf("Sum of entered matrices:-n");
for (c = 0; c < m; c++)
{
for (d = 0 ; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
printf("%dt", sum[c][d]);
}
printf("n");
}
return 0;
}
Exercise
• Program to Find the Transpose of a Matrix
Strings
Character
• char is a C data type designed for the storage of letters.
• A char takes a memory size of 1 byte. It also stores a
single character.
• Example :
• char a;
scanf (“%c”, &a);
printf (“%c”, a);
Strings
• A sequence of characters that is treated as a single data
item.
itle String
• Group of characters defined between double quotation
marks.
“ You are the best. ”
Declaration of String
Since string is an array, the declaration of a string is the
same as declaring a char array.
Syntax:
char string-name[ size ];
Example :
char subject [10];
Initializing String variables
•The string is always ended with a null
character ‘0’.
•The characters after the null character are
ignored.
•e.g., char str[20] = “Initial value”;
Reading strings: %s format
o %s reads a string into a character array
o given the array name or start address.
o It ends the string with ‘0’
#include<stdio.h>
void main()
{
char name[25];
printf("Enter any Name:");
scanf("%s", &name);
printf("Name = %s n", name);
}
Assigning Values to Strings
• Arrays and strings are second-class citizens in C;
• they do not support the assignment operator once it is
declared.
• For example,
char c[100];
c = "C programming"; // Error! array type is not
assignable.
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 string.h library.
• Hence, you must include string.h header file in your
programs to use these functions.
String functions
• Function strlen()
• Function strcpy()
• Function strcmp()
• Function strcat()
• Function strlwr()
• Function strupr()
• Function strrev()
• Function strstr() - sub string
String Handling functions
String Length: strlen() function
The strlen() function returns the length of the given string.
It doesn't count null character '0’.
Syntax:
strlen(variable);
Example:
char ch[20]=“ Computer ” ;
printf("Length of string is: %d",strlen(ch));
String Handling functions
Copy String: strcpy()
The strcpy(destination, source) function copies the source string in
destination.
Syntax:
strcpy(destination, source);
Example :
char ch[20]=“ Computer ”;
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
String Handling functions
Compare String: strcmp()
The strcmp(first-string, second-string) function compares two string and
returns 0 if both strings are equal.
Syntax:
strcmp(first-string, second-string);
Example:
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
String Handling functions
String Concatenation: strcat()
The strcat(first-string, second-string) function concatenates
two strings and result is returned to first-string.
Syntax:
strcat(first_string, second_string)
Example:
char ch[10]={'h', 'e', 'l', 'l', 'o', '0'};
char ch2[10]={'c', '0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
String Handling functions
Reverse String: strrev()
The strrev(string) function returns reverse of the given
string.
Syntax:
strrev(string_var);
Example :
char str[20]= “ Comp”;
printf("nReverse String is: %s",strrev(str));
String Handling functions
C String Lowercase: strlwr()
The strlwr(string) function returns string characters in
lowercase. Let's see a simple example of strlwr() function.
Syntax:
strlwr(string_var);
Example:
char str[20]= “ENGINEER”;
printf("String is: %s",str);
printf("nLower String is: %s",strlwr(str));
String Handling functions
String Uppercase: strupr()
The strupr(string) function returns string characters in
uppercase.
Syntax:
strupr(string_var);
Example:
char str[20]= “Engineer”;
printf("String is: %s",str);
printf("nUpper case String is: %s",strupr(str));
String Handling functions
String strstr()
The strstr() function returns pointer to the first occurrence of
the matched string in the given string. It is used to return
substring from first match till the last character.
Syntax:
strstr(str,“sub_string");
Example:
char str[100]="this is javatpoint with c and java";
char *sub;
sub=strstr(str,"java");
printf("nSubstring is: %s",sub);
Example – All functions
#include<stdio.h>
#include<string.h> // you must include string header file
int main()
{
int a,b;
char s1[50], s2[50];
printf( "Enter the string: n");
scanf("%s",&s1);
printf("Enter the options:n1.String Lengthn2.String reversen3.String concatenationn4.String
copyn5.String upper casen6.string Lower casen7.string comparison n");
scanf("%d",&a);
switch(a)
{
Example – All functions
case 1:
{
b=strlen(s1);
printf("String Length= %d",b);
break;
}
case 2:
{
printf("String reverse = %s",strrev(s1));
break;
}
Example – All functions
case 3:
{
printf(" Enter the target string: n");
scanf("%s",&s2);
strcat(s2,s1);
printf(" result of concat = %s", s2);
break;
}
case 4:
{
strcpy(s2,s1);
printf("Copied string = %s", s2);
break;
}
Example – All functions
case 5:
{
printf("the upper case of given string = %s", strupr(s1));
break;
}
case 6:
{
printf("the Lower case of given string = %s", strlwr(s1));
break;
}
Example – All functions
case 7:
{
printf ("enter the string you wish to compare with your prevoius string n");
scanf("%s",&s2);
a=strcmp(s1,s2);
if(a==0)
{
printf("Strings are same");
}
else
{
printf("Strings are not same");
}
break;
}
Example – All functions
{
printf("Enter the correct option:");
}
return 0;
}
}
Thank You!!

More Related Content

PDF
PDF
Array and its types and it's implemented programming Final.pdf
PPTX
ARRAYS.pptx
PPTX
Programming in c Arrays
PDF
Unit ii data structure-converted
PPTX
PPT
C array and Initialisation and declaration
Array and its types and it's implemented programming Final.pdf
ARRAYS.pptx
Programming in c Arrays
Unit ii data structure-converted
C array and Initialisation and declaration

Similar to Unit4pptx__2024_11_ 11_10_16_09.pptx (20)

PPT
show the arrays ppt for first year students
PPTX
Arrays.pptx
PPTX
Module_3_Arrays - Updated.pptx............
PPT
PDF
CP PPT_Unit IV computer programming in c.pdf
PPTX
Unit 6. Arrays
PDF
Introduction to Arrays in C
PDF
Functions, Strings ,Storage classes in C
PPTX
10 arrays and pointers.pptx for array and pointer
PPTX
data structure unit -1_170434dd7400.pptx
PPTX
arrays in c programming - example programs
PPTX
unit 2.pptx
PPTX
PPTX
Arrays in programming
PPTX
Array 2 hina
PPTX
Various Operations Of Array(Data Structure Algorithm).pptx
PPTX
01245xsfwegrgdvdvsdfgvsdgsdfgsfsdgsdgsdgdg
PPTX
show the arrays ppt for first year students
Arrays.pptx
Module_3_Arrays - Updated.pptx............
CP PPT_Unit IV computer programming in c.pdf
Unit 6. Arrays
Introduction to Arrays in C
Functions, Strings ,Storage classes in C
10 arrays and pointers.pptx for array and pointer
data structure unit -1_170434dd7400.pptx
arrays in c programming - example programs
unit 2.pptx
Arrays in programming
Array 2 hina
Various Operations Of Array(Data Structure Algorithm).pptx
01245xsfwegrgdvdvsdfgvsdgsdfgsfsdgsdgsdgdg
Ad

Recently uploaded (20)

PPTX
An introduction to Dialogue writing.pptx
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PDF
Module 3: Health Systems Tutorial Slides S2 2025
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
PDF
Landforms and landscapes data surprise preview
PDF
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Sunset Boulevard Student Revision Booklet
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
PPTX
An introduction to Prepositions for beginners.pptx
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
PDF
UTS Health Student Promotional Representative_Position Description.pdf
PPTX
Software Engineering BSC DS UNIT 1 .pptx
PPTX
How to Manage Global Discount in Odoo 18 POS
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
An introduction to Dialogue writing.pptx
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Module 3: Health Systems Tutorial Slides S2 2025
Open Quiz Monsoon Mind Game Final Set.pptx
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
vedic maths in python:unleasing ancient wisdom with modern code
Landforms and landscapes data surprise preview
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Week 4 Term 3 Study Techniques revisited.pptx
Sunset Boulevard Student Revision Booklet
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
An introduction to Prepositions for beginners.pptx
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
UTS Health Student Promotional Representative_Position Description.pdf
Software Engineering BSC DS UNIT 1 .pptx
How to Manage Global Discount in Odoo 18 POS
Revamp in MTO Odoo 18 Inventory - Odoo Slides
Ad

Unit4pptx__2024_11_ 11_10_16_09.pptx

  • 1. Unit - 4 Array and String 01CE1101 Computer Programming
  • 2. Arrays • An array is a collection of data items, all of the same type, accessed using a common name. • Array is a data structure that hold finite sequential collection of homogeneous data. • Array is a collection - Array is a container that can hold a collection of data. • Array is finite - The collection of data in array is always finite, which is determined prior to its use. • Array is sequential - Array stores collection of data sequentially in memory. • Array contains homogeneous data - The collection of data in array must share a same data type.
  • 3. Arrays • Examples: - List of customers and their phone numbers -Table of daily rainfall data - List of employees in an organization - Test scores of a class of students and so on…. • Structure of array:
  • 4. Declaration of Arrays • Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for each dimension of the array. • Syntax: type arrayName [ arraySize ]; • Example: int group[10]; float height[50]; char name[15];
  • 5. Initialization of Arrays • After an array is declared, its elements must be initialized. • There are two ways to initialize an array. 1.Static array initialization - Initializes all elements of array during its declaration. 2.Dynamic array initialization - The declared array is initialized some time later during execution of program.
  • 6. Static initialization of array • We define value of all array elements within a pair of curly braces { and } during its declaration. • Values are separated using comma , and must be of same type. • Example int marks[5] = {90, 86, 89, 76, 91};
  • 7. Dynamic initialization of array • You can assign values to an array element dynamically during execution of program. First declare array with a fixed size. • Then use the following syntax to assign values to an element dynamically. Syntax: array_name[index] = some_value; EX: scanf("%d",&arr[i]);
  • 8. Advantages and Disadvantages • Advantages: 1.Use of less line of code as it creates a single array of multiple elements. 2.Random access of elements using array index. 3.Easy access to all the elements. 4.Traversal through the array becomes easy using a single loop. 5.Sorting becomes easy as it can be accomplished by writing less line of code. • Disadvantages: 1.Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation. 2.Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
  • 9. Types of Arrays •One-dimensional arrays(single) •Two-dimensional arrays •Multidimensional arrays
  • 10. One – Dimensional Array • A one-dimensional array as a row, where elements are stored one after another. • Syntax: datatype array name[size]; Where …. datatype: It denotes the type of the elements in the array. array name: Name of the array. It must be a valid identifier. size: Number of elements an array can hold. here are some example of array
  • 11. • The elements of an array can be accessed by specifying array name followed by subscript or index inside square brackets (i.e []). • Array subscript or index starts at 0. If the size of an array is 10 then the first element is at index 0, while the last element is at index 9. • The first valid subscript (i.e 0) is known as the lower bound, while last valid subscript is known as the upper bound. Accessing elements of an array
  • 12. Accessing elements of an array Example: int a[5]; then elements of this array are; First element – a[0] Second element – a[1] Third element – a[2] Fourth element – a[3] Fifth element – a[4]
  • 13. Accessing elements of an array Array subscript or index can be any expression that yields an integer value. For example: int a[5]; int i = 0, j = 2; a[i]; // 1st element a[i+1]; // 2nd element a[i+j]; // 3rd element In the array a, the last element is at a[4],
  • 14. Example Program #include<stdio.h> int main() { int a[5], i; for(i = 0; i < 5; i++) { printf("Enter a[%d]: ", i); scanf("%d", &a[i]); } printf("nPrinting elements of the array: nn"); for(i = 0; i < 5; i++) { printf("%d ", a[i]); } return 0; }
  • 15. Example Program • 1. Write down a program to enter 20 elements in an array and print the elements in reverse order. • 2. Write a program to add all the elements in an array. • 3.Write a program to copy one array to another array. • 4. Write a program to find out all the even and odd numbers present in an array. • 5. Write a program to swap two arrays.
  • 16. Two Dimensional Array in C • Two – dimensional array is the simplest form of a multidimensional array. • The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. • It provides ease of holding the bulk of data at once.
  • 17. Declaration of two dimensional Array in C Syntax: datatype array_name[rows][columns]; Where datatype: It denotes the type of the elements in the array. array name: Name of the array. It must be a valid identifier. Row – size of rows Column – size of column
  • 18. Initializing Two – Dimensional Arrays There are two ways in which a Two-Dimensional array can be initialized. First Method: int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11} The above array have 3 rows and 4 columns. The elements in the braces from left to right are stored in the table also from left to right. The elements will be filled in the array in the order, first 4 elements from the left in first row, next 4 elements in second row and so on. Better Method: int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
  • 19. Accessing the 2- D Arrays arr[0][0] = 1 arr[0][1] = 2 arr[0][2] = 3 arr[1][0] = 2 arr[1][1] = 3 arr[1][2] = 4 arr[2][0] = 3 arr[2][1] = 4 arr[2][2] = 5
  • 20. Example #include <stdio.h> int main () { int a[3][3],i,j; for (i=0;i<3;i++) { for (j=0;j<3;j++) { printf("Enter a[%d][%d]: ",i,j); scanf("%d",&a[i][j]); }
  • 21. Example printf("n printing the elements ....n"); for(i=0;i<3;i++) { printf("n"); for (j=0;j<3;j++) { printf("%dt",a[i][j]); } } return 0; }
  • 22. Sorting operation using array • The process of Sorting can be explained as a technique of rearranging the elements in any particular order, which can be set ready for further processing by the program logic. • We can easily sort a list of elements by means of iterations and condition check statements. • We require one outer loop and one inner loop and one swap function to do the purpose.
  • 23. Sorting operation using array • We can do sorting the elements in 2 ways • Ascending order • Descending order
  • 24. Sorting operation –Example #include <stdio.h> int main() { int a[5],i,j,temp = 0; printf("Enter the Elements of array: n"); for(i = 0; i < 5; i++) { scanf("%d", &a[i]); } for (i = 0; i < 5; i++) { for (j = i+1; j < 5; j++) { if(a[i] > a[j]) { temp = a[i]; a[j] = temp; } } } printf("n"); printf("Elements of array sorted in ascending order: n"); for (i = 0; i <5; i++) { printf("%d ", a[i]); } return 0; }
  • 25. Matrix operation using array • A matrix is a grid that is used to store data in a structured format. • It is often used with a table, where the data is represented in horizontal rows and vertical columns. • Addition, subtraction and multiplication are the basic operations on the matrix. • Matrix multiplication in C language to calculate the product of two matrices (two-dimensional arrays). A user inputs the orders and elements of the matrices.
  • 26. Matrix operation using array • In programming if the user wants to multiply, add, subtract and divide two matrices, then the order of the matrix should be declared first. • A matrix that contains the same number of rows and columns then it is called a square matrix. • Matrix is used to store a group of related data. Some of the programming languages are used to support matrices as a data type that offers more flexibility than a static array. • Instead of storing the values in a matrix, it can be stored as an individual variable, a program can access and perform operations on the data more efficiently.
  • 27. Algorithm for Matrix Multiplication Step 1: Start the Program. Step 2: Enter the row and column of the first (a) matrix. Step 3: Enter the row and column of the second (b) matrix. Step 4: Enter the elements of the first (a) matrix. Step 5: Enter the elements of the second (b) matrix. Step 6: Print the elements of the first (a) matrix in matrix form.
  • 28. Algorithm for Matrix Multiplication Step 7: Print the elements of the second (b) matrix in matrix form. Step 8: Set a loop up to row. Step 9: Set an inner loop up to the column. Step 10: Set another inner loop up to the column. Step 11: Multiply the first (a) and second (b) matrix and store the element in the third matrix (c) Step 12: Print the final matrix. Step 13: Stop the Program.
  • 30. Matrix Multiplication #include<stdio.h> int main() { int a[10][10],b[10][10],mul[10][10],r,c,i,j,k; printf("enter the number of row="); scanf("%d",&r); printf("enter the number of column="); scanf("%d",&c); printf("enter the first matrix element=n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&a[i][j]); } } printf("enter the second matrix element=n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&b[i][j]); } } printf("multiply of the matrix=n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { mul[i][j]=0; for(k=0;k<c;k++) { mul[i][j]+=a[i][k]*b[k][j]; } } } //for printing result for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%dt",mul[i][j]); } printf("n"); } return 0; }
  • 32. Matrix Addition #include <stdio.h> int main() { int m, n, c, d, first[10][10],second[10][10],sum[10][10]; printf("Enter the number of rows and columns of matrixn"); scanf("%d%d",&m,&n); printf("Enter the elements of first matrixn"); for (c = 0; c < m; c++) { for (d = 0; d < n; d++) { scanf("%d",&first[c][d]); } } printf("Enter the elements of second matrixn"); for (c = 0; c < m; c++) { { scanf("%d", &second[c][d]); } } printf("Sum of entered matrices:-n"); for (c = 0; c < m; c++) { for (d = 0 ; d < n; d++) { sum[c][d] = first[c][d] + second[c][d]; printf("%dt", sum[c][d]); } printf("n"); } return 0; }
  • 33. Exercise • Program to Find the Transpose of a Matrix
  • 35. Character • char is a C data type designed for the storage of letters. • A char takes a memory size of 1 byte. It also stores a single character. • Example : • char a; scanf (“%c”, &a); printf (“%c”, a);
  • 36. Strings • A sequence of characters that is treated as a single data item. itle String • Group of characters defined between double quotation marks. “ You are the best. ”
  • 37. Declaration of String Since string is an array, the declaration of a string is the same as declaring a char array. Syntax: char string-name[ size ]; Example : char subject [10];
  • 38. Initializing String variables •The string is always ended with a null character ‘0’. •The characters after the null character are ignored. •e.g., char str[20] = “Initial value”;
  • 39. Reading strings: %s format o %s reads a string into a character array o given the array name or start address. o It ends the string with ‘0’ #include<stdio.h> void main() { char name[25]; printf("Enter any Name:"); scanf("%s", &name); printf("Name = %s n", name); }
  • 40. Assigning Values to Strings • Arrays and strings are second-class citizens in C; • they do not support the assignment operator once it is declared. • For example, char c[100]; c = "C programming"; // Error! array type is not assignable.
  • 41. 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 string.h library. • Hence, you must include string.h header file in your programs to use these functions.
  • 42. String functions • Function strlen() • Function strcpy() • Function strcmp() • Function strcat() • Function strlwr() • Function strupr() • Function strrev() • Function strstr() - sub string
  • 43. String Handling functions String Length: strlen() function The strlen() function returns the length of the given string. It doesn't count null character '0’. Syntax: strlen(variable); Example: char ch[20]=“ Computer ” ; printf("Length of string is: %d",strlen(ch));
  • 44. String Handling functions Copy String: strcpy() The strcpy(destination, source) function copies the source string in destination. Syntax: strcpy(destination, source); Example : char ch[20]=“ Computer ”; char ch2[20]; strcpy(ch2,ch); printf("Value of second string is: %s",ch2);
  • 45. String Handling functions Compare String: strcmp() The strcmp(first-string, second-string) function compares two string and returns 0 if both strings are equal. Syntax: strcmp(first-string, second-string); Example: char str1[20],str2[20]; printf("Enter 1st string: "); gets(str1);//reads string from console printf("Enter 2nd string: "); gets(str2); if(strcmp(str1,str2)==0) printf("Strings are equal"); else printf("Strings are not equal");
  • 46. String Handling functions String Concatenation: strcat() The strcat(first-string, second-string) function concatenates two strings and result is returned to first-string. Syntax: strcat(first_string, second_string) Example: char ch[10]={'h', 'e', 'l', 'l', 'o', '0'}; char ch2[10]={'c', '0'}; strcat(ch,ch2); printf("Value of first string is: %s",ch);
  • 47. String Handling functions Reverse String: strrev() The strrev(string) function returns reverse of the given string. Syntax: strrev(string_var); Example : char str[20]= “ Comp”; printf("nReverse String is: %s",strrev(str));
  • 48. String Handling functions C String Lowercase: strlwr() The strlwr(string) function returns string characters in lowercase. Let's see a simple example of strlwr() function. Syntax: strlwr(string_var); Example: char str[20]= “ENGINEER”; printf("String is: %s",str); printf("nLower String is: %s",strlwr(str));
  • 49. String Handling functions String Uppercase: strupr() The strupr(string) function returns string characters in uppercase. Syntax: strupr(string_var); Example: char str[20]= “Engineer”; printf("String is: %s",str); printf("nUpper case String is: %s",strupr(str));
  • 50. String Handling functions String strstr() The strstr() function returns pointer to the first occurrence of the matched string in the given string. It is used to return substring from first match till the last character. Syntax: strstr(str,“sub_string"); Example: char str[100]="this is javatpoint with c and java"; char *sub; sub=strstr(str,"java"); printf("nSubstring is: %s",sub);
  • 51. Example – All functions #include<stdio.h> #include<string.h> // you must include string header file int main() { int a,b; char s1[50], s2[50]; printf( "Enter the string: n"); scanf("%s",&s1); printf("Enter the options:n1.String Lengthn2.String reversen3.String concatenationn4.String copyn5.String upper casen6.string Lower casen7.string comparison n"); scanf("%d",&a); switch(a) {
  • 52. Example – All functions case 1: { b=strlen(s1); printf("String Length= %d",b); break; } case 2: { printf("String reverse = %s",strrev(s1)); break; }
  • 53. Example – All functions case 3: { printf(" Enter the target string: n"); scanf("%s",&s2); strcat(s2,s1); printf(" result of concat = %s", s2); break; } case 4: { strcpy(s2,s1); printf("Copied string = %s", s2); break; }
  • 54. Example – All functions case 5: { printf("the upper case of given string = %s", strupr(s1)); break; } case 6: { printf("the Lower case of given string = %s", strlwr(s1)); break; }
  • 55. Example – All functions case 7: { printf ("enter the string you wish to compare with your prevoius string n"); scanf("%s",&s2); a=strcmp(s1,s2); if(a==0) { printf("Strings are same"); } else { printf("Strings are not same"); } break; }
  • 56. Example – All functions { printf("Enter the correct option:"); } return 0; } }