Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Module 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

MODULE 3

ARRAYS & STRINGS


Module III

Arrays Declaration and Initialization, 1-Dimensional Array, 2-


Dimensional Array.

String processing: In built String handling functions (strlen,


strcpy, strcat and strcmp, puts, gets)

Linear search program, bubble sort program,


simple programs covering arrays and strings

Course Outcome:-

CO3: Write readable C programs with arrays, structure or union for


storing the data to be processed
Array


An array is a collection of elements all of the same data type.

Elements of array can be of any data type in C.

Array has a unique name.

An array element is referred to by specifying the array name followed
by the subscript enclosd in square brackets.

subscript must be expressed as a nonnegative integer.

Arrays are used when we need to store a group of data of same type
and do different processing on it.
Why do we need arrays?

• We can use normal variables (v1, v2, v3) when we have a small
number of objects, but if we want to store a large number of
instances, it becomes difficult to manage them with normal
variables.

• The idea of an array is to represent many instances in one


variable.

• Elements of the array are stored at contiguous memory locations


where the first element is stored at the smallest memory location.
One Dimensional Arrays in C

Defining a one dimensional array:


data_type array_name [Number of Elements];
Example:
int a[5];
float temperature[1000];
char name[30]
One Dimensional Arrays in C

int A[10];


Data type of A[i] is int.

A[i] is treated as a simple variable.

So it can be used in printf(), scanf() or in an expression.


A[2]=10; A[0]=20; A[5]=25;

A[7]=A[2]+A[0];

scanf(“%d”, &A[1]); printf(“%d”,A[0]);
One Dimensional Arrays in C

main()

{

int a[10], n, i;
 scanf(“%d”,&n);
 for (i=0; i<n; i++) // Reading n numbers

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

 for (i=0; i<n; i++) // Displaying n numbers



printf(“%d ”,a[i]);

}
Initialization of Array

• 1st approach
int Mark[5] = {25,35,30,45,40};
• 2nd approach
int Mark[ ] = {25,35,30,45,40};
• 3rd approach
int Mark[5] = {25,35,30};
• 4th approach
for(int i=0;i<5;i++)
{
scanf(“%d”,&Mark[i]);
}
One Dimensional Arrays in C

Note :-

Array name is treated as a constant pointer.


So it can not be used on the LHS of an assignment expression.


Array name without square brackets represents the address of the first
element of the array.


&array[0] is same as array.
Accessing Array Elements
• We can access the elements of an array using index.

• Using index we can access or alter/change each and every


individual element present in the array separately.
• Index value starts at 0 and end at n-1 where n is the size of an
array.
Write a program to read and display an array of size n.

#include<stdio.h>
void main()
{
int n,A[20],i;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}
for(i=0;i<n;i++)
{
printf("%d\t",A[i]);
}
}
Write a program to read and display an array of size n in reverse order.

#include<stdio.h>
void main()
{
int n,A[20],i;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}
for(i=n-1;i>=0;i--)
{
printf("%d\t",A[i]);
}
}
1) Increment every element by 1.
2) Linear Search.
3) Bubble sort.
4) Exchange sort
5) Selection sort
6) Decimal number to Binary number
7) Binary search
Write a program to read and display even numbers in an array of size n.

#include<stdio.h>
void main()
{
int n,A[20],i;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}
for(i=0;i<n;i++)
{
if(A[i]%2 == 0)
{
printf("%d\t",A[i]);
}
}
}
Write a program to find largest element in array of size n.

#include<stdio.h>
void main()
{
int n,A[20],i,large;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}

large=A[0];
for(i=0;i<n;i++)
{
if(large < A[i])
{
large = A[i]
}
}
printf("Large =%d",large);
}
Deleting an element from array

To delete an element at index k, shift all elements from k+1, one position
to left

i = k;

while(i<n-1)
{

array[i] = array [i+1];

i++;

}

n=n-1;
Inserting an element to array

To insert an element at index k, shift all elements from position k, one
position to right.

i = n;

while(i>k)

{

array[i] = array [i-1];

i--;

}

array[k]=value;

n=n+1;
Two Dimensional Arrays 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.

• We can access the record using both the row index and column
index.
Two Dimensional Arrays in C

Two dimensional array is a table of rows and columns.

Syntax of array definition of a 2-D array is :
data_type array_name[No.of rows][No.of columns];

Normarlly No.of rows and No.of columns are expressed as unsigned integers.
0 1 2 3 Column no
0 3 6 1 7
Examples :-
1 5 4 2
int a[3][4]; 1
2 6 10 17 0 a[1][2]

Row No
An element is accessed by

