0% found this document useful (0 votes)
4 views17 pages

CP Unit 3

The document provides a comprehensive overview of arrays in C programming, detailing one-dimensional and two-dimensional arrays, their declaration, initialization, and methods for accessing and storing values. It also covers multidimensional arrays and strings, including their declaration, initialization, and input/output operations. Examples and explanations illustrate how to manipulate arrays and strings effectively in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

CP Unit 3

The document provides a comprehensive overview of arrays in C programming, detailing one-dimensional and two-dimensional arrays, their declaration, initialization, and methods for accessing and storing values. It also covers multidimensional arrays and strings, including their declaration, initialization, and input/output operations. Examples and explanations illustrate how to manipulate arrays and strings effectively in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

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.


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.
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

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


The values in the list are separated
by commas.
Ex: The statement

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].

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.
Example program:

/*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:

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.
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]

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 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
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.

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

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


we can also initialize a two dimensional array as follows For ex, the statement
int a[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 a[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.
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");
}

C Programming Notes Page 6


C Programming Language Unit – III
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 30 integer type elements.
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.
The memory allocation is as follows.

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]);
}

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
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.
Example Program to find length of string using strlen():
#include<stdio.h>
#include <string.h>
void main()
{
char str[100];
int len;
printf("Enter a string : ");
scanf("%s",&str);
len=strlen(str);
printf("Length=%d",len);
}
Output :
Enter a string : ramana
Length=6

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

/* program to copy a string into another string without using strcpy() */


#include <stdio.h>
void main()
{
char str1[100],str2[100];
int i;
printf("Enter a string : ");
scanf("%s",&str1);
for( i=0;str1[i]!='\0'; i++ )
str2[i]=str1[i];
str2[i]='\0';
printf("String 1=%s",str1);
printf("\nString 2=%s",str2);
}
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 non matching
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

Example program:
Page 12
C Programming Language Unit – III

/* program to compare two strings using strcmp() function */


#include <stdio.h>
#include <string.h>
void main()
{
char str1[100],str2[100];
printf("Enter 1st string : ");
scanf("%s",&str1);
printf("Enter 2nd string : ");
scanf("%s",&str2);
if( strcmp(str1,str2)==0 )
printf("Both the strings are equal");
else
printf("Both the strings are not equal");
}
output :
Enter 1st string : rama
Enter 2nd string : rama
Both the strings are equal
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”.
#include <stdio.h>
#include <string.h>
void main()
{
char str1[100],str2[100];
printf("Enter 1st string : ");
scanf("%s",&str1);
printf("Enter 2nd string : ");
scanf("%s",&str2);
strcat(str1,str2);
printf("String 1 after concatenation : %s",str1);
printf("\nString 2 after concatenation : %s",str2);
}
output :
Page 13
C Programming Language Unit – III
Enter 1st string : good
Enter 2nd string : night
String 1 after concatenation : goodnight
String 2 after concatenation : night

/* program to concatenate 2 string without using strcat() function */


#include <stdio.h>
void main()
{
char str1[100],str2[100];
int len,i,j;
printf("Enter 1st string : ");
scanf("%s",&str1);
printf("Enter 2nd string : ");
scanf("%s",&str2);
for( len=0; str1[len]!='\0'; len++ );
for( i=0,j=len; str2[i]!='\0';i++,j++)
str1[j]=str2[i];
str1[j]='\0';
printf("String 1 after concatenation : %s",str1);
printf("\nString 2 after concatenation : %s",str2);
}
output :
Enter 1st string : good
Enter 2nd string : night
String 1 after concatenation : goodnight
String 2 after concatenation : night
Additional Programs:
1. C Program to reverse given string without using strrev() functions.
#include<stdio.h>
void main()
{
char str[100],rev[100];
int i,j,len;
printf("Enter a string : ");
scanf("%s",&str);
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';
printf("Reverse=%s",rev);
}
2. C Program to check whether the given string is palindrome or not.

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

You might also like