0% found this document useful (0 votes)
13 views33 pages

CP Unit V-2

The document provides a comprehensive overview of arrays in C programming, including one-dimensional and two-dimensional arrays, their declaration, initialization, and methods for accessing and storing values. It also covers multidimensional arrays and strings, explaining how strings are represented as character arrays and how to input and output string data. Example programs illustrate the practical application of these concepts.

Uploaded by

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

CP Unit V-2

The document provides a comprehensive overview of arrays in C programming, including one-dimensional and two-dimensional arrays, their declaration, initialization, and methods for accessing and storing values. It also covers multidimensional arrays and strings, explaining how strings are represented as character arrays and how to input and output string data. Example programs illustrate the practical application of these concepts.

Uploaded by

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

Unit - V

Arrays:

An array is defined as collection of logically related data items of the same data type,
stored in contiguous memory locations, sharing a common name.

Each element of the array can be referred by using a value called index (or) subscript in
brackets after the array name. The index must be an integral value or an expression that evaluates
to an integral value.

Depending on the number of subscripts used, arrays can be categorized into one-
dimensional arrays, two-dimensional arrays and so on.

One-dimensional arrays:

An array with only one subscript is called as one-dimensional array (or) 1-d array. It is
used to store a list of values, all of which share a common name.

Declaration of one-dimensional arrays:

Arrays must be declared before they are used. Array declaration tells the compiler the
name of the array, type of each element, and the size (or) number of elements in the array. The
general form of declaring a one-dimensional array is

datatype array-name[size];

The type specifies any valid data type supported by C such as int, float or char, array-
name is any valid C identifier, size indicates the maximum number of elements that can be stored
in an array.

Ex: 1.The statement

int score[9];

declares score is an array containing maximum of 9 integer elements.

2.The statement

float height[50];

declares height is an array containing maximum of 50 real elements.


C Programming Notes Page 1
Unit - V
Accessing elements in one-dimensional Arrays:

Each element of the array can be referred by using a value called index (or) subscript in
brackets after the array name. The index must be an integral value or an expression that evaluates
to an integral value. The subscript value is indexed from 0 to size-1.when the subscript value is
0, first element in the array is selected, when the subscript value is 1, second element is selected
and so on.

Storing values in one-dimensional sarrays:

Declaration and definition only reserve space for the elements in the array. No values are
stored. If we want to store values in the array, we must either initialize the elements, read values
from the keyboard (or) assign values to each individual element.

Initialization of one-dimensional arrays:

We can initialize the elements of the one-dimensional array when the array is declared.
The general form is

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

The values in the list are separated by commas.

Ex: The statement

int x[6]={10,20,30,40,50,60};

declares that x is an array containing 6 integer elements whose values are given in the list which
are as follws.

10 20 30 40 50 60
x[0] x[1] x[2] x[3] x[4] x[5]

Note: when the array is completely initialized, there is no need to specify the size of the array.

C Programming Notes Page 2


Unit - V
Ex: The statement

int x[ ]={3,6,9,10,11,12};

declares that x is an array containing 6 integer elements whose initial values are given in the list
which are as follows. since the number of values in the list for the array x is six, the size of x is
automatically supplied as six.

3 6 9 10 11 12
x[0] x[1] x[2] x[3] x[4] x[5]

Note: If the number of elements in the list is less than the size of the array, then only that many
elements will be initialized. The remaining elements will be set to zero automatically.

Ex: The statement

int x[6]={3,6,9,10};

will initialize the first four elements to 3,6,9 and 10 and the remaining elements two elements are
set to zero.

3 6 9 10 0 0
x[0] x[1] x[2] x[3] x[4] x[5]

Inputting Values from the Keyboard:

We can store the values in to the array from the keyboard. This can be done
using a loop in which the index can be varied as shown below. For example, the statement

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

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

stores 6 values in to the array integer array x[ ].Here index i varies from 0 to 5.

C Programming Notes Page 3


Unit - V
Ex program:

/*program to read 10 values into one dimensional array using keyboard and printing them*/

#include<stdio.h>

#include<conio.h>

main( )
{
int i,x[10];
clrscr( );
printf(“enter the elements of the array\n”);
for(i=0;i<10;i++)
scanf(“%d”,&x[i]);
printf(“the elements of the array are \n”);
for(i=0;i<10;i++)
printf(“%d\t”,x[i]);
}
Assigning Values:

