C Program Unit3

You might also like

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

MIRMADAN MOHANLAL GOVT.

POLYTECHNIC
Gobindapur ,plassey,west Bengal,741156

DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

2nd YEAR-3rd SEMESTER

E-CONTENTS:-C PROGRAMMING

UNIT 3:ARRAYS AND STRINGS

Developed By

SAHNOAJ AHMED ,LECTURER IN CST

COMPUTER SCIENCE & TECHNOLOGY

MIRMADAN MOHANLAL GOVT. POLYTECHNIC

Gobindapur ,plassey,west Bengal,741156


contents
3.1 .1. array definition and it’s advantages 1

3.1.2. Declaration and initialization of array 1

3.1.3. accessing 1-dimensioal array 3

3.1.4.declare and initialize 2D arrays 7

3.1.5.Accessing 2-D array elements 8

3.2.1 declaration and initialization of Strings 12

3.2.2 String functions with example 13

3.2.3. program to extract substring from string 16


3.2.4. Replacement of string characters 17

3.2.5.concatenation of two strings 18


3.1 .1. array definition and it’s advantages

Array:-An array is defined as an ordered set of similar data items. The elements of an array are
of same data type and each item can be accessed using the same name. All the data items of an
array are stored in consecutive memory locations

Advantages of Arrays

1.Arrays represent multiple data items of the same type using a single name.

2.In arrays, the elements can be accessed randomly by using the index number.

3.Arrays allocate memory in contiguous memory locations for all its elements. Hence there is
no chance of extra memory being allocated in case of arrays. This avoids memory overflow or
shortage of memory in arrays.

3.1.2 Declaration and initialization of array:-

Declaratioin of array :-an array must be declared before it is used. During declaration, the size
of the array has to be specified. The size used during declaration of the array informs the
compiler to allocate and reserve the specified memory locations.

Syntax:-data_type array_name[n]; where, n is the number of data items (or) index(or)


dimension. 0 to (n-1) is the range of array.

Example: int arr[5]; float arr[10];

Initialization of Arrays:-The different types of initializing arrays:


1. during Compile time
(a) Initializing all specified memory locations.
(b) Partial array initialization
(c) Initialization without size.
(d) String initialization.
2. during Run Time

1. Compile Time Initialization

We can initialize the elements of arrays in the same way as the ordinary variables when they
are declared. The general form of initialization of arrays is

type array-name[size]={ list of values};

1|P ag e
(a) Initializing all specified memory locations:-Arrays can be initialized at the time of declaration
when their initial values are known in advance. Array elements can be initialized with type int,
char etc.

Ex:-int arr[5]={10,15,5,20,30};

During compilation, 5 contiguous memory locations are reserved by the compiler for the
variable arr and all these locations are initialized as shown in figure.

(b) Partial array initialization:-. If the number of values to be initialized is less than the size of
the array, then the elements will be initialized to zero automatically.

Ex:-int arr[5]={10,15};

Even though compiler allocates 5 memory locations, using this declaration statement; the
compiler initializes first two locations with 10 and 15, the next set of memory locations are
automatically initialized to 0's by compiler.

Fig: Partial Array Initialization

(c) Initialization without size:-Consider the declaration along with the initialization.

Ex:- char b[]={'C','O','M','P','U','T','E','R'};

In this declaration, eventhough we have not specified exact number of elements to be used in
array b, the array size will be set of the total number of initial values specified. So, the array size
will be set to 8 automatically. The array b is initialized as shown in figure

Fig: Initialization without size

2|P ag e
(d) Array initialization with a string: -Consider the declaration with string initialization.

Ex:- char str[]="COMPUTER"; The array str is initialized as shown in figure

Fig: Array Initialized with a String Even though the string "COMPUTER" contains 8 characters,
because it is a string, it always ends with null character(\0). So, the array size is 9 bytes i.e.,
string length 1 byte for null character(\0).

2. Run Time Initialization


An array can be explicitly initialized at run time. This approach is usually applied for initializing
large arrays.

Ex:-scanf can be used to initialize an array.

for(i=0;i<100;i=i+1)

{ if(i<50)

sum[i]=0;

else

sum[i]=1; }

The first 50 elements of the array sum are initialized to 0 while the remaining 50 are initialized
to 1 at run time.

3.1.3. accessing 1-dimensioal array

access element of 1-D array

#include<stdio.h>

