Module 3
Module 3
MODULE 3
ARRAYS
WHY DO WE NEED ARRAYS?
Say we have a problem in our hand to store marks scored by 50 students in C language
subject. To store 50 marks we have to declare 50 variables of integer data type as shown
below:
int marks_1, marks_2, marks_3, marks_4… ....................marks_50;
Now suppose we have to store values into these variables then 50 scanf statements or
initializing 50 values has to be done as shown:
scanf(“%d”, &marks_1); scanf(“%d”, &marks_2); scanf(“%d”, &marks_3);
………………..scanf(“%d”, &marks_50);
OR
………….. so on marks_50=21;
Definition of Arrays
The array is a fixed-size sequenced collection of elements of same data type.
The array is a collection of homogeneous elements of same data type.
Array groups the data items of similar types sharing the common name.
Arrays are called as subscripted variables because; it is accessed using
subscripts/indexes.
Ex: 1. List of employees in an organization.
2. List of products and their cost sold by a store.
Test scores of a class of students
www.vtuupdates.com Page 1
C Programming for Problem solving 18CPS13
TYPES OF ARRAYS
I. One-Dimensional Arrays: A list of items can be given one variable name using
only one subscript and such a variable is called a single subscripted variable or one
dimensional array.
Ex: int marks[4];
Here marks is the name of the array which is capable of storing 4 integer values. The
first value will be stored in marks[0], the second value will be stored in marks[1] and so on
and the last value will be in marks[3].
1. Compile-time initialization
2. Run-time initialization
a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[size]={list of values};
Examples: int marks[4]={ 95,35, 67, 87};
www.vtuupdates.com Page 2
C Programming for Problem solving 18CPS13
b) Initialization without size: We needn’t have to specify the size of array provided we
are initializing the values in beginning itself.
Syntax: data_type array_name[ ]={list of values};
Examples: int marks[ ]={ 95,35, 67, 87};
float temperature[ ]={29.5, 30.7, 35.6, 45.7, 19.5};
c) Partial initialization: If we not specify the all the elements in the array, the
unspecified elements will be initialized to zero.
Example: int marks[5]={10,12,20};
Here, marks[3] and marks[4] will be initialized to zero.
float temperature[5]={0};
{
scanf(“ %d”, &marks[i]);
}
Note: Every iteration of for loop will help us to fill values into marks array (i.e.
marks[0]=95, marks[1]=35, marks[2]=67, marks[3]=87)
Accessing the array elements: Accessing the array element is done using a loop statement
in combination with printf statements or any other processing statements. Example of
accessing the array elements and calculating total marks is given below:
www.vtuupdates.com Page 3
C Programming for Problem solving 18CPS13
Example:
void main( )
{
int total=0,
marks[4]={35,44,55,67};
for(i=0; i<4; i++)
total=total+marks[i]; /* calculating
total marks*/ printf(“Total
marks=%d”,total);
}
Output: Total marks=201
This diagram clearly illustrates how each individual element of array num[ ] is passed to
function square through parameter no
www.vtuupdates.com Page 4
C Programming for Problem solving 18CPS13
3 4 8 9 10
0 1 2 3 4 num[3]=9 no
num[2]=8 no
Next program illustrates how to pass an entire array to a function average( ) and calculate
average marks. First sum of all the elements of array marks
(i.e.35+65+75+95+85) is calculated and average is stored in a variable avg. value in avg
variable is returned to main( ) and stored in avg1.
In the above example each value of array marks[ ] is copied to array scores[ ] as
shown.
www.vtuupdates.com Page 5
C Programming for Problem solving 18CPS13
II. Two-Dimensional Arrays: A list of items can be given one variable name using
two subscripts and such a variable is called a single subscripted variable or one dimensional
array.
1. Compile-time initialization
2. Run-time initialization
www.vtuupdates.com Page 6
C Programming for Problem solving 18CPS13
2. Run time initialization: Run time initialization is storing values in an array when
program is running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example: printf(“Enter the marks”);
www.vtuupdates.com Page 7
C Programming for Problem solving 18CPS13
www.vtuupdates.com Page 8
C Programming for Problem solving 18CPS13
STRING CONCEPTS
Definition: String is a variable length data stored in a character array.
Example: “hello”, “India”
I. C- strings
In C a string is a data structure based on an array of char.
A string is a sequence of elements of the char data type.
There is no separate data-type called string in C language.
As strings are variable-size data we have to represent them using character Arrays.
Example string is:
1. String literals
2. String variables
String literals are also known as string constants, is a sequence of characters enclosed
by double quotation marks is called string literals. A string literal is a constant its value
cannot be changed. Some examples are:
Examples: “New Delhi”, “I Love India” etc.
String variables are nothing but character array. Following syntax and examples
illustrates declaring string variables.
Example: char array_name[ ]= “raj”
How string is stored?
A T M E \0
www.vtuupdates.com Page 9
C Programming for Problem solving 18CPS13
Size 21 means it can store up to 20 characters plus the null character. Entire storage location
name is divided in to 21 boxes called bytes, each of which holds one character. Each
character is element of data type char.
Initializing the string in the declaration char
first[10]={‘t’,’a’,’b’,’l’,’e’,’\0’}; char
second[10]=”table”;
Difference between a single character string and a single character array is:
Single character array takes 1 byte whereas single character string occupies two bytes.
But this initialization can be done using a loop and assigning individual
characters of name1 to name2 as shown below:
void main( )
{
int char name1[ ]= “hello”;
int char name2[5];
for (int i=0; i<4;i++)
{
name2[i] =name1[i];
}
name2[i]= ‘\0’;
}
www.vtuupdates.com Page 10
C Programming for Problem solving 18CPS13
Disadvantage of reading strings using scanf( ) function is multiple words strings cannot be
read. For example say we have to read NEW DELHI, following scanf( ) reads only NEW
and stops.
www.vtuupdates.com Page 11
C Programming for Problem solving 18CPS13
N E W D E L H I
Only part of a string (NEW) is read and second half (DELHI) is ignored.
N E W
Edit set Conversion code %[ ]: In addition to %s we can also use edit set conversion code
%[ ], which specifies the type of characters that can be accepted by scanf ( ) function.
^ symbol in edit set conversion code. Following example illustrates same:
Example 1:
char name[20];
scanf(“%[^A-Z]”, name)
Char name[20];
Scanf(“%[^\n]”,name);
www.vtuupdates.com Page 12
C Programming for Problem solving 18CPS13
www.vtuupdates.com Page 13
C Programming for Problem solving 18CPS13
Char
days[7][10]={“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday”};
www.vtuupdates.com Page 14
C Programming for Problem solving 18CPS13
Bubble sort:
Bubble sort will start by comparing the first element of the array with the second element,
if the first element is greater than the second element, it will swap both the elements, and then
move on to compare the second and the third element, and so on.
#include<stdio.h>
void main()
{
int a[10], n, i, j, temp;
printf("Enter the number of elements\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(j=1; j<n;j++)
{
for(i=0;i<n;i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf("The sorted array is\t");
for(i=0; i<n;i++)
printf(“%d\t”,a[i]);
}
Output
Enter the number of elements 7
Enter the array elements 12 23 10 13 15 1 8
The sorted array is 1 8 10 12 13 15 23
Selection Sort
Selection sort will start by comparing the first element with other elements and finds
minimum element and swaps, then it starts comparing by taking second element with other
elements and so on.
www.vtuupdates.com Page 15
C Programming for Problem solving 18CPS13
#include<stdio.h>
void main( )
{
int
a[100],i,j,n,temp,p
os; printf("Enter
the value of n\n");
scanf("%d",&n);
printf("Enter the numbers in unsorted
order:\n"); for(i=0;i<n;i++)
scanf("%d",
&a[i]);
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if( a[pos]>a[j])
Pos=j;
}
if(pos !=i )
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
SEARCHING: It is the process of finding the location of the specified element in a list.
The specified element is often called the search key.
If it is found search is successful, otherwise it is unsuccessful.
www.vtuupdates.com Page 16
C Programming for Problem solving 18CPS13
LINEAR SEARCH
Linear search is a very basic and simple search algorithm. In Linear search, we search an
element or value in a given array by traversing the array from the starting, till the desired
element or value is found.
#include<stdio.h>
#include<stdlib.h>
void main( )
{
int n, a[100], i, key,loc;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key == a[i]
{
loc=i+1;
break;
}
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc);
else
printf("The search is unsuccessful\n");
}
Binary Search
Binary search works only on a sorted set of elements. To use binary
search on a collection, the collection must first be sorted. The array is divided
into two parts, compared with middle element if it is not successful, then it is
compared whether it is lesser or greater than middle element. If it is lesser,
search is done towards left part else right part.
www.vtuupdates.com Page 17
C Programming for Problem solving 18CPS13
#include<stdio.h>
void main()
{
int a[100], n, i, mid, low, high, found, key;
printf("\nEnter the number of elements\n");
scanf("%d",&n);
printf("\nEnter the elements in ascending order\n");
for(i=0; i<;i++)
scanf(“%d”,&a[i]);
printf("\nEnter the key element\n");
scanf("%d", &key);
found = 0;
low = 0;
high = n-1;
while(low <= high)
{
mid = (low+high)/2;
if(key == a[mid])
{
found = 1;
break;
}
else if(key < a[mid])
high = mid-1;
else
low = mid+1;
}
if(found==1)
printf("\nKey element %d found at position %d\n", key, mid+1);
else
printf("\nKey element not found\n");
}
www.vtuupdates.com Page 18
C Programming for Problem solving 18CPS13
PROGRAMS
void main()
{
int a[10][10],i,j,m,n;
printf(“enter the size1 and size2 of 2 dimensional array\n”);
scanf(“%d”,&m,&n)
printf(“enter the elements of an
array\n”); for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf(“the elements of 2 dimensional
array are\n”); for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf(“%d”,
a[i][j]);
printf(“\n”);
}
}
www.vtuupdates.com Page 19
C Programming for Problem solving 18CPS13
www.vtuupdates.com Page 20
C Programming for Problem solving 18CPS13
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j]; i++;
j++;
}
str1[i]='\0' ;
printf("concatanation of string is %s",str1);
}
5. Implement string copy operation STRCOPY(str1,str2) that copies a
string
str1 to another string str2 without using library function.
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[100],s2[100]; int i;
printf("\nEnter the string1 :");
gets(s1);
i=0;
while(s1[i]!='\0')
{
S2[i]=s1[i]; i++;
}
s2[i]='\0';
printf("\nString2 value is %s ",s2);
}
www.vtuupdates.com Page 21