We can assign values to individual elements using the assignment operator. For example, simple
assignment statement

x[0]=100;

assigns 100 to x[0].

Similarly the statement

number[0]=35;

assigns 35 to number[0].

Similarly we can write number[2]=number[0]+number[1];

Note: one array cannot be copied to another using assignment statement.

C Programming Notes Page 4


Unit - V
Example program:

/*program to find maximum and minimum element from the list of elements*/
#include<stdio.h>
#include<conio.h>
main( )
{
int i,n,max,min,x[50];
clrscr( );
printf(“enter the total number of elements of the array\n”)
scanf(“%d”,&n);
printf(“enter the elements of the array\n”);
for(i=0;i<n;i++)
scanf(“%d”,&x[i]);
printf(“the elements of the array are \n”);
for(i=0;i<n;i++)
printf(“%d\t”,x[i]);
max=min=x[0];
for(i=0;i<n;i++)
{
if(max<x[i])
max=x[i];
if(min>x[i])
min=x[i];
}
printf(“maximum element =%d\n”,max);
printf(“minimum element =%d\n”,min);
}

C Programming Notes Page 5


Unit - V
Two Dimensional Arrays:

An array with two subscripts is called as two dimensional array. A two dimensional
array can be thought of as a group of one or more one-dimensional arrays all of which share a
common name and are separable by subscript values.

Declaration of Two-dimensional arrays:

Arrays must be declared before they are used. Array declaration tells the compiler the
name of the array, type of each element, and the size (or) number of elements in the array. The
general form of declaring a two-dimensional array is

type array-name[rowsize][colsize];

The type specifies any valid data type supported by C such as int, float or char, array-
name is any valid C identifier, rowsize indicates the number of rows and colsize indicates the
number of elements in each row.

Ex: 1.The statement

int marks[3][3];

declares marks is a two dimensional array containing 3 rows and each row contains maximum of
3 elements.

Accessing elements in Two-dimensional Arrays:

Each element of the two dimensional array can be referred by using two indexes (or)
subscripts in brackets after the array name. The first index and second index must be an integral
value or an expression that evaluates to an integral value. The first subscript value is indexed
from 0 to rowsize-1. The second subscript value is indexed from 0 to colsize-1.

Memory gets allocated to store the array marks as follows.

C Programming Notes Page 6


Unit - V

Column numbers
0 1 2
0 Marks[0][0] Marks[0][1] Marks[0][2]
numbers

1 Marks[1][0] Marks[1][1] Marks[1][2]


Row

2 Marks[2][0] Marks[2][1] Marks[2][2]

Storing values in two-dimensional sarrays:

Declaration and definition only reserve space for the elements in the array. No values are
stored. If we want to store values in the array, we must either initialize the elements, read values
from the keyboard (or) assign values to each individual element.

Initialization of two-dimensional arrays:

We can initialize the elements of the two-dimensional array when the array is declared.
The general form is

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

The values in the list are separated by commas.

Ex: The statement

int x[2][3]={10,20,30,40,50,60};

declares that x is a two dimensional array containing 2 rows, each row containing 3 elements
whose values are given in the list which are as follws.

Column numbers
0 1 2
0 10 20 30
numb
Row

ers

1 40 50 60

C Programming Notes Page 7


Unit - V
we can also initialize a two dimensional array as follows.

type array-name[rowsize][colsize]= {{list 1 of values},{list 2 of values}};

Ex: int x[2][3]={{10,20,30 },{40,50,60}};

we can also initialize a two dimensional array as follows

For ex, the statement int x[2][3]={

{10,20,30 },
{40,50,60}

};
Note: If the elements are missing in an initializing list they are automatically set to zero.for
example, the statement

int x[2][3]={

{10,20,},
{40}

};
Will initialize the first two elements of the first row to 10 and 20, the first element of the second
row to 40 and all other elements to zero.

Inputting Values from the Keyboard:

We can store the values in to the two dimensional array from the keyboard.
This can be done using two loops in which the two indexes can be varied as shown below. For
example, the statement

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

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

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