int main() {

int i, arr[50], num;

printf("\nEnter no of elements :");

scanf("%d", &num);

3|P ag e
printf("\nEnter the values :");

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

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

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

printf("\narr[%d] = %d", i, arr[i]);

return (0);

Insert element in 1-D array

#include<stdio.h>

#include<conio.h>

int main()

int arr[30], element, num, i, location;

printf("\nEnter no of elements :");

scanf("%d", &num);

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

printf("enter elements");

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

printf("\nEnter the element to be inserted :");

4|P ag e
scanf("%d", &element);

printf("\nEnter the location");

scanf("%d", &location);

for (i = num; i >= location; i--)

arr[i] = arr[i - 1];

num++;

arr[location - 1] = element;

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

printf(" %d", arr[i]);

return 0;

getch();

Output of program
Enter no of elements :4
enter elements 10
enter elements 20
enter elements 40
enter elements 50
Enter the element to be inserted 30

5|P ag e
Enter the location 3
10 20 30 40 50

Deletion element from array

#include<stdio.h>

#include<conio.h>

int main()

int arr[30], num, i, loc;

printf("\nEnter no of elements :");

scanf("%d", &num);

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

printf("\nEnter elements :");

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

printf("\n location of element to be deleted :");

scanf("%d", &loc);

while (loc<num)

arr[loc - 1] = arr[loc];

loc++;

num--;

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

printf("\n %d", arr[i]);

6|P ag e
return 0;

getch();

Output of program
Enter no of elements:4
Enter elements: 10
Enter elements: 20
Enter elements: 30
Enter elements: 40
location of element to be deleted: 3
10 20 40

3.1.4.declare and initialize 2D arrays

In two dimensional arrays the array is divided into rows and columns. These are well suited to
handle a table of data. In 2-D array we can declare an array as :

Declaration two-dimensional arrays:-


Syntax: data_type array_name[row_size][column_size];

Example:-int arr[3][3];

where first index value shows the number of the rows and second index value shows the
number of the columns in the array.

Initializing two-dimensional arrays: Like the one-dimensional arrays, two-dimensional arrays


may be initialized by following their declaration with a list of initial values enclosed in braces.

Example: int arr[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the
second row to one. The initialization is done row by row.

The above statement can also be written as int arr[2][3] = {{ 0,0,0},{1,1,1}};

Example:

int a[3][3] = {

{1, 2, 3},

7|P ag e
{4, 5, 6},

{7, 8, 9} };

The above mentioned 2-D array elements can be organized in the following manner

3.1.5.Accessing 2-D array elements

#include<stdio.h>
#include<conio.h>
int main(){

int a[3][3];

int i, j;
for(i=0; i<3; i++)
{
for(j=0;j<3;j++)
{
printf("Enter value for a[%d][%d]:", i, j);
scanf("%d",&a[i][j]);
}
}

printf("Two Dimensional array elements:\n");


for(i=0; i<3; i++)
{
printf("\n");
for(j=0;j<3;j++)
{

8|P ag e
printf("%d\t",a[i][j]);

}
}
getch();
return 0;
}

Output of program

Enter value for a[0][0]:1


Enter value for a[0][1]:2
Enter value for a[0][2]:3
Enter value for a[1][0]:4
Enter value for a[1][1]:5
Enter value for a[1][2]:6
Enter value for a[2][0]:7
Enter value for a[2][1]:8
Enter value for a[2][2]:9
1 2 3
4 5 6
7 8 9

C program to multiply two matrices

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

int main()

int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;

system("cls");

printf("enter number of row");

scanf("%d",&r);

printf("enter number of column");

scanf("%d",&c);

9|P ag e
printf("enter first matrix element\n");

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

for(j=0;j<c;j++)

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

printf("enter 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];

10 | P a g e
}

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

for(j=0;j<c;j++)

printf("%d\t",mul[i][j]);

printf("\n");

getch();

return 0;

Output of program
enter number of row 3
enter number of column 3
enter first matrix element
111
222
333
enter second matrix element
111
222
333
multiply of the matrix
6 6 6
12 12 12
18 18 18

11 | P a g e
3.2.1 declaration and initialization of Strings:-

In C language a string is group of characters (or) array of characters, which is terminated by


delimiter \0 (null). hence C uses variable-length delimited strings in programs.

Declaring Strings:- C does not support string as a data type. It allows us to represent strings as
character arrays. In C, a string variable is any valid C variable name and is always declared as an
array of characters.

Syntax:-char string_name[size]; The size determines the number of characters in the string
name

Example:-char city[10]; char name[30];

Initializing strings:- There are several methods to initialize values for string variables

Example:- char city[8]=”NEWYORK”;

char city[8]={“N”,”E”,”W”,”Y”,”O”,”R”,”K”,”\0”};

The string city size is 8 but it contains 7 characters and one character space is for NULL
terminator(\0)

12 | P a g e
Storing strings in memory:-

In C a string is stored in an array of characters and terminated by \0 (null).

A string is stored in array. The character requires only one memory location. If we use one-
character string it requires two locations.

The difference between array and string is shown below

3.2.2 String functions


 strlen() function
 strcpy() function
 strcat() function
 strcmp()function

strlen( ) :This function is used to find the length of the string excluding the NULL character. Its
syntax is as follows: Int strlen(string);

int main()

char str[20]="Programming";int len;

len=strlen(str);

printf("Length of string str = %d \n",len);

getch();

return 0;

13 | P a g e
}

Output of program

Length of string str =11

strcpy( ): This function is used to copy one string to the other. Its syntax is as follows

strcpy(string2,string1);

This function copies the content of string1 to string2

int main() {

char str1[20] = "programming";

char str2[20];

// copying str1 to str2

strcpy(str2, str1);

puts(str2);

return 0;

output of program

programming

strcat ( ) This function is used to concatenate two strings. i.e., it appends one string at the end
of the specified string.

Its syntax as follows: strcat(string1,string2);

int main()

char str1[100] = "This is ", str2[] = "c program";

// concatenates str1 and str2

// resultant string is stored in str1.

14 | P a g e
strcat(str1, str2);

puts(str1);

return 0;

output of program

This is c program

strcmp ( ) :This function compares two strings character by character (ASCII comparison)

• if both strings are identical (equal) return value is zero.

• if the ASCII value of the first unmatched character is less than the second then return
value is negative.

• if the ASCII value of the first unmatched character is greater than the second then
return value is positive.

Its syntax is as follows: Int strcmp(string1,string2);

int main()

char str1[] = "abcde", str2[] = "abCde";

int result;

result = strcmp(str1, str2);

printf("strcmp(str1, str2) = %d\n", result);

getch();

return 0;

Output of program

Strcmp(str1,str2)=32

N.B.-The ASCII value of 'c' is 99 and the ASCII value of 'C' is 67.hence the return value is 32

15 | P a g e
3.2.3. program to extract substring from string
#include <stdio.h>

#include<string.h>

#include<conio.h>

int main()

char str[100], substr[100];

int position, length, ch = 0;

printf("Input a string\n");

gets(str);

printf("Enter position and length of substring\n");

scanf("%d%d", &position, &length);

while (ch < length) {

substr[ch] = str[position+ch-1];

ch++;

substr[ch] = '\0';

printf("Required substring is \"%s\"\n",substr);

return 0;

getch();

Output of program
Enter a string
C programming
Enter position and length of substring
3
7
Required substring is “program”

16 | P a g e
3.2.4. Replacement of string characters
#include <stdio.h>

#include <string.h>

#include<conio.h>

int main()

char str[100],ch,nch;

int i;

printf("Enter the string : ");

gets(str);

printf("Enter character to replace ");

ch=getchar();

getchar();

printf("\nEnter character to replace with ");

nch=getchar();

printf("\n before replace:%s",str);

for(i=0;i<=strlen(str);i++)

if(str[i]==ch)

str[i]=nch;

printf("\nafter replace:%s",str);

getch();

return 0;

17 | P a g e
}

Output of program
Enter the string : hello

Enter character to replace:l

Enter character to replace with:x

before replace:hello

nafter replace:hexxo

3.2.5.concatenate two strings without strcat()

#include <stdio.h>

#include<string.h>

#include<conio.h>

int main()

char str1[50], str2[20], i, j;

printf("\nEnter first string: ");

scanf("%s",str1);

printf("\nEnter second string: ");

scanf("%s",str2);

for(i=0; str1[i]!='\0'; i++);

for(j=0; str2[j]!='\0'; j++, i++)

str1[i]=str2[j];

18 | P a g e
str1[i]='\0';

printf("\nOutput: %s",str1);

return 0;

getch();

Output of program

Enter first string: hello

Enter second string: world

Output: helloworld

19 | P a g e

You might also like