0% found this document useful (0 votes)
4 views

CP_Module-4_ppt-2023-24 (1)

Module 4 covers arrays and strings in C programming, detailing the declaration, initialization, and properties of one-dimensional and two-dimensional arrays. It also discusses the advantages and disadvantages of arrays, memory representation, and provides examples of array operations and string functions. Key string handling functions like strlen, strcpy, strcat, and strcmp are introduced, along with their usage in C programs.

Uploaded by

niharpadave2812
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)
4 views

CP_Module-4_ppt-2023-24 (1)

Module 4 covers arrays and strings in C programming, detailing the declaration, initialization, and properties of one-dimensional and two-dimensional arrays. It also discusses the advantages and disadvantages of arrays, memory representation, and provides examples of array operations and string functions. Key string handling functions like strlen, strcpy, strcat, and strcmp are introduced, along with their usage in C programs.

Uploaded by

niharpadave2812
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/ 43

Module 4.

Arrays and Strings


● Introduction to Arrays
● Declaration and initialization of one dimensional and two-dimensional
arrays.
● Definition and initialization of String
● String functions
What is Array?
- An array is defined as the collection of similar type of data items stored at
contiguous memory locations. Arrays are the derived data type in C programming
language which can store the primitive type of data such as int, char, double, float,
etc. It also has the capability to store the collection of derived data types, such as
pointers, structure, etc. The array is the simplest data structure where each data
element can be randomly accessed by using its index number.

- C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different
variables for the marks in the different subject. Instead of that, we can define an
array which can store the marks in each subject at the contiguous memory locations.

- By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.
Properties of Array:-
The array contains the following properties.

○ Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
○ Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
○ Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data
element.
Advantages and Disadvantages of Array in C
Advantage of C Array:-
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array:-
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn
later.
Array Representation in memory

The amount of storage space required to hold an array is directly related to


its type and size. The total size in bytes is computed as shown here.
total bytes= size of (base type ) x size of array
Array Representation in memory
- For an integer array

int x [8];

- 16 bytes of memory gets reserved for 8 integers, as every


integer is 2-byte long. If the array not initialized it may contain
garbage values. This is because the storage class of array is
assumed as auto.
- If the storage class is declared as static then all the array
elements would have a default initial value as zero.
- Suppose first element is stored at an address 1000 then the
last 8th elements will be stored at address 1014. The total
bytes required are 16.
Array Representation in memory
- Consider another declaration,

char a [7];
- char elements requires one byte of
storage. Their memory
representation is shown below.
Declaration of Array in C
We can declare an array in the c language in the following way.

data_type array_name[array_size]; // One-dimensional array

Now, let us see the example to declare the array.

int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

0 to (n-1) ex. int a[6];

Means 0 to 5 how it is a[0] a[1] a[2] a[3] a[4] a[5]

int a[5] = {1,2,3}; then 3,4 will be 0


Initialization of C Array

The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.

marks[0]=80;//initialization of array

marks[1]=60;

marks[2]=70;

marks[3]=85;

marks[4]=75;
Example on array declaration and
initialization and access the data of
array

Output
80
60
70
85
75
Example on array declaration and initialization and access the
data of array
Array Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};

OR

int marks[]={20,30,40,50,60};
C program to declare and initialize the array
Example:-
WAP to find sum of all elements of
one dimensional array.

Output
Example:-
WAP to find sum of even
and odd elements present
in an array of n elements.

Output
Example:-
WAP in C to search given
element in an array.