stores 6 values in to the array integer array x[ ].Here index i varies from 0 to 5.
C Programming Notes Page 8
Unit - V
/* c program to find addition of two matrices */

#include<stdio.h>

#include<conio.h>

main()

int m,n,p,q,i,j,A[10][10],B[10][10],C[10][10];

clrscr();

printf("enter no. of rows and columns of first matrix\n");

scanf("%d%d",&m,&n);

printf("enter no. of rows and columns of second matrix \n");

scanf("%d%d",&p,&q);

if((m==p)&&(n==q))

printf("matrix addition is possible\n");

printf("enter the elements of the first matrix\n");

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

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

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

C Programming Notes Page 9


Unit - V
printf("enter the elements of the second matrix \n");

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

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

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

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

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

C[i][j]=A[i][j]+B[i][j];

printf("the elements of the resultant matrix are \n");

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

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

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

printf("\n");

else

printf("matrix addition is not possible\n");

C Programming Notes Page 10


Unit - V
Multidimensional Arrays:

C allows arrays of three or more dimensions. The exact limit is determined by the compiler. The
general form of multidimensional array is

type array-name[s1][s2]………[sm];

where si is the size of the ith dimension.

Ex: The statement

int survey[3][5][2];

Declares that survey is a three dimensional array to contain 180 integer type elements.

C Programming Notes Page 11


Unit - V
Strings:
A string (or) string literal (or) string constant is any sequence of characters enclosed in
double quotes.

Ex:1. “this is c string”

2. “Hello World”

In C, a string is stored as an array of characters ended with NULL character (‘\0’). This null
character indicates the end of the string. All the strings in C are ended by this character. This
NULL character will be appended automatically at the end of string by the compiler.

If we can change the contents of an array of characters then that character array is called string
variable.

Declaration of String Variable:


A string variable is declared as follows.

char stringname[size];
Where stringname is any valid identifier and size indicates maximum number of characters that
can be stored in the array including the NULL character (\0)

Ex: char str1[8];


Here str1 is a string variable that can store maximum of 8 characters including the NULL
character(\0).

Initialization of string variable:


A string variable (or) character arrays can be initialized when they are declared. This can be done
in one of two ways.

1. char str1[12]= { ‘H’, ’e’, ’l’, ’l’, ’o’, ’ ‘, ‘w’, ’o’, ’r’, ’l’, ’d’, ’\0’};
The initialize list consists of comma separated character constants and we must explicitly
specify the NULL character.

2. char str1[12]={“Hello world”};


Here str1 is declared as a string variable of size 12. It can store maximum 12 characters including
the NULL character. The NULL character ‘\0’ will be automatically added to the end of the
string by the compiler.
C Programming Notes Page 12
Unit - V

The memory allocation is as follows.

Note:

1. C permits to initialize the character array without specifying the number of elements . In these
cases, the size of the array will be determined automatically based on the number of elements
initialized. For ex, the statement

char str1[ ] = {“Hello world”};


defines str1 as a 12 element array.

2. we can also declare the size much larger than the string size in the initialize list. For ex, the
statement

char str1[12 ] = {“Hello”}; is valid.


The memory allocation for the above will be as follows

char str1[12]= { ‘H’, ’e’, ’l’, ’l’, ’o’,’\0’, ’\0’, ’\0’, ’\0’, ’\0’};

String Input/Output:
a. using scanf( ) and printf( ):

scanf( ) is used to accept a string through standard input keyboard


with %s format specification.

Ex: char str[10]; /* declaration of a string*/

scanf(“%s”, str); /* reading the string in to str using keyboard*/

The above statement accepts a string into str up to a white space character.
The NULL character will be automatically appended to the string and therefore the
size of the character array should be large enough to hold the input string plus the

C Programming Notes Page 13


Unit - V
NULL character. In case of character arrays for scanf( ) calls, the ampersand(&) is
not required before the variable name.

The printf( ) function is used to display the strings on the screen with %s
format specification. For ex, the statement

printf(“%s”,str);

Will display the contents of string str on to the screen.

/* program to illustrate string initialization, reading and display the string using
scanf( ) and printf( )*/

#include<stdio.h>

main()

char str1[12]="New york";

char str2[10];

clrscr( );

printf("enter the string to be read into str2\n");

scanf("%s",str2);

