CP Unit-III - RIT CSE
CP Unit-III - RIT CSE
CP Unit-III - RIT CSE
UNIT-III
ARRAY: An array is a group of related data items that share a common name and stored in
contiguous memory locations.
Arrays offer a convenient means of grouping together several related variables, in one
dimension or more dimensions. An array is also known as subscripted variable. Before using an
array its type and dimension must be declared. The elements are always stored in contiguous
memory locations. First element is at position „0‟, so the last element is at position 1 less than the
size of the array.
Examples:
product part numbers:
int part_numbers[ ] = {123, 326, 178, 1209};
student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};
One-Dimensional Arrays
A one-dimensional array is a list of related variables. The general form of a one-dimensional
array declaration is:
type : base type of the array, determines the data type of each element in the array
size: how many elements the array will hold
variable_name : the name of the array
Examples:
int sample[10];
float float_numbers[100];
char last_name[40];
Initialization of arrays:
We can initialize the elements of an array in the same way as the ordinary variables when they
are declared.
type array-name [size] = {list of values};
The values in the list are separated by commas. If the number of values in the list is less than the
size, then only that many elements will be initialized. The remaining elements will be set to zero
automatically.
Ex.
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};
EXAMPLES
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
average = sum/n;
printf("Average = %d", average);
return 0;
}
Output
#include<stdio.h>
int main()
{
int my_arr[100];
int n,i, max, min;
printf(“enter the number of elements of the array”);
scanf(“%d”, &n);
printf(“Enter elements into the array”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
max = min = my_arr[0];
return 0;
}
OUTPUT:
Enter the size of the array: 5
Enter array elements:
10
15
20
54
26
Even numbers in the array are:
CSE, RIT Page 4
10 20 54 26
Odd numbers in the array are:
15
#include <conio.h>
int main()
{
int a[10000],i,n,j,temp;
}
printf("\narray elements in ascending order:\n ");
APPLICATIONS OF ARRAYS
1) Array stores data elements of the same data type.
2) Maintains multiple variable names using a single name. Arrays help to maintain large data
under a single variable name. This avoid the confusion of using multiple variables.
3) Arrays can be used for sorting data elements. Different sorting techniques like Bubble sort,
Insertion sort, Selection sort etc use arrays to store and sort elements easily.
4) Arrays can be used for performing matrix operations. Many databases, small and large, consist
of one-dimensional and two-dimensional arrays whose elements are records.
5) Arrays can be used for CPU scheduling.
6) Arrays are also used to implement other data structures like Stacks, Queues, Heaps, Hash
tables etc.
TWO-DIMENSIONAL ARRAYS
So far we have looked at arrays with only one dimension. It is also possible for arrays to have
two or more dimensions. The two dimensional array is also called a matrix.
The table contains a total of 12 values, i.e in each line. We can think of this table as a matrix
consisting of 3 rows and 4 columns. Each row represents the marks obtained in 4 subjects by a
particular student. Each column represents the marks obtained in a particular subject.
In mathematics, we represent a particular value in a matrix by using two subscripts, such as vij.
Here v denotes the entire matrix and vij refers to the value in the ith row and jth column.
For example in the above table v23 refers to the value 50. C allows us to define such tables of
items by using two-dimensional arrays, the above table can be defined in C as
int v[3][4];
If the values are missing in an initializer, they are automatically set to zero. For instance the
statement static int num[2][3] = {{1,1},{2}};
will initialize the first two elements of the first row to one, the first element of the second row to
two. And all other elements to zero.
12 22 23 33 11 13 14 15 11
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("enter a size of the array B:" );
scanf("%d%d",&p,&q);
printf("enter the elements of matrix B\n");
for (i=0;i<p;i++)
for (j=0;j<q;j++)
CSE, RIT Page 8
scanf("%d",&b[i][j]);
if (n==p)
{
for (i=0;i<m;i++) /*initialisation of C*/
for (j=0;j<q;j++)
c[i][j]=0;
for (i=0;i<m;i++)
for (j=0;j<q;j++)
for (k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
printf("The Resultant array\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d ",c[i][j]);
printf("\n");
}
}
else
printf("Matrix multiplication is not possible\n");
}
#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
OUTPUT:
Enter rows and columns: 2
3
Entered matrix:
1 4 0
-5 2 7
STRINGS:
A string is an array of characters. Any group of characters defined between double quotation
marks is a constant string.
Ex.
“c programming”
CSE, RIT Page 10
“Rama is a good boy”
Declaration:
char string_name[size];
A string variable is any valid C variable and is always declared as an array. The size determines
the number of characters in the string.
char city[10];
char name[20];
When the compiler assigns a character string to a character array, it automatically supplies a null
character („\0‟) at the end of the string. Therefore the size should be equal to the maximum
number of character in the string plus one. Character array may be initialized when they are
declared. C permits a character array to be initialized in either of the following two forms.
The reason that city had to be 7 elements long is that the string „guntur‟ contains 6 characters and
one element space is provided for the null terminator.
C also permits us to initialize a character array without specifying the number of elements. In
such cases, the size of the array will be determined automatically based on the number of
elements initialized. For example
static char string [ ] = {„g‟,‟o‟,‟o‟,‟d‟,‟\0‟}
defines the array string as a five element array.
Note that unlike previous scanf() calls, in the case of character arrays, the ampersand (&) is not
required before the variable name.
The scanf() function automatically terminates the string that is read with a null character and
therefore the character
The scanf() and printf() are generic i/o functions that they support all built-in data types such as
int, float, long, double, strings,..etc. But gets() and puts() are specialized to scan and print only
string data. There is a little difference between scanf() and gets(), while reading string from
keyboard, the scanf() accepts character by character from keyboard until either a new line („\n‟)
or blank space is found, which ever comes earlier. Whereas “gets()” accepts until a newline is
The scanf() function consider the jack and Jill as 3 strings, whereas gets() considers as single
string. In case to scan total string using scanf(), then it should be scanf(“%s%s%s”,
a,b,c); here a,b,c are three arrays.
The printf() and puts() is work in similar way. All I/O functions take first byte address (base
address of array) as argument and prints the given string using pointer.
Program : The following program is an example of string I/O functions.
#include<stdio.h>
#include<string.h>
int main()
{
char name[30];
printf(“Enter name: “);
gets(name); //Function to read string from user.
printf(“Name: “);
puts(name); //Function to display string.
return 0;
}
Output :
Enter name: INDIA IS A GREAT COUNTRY
Name: INDIA IS A GREAT COUNTRY
ARRAYS OF STRINGS:
A string is a 1-D array of characters, so an array of strings is a 2-D array of characters. Just like
we can create a 2-D array of int, float etc; we can also create a 2-D array of character or array
of strings. Here is how we can declare a 2-D array of characters.
char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};
It is important to end each 1-D array by the null character, otherwise, it will be just an
array of characters. We can't use them as strings.
Declaring an array of strings this way is rather tedious, that's why C provides an
alternative syntax to achieve the same thing. This above initialization is equivalent to:
char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};
The first subscript of the array i.e 3 denotes the number of strings in the array and the
second subscript denotes the maximum length of the string. Recall the that in C, each
character occupies 1 byte of data, so when the compiler sees the above statement it
allocates 30 bytes (3*10) of memory.
We already know that the name of an array is a pointer to the 0th element of the array.
Can you guess the type of ch_arr?
We know that when we dereference a pointer to an array, we get the base address of
the array. So, on dereferencing ch_arr + i we get the base address of the 0th 1-D
array.
We know that when we dereference a pointer to an array, we get the base address of
the array. So, on dereferencing ch_arr + i we get the base address of the 0th 1-D
array.
#include<stdio.h>
int main()
{
int i;
char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};
STRCAT():
strcat(str1, str2)
The strcat() function joins two strings together. Str1 and str2 are character arrays.
When the function strcat() is executed, str2 is appended to str1. It removes the „\0‟ at the end of
the string, and places str2 from there.
#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"sastry"};
char str[20];
clrscr();
printf("strings before concatenation\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
STRCMP():
The strcmp() function compares two strings identified by the arguments and has a value 0 if they
are equal. If they are not equal, it has the numeric difference between the first non-matching
characters in the strings.
strcmp(str1, str2)
#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"ezra"};
char str[20];
clrscr();
printf("strings before comparision\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
if (strcmp(str1,str2)==0)
printf("strings are same\n");
else
printf("strings are different\n");
getch();
}
STRCPY():
strcpy(str1, str2);
Assigns the content of str2 to str1.
#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"sastry"};
char str[20];
clrscr();
CSE, RIT Page 16
printf("strings before copy\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
strcpy(str1,str2);
printf("strings after copy\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
getch();
}
STRLEN():
#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"sastry"};
int n;
clrscr();
n=strlen(str1);
printf("length of string %s is %d\n",str1,n);
n=strlen(str2);
printf("length of string %s is %d\n",str2,n);
getch();
}
Ex: Program to check whether a given string is palindrome or not. (WITHOUT USING
STRING HANDLING FUNCTIONS)
#include<stdio.h>
int main()
{
char a[20],b[20];
int i,n=0,flag=0;
printf(“\n Enter a string”);
scanf(“%s”,a);
n=strlen(a);
for (i=0;i<n;i++)
{
b[i]=a[n-(i+1)];
}
for (i=0;i<n;i++)
{
CSE, RIT Page 17
if (b[i]!=a[i])
flag=1;
}
if (flag==1)
printf(“\n %s is not palindrome”,a);
else
printf(“\n %s is palindrome”,a);
}
Output:
string is palindrome
#include <stdio.h>
#include <string.h>
int main()
{
char s1[1000],s2[1000];
printf("Enter the string: ");
gets(s1);
strcpy(s2,s1);
strrev(s2);
if(!strcmp(s1,s2))
printf("string is palindrome");
else
printf("string is not palindrome");
return 0;
}
Output:
string is palindrome
#include <stdio.h>
#include <stdlib.h>
void main()
int l= 0;
printf("---------------------------------\n");
while(str[l]!='\0')
l++;
---------------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define str_size 100 //Declare the maximum size of the string
void main()
{
char str[str_size];
int i, wrd;
printf("\n\nCount the total number of words in a string :\n");
printf("------------------------------------------------------\n");
printf("Input the string : ");
fgets(str, sizeof str, stdin);
i = 0;
wrd = 1;
/* loop till end of string */
while(str[i]!='\0')
{
/* check whether the current character is white space or new line or tab character*/
if(str[i]==' ' || str[i]=='\n' || str[i]=='\t')
{
i++;
}
printf("Total number of words in the string is : %d\n", wrd-1);
}
OUTPUT:
Count the total number of words in a string :
------------------------------------------------------
Input the string : India is a great country
Total number of words in the string is : 5
Example: Write a program in C to count total number of alphabets, digits and special
characters in a string.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
char str[str_size];
printf("--------------------------------------------------------------------\n");
while(str[i]!='\0')
{
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
{
alp++;
}
else if(str[i]>='0' && str[i]<='9')
{
digit++;
}
else
{
splch++;
}
i++;
}
printf("Number of Alphabets in the string is : %d\n", alp);
printf("Number of Digits in the string is : %d\n", digit);
printf("Number of Special characters in the string is : %d\n\n", splch);
}
OUTPUT:
Count total number of alphabets, digits and special characters :
--------------------------------------------------------------------
Input the string : Welcome to VISAKHA-6
Number of Alphabets in the string is : 16
Number of Digits in the string is : 1
Number of Special characters in the string is : 4