Output
#include <stdio.h>
WAP to find sum of
void main() {
even and odd elements
int a[50],n,i,sumo=0,sume=0; present in an array of n
printf("Enter number of elements: "); elements.
scanf("%d",&n);

for(i=0;i<n;i++) {

printf("Enter No: ");

scanf("%d",&a[i]);

if(a[i]%2==0)

sume=sume+a[i];

else

sumo=sumo+a[i]; }

printf("Sum of odd Elements: %d",sumo);

printf("\nSum of Even Elements: %d",sume);

getch();
#include <stdio.h>
void main() {
WAP to find
int a[50],n,i,max;
largest element
printf("Enter number of elements: ");
scanf("%d",&n);
of one
for(i=0;i<n;i++) {
dimensional
printf("Enter No: "); array.
scanf("%d",&a[i]); }
max=a[0];
for(i=1;i<n;i++) {
if(a[i]>max)
max=a[i]; }
printf("Largest Elements: %d",max);
getch();
#include<stdio.h> WAP to accept and sort ‘n’ elements
#include<stdio.h> of an array in ascending
void main() { order.temp=a[i];
int n,a[50],temp,i,j;
a[i]=a[j];
a[j]=temp;
clrscr();
}
printf("Enter no. of elements:\n"); }
scanf("%d",&n); }
printf("Enter elements:\n"); printf("sorted array=\n");
for(i=0;i<n;i++) { for(i=0;i<n;i++)
scanf("%d",&a[i]); } {
printf("%d\t",a[i]);
for(i=0;i<n;i++) {
}
for(j=i+1;j<n;j++) {
getch();
if(a[i]>a[j]) {
Arrays as function arguments/Passing array to a function:
- Array element can be passed to a function by calling the function by value or by
reference.
- In call by value, we pass values of the array elements to the function, whereas in
call by reference, we pass address of array elements to the function.

Passing individual array element:


Arrays as function arguments/Passing array to a function:
Passing array to function:

Example:

WAP in C to calculate the sum


of array elements by passing
to a function

Output

Result=154
Two dimensional arrays:
- Suppose we have been given a table of values. It consists of rows and columns.
We can think of this table as a matrix. The particular value in this matrix can be
represented by using two subscripts such as Aij where A is the name of matrix
and Aij refer to value in ith row and jth column.
- C support multidimensional array. The simplest form of multidimensional arrays is
two dimensional arrays. The general form of declaration of two dimensional
arrays is:
data_type array-name [row size] [column size];
- For example, to declare a two dimensional array A of size 10, 20 we would write,
int A[10] [20];
- Observe that we use separate set of brackets for each dimension. To load data
into two dimensional arrays we need to form loops, one for rows and other for
columns. The data can be entered row wise or column wise. Similarly to read
array elements of two dimensional arrays we need two loops.
Two dimensional arrays:
We can write code for reading the table of numbers.

num[i] [j]

0 1 2 3

0 55 25 11 10

1 78 26 9 7

2 12 15 16 26
C Multidimensional Arrays

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a
table with 3 rows and each row has 4 columns.

float x[3][4];
Memory representation of two dimensional arrays:
In case of two dimensional arrays, the number of bytes of memory required
can be calculated by using formula.

Bytes = size of 1st index * size of 2st index *size of base type

Memory does not have row and column. Therefore the two dimensional
array elements are also stored in one continues chain as shown below.
Two dimensional Array initialization
A two dimensional array can be initialized by declaration.

int num [3] [4] = {55, 25, 11, 10, 78, 26, 9, 7, 12, 15, 16, 26};

Observe that first dimension is optional while need to mention second


dimension.

int num [ ] [4] = {55, 25, 11, 10, 78, 26, 9, 7, 12, 15, 16, 26};

is permitted but

int num [2] [ ] = {--------};

is not allowed.

It is necessary to mention rightmost dimension so that compiler will know the


length of each row.
Two dimensional arrays:
WAP to find sum of elements of
an array of size m*n.

Output
Two dimensional arrays:
WAP to find transpose of
a square matrix using
only one matrix.

Output:
Strings:
- A string is one dimensional array of characters. The most common use of one
dimensional array is a character string. The string consists of null (‘\0’) as the last
character or terminated by’\0’. ASCII value of null character is 0. For a string of 10
characters we need to declare size of array 11 as:
char str [11];

- This makes provision for the null at the end of the string.
- You can assign a value of string. It is called as string constant. A string constant is
enclosed in double quotes.
- For example,
char name [ ] =”MADAM”;

- Observe that you need not add null at the end of the string constant. The C
compiler does this for you automatically.
Strings:
- You can read a string from keyboard by using scanf(). For example

char name [15];

scanf(“%s”,name);

- Observe that you cannot incorporate white space into the value of the string. It
will cause termination of string.

- C compiler has a large set of useful string handling library functions. Out of these,
strlen ( ), strcpy ( ), strcat ( ) and strcmp ( ) are more commonly used. These
functions use the standard header file string.h. when we use these functions, we
need to include this file in the program. Let’s discuss how to use these functions.
- Drawback of string is it will not take string after space
String code

#include <stdio.h>

int main() {

char a[20]={'s','a','k','e','c'};

for(int i=0;i<=6;i++)

printf("%c",a[i]);

return 0;

Output :- sakec
Strings
1. strlen( ):
- This function counts numbers of character in the string. Consider the
Example:
void main ( )
{
char arr[ ] = “Heloow”;
int len1, len2;
len1= strlen(arr);
len2= strlen(“Hi”);
printf(“%d %d”, len1,len2);
}
- The output would be 6 2
- While calculating the length, the function does not consider the last
null character.
#include <stdio.h>

#include<string.h>

int main() {

char arr[ ] = "Heloow";

int len1, len2;

len1= strlen(arr);

len2= strlen(“Hii”);

printf("%d %d", len1,len2);

}
Length code

#include <stdio.h>

#include<string.h>

int main() {

char arr[ ] = "Heloow";

int len1, len2;

len1= strlen(arr);

len2= strlen(“Hii”);

printf("%d %d", len1+2,len2);

output:-8 3
Strings
2. strcpy( ):
- The function copies the contents of one string into another. The base
address of the source and target strings should be supplied to this function.
For example consider the program,
void main ( )
{
char source [ ] = "MADAM";
char target [20];
strcpy (target, source);
printf("%s %s",source, target);
}
- The output is MADAM MADAM
- The strcpy() goes on coping the character of source string into target till it
does not encounter the null character(‘\0’) of the source string.
Strings
3. strcat( ):
- This function concatenates the source string at the end of the target string.
For example consider the program,

void main ( )
{
char source[ ] = “Chavan“;
char target [ ] = “Ashok“;
strcat (target, source);
printf(“%s”,target);
}
- The output is Ashok Chavan
Strings
4. strcmp( ):
- This function compares two strings to find out whether they are same or different.
The two strings are compared character by character until there is mismatch or end
of one of the string is reached, whichever occurs first. If the two string are identical,
strcmp( ) returns value zero, otherwise it will return a numeric difference between
ASCII values the non matching characters.
- Return Value from strcmp()
Strings
4. strcmp( ):
Consider the program.
int main() {
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
result = strcmp(str1, str2); // comparing strings str1 and str2
printf("strcmp(str1, str2) = %d\n", result);
result = strcmp(str1, str3); // comparing strings str1 and str3
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
Strings
5. strrev(): The strrev(string) function returns reverse of the given string. Let's see a simple
example of strrev() function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console Output:
Enter string: Welcome
printf("String is: %s",str);
String is: Welcome
printf("\nReverse String is: %s",strrev(str)); Reverse String is: emocleW
return 0;
}
#include <stdio.h>

int main()

char name[20];

printf("Enter name: ");

scanf("%s", name);

printf("Your name is %s.", name);

return 0;

OUTPUT:- Enter name: C PROGRAMMING


Strings
6. strlwr: The strlwr(string) function returns string characters in lowercase. Let's see
a simple example of strlwr() function.

Output:
Enter string: WELcome
String is: WELcome
Lower String is: welcome
Strings
7. strupr(): The strupr(string) function returns string characters in uppercase. Let's
see a simple example of strupr() function.

Output:
Enter string: welcome
String is: welcome
Lower String is: WELCOME
Strings
WAP in C to count the no
of vowels and consonants
in given string.

Output

You might also like