printf("str1= %s\n",str1);

printf("str2=%s\n",str2);

Output of the above program:

enter the string to be read into str2

hello world

str1= New york

str2=hello

C Programming Notes Page 14


Unit - V
b. gets( ) and puts( ) functions:

The function gets( ) is used to accept a string upto a new line


character into a string variable. It automatically appends the NULL character to the
end of the string

Ex: char str[80]; /* declaration of a string*/

gets(str); /* reading the string in to str using keyboard*/

The statement gets (str); accepts a string upto a new line character into str.

The function puts ( ) is used to display the string contained the string
variable. It also appends the new line character to the string automatically after the
string is displayed.

/* program to illustrate reading and display the string using gets( ) and puts( )*/

#include<stdio.h>
main()
{
char str2[10];
clrscr( );
printf("enter the string to be read into str2\n");
gets(str2);
printf("the string entered is\n");
puts(str2);
}
Output of the above program:

enter the string to be read into str2

hello

the string entered is

C Programming Notes Page 15


Unit - V
hello

c.getchar( ) and putchar( ) functions:

The function getchar( ) is used to read a character from the terminal. It


takes the following form
ch=getchar( );
where ch is a variable of char type. This can be repeatedly used to read
successive single characters from the terminal and place them into a
character array.
The function putchar( ) is used to display a character on the screen.
It takes the following form
putchar(ch);
Where ch represents a variable of type char or a character constant. It
displays the character stored in ch on the screen. This can be repeatedly
used to display a line of characters.
/* program to illustrate reading and display the string using getchar( ) and
putchar( )*/

#include<stdio.h>

main()

char str2[10],ch;

int i;

clrscr( );

printf("enter the string to be read into str2 \n");

ch=getchar( );

C Programming Notes Page 16


Unit - V
while(ch!=’\n’)

str2[i]=ch;

ch=getchar( );

i++;

str2[i]=’\0’;

printf("the string entered is\n");

for(i=0;str2[i]!=’\0’;i++)

putchar(str2[i]);

string handling functions:


String handling functions are helpful to perform various operations on
strings such as finding the length of the string, copying one string to another string,
reversing the string etc. The header file <string.h> contains these string handling
functions. Some of the commonly used string handling functions is give below

Function name Meaning


strlen( ) Finds the length of the string
strcpy( ) Copies one string to another string
strcmp( ) Compares the two strings
strcat( ) Concatenates the two strings

C Programming Notes Page 17


Unit - V
strlen( ) function:
the function strlen( ) is used to find the length of the given string. The
general form is
length= strlen(stringname);
where length is the variable of int data type which receives the value of
the length of the string.
Ex1: char str[80]= “pavan”;

length= strlen(str);

the above statement returns the length of string str as 5 and it is stored in variable
length.

Note:

The strlen( ) will not count the NULL character as a character of the string.

C Programming Notes Page 18


Unit - V
Example Program:

Output:

enter the string to be read into str


pavan
the length of the string pavan is 5

C Programming Notes Page 19


Unit - V
Example program:

Output:

enter the string to be read into str


pavan
the length of the string pavan is 5

C Programming Notes Page 20


Unit - V
strcpy( ) function:
The function strcpy( ) is used to copy the content of one string into another string.
the general form is

strcpy(str1,str2);

where str1 and str2 are string variables.

Here str2 is the source string and str1 is the destination string. After the execution
of the function, the contents of str2 are copied into str1 and finally both the str1
and str2 contains the same string values.

Ex:

char str1[80]=”good”;

char str2[80]=”night”;

strcpy(str1,str2);

After the execution of above statement, the content of str2 is copied into str1 and
finally both str1 and str2 contains the string “night”.

C Programming Notes Page 21


Unit - V

Output:

enter the string to be read into str1

good

enter the string to be read into str2

night

before copying str1=good and str2=night

After copying str1=night and str2=night

C Programming Notes Page 22


Unit - V
Example program:

Output:

enter the string to be read into str1

good

enter the string to be read into str2

night

before copying str1=good and str2=night

After copying str2 into str1,str1=night and str2=night

C Programming Notes Page 23


