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

EContent 3 2024 11 21 12 27 54 UNIT4pptx 2024 11 18 12 46 11

Uploaded by

hackerrz.0077
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views57 pages

EContent 3 2024 11 21 12 27 54 UNIT4pptx 2024 11 18 12 46 11

Uploaded by

hackerrz.0077
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

01CE1101

Computer Programming

Unit - 4
Array and String
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
Accessing elements of an
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

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: \n\n");
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("%d\t",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> a[j] = temp;
int main() }
{ }
int a[5],i,j,temp = 0; }
printf("Enter the Elements of array: \n"); printf("\n");
for(i = 0; i < 5; i++)
{ printf("Elements of array sorted in
scanf("%d", &a[i]); ascending order: \n");
} for (i = 0; i <5; i++)
{
for (i = 0; i < 5; i++) printf("%d ", a[i]);
{ }
for (j = i+1; j < 5; j++) return 0;
{ }
if(a[i] > a[j])
{
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> printf("multiply of the matrix=\n");
int main() for(i=0;i<r;i++)
{ {
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k; for(j=0;j<c;j++)
printf("enter the number of row="); {
scanf("%d",&r); mul[i][j]=0;
printf("enter the number of column="); for(k=0;k<c;k++)
scanf("%d",&c); {
printf("enter the first matrix element=\n"); mul[i][j]+=a[i][k]*b[k][j];
for(i=0;i<r;i++) }
{ }
for(j=0;j<c;j++) }
{ //for printing result
scanf("%d",&a[i][j]); for(i=0;i<r;i++)
} {
} for(j=0;j<c;j++)
printf("enter the second matrix element=\n"); {
for(i=0;i<r;i++) printf("%d\t",mul[i][j]);
{ }
for(j=0;j<c;j++) printf("\n");
{ }
scanf("%d",&b[i][j]); return 0;
} }
}
Matrix addition
Matrix Addition
#include <stdio.h> for (d = 0 ; d < n; d++)
int main() {
{ scanf("%d", &second[c][d]);
int m, n, c, d, first[10][10],second[10][10],sum[10][10]; }
printf("Enter the number of rows and columns of matrix\ }
n"); printf("Sum of entered matrices:-\n");
scanf("%d%d",&m,&n);
printf("Enter the elements of first matrix\n"); for (c = 0; c < m; c++)
{
for (c = 0; c < m; c++) for (d = 0 ; d < n; d++)
{ {
for (d = 0; d < n; d++) sum[c][d] = first[c][d] + second[c][d];
{ printf("%d\t", sum[c][d]);
scanf("%d",&first[c][d]); }
} printf("\n");
} }
printf("Enter the elements of second matrix\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
#include<stdio.h>
void main()
{
char name[25];
printf("Enter any Name:");
scanf("%s", &name);
printf("Name = %s \n", name);
}
o %s reads a string into a character array
o given the array name or start address.
o It ends the string with ‘\0’
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
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 Length\n2.String reverse\n3.String concatenation\n4.String
copy\n5.String upper case\n6.string Lower case\n7.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!!

You might also like