array_name[row_no][col_no]
Two Dimensional Arrays in C

int A[10][10];


Data type of A[i][j] is int.

A[i][j] is treated as a simple variable.

So it can be used in printf(), scanf() or in an expression.

A[2][1]=10; A[0][0]=20;
A[0][2]=A[1][2]+A[1][1];
scanf(“%d”, &A[1][2]); printf(“%d”,A[0][2]);
Two Dimensional Arrays in C
main()
{ int a[10][10], n, i;

scanf(“%d%d”,&m,&n);

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


for (j=0; j<n; j++) // Reading elements
scanf(“%d”,&a[i][j]);

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


{ for (j=0; j<n; j++) // Displaying elements
printf(“%d ”,a[i][j]); // in matrix form
printf(“\n”);
}
}
• Initializing a Two Dimensional Array

First Approach

int Emp[4][3] = {10,20,30,40,50,60,70,80,90,100,110,120};

int Emp[4][3] = {{10,20,30},{40,50,60},{70,80,90},{100,110,120}};

Second Approach

int Emp[][] = {{10,20,30},{40,50,60},{70,80,90},{100,110,120}};

Third Approach

int Emp[4][3] = {{30},{40,50}};

Fourth Approach
int rows,columns,Emp[4][3];
for(rows=0;rows<4;rows++)
{
for(columns=0;columns<3;columns++)
{
Emp[rows][columns]=rows+columns;
}
}
Write a program to read a matrix
of size mXn and display it
for(i=0;i<m;i++) // Row
{ for(j=0;j<n;j++) //Column
{
scanf("%d",&A[i][j]);
}
}
for(i=0;i<m;i++) // Row 2 3 4
{
for(j=0;j<n;j++) //Column 6 5 8
{
printf("%d",A[i][j]);
}
printf(“\n”);
}
1) Find the largest element in a mxn matrix. Also display its position.
2) Find the sum of the diagonal elements of a square matrix.
3) Display the prime numbers is a matrix
4) Display the fibonacci numbers is a matrix
5) Find the sum of two mxn matrices.
6) Matrix multiplication
7) Sum of each rows and columns of a matrix.
8) Display the palindrome numbers in a matrix.
9) Display the sum of the boundary elements in a matrix.
10) Find the transpose of a matrix.
11) Check whether a square matrix is symmetric.
• Program to find transpose of a Matrix

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


{
for (int j = 0; j < c; ++j)
{
t[j][i] = a[i][j];
}
}
STRINGS
Strings in C

• String is stored in an array of characters.

• Each character in the string is stored in one position in the array,


starting at position 0.

• Strings are actually one-dimensional array of characters


terminated by a null character '\0'.

• This is done so that programs can tell when the end of a string has
been reached.

• For example,
• char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Strings in C
• If you follow the rule of array initialization then you can
write the previous statement as follows −
• char str[] = "Hello";
Declaration of String
• String can be declared in the same way we declare an array.

• We just need to use char data type followed by string name and its
size.

• Syntax:

char String_Name [String_Size];

• String_Name: specify the name of a string.

• String_Size: Number of characters required for this string plus one (\0)
Initialization of String

• There are multiple ways to initialize string

• Declare C String without size

char str[ ] = “CET Trivandrum”;

• Declare String with Size

char str[50] = “CET Trivandrum”;

• Declare String of characters

char str[ ] = {‘T’,’r’,’i’,’v’,’a’,’n’,’d’,’r’,’u’,’m’,’\0’};

char str[11] = {‘T’,’r’,’i’,’v’,’a’,’n’,’d’,’r’,’u’,’m’,’\0’};


String variable definition with initialization

char s1[ ] = ”abc”;


char s2[ ] = {‘x’, ‘y’, ‘z’}; // null char is not stored.
sizeof(s1) -> 4
sizeof(s2) -> 3

char name[30];
name = “Mahatma Gandhi”;
/* Error. Array name is a constant pointer.
A constant can not be used on the LHS of
assignment expression */
Reading/Displaying Strings

scanf() :
char name[30];
scanf (“%s”, name); // note that no & before name.
Reads upto the first white space character (space, tab, newline)
Null character is stored as the end of the string.
If you are giving the input as GRACE HOPPER it will store only
GRACE

printf() :
printf() is used for displaying strings using %s
printf(“Name : %s\n“, name)
Reading/Displaying Strings

scanf() :
The follwing scanf() can be used for reading string containg
spaces.
scanf (“%[^\n]”, name); // note that no & before name.
Reads upto the newline character(\n)
Newline character is not stored in string.
Null character is stored as the end of the string.

printf() :
printf(“Name : %s\n“, name)
Reading/Displaying Strings
gets() :