Unit - V
strcmp( ) function:
The strcmp( ) function compares two strings and has a value 0 if
they are equal. If they are not equal, it has the value equal to the numeric
difference between the first nonmatching characters in the strings. It
takes the following form
strcmp(string1,string2);
where string1 and string2 may be string variables or string constants.
Ex1:

char str1[80]=”RAM”;

char str2[80]=”RAM”;

strcmp(str1,str2);

the above statement returns 0 as a result because both str1 and str2 contain the
same characters.

Ex:2

char str1[80]=”RAM”;

char str2[80]=”ROM”;

strcmp(str1,str2);

the above statement returns -14 as a result, since ASCII difference between first
non matching characters A(ASCII value 65) and O(ASCII value79) is -14

Ex:3

char str1[80]=”ROM”;

char str2[80]=”RAM”;

strcmp(str1,str2);

the above statement returns 14 as a result, since ASCII difference between first non
matching characters O(ASCII value79) and A(ASCII value 65) is 14
C Programming Notes Page 24
Unit - V
Example program:

Output:

enter the string to be read into str1

ROM

enter the string to be read into str2

RAM

the difference between the string ROM and string RAM is 14

Example program:

C Programming Notes Page 25


Unit - V

Output:

enter the string to be read into str1

ROM

enter the string to be read into str2

RAM

the difference between the string ROM and string RAM is 14

C Programming Notes Page 26


Unit - V
strcat( ) function:
The function strcat( ) is used to join two strings. The general form is

strcat(str1,str2);

where str1and str2 are string variables. Here the content of str2 is appended (or)
joined to the contents of str1.

Ex:

char str1[80]=”good”;

char str2[80]=”night”;

strcat(str1,str2);

After the execution of the above statement, str1 contains “goodnight” and str2
contains “night”.

C Programming Notes Page 27


Unit - V
Example program:

Output:

enter the string to be read into str1

good

enter the string to be read into str2

night

before concatenation str1=good and str2=night

After concatenation str1=goodnight and str2=night

C Programming Notes Page 28


Unit - V
Example program:

Output:

enter the string to be read into str1

good

enter the string to be read into str2

night

before concatenation str1=good and str2=night

After concatenation str1=goodnight and str2=night


C Programming Notes Page 29
Unit - V
Additional Programs:

1. C Program to reverse given string without using strrev() functions.

#include<stdio.h>
#include<string.h>
void main()
{
char str[100], temp;
int i, j = 0;
clrscr();
printf("\nEnter the string :");
gets(str);
i = 0;
j = strlen(str) - 1;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
printf("\nReverse string is :%s", str);
getch();
}

C Programming Notes Page 30


Unit - V
2. C Program to check whether the given string is palindrome or not.

#include<stdio.h>
void main()
{
char str[100];
int i=0,j=-1,flag=0;
clrscr();
printf("Enter a string: ");
scanf("%s",str);
while(str[++j]!='\0');
j--;
while(i<j)
if(str[i++] != str[j--])
{
flag=1;
break;
}
if(flag == 0)
printf("The string is a palindrome");
else
printf("The string is not a palindrome");

getch();
}

C Programming Notes Page 31


Unit - V
3. C Program to count characters, words and lines from the text or in the
given string

#include <stdio.h>
void main()
{
char line[81], ctr;
int i, c,
end = 0,
characters = 0,
words = 0,
lines = 0;
clrscr();
printf(“KEY IN THE TEXT.\n”);
printf(“GIVE ONE SPACE AFTER EACH WORD.\n”);
printf(“WHEN COMPLETED, PRESS ‘RETURN’.\n\n”);
while( end == 0)
{
/* Reading a line of text */
c = 0;
while((ctr=getchar()) != ‘\n’)
line[c++] = ctr;
line[c] = ‘\0’;
/* counting the words in a line */
if(line[0] == ‘\0’)
break ;
else
{

C Programming Notes Page 32


Unit - V
words++;
for(i=0; line[i] !=’\0’;i++)
if(line[i] == ‘ ‘ || line[i] == ‘\t’)
words++;
}
/* counting lines and characters */
lines = lines +1;
characters = characters + strlen(line);
}
printf (“\n”);
printf(“Number of lines = %d\n”, lines);
printf(“Number of words = %d\n”, words);
printf(“Number of characters = %d\n”, characters);
}

C Programming Notes Page 33

You might also like