CP Unit 3
CP Unit 3
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];
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.
C Programming Notes Page 1
Unit - V
Initialization of one-dimensional arrays:
We can initialize the elements of the one-dimensional array when the array is
declared.
The general form is
int a[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 follows.
10 20 30 40 50 60
a[0] a[1] a[2] a[3] a[4] a[5]
Note: when the array is completely initialized, there is no need to specify the size of the
array.
Ex: The statement
int a[ ]={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
a[0] a[1] a[2] a[3] a[4] a[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 a[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
a[0] a[1] a[2] a[3] a[4] a[5]
C Programming Notes Page 2
Unit - V
Inputting Values from the Keyboard / Dynamic initialization of array:
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”,&a[i]);
stores 6 values in to the array.Here index i varies from 0 to 5.
Ex program:
/*program to read 10 values into one dimensional array using keyboard and printing them*/
#include<stdio.h>
main( )
{
int i,a[10];
printf(“enter the elements of the array\n”);
for(i=0;i<10;i++)
scanf(“%d”,&a[i]);
printf(“the elements of the array are \n”);
for(i=0;i<10;i++)
printf(“%d ”,a[i]);
}
Assigning Values:
We can assign values to individual elements using the assignment operator. For example,
simple assignment statement
a[0]=100;
assigns 100 to a[0].
/*program to find maximum and minimum element from the list of elements*/
#include<stdio.h>
void main( )
{
int
i,n,max,min,a[50];
printf(“enter the total number of elements of the array\n”)
scanf(“%d”,&n);
C Programming Notes Page 3
Unit - V
printf(“enter the elements of the array\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“the elements of the array are \n”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
max=min=x[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf(“maximum element =%d\n”,max);
printf(“minimum element =%d\n”,min);
}
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.
C Programming Notes Page 4
Unit - V
Memory gets allocated to store the array marks as follows.
Column index
0 1 2
0 Row index Marks[0][0] Marks[0][1] Marks[0][2]
1
2 Marks[1][0] Marks[1][1] Marks[1][2]
Marks[2][0] Marks[2][1] Marks[2][2]
We can initialize the elements of the two-dimensional array when the array is
declared.
The general form is
Datatype array-name[rowsize][colsize]= {list of values};
The values in the list are separated by commas.
Ex: The statement
int a[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 follows.
Column index
0 1 2
Row index
0 10 20 30
1 40 50 60
we can also initialize a two dimensional array as follows.
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.
C Programming Notes Page 5
Unit - V
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”,&a[i][j]);
stores 6 values in to the array integer array a[ ].Here index i varies from 0 to 5.
/* c program to find addition of two matrices */
#include<stdio.h>
main()
{
int A[10][10],B[10][10],C[10][10],m,n,p,q,i,j;
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]);
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");
}
Page 7
C Programming Language Unit – III
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 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];
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
Page 8
C Programming Language Unit – III
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];
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 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;
printf("enter the string to be read into str2 \n"); ch=getchar(
);
while(ch!=’\n’)
{
str2[i]=ch;
ch=getchar( ); i++;
}
str2[i]=’\0’;
printf("the string entered is\n");
Page 9
C Programming Language Unit – III
for(i=0;str2[i]!=’\0’;i++)
putchar(str2[i]);
}
Example program:
Page 10
C Programming Language Unit – III
/* program to find the length of the string without using strlen() function. */
#include<stdio.h>
void main()
{
char str[100];
int len;
/// read the string
printf("Enter a string : ");
scanf("%s",&str);
///find the length
for( len=0;str[len]!='\0';len++);
printf("Length=%d",len);
}
Output :
Enter a string : ramana
Length=6
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”.
#include <stdio.h>
#include <string.h>
void main()
{
char str1[100],str2[100];
printf("Enter a string : ");
scanf("%s",&str1);
strcpy(str2,str1);
printf("String 1=%s",str1);
printf("\nString 2=%s",str2);
}
output :
Page 11
C Programming Language Unit – III
Enter a string : india
String 1=india
String 2=india
Example program:
Page 12
C Programming Language Unit – III
Page 14
C Programming Language Unit – III
#include<stdio.h>
void main()
{
char str[100],rev[100];
int i,j,len,flag=1;
/// read a string
printf("Enter a string : ");
scanf("%s",&str);
///reverse the string
for( len=0;str[len]!='\0';len++);
for(i=0,j=len-1;str[i]!='\0';i++,j--)
rev[j]=str[i];
rev[len]='\0';
for(i=0;str[i]!='\0';i++)
if( str[i] != rev[i] )
flag=0;
if( flag==1 )
printf("Palindrome");
else
printf("Not a palindrome");
}
Output1 :
Enter a string : dad
Palindrome
Output2:
Enter a string : nrt
Not a palindrome
3. WAP to read a string, convert it to upper case.
#include<stdio.h>
void main()
{
char str[100];
int i;
printf("Enter a string : ");
scanf("%s",&str);
for( i=0;str[i]!='\0';i++)
{
if( str[i]>='a' && str[i]<='z' )
str[i]=str[i]-32;
}
printf("result=%s",str);
}
Output1 :
Page 15
C Programming Language Unit – III
Enter a string : RAmana
result=RAMANA
4. WAP to read a string. convert it to lower case.
#include<stdio.h>
void main()
{
char str[100];
int i;
printf("Enter a string : ");
scanf("%s",&str);
for( i=0;str[i]!='\0';i++)
{
if( str[i]>='A' && str[i]<='Z' )
str[i]=str[i]+32;
}
printf("result=%s",str);
}
Output1 :
Enter a string : RAmana
result=ramana
5. WAP to read a string. Count the alphabets, vowels, consonants, spaces, digits, symbol.
#include<stdio.h>
void main()
{
char str[100];
int ac=0,vc=0,cc=0,sc=0,dc=0,ssc=0,i;
printf("Enter a string : ");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if( (str[i]>='A'&&str[i]<='Z') || (str[i]>='a'&&str[i]<='z'))
{
ac++;
if( str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'|| str[i]=='A'|| str[i]=='E'||
str[i]=='I'||str[i]=='O'||str[i]=='U')
vc++;
else
cc++;
}
else if( str[i]==' ')
sc++;
else if( str[i]>='0'&&str[i]<='9')
Page 16
C Programming Language Unit – III
dc++;
else
ssc++;
}
printf("Alphabets count=%d",ac);
printf("\nVowels count=%d",vc);
printf("\nConsonants count=%d",cc);
printf("\nDigits count=%d",dc);
printf("\nSpaces=%d",sc);
printf("\nSymbols=%d",ssc);
}
Output :
Enter a string : rama,raman are brothers. rama got 80%. raman got 75%.
Alphabets count=35
Vowels count=14
Consonants count=21
Digits count=4
Spaces=8
Symbols=6
Page 17