Usage is

gets(string_var);

Reads upto the newline character(\n), skips the newline
character.

The gets() allows the user to enter the space-separated
strings

Newline character is not stored in string.

Null character is stored as the end of the string.
puts() :

Usage is

puts(string_item);

puts() displays a newline after the string_item.
• Example program
 #include<stdio.h>

int main()

{
 char str[50]="An Engineering Student";
 int x=0;

while(str[x]!='\0')

{

printf("%c",str[x]);

x++;

}
 return 0;
 }
String Handling Functions
• With every C compiler a large set of useful string handling library
functions are provided.

• Some of the most commonly used functions are:

strlen()

strcpy()

strcat()

strcmp()

• The header file that we will use for these functions is string.h
strlen() function

• The strlen() function returns the length of the given


string.

• It doesn't count null character '\0'.

• By using this function we can calculate the number of


characters in any string.

Syntax

strlen(string_name)
strlen() function
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
int l;
printf("Enter a string: ");
scanf("%s",str);
l=strlen(str);
printf("Length of the entered string is %d",l);
return 0;
}
strcpy() function

• The strcpy() function is used to copy contents of one


string to another.

• The strcpy(destination, source) function copies the


source string in destination.
strcpy() function
#include<stdio.h>
#include<string.h>
int main()
{
char str1[50], str2[50], str3[50];
printf("Enter a string: ");
scanf("%s",str1);
strcpy(str2,str1);
strcpy(str3,"World");
printf("Copied string to str2 is %s",str2);
printf("\nCopied string to str3 is %s",str3);
return 0;
}
strcat() function

• This string function is used to concatenate / combine


two strings.

• The strcat(first_string, second_string) function


concatenates two strings and result is returned to
first_string.
strcat() function
#include<stdio.h>
#include<string.h>
int main()
{
char str1[50], str2[50];
printf("Enter first string: ");
scanf("%s",str1);
printf("Enter second string: ");
scanf("%s",str2);
strcat(str1,str2);
printf("The concatenated string is %s",str1);
return 0;
}
strcmp() function

• This string function strcmp(first_string, second_string) compares two string


and returns 0 if both strings are equal.

• The two strings are compared character by character until there is a


mismatch or end of one string is reached.

• If the two strings are identical, strcmp( ) returns a value zero.

• If they are not, it returns the numerical difference between the ASCII values
of the first non-matching pairs of characters.

• The return value is less than 0 if first_string compares less than


second_string , and greater than 0 if first_string compares greater than
second_string.
strcmp() function
#include<stdio.h>
#include<string.h>
int main()
{
char str1[50], str2[50];
int result;
printf("Enter first string: ");
scanf("%s",str1);
printf("Enter second string: ");
scanf("%s",str2);
result=strcmp(str1,str2);
printf("The result of the comparison is %d", result);
if(result==0)
{
printf("\nTwo strings are same");
}
else
{
printf("\nTwo strings are different");
}
return 0;
}
String Comparison
• i=0;
• while(str1[i] ==str2[i] && str1[i]!=’\0’ &&str2[i]!= ‘\0’)

{
• i=i+1;

}
• if(str1[i] ==’\0’ && str2[i] ==’\0’)
• printf(“Strings are equal\n”);
• else
• printf(“strings are not equal\n”);
some important string functions defined in
"string.h" library.
No. Function Description

1) strlen(string_name) returns the length of string name.


2) strcpy(destination, source) copies the contents of source string to destination
string.
3) strcat(first_string, second_strin concats or joins first string with second string. The
g) result of the string is stored in first string.
4) strcmp(first_string, second_stri compares the first string with second string. If
ng) both strings are same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.
1. Read a string (word), store it in an array and check
whether it is a palindrome or not.
2. Read two strings, store them in arrays and
concatenate them without using library functions.
3. Read a string, store it in an array and count the
number of vowels, consonants and spaces in it.
Table of strings

We often use a list of character strings, such as a list of
the names of students in a class, list of employees in an
organization etc.

A list of names can be treated as a table of strings and a
two dimensional character array can be used to store
the entire list.

For example a character array student[30][15] may be
used to store a list of 30 names, each of length not
more than 15 characters.
Table of strings


For example a character array cities[4][10] may be used
to store a list of 4 cities, each of length not more than
10 characters.
Sort a list of names in alphabetical order
for (i=0; i < N-1 ; i++) {

for (j=0; j< N-i-1; j++) {

if(strcmp(name[j],name[j+1]) > 0) {

strcpy(temp,name[j]);

strcpy(name[j],name[j+1]);

strcpy(name[j+1],temp);

You might also like