UNIT – III
Department of Computer Science
ARRAYS
Consider a problem to find the average of marks secured
by five students in a course. The following piece of code is
written for it:
//Comment: Average of marks secured by students
#include<stdio.h>
main()
{
int marks1=10, marks2=12, marks3=9,
marks4=11,marks5=17;
int sum; float average;
sum=marks1+marks2+marks3+marks4+marks5;
average=sum/5.0;
printf(“Average marks secured is %f ”,average);
}
NOW, SUPPOSE THERE ARE TWO HUNDRED STUDENTS IN A COURSE!
INTRODUCTION
So far we have used only single variable name
for storing one data item.
Ifwe need to store multiple copies of the same
data then it is very difficult for the user.
To overcome the difficulty a new data
structure is used called arrays.
An array is a data structure that is used for
the storage of homogeneous data i.e. data of
the same type.
INTRODUCTION (CONT…)
Arrayis a finite collection of homogeneous
elements in contiguous memory locations.
Finitemeans fixed and finite size (No. of
elements).
Homogeneous means all elements are of
same data type.
Contiguous memory locations means
consecutive memory locations. The elements
will be stored in sequence one after another in
memory.
INTRODUCTION (CONT…)
Pictorial representation of C Programming Arrays
The above array is declared as int a [5];
a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1;
Inthe above figure 4, 5, 33, 13, 1 are actual data
items. 0, 1, 2, 3, 4 are index variables.
ARRAY DECLARATION
Arrayhas to be declared before using it in C
Program.
Syntax:
<Data Type> array_name [size1]…[sizeN];
Data type: Data Type of Each Element of the
array
Array name: Valid variable name
Size: It is maximum size that array can have.
TYPES OF ARRAY
• Single
1. Dimensional
Arrays
• Multi
2. Dimensional
Arrays
SINGLE DIMENSIONAL ARRAY
Single or One Dimensional array is used to
represent and store data in a linear form.
Arrayhaving only one subscript variable is called
One-Dimensional array.
It is also called as Single Dimensional Array or
Linear Array.
Syntax for declaration:
<data type> <array Name> [size];
Examples:
int iarr[3]; char carr[20]; float farr[3];
INITIALIZING 1-D ARRAY
INITIALIZING 1-D ARRAY (CONT…)
If array elements are not given any specific values,
they are supposed to contain garbage values.
The values can be assigned to element at time of array
declaration, which is called array initialization.
Since an array his multiple elements, braces are used
to denote the entire array and commas are used
separate the individual values assigned to the
elements in the array initialization statements.
Syntax:
<data types> <array name> [size] = {value1, value2,
value3}
INITIALIZING 1-D ARRAY (CONT…)
Ways of Array Initializing 1-D Array
Method 1: Array Size Specified Directly.
In this method, we try to specify the Array
Size directly.
int num [5] = {2,8,7,6,0};
Method 2: Size Specified Indirectly
In this scheme of compile time Initialization,
We do not provide size to an array but instead
we provide set of values to the array.
int num[ ] = {2,8,7,6,0};
INITIALIZING 1-D ARRAY (CONT…)
Graphical Representation
INITIALIZING 1-D ARRAY (CONT…)
Comma separated list of initialzers called
Initialization list.
An initializer is an expression that determines
the initial value of an element of the array.
If the type of initializers is not the same as the
element type of an array, implicit type casting
will be done, if the types are compatible. If types
are not compatible, there will be a compilation
error.
The number of initializers in the initialization list
should be less than or at most equal to the
value of size specifier, if it is present.
INITIALIZING 1-D ARRAY (CONT…)
If the number of initializers in the
initialization list is less than the value of size
specifier, the leading array locations get
initialized with the values of initializers.
The rest of the array locations gets initialized
to:
0 (if it is an integer array),
0.0 (if case of floating point array)
‘\0’ (i.e. null character if array is of
character type).
ACCESSING ARRAY
Theelements of a single-dimensional array can be
accessed by using a subscript operator (i.e. [])
and a subscript.
Subscript, often referred as index as well,
indicates the position of an element in an array.
Subscript is mentioned within a square bracket
and in C subscript begins from 0.
This means the first element in an array is
referred as array[0]. Similarly the second element
as array[1] and last element in an array of length
n is referred as array[n-1].
ACCESSING ARRAY (CONT..)
Consider the below example of an array
In this example we will be accessing array like this.
arr[3] = Forth Element of Array
arr[5] = Sixth Element of Array
whereas elements are assigned to an array using
below way
arr[0] = 51; arr[1] = 32; arr[2] = 43; arr[3] = 24; arr[4]
= 5; arr[5] =26;
EXAMPLE PROGRAM1: ACCESSING ARRAY
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++)
{
printf("\nElement at arr[%d] is %d",i,arr[i]);
}
getch();
}
Output:
Element at arr[0] is 51
Element at arr[1] is 32
Element at arr[2] is 43
Element at arr[3] is 24
Element at arr[4] is 5
Element at arr[5] is 26
PROGRAMS FOR PRACTICE
WAP in C to display array elements with addresses
WAP in C for Reading and printing Array Elements
WAP in C to calculate addition of all elements in an
array
WAP in C to calculate average marks of all students.
WAP in C to find smallest element in an array
WAP in C to find largest element in an array
WAP in C to reverse an array elements in an array
ADVANTAGES OF ARRAY IN C
Efficient Random Access: Arrays provide constant-
time access to elements using their index, making data
retrieval and manipulation fast.
Memory Efficiency: Arrays store elements in
contiguous memory locations, making them memory-
efficient for homogeneous data types.
Simple and Easy to Use: Arrays in C are
straightforward to declare and use, making them
accessible to beginners and widely used in
programming.
Predictable Performance: Since arrays have a fixed
size, accessing elements is predictable and fast,
making them suitable for performance-critical
applications.
DISADVANTAGES OF ARRAY IN C
Fixed Size: Arrays in C have a fixed size, requiring
knowledge of the maximum number of elements
beforehand. Resizing arrays dynamically can be
inefficient or not directly supported.
No Bounds Checking: C arrays do not have built-in
bounds checking, which can lead to buffer overflow
issues if not managed carefully.
Lack of Flexibility: Once an array is created, its size
cannot be changed, and inserting or deleting elements
in the middle of the array can be cumbersome and
inefficient.
Wasted Space: If the large array size and the actual
data stored are small, it can lead to wasted memory.
APPLICATIONS OF ARRAY
Storing and accessing data: Arrays are used to store
and retrieve data in a specific order. For example, an array
can be used to store the scores of a group of students, or the
temperatures recorded by a weather station.
Sorting: Arrays can be used to sort data in ascending or
descending order. Sorting algorithms such as bubble sort,
merge sort, and quicksort rely heavily on arrays.
Searching: Arrays can be searched for specific elements
using algorithms such as linear search and binary search.
Matrices: Arrays are used to represent matrices in
mathematical computations such as matrix multiplication,
linear algebra etc.
2D ARRAYS
In C programming, you can create an array of arrays. These arrays are
known as multidimensional arrays. For example two dimensional array
(matrix).
Declaration of 2-D Array
Data_type arrayName [rowsize][columnsize];
int a[2][3];
Initializing Two-Dimensional Arrays
2-D arrays may be initialized by specifying bracketed values for each
row and corresponding columns. Following is an array with 3 rows and
each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
2D ARRAYS (CONT…)
Accessing Two-Dimensional Array Elements
An element in a two-dimensional array is accessed by using the
subscripts, i.e., row index and column index of the array. For
example −
#include <stdio.h>
void main () {
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
}
2D ARRAYS (IMP. PROGRAMS)
WAP in C for Addition of two matrices.
WAP in C to find Transpose of given matrix.
WAPin C to check that given square matrix is
symmetric or not.
WAP in C to find Trace (Sum of diagonal
Elements) of matrix.
WAP in C to find multiplication of two matrices.
WAP to find the largest element in a 4*4 matrix.
STRINGS
The string can be defined as the one -
dimensional array of characters terminated by
a null ('\0').
Thecharacter array or the string is used to
manipulate text such as word or sentences.
Declaration of string:
Syntax: char stringname[size];
Ex. char s[20];
STRINGS (CONT…)
String Initialization:
Char s[6]={‘h’,’e’,’l’,’l’,’o’,’\0’};
Char s[]=”hello”;
Note: computer automatically appends a null
character(‘\0’) at the end of the string.
The size of string should be no of characters
plus 1.
STRINGS (CONT…)
char name[6]={‘r’,’a’,’h’,’u’,’l’,’\0’};
char name[]=“rahul”;
Here the string “rahul” contains 5 characters
so compiler automatically allocates 6 memory
locations (1 extra for storing NULL character).
Print String
for(i=0; name[i] != ‘\0’; i++)
{
printf(“%c”,name[i]);
}
STRINGS (CONT…)
Reading & Writing of String using
Character Array
C programming language provides a separate
access specifier i.e. %s to read and write
sequence of characters using ‘%s’ access
specifier.
char name[12];
scanf(“%s”, name);
r a h u l \0
printf(“%s”, name);
STRINGS (CONT…)
include <stdio.h>
int main()
{
Char name[20];
printf("Enter your name:");
scanf("%s",name);
printf("%s",name);
return 0;
}
OUTPUT
Shikha Jain
Shikha
Note: The drawback of %s access specifier is that it stops reading
the input as soon as it encounters whitespace (normal space, tab
space). scanf() function is not capable of receiving multiword string.
Function is terminated when space is encountered.
STRINGS (CONT…)
Thereare another built-in function provided
by C which can read the input character
sequence that includes white space too.
Input function: gets()-
reads characters into string from keyboard
until new line character is pressed & then
append null character at the end.
Output function: puts()-
can display only one string at a time & place
the cursor on the new line.
STRINGS (CONT…)
Input
main()
{
char s[20];
printf(“enter string”);
gets(s);
puts(s);
}
STRING HANDLING FUNCTIONS
Library Function Use Description
in <string.h>
strlen() strlen(“hello”); or computes string's
strlen(s); length
strcpy() strcpy(s1,”hello”); or copies a string to
strcpy(s1,s2); another
strcat() strcat(s1, s2); or Concatenates (joins)
strcat(s1, “hello”); second argument to
first argument
strcmp() strcmp(s1, s2); or compares two strings
strcmp(s1, “hello”); or s1, s2 and if they
strcmp(“hello”, s2); or matched returns 0
strcmp(s1, “hello”); otherwise returns
non zero value.
STRING HANDLING FUNCTIONS
Library Function Use Description
in <string.h>
strlwr() strlwr(s1); Converts string to
lowercase
strupr() strupr(s1); Converts string to
uppercase
strrev() strrev(s1); Reverse string
STRING HANDLING FUNCTIONS
#include<stdio.h>
void main()
{
char s1[20],s2[10],s[10];
int l;
printf(“enter strings”);
gets(s1); // hello
gets(s2); //students
l=strlen(s1);
printf(“%d”,l); //5
strcpy(s,s1);
puts(s); // hello
if(strcmp(s1,s2)==0)
printf(“strings are equal”);
else printf(“strings are not equal”); // strings are not equal
strcat(s1,s2); // hellostudents
puts(s1);
}
IMPORTANT STRING BASED PROGRAMS
WAP in C to find length of string without using
string handling functions.
WAP in C to copy one string to another string
without using string handling functions.
WAP in C to concatenate one string with another
string without using string handling functions.
WAP in C to compare two string whether they are
same or not without using string handling
functions.
WAP in C to reverse a given string without using
string handling functions.
FIND LENGTH OF STRING
#include<stdio.h>
void main()
{
int i, count=0;
char s[20];
printf("Input string \n");
gets(s);
printf("Calculate Length of String \n");
for(i=0; s[i]!='\0'; i++)
{
count=count+1;
}
printf("Length of String is: %d",count);
}
COPY ONE STRING TO ANOTHER STRING
#include<stdio.h>
void main()
{
int i;
char s1[20],s2[20];
printf("Input string \n");
gets(s1);
//Copy s1 to s2
for(i=0; s1[i]!='\0'; i++)
{
s2[i]=s1[i];
}
s2[i]='\0';
printf("Print Copied String \n");
puts(s2);
}
CONCATENATE TWO STRINGS
#include<stdio.h>
void main()
{
int i, j, count=0;
char s1[20],s2[20];
printf("Input string s1\n");
gets(s1);
printf("Input string s2\n");
gets(s2);
//Find last Index Value of string s1
for(i=0;s1[i]!='\0';i++)
count++;
//Concate s2 to s1
for(i=count,j=0; s2[j]!='\0'; i++,j++)
s1[i]=s2[j];
s1[i]='\0';
printf("Print Concatenated String \n");
puts(s1);
}
COMPARE TWO STRINGS
#include<stdio.h>
void main()
{
int i, flag=0;
char s1[20],s2[20];
printf("Input string s1\n");
gets(s1);
printf("Input string s2\n");
gets(s2);
//Compare s1 & s2
for(i=0; s1[i]!='\0' && s2[i]!='\0'; i++)
{
if(s1[i]!=s2[i])
{
flag=1;
break;
}
}
if(flag==0) printf("Strings are Same \n");
else printf("Strings are Not Same");
}
REVERSE A GIVEN STRING
#include<stdio.h>
#include<math.h>
void main()
{
int i,j,count=0;
char s1[30], s2[30];
printf("Enter String:\n");
gets(s1);
for(i=0; s1[i]!='\0'; i++)
count++;
for(i=count-1,j=0; i>=0; i--,j++)
{
s2[j]=s1[i];
}
s2[j]='\0';
printf("Print Reverse String: \n");
puts(s2);
}
STRUCTURE
Structureis a user defined data type available in
C that allows to combine data items of different
kinds. Structures are used to represent a record.
Declaring a Structure
To declare a structure, you must use
the struct statement.
struct struct_name
{
DataType member1_name;
DataType member2_name;
DataType member3_name;
…
};
STRUCTURE (CONT…)
Example:
struct book
{
char title[50];
char author[50];
char subject[100];
int book_id;
} b1;
Declare structure variables: A structure variable
can either be declared with structure declaration or as a
separate declaration.
Syntax:
struct structurename variable1;
struct book b1;
STRUCTURE (CONT…)
Accessing Structure Members
To access any member of a structure, we use
the member access operator (.).
The member access operator is coded as a
period between the structure variable name
and the structure member.
Example:
b1.title
b1.author
STRUCTURE (CONT…)
Structure Initialization:
Struct student
{
int roll;
char name[20];
float marks;
}s;
s.roll=101;
s.name=”Rahul”;
s.marks=80.5;
OR
s={101,”Rahul”,80.5};
STRUCTURE (CONT…)
#include<stdio.h>
struct emp
{
int id;
char ename[20];
float sal;
};
void main()
{
struct emp e1,e2;
printf("------Enter Details of Employee-1 -------\n");
printf("Enter Employee Id \n");
scanf("%d",&e1.id);
printf("Enter Employee Name \n");
scanf("%s",e1.ename);
printf("Enter Employee Salary \n");
scanf("%f",&e1.sal);
STRUCTURE (CONT…)
printf("-----Print Employee-1 Details-----\n");
printf("%d\n",e1.id);
printf("%s\n",e1.ename);
printf("%f\n",e1.sal);
printf("------Enter Details of Employee-2 -------\n");
printf("Enter Employee Id \n");
scanf("%d",&e2.id);
printf("Enter Employee Name \n");
scanf("%s",e2.ename);
printf("Enter Employee Salary \n");
scanf("%f",&e2.sal);
printf("-----Print Employee-2 Details-----\n");
printf("%d\n",e2.id);
printf("%s\n",e2.ename);
printf("%f\n",e2.sal);
}
ARRAY OF STRUCTURE
We can also declare an array of structure variables, in which
each element of the array will represent a structure variable.
Example:
struct student s[5];
#include<stdio.h>
struct student
{
int roll;
char name[20];
float marks;
}s[20];
void main()
{
int i;
printf(“enter information”);
for(i=0;i<20;i++)
scanf(“%d%s%f”,&s[i].roll,s[i].name,&s[i].marks);
printf(“display information”);
for(i=0;i<20;i++)
printf((“%d%s%f”,s[i].roll,s[i].name,s[i].marks);
}
ARRAY VS STRUCTURE
S. No. Array Structure
Array refers to a collection Structure refers to a collection
1 consisting of elements of consisting of elements of heterogeneous
homogeneous data type. data type.
Array uses subscripts or “[ ]”
2 Structure uses “.” (Dot operator) for
(square bracket) for element
element access
access
Array is pointer as it points to the
3 Structure is not a pointer
first element of the collection.
Array declaration is done simply Structure declaration is done with the
4 using [] and not any keyword. help of “struct” keyword.
Array traversal and searching is Structure traversal and searching is
5 easy and fast. complex and slow.
Array elements are stored in Structure elements may or may not be
6 contiguous memory locations. stored in a contiguous memory location.
UNION
It is also a user defined data type.
1) Capable of grouping different types of data items
in a single unit.
2) Union variable is allocated a common
memory equal to the memory size required by
the maximum sized data member.
3) All members share the same common
memory but one at a time.
4) Union are used to efficiently use the memory.
UNION (CONT…)
UNION (CONT…)
#include<stdio.h>
union emp
{
int id;
char ename[20];
float sal;
};
void main()
{
union emp e[10];
int i,n;
printf("Enter Number of Students \n");
scanf("%d",&n);
printf("------Enter Details of Employees -------\n");
UNION (CONT…)
for(i=0;i<n;i++)
{
printf("Enter Employee-%d Id \n",i+1);
scanf("%d",&e[i].id);
printf("%d\n",e[i].id);
printf("Enter Employee-%d Name \n",i+1);
scanf("%s",e[i].ename);
printf("%s\n",e[i].ename);
printf("Enter Employee-%d Salary \n",i+1);
scanf("%f",&e[i].sal);
printf("%0.2f\n",e[i].sal);
}
}
UNION (CONT…)
Difference between Structure & Union
ENUMERATED DATA TYPES
Enumeration (or enum) is a user defined data
type in C.
It
is mainly used to assign names to integral
constants.
The use of enum in C to name the integer
values makes the entire program easy to
learn, understand, and maintain by the same
or even different programmer.
ENUMERATED DATA TYPES (CONST…)
Syntax to Define Enum in C
An enum is defined by using the ‘enum’ keyword
in C, and the use of a comma separates the
constants within.
The
basic syntax of defining an enum is:
enum enum_name {const1, const2, …, constN};
In the above syntax, the default value of const1 is
0, const2 is 1, const3 is 2, and so on.
However, you can also change these default values
while declaring the enum.
ENUMERATED DATA TYPES (CONST…)
enum cars{BMW, Ferrari, Jeep, Mercedes-Benz};
Here, the default values for the constants
are:
BMW=0, Ferrari=1, Jeep=2, and Mercedes-
Benz=3.
However, to change the default values, you can
define the enum as follows:
enumcars{BMW=3, Ferrari=5, Jeep=0, Mercedes-
Benz=1};
ENUMERATED DATA TYPES (CONST…)
Creation of Enumeration Variable
Syntax:
enum enum_name var_name;
Example1:
#include<stdio.h>
enum status{off=0, on=1};
void main()
{
enum status switch;
switch=on;
printf(“%d”,switch);
}
ENUMERATED DATA TYPES (CONST…)
Example2:
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat,
Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
ENUMERATED DATA TYPES (CONST…)
Example3:
#include<stdio.h>
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul,
Aug, Sep, Oct, Nov, Dec};
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
ENUMERATED DATA TYPES (CONST…)
Example4:
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,
wednesday, thursday = 10, friday, saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday,
monday, tuesday, wednesday, thursday,
friday, saturday);
return 0;
}