0% found this document useful (0 votes)
7 views145 pages

Understanding One-Dimensional Arrays

This document provides an overview of one-dimensional arrays (1-D arrays) in programming, detailing their definition, syntax, memory allocation, and initialization methods. It includes examples of declaring, initializing, and manipulating arrays, as well as common pitfalls to avoid. The document also presents practical coding exercises related to array operations.

Uploaded by

Dimple Parekh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views145 pages

Understanding One-Dimensional Arrays

This document provides an overview of one-dimensional arrays (1-D arrays) in programming, detailing their definition, syntax, memory allocation, and initialization methods. It includes examples of declaring, initializing, and manipulating arrays, as well as common pitfalls to avoid. The document also presents practical coding exercises related to array operations.

Uploaded by

Dimple Parekh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

MODULE 3 : ARRAY(1D)

Department of
Computer Science & Engineering

[Link].
in
Arrays

Data Types

Fundament User
Derived
al data defined
data types
types data types
Arrays int
float
Structures
Unions
Functions
double Enumeration
Pointers
char
• An array is a derived datatype used to store a
collection of similar (same type) data items, stored
contiguously in memory under a single name.
• If you want to declare 100 numbers, we need 100
variables.
• Instead of declaring individual variables, such as
Arrays

number0, number1, ..., and number99, we can


declare one array variable such as number and use
number[0], number[1], and ..., number[99] to
represent individual variables.
• number[0] index
• An index is an integer positive number that starts
with 0.
• All arrays consist of contiguous memory locations. The
lowest address corresponds to the first element and the
highest address to the last element.
Arrays

• Array name refers to the starting address of the


array. Arrays are also called as subscripted value.
Some examples where the concepts of an array can be
used:
• List of employees in an organization.
• List of customers and their telephone numbers.
ONE DIMENSIONAL ARRAYS (1-D)
• One dimensional arrays (1-D)
• Two dimensional arrays(2-D) – eg: matrices
• Multi-dimensional arrays
Types of Arrays

• Example:
20 12 34 56 78 28 num[6]

num[0] num[1] num[2] num[3] num[4]


num[5][5]
• A linear list of data items of same type which are stored
contiguously in memory is called one dimensional array
(1-D array).
Syntax: type array_name[size];
One dimensional
Arrays (1-D)

Example:
float height[50];
Declares the height to be an array containing 50 real
elements. Any subscripts 0 to 49 are valid.
int number[4];
Declares the number to be an array containing 4 integer
elements. Any subscripts 0 to 3 are valid.
int number[5];
number[0]
Memory layout of

number[1]
number[2
]
number[3]
1D Array

number[4
]

• The values to the array elements can be assigned as


follows :
number[0] = 10 ;
number[1] = 20 ;
number[2] = 30 ;
number[3] = 40 ;
number[4] = 50;
Memory Layout of 1D Array

• This would cause the array number to store the values


as shown below :
number[0] 10
number[1] 20
number[2] 30
number[3] 40
number[4] 50
Memory Allocation
• Syntax: Total allocated
memory=size*sizeof(datatype);
• Example:
int num[5]; Size of the
array
Total_memory= 5*sizeof(int);
= 5*4
=20 bytes
Try these:
float height[6]; char ch[8]; int number[20];
Memory Allocation
• Syntax: Total allocated
memory=size*sizeof(datatype);
Try these:
float height[6]; char ch[8]; int number[20];
float height[6]; Total allocated
memory=size*sizeof(datatype);
= 6*4;
= 24 bytes.
char ch[8]; Total allocated
memory=size*sizeof(datatype);
= 8*1;
int = 8 bytes.
Total allocated
number[20]; memory=size*sizeof(datatype);
= 20*4;
=80 bytes.
Memory Allocation
• int number[4];
• If the starting address is 8000.
• Address of an element=starting address +(index value *
sizeof(datatype))

• Address of number[2]=8000+2*sizeof(int)
=8000+2*4
=8008
Note: [sizeof(int)=2 bytes in a 16-bit machine ,
4 bytes in 32-bit machine]
Memory Layout

int number[4];

• Memory layout
number[0]8000
10

20
number[1]8004
30
number[2]8008
40
number[3]8012
Memory Layout

float
number[4];
• Memory layout
10.0
number[0]8000
20.5
number[1]8004
30.3
number[2]8008
40.5
number[3]8012
Memory Layout

char name[4];

• Memory layout
name[0] 8000
‘C’

name[1] 8001
‘A’

‘R’
name[2] 8002
‘\0’
name[3] 8003
DECLARATION OF ONE-DIMENSIONAL ARRAYS

• Syntax: type array_name[size];


• Examples: Index must be
integer
int a[10];
• Declares a as an array to contain a maximum of
10 integer constants.
char name[10];
• This declares the name as a character array
(string) variable that can hold a maximum of 10
characters.
INITIALIZATION OF ONE-DIMENSIONAL ARRAYS

INITIALIZATION

Compile time Runtime

Full initialization Using scanf()


Partial Initialization
Without size
With character
constants
With string
Compile time Initialization
1. Full initailization
type array-name[size] = {list of
values};
The values in the list are separated by commas.
Example:
int a[3] = { 11,20,3a[0]}; 11
will assign a[0]=11, a[1] 20
a[1]=20, a[2] 3
a[2]=3
Compile time Initialization
2. Partial initialization Num[0 10
int Num [5] = {10, ]20};
Num[1 20
]
Num[2 0
]
will initialize the first two
Num[3 0
elements to 10 and 20 respectively,
]City[0] ‘B’ and the
remaining elements to 0. Num[4 City[1] 0
‘\0’
]City[2] ‘\0’
char City [4] = {‘B’};City[3] ‘\0’

• will initialize the first element to 'B' and the


remaining Three to NULL.
Compile time Initialization
3. Without size
A[0] 1
no size A[1] 1
int A[ ] = {1,1,1,1};A[2] 1
A[3] 1

will declare the A array to contain four elements with


initial values 1.
Note: This approach works fine as long as we initialize
every element in the array.
char c[]={‘a’,’a’,’a’};
char c[4]={‘a’,’a’,’a’};
Compile time Initialization
4. With character constants
char name [ ] = { 'J' , 'o ‘ , ‘ h ‘, ‘ n ‘, ‘\0’};
• Declares the name to be an array of five
characters, initialized with the string "John"
ending with the null (‘\0’) character.
name[0] ‘J’
name[1] ‘o’
name[2] ‘h’
name[3] ‘n’
name[4] ‘\0’
Compile time Initialization

5. With string name[0] J


char name [] = "JOHN"; name[1] O
name[2] H
name[3] N
In this size is calculated as five. name[4] \0
Here null character need not be explicitly specified.

Note: difference between character constant and a


string constant is null character(we need to specify
for character constant)
Mistakes
• If we have more initializers than the declared size, the
compiler will produce an error.
int number [3] = {10, 20, 30, 40};
• index must be integer
float num[11.3];
int number[10.2];
the compiler will produce an error.
Run Time Initialization
• int a[3] ;
printf(“Enter three numbers”); a[0]
scanf("%d%d%d", &a[0],&a[1],&a[2]);
a[1]

(OR) a[2]
int i, a[3] ;
printf(“Enter three numbers”);
for(i=0;i<3;i++)
{
scanf("%d", &a[i]);
}
• This approach is usually applied for initializing large
arrays.
Tracing

Pass 1 Pass 2 Pass 3


i=0 0<3 i=1 1<3 i=2 2<3
Read value in a[i] Read value in a[i] Read value in a[i]
i.e a[0] i,.e a[1] i,e a[2]
i++…. Now i=1 i++…. Now i=2 i++…. Now i=3
Pass 4 Here we read 3
Output:
i=3 3<3 values
Enter three
Condition failed
numbers a[0] 12
Comes out from
the loop
12 a[1] 34
34
15 a[2] 15
Note: To read or to print elements of 1D
array we have to use one for loop for each.
MODULE 3 : ARRAY(1D)
EXAMPLES

Department of
Computer Science & Engineering

[Link].
in
Input and Output an array elements
void main( )
a[0] a[1] a[2] a[3] a[4]
{
int a[5]; 10 20 30 40 50
printf("Enter the 1st array
element");
scanf("%d",&a[0]);
printf("Enter the 2nd array
element");
scanf("%d",&a[1]);
printf("Enter the 3rd array Output : 10
element"); 50
scanf("%d",&a[2]);
printf("Enter the 4th array
element");
scanf("%d",&a[3]);
printf("Enter the 5th array
element");
scanf("%d",&a[4]);
printf("1st array element is %d\n
",a[0]); Drawback : The number of statement in the program
printf("2nd array element is %d increases as we try to input individual element in the
",a[4]); array, to overcome this problem, we make use of for loop.
}
Read and display of array elements
// read array element a[0] a[1] a[2]
2 4 5
for(i=0 ; i<3;
i++)
Pass1: Pass2: Pass3:
{ i=0;0< i=1;1<3 i=2;2<3
scanf(“%d”,&a[i]); 3 ; i++ ; i++ ; i++
&a[0] = 2 &a[1] = 4 &a[2] = 5
}
i = 1 ( incr )
Pass4: i = 2 ( incr ) i = 3 ( incr )
//display array element
i=3;3<3
for(i=0 ; i<3; condition is false comes out of the
i++) loop

{ Output : 2 4 5

printf(“%d\t”,a[i]);
}
Input & Output an array elements of size n
#include<stdio.h>
void main()
{
int n, i, a[5];
n 3
printf("enter size");
scanf("%d",&n); a[2]
a[0] a[1]
printf("enter the elements");
30 60 10
for(i=0;i<n;i++) 0

scanf("%d",&a[i]);
printf("The elements are");
OUTPUT: 3 60 100
for(i=0;i<n;i++) 0
printf("%d\t",a[i]);
}
Addition of two array element
#include<stdio.h>
void main( ) n 3
{
int a[5], b[5], sum[5] , i, n; a[0] a[1 a[2]
printf("Enter the size of the ]
array"); 1 2 3
scanf("%d",&n);
printf("Enter the elements of sum[0] sum[1] sum[2
b[0] b[1 b[2] ]
1st array");
for(i=0;i<n;i++) 2 1] 3
scanf("%d",&a[i]);
3 3 6
printf("Enter the elements of
2nd array"); Pass1: Pass2: Pass2:
for(i=0;i<n;i++) i=0 0<3 i=1 1<3 i=2 2<3
scanf("%d",&b[i]); sum[0] = a[0] + sum[1] = a[1] + sum[2] = a[2] +
for(i=0;i<n;i++) // addition of b[0] b[1] b[2]
two array sum[1]= 2 + 1 sum[1]= 3 + 3 =
sum[0]= 1 + 2
sum[i] = a[i] + b[i]; =3 6
=3
printf("sum of two array is "); i = 2 (incr) i = 3(incr)
i = 1 (incr)
for(i=0;i<n;i++)
Output : 3 3 6
printf("%d\t",sum[i]);
}
Sum of array elements
#include<stdio.h> sum 0
void main()
{ n 3
int n,i,a[5],sum=0;
printf("enter size");
a[0] a[1] a[2]
scanf("%d",&n);
printf("enter the 1 2 3
elements"); b
for(i=0;i<n;i++) Pass1: Pass2: Pass3: Pass4:
scanf("%d",&a[i]); i=0 0<3 i=1 1<3 i=2 2<3 i =33
sum = sum + sum = sum + sum = sum + <3
for(i=0;i<n;i++)
a[0] a[1] a[2] false
{ i.e sum = 0 + 1 i.e sum = 1 + i.e sum = 3 +
sum=sum+a[i]; =1 2=3 3=6
}
printf("The sum is %d i = 1 (incr) i = 2 (incr) i = 3 (incr)
",sum);
Output : The sum is 6
}
Hands on session

Write a c program to find the smallest element in


the array.
Write a c program to find the product of two array
elements.
Write a c program to add the elements of an array.
Prog: smallest element in an array
#include <stdio.h>
int main()
{
int i, small;
int a[3] = {10,4,6};
for(i =0; i<3;i++)
{
if(a[i]<a[i+1])
small = a[i];
else
small = a[i+1];
}
printf("%d", small);
return 0;
}
MODULE 3 : SORTING
ALGORITHMS

Department of
Computer Science & Engineering

[Link].
in
Pass
Working of Bubble Sort.
1: Pass
50 40 30 20 10 2:
40 30 20 10 50

40 50 30 20 10
30 40 20 10 50

40 30 50 20 10
30 20 40 10 50

40 30 20 50 10
30 20 10 40 50
40 30 20 10 50
O
Working of Bubble Sort.
Pass Pass
3: 4:
30 20 10 40 50 20 10 30 40 50

20 30 10 40 50 10 20 30 40 50

20 10 30 40 50

O
BUBBLE SORT
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares
adjacent elements and swaps them if they are in the wrong order. The pass through the list is
repeated until the list is sorted.

Input : a[0] a[1] a[2] a[3]


n 4
40 30 20 10

Pass 1 : a[1] a[2] a[3] Pass 2 : a[1] a[2] a[3]


a[0]
a[0]
40 20 10
a[1] a[2] a[3] 30 10 40
30
a[0] 20
a[1] a[2] a[3]
a[0] Pass 3 :
20 40 10
30 a[1] a[2] a[3] 10 30 40 a[1] a[2] a[3]
a[0] 20 a[0]
20 10 40 20 30 40
30 10
BUBBLE SORT
Pass 1 : Outerloop : i = 0 ; 0 < 3 a[1] a[2] a[3]
Innerloop : j = 0 ; 0 < 4 – 1 – 0 = 3
for(i=0; i< n-1; i++) if ( a[0] > a[0+1] ) a[0]
{ i.e ( 40 > 30 ) true 40 20 10
for(j=0; j< n-1-i; j++) temp = a[0]; // 40 30
{ a[0] = a[0+1]; // 30
if(a[j]>a[j+1]) //asc order a[0+1] = temp; // 40
{ j = 1 (incr) a[1] a[2] a[3]
1 < 3 true a[0]
temp=a[j]; if ( a[1] > a[1+1] )
a[j]=a[j+1]; i.e ( 40 > 20 ) true 20 40 10
a[j+1]=temp; temp = a[1]; // 40 30
} a[1] = a[1+1]; // 20
a[1+1] = temp; // 40 a[1] a[2] a[3]
} j = 2 (incr) a[0]
} 2 < 3 true 20 10 40
if ( a[2] > a[2+1] ) 30
n 4 i.e ( 40 > 10 ) true
temp = a[2]; // 40
a[2] = a[2+1]; // 10
a[1] a[2] a[3] a[2+1] = temp; // 40
j = 3 (incr)
a[0]
3 < 3 false (goes to out loop)
30 20 10
40
Prof. Rajesh kumar S, Dept. of CSE, CITech, Bangalore.
BUBBLE SORT
Pass 2 : Outerloop : i = 1 (incr ) a[1] a[2] a[3]
1 < 3(true)
Innerloop : j = 0 ; 0 < 4 – 1 – 1 = 2 a[0]
for(i=0; i< n-1; i++) if ( a[0] > a[0+1] ) 30 10 40
{ i.e ( 30 > 20 ) true 20
for(j=0; j< n-1-i; j++) temp = a[0]; // 30
a[0] = a[0+1]; // 20 a[1] a[2] a[3]
{ if(a[j]>a[j+1])
a[0+1] = temp; // 30 a[0]
{
j = 1 (incr)
temp=a[j]; 10 30 40
1 < 2 true
a[j]=a[j+1]; 20
if ( a[1] > a[1+1] )
a[j+1]=temp;
i.e ( 30 > 10 ) true
}
temp = a[1]; // 30
}
a[1] = a[1+1]; // 10
}
a[1+1] = temp; // 30
n 4 j = 2 (incr)
2 < 2 false (goes to out loop)
a[1] a[2] a[3]
a[0]
20 10 40
30
BUBBLE SORT
Pass 3 : Outerloop : i = 2 (incr )
2 < 3(true) a[1] a[2] a[3]
for(i=0; i< n-1; i++) Innerloop : j = 0 ; 0 < 4 – 1 – 2 = 1
a[0]
{ if ( a[0] > a[0+1] )
for(j=0; j< n-1-i; j++) i.e ( 20 > 10 ) true 20 30 40
{ temp = a[0]; // 20 10
if(a[j]>a[j+1]) a[0] = a[0+1]; // 10
{ a[0+1] = temp; // 20
temp=a[j]; j = 1 (incr)
a[j]=a[j+1]; 1 < 1 false (goes to out loop)
a[j+1]=temp; Pass 4 : Outerloop : i = 3 (incr )
}
} 3 < 3(false)
} exit nested for loop

n 4

a[1] a[2] a[3]


a[0]
10 30 40
20
#include<stdio.h> for(i=0;i<n-1;i++)
void main() {
{ for(j=0;j<n-1-i;j++)
int i,j,n,a[10],temp; {
printf("Enter the no of if(a[j]>a[j+1])
elements"); {
scanf("%d",&n); temp=a[j];
Bubble sort

a[j]=a[j+1];
printf(" Enter the array a[j+1]=temp;
elements"); }
for(i=0;i<n;i++) }
scanf("%d",&a[i]); }
printf("\nSorted array is : ");
printf("original array is : "); for(i=0;i<n;i++)
printf("%d\t",a[i]);
for(i=0;i<n;i++)
}
printf("%d\t",a[i]);
LINEAR SEARCH & BINARY
SEARCH
Searching
What is Searching ?
Searching is an operation or a technique that helps finds the
place of a given element or value in the list.

What is a Linear Search?


A linear search, also known as a sequential search, is a method of finding an element
within a list. It checks each element of the list sequentially until a match is found or the
whole list has been searched. Works on both sorted and unsorted array elements.

What is a Binary Search?


A binary search technique works only on a sorted array, so an array must be sorted to
apply binary search on the array. It is a searching technique that is better then the
linear search technique as the number of iterations decreases in the binary search.
Prof. Rajesh kumar S, Dept. of CSE, CITech, Bangalore.
Linear Search
n 5 a[0] a[1] a[2] a[3] a[4]
int found = 0; 10 30 100 50 60
for(i=0; i<n; i++)
{ key 50
if(key == a[i])
{ Pass 3:
Pass 1:
found=1; i=2 2<5
i=0 0<5
if(key == a[i]) Pass 2: if(key == a[i])
break; i=1 1<5 i.e( 50 == a[2]) Pass 4:
i.e( 50 == a[0]) i=3 3<5
}
i.e( 50 == 10) false if(key == a[i]) i.e( 50 == 100) false
} i.e( 50 == a[1]) if(key == a[i])
i.e( 50 == a[3])
if(found==1) i = 1 (incr) i.e( 50 == 30) false i = 3 (incr)
i.e( 50 == 50) false
printf(“ location i = 2 (incr) found = 1;
%d",i+1); break;
else ( out of for loop)
printf("element not Output : location 4
found");
Linear Search
#include<stdio.h> for(i=0;i<n;i++)
void main() {
{ if(key == a[i])
int n, i,a [10], key, found=0; {
found=1;
printf(“Enter the no of the
elements");
break;
scanf("%d",&n); }
}
printf(“Enter the elements");
for(i=0;i<n;i++) if(found==1)
scanf("%d",&a[i]); printf("The element found at %d location", i+1);
else
printf("element not found");
printf("enter the key element"); }
scanf("%d",&key);

Prof. Rajesh kumar S, Dept. of CSE, CITech, Bangalore.


Binary Search
low = 0; n 5 a[0] a[1] a[2] a[3] a[4]
high = n – 1; 10 30 40 50 60
while(low<=high)
{ key 30 low 0 hig 4
mid=(low + high)/2; h
if(key == a[mid])
{ Pass 1: while ( 0 <= 4) lo mi hig
found=1; mid = ( 0 + 4 ) / 2 = 2; w d h
break; if ( 30 = = a[mid]) a[ 0 1 2 3 4

} i.e ( 30 = = a[2]) ] 30 40 50 60
10
else if(key < a[mid]) i.e ( 30 = = 40) false
else if ( 30 < 40) true lo hig
high=mid-1; w h
high = mid -1;
else
i.e high = 2 -1 = 1; a[ 0 1 2 3 4
low=mid+1; ] 30 40 50 60
high 1
} 10
Binary Search
low = 0; n 5 a[0] a[1] a[2] a[3] a[4]
high = n – 1; 10 30 100 50 60
key 30
while(low<=high)
{ low 0 high 1
mid=(low + high)/2;
if(key == a[mid]) Pass 2: while ( 0 <= 1)
{ mid = ( 0 + 1 ) / 2 = 0; mi lo high
if ( 30 = = a[mid]) d w
found=1;
break; i.e ( 30 = = a[0]) a[ 0 1 2 3 4
i.e ( 30 = = 10) false ] 30 40 50 60
} 10
else if ( 30 < 10) false
else if(key < a[mid]) else low = mid + 1; lo high
high=mid-1; i.e low = 0 + 1 = 1; w
else
low 1 a[ 0 1 2 3 4
low=mid+1; ] 30 40 50 60
} 10
Binary Search
low = 0; n 5 a[0] a[1] a[2] a[3] a[4]
high = n – 1;
10 30 100 50 60
while(low<=high) key 30
{
mid=(low + high)/2; low 1 hig 1
if(key == a[mid]) h
{
found=1;
break; Pass 3: while ( 1 <= 1) lo hig mi
} mid = ( 1 + 1 ) / 2 = 1; w h d
else if(key < a[mid])
if ( 30 = = a[mid]) a[ 0 1 2 3 4
high=mid-1;
else
i.e ( 30 = = a[1]) ] 30 40 50 60
10
low=mid+1; i.e ( 30 = = 30) true
} found=1;
if (found = = 1) break ;
Printf(“location if (found = = 1)
%d”,mid+1);
location mid + 1;
else
printf(“not found”);
#include<stdio.h> while(low <= high)
void main() {
{ mid=(low + high)/2;
if(key == a[mid])
int n, i, a[10], key, found=0,
{
mid, low, high;
Binary Search
found=1;
printf("enter the size of the break;
array"); }
scanf("%d",&n); else if(key < a[mid])
high=mid-1;
else
printf("enter the ele ents"); low=mid+1;
for(i=0;i<n;i++) }
scanf("%d",&a[i]); if(found==1)
printf("number found at postion :
%d",mid+1);
printf("enter the key
else
element"); printf("number is not found");
scanf("%d",&key);
low=0; }
high=n-1;
Prof. Rajesh kumar S, Dept. of CSE, CITech, Bangalore.
MODULE 3 : ARRAY(2D)

Department of
Computer Science & Engineering

[Link].
in
It is a table of data items of similar datatype (same
datatype) with two subscripts stored contiguously in
TWO DIMENSIONAL

memory under a single name.


• Declaration:
type array_name [row_size][column_size];
ARRAYS

As with the single-dimensional arrays, each


dimension of the array is indexed from zero to its
maximum size minus one.
the first index selects the row.
the second index selects the column within that row.
Example
Matrix A Memory Layout int
B[3][2]
Col 0 Col 1

3 10 6 Row 00 01
8 0
4 56 7 Row 10 11
9 1
55 20 1 20 21
Row
0
2
B[0][0] 8000
B[0][1] 8004
int A[3][4]; B[1][0] 8008
B[1][1] 8012
B[2][0] 8016
B[2][1]
8020
Memory Size

No of
elements=row_size*col_size;
Memory size=row size*col size*sizeof(datatype)

• Solve these:
• int Marks[30][6];
• float avg[4][5];
• int Marks[30][6];
• char C[20][10];
• float avg[4][5];
Example
INITIALIZATION OF TWO-DIMENSIONAL ARRAYS

At compile time At run time


• Using scanf()
• Full initialization(by (using 2 for loops,
giving list of values) one for row and one
• Full initialization( by for column)
giving values row by
row)
• Full initialization (in
matrix form)
• Partial initialization
• Initialization without size
INITIALIZATION OF TWO-DIMENSIONAL ARRAYS

• Full initialization (by giving list of values)


Syntax:
type array_name[row-size][col-size] = {list of
values};
Example: a[0][0] 1
a[0][1] 2
int a[3][2]={1,2,3,4,5,6};
a[1] 3
[0]
a[1][1] 4
a[2] 5
[0]
a[2][1] 6
INITIALIZATION OF TWO-DIMENSIONAL
ARRAYS
• Full initialization( by giving values row by row)

int a[3][2]={{1,2},{3,4},{5,6}};
1
a[0]
[0]
a[0] 2
[1]
a[1] 3
[0]
a[1] 4
[1]
a[2] 5
[0]
a[2] 6
[1]
INITIALIZATION OF TWO-DIMENSIONAL ARRAYS

• Full initialization( by giving values in Matrix form)

int a[3][2]={ a[0] 11


[0]
{11,21},
a[0] 21
{33,44},
[1]
a[1] 33
{50,60} [0]
}; a[1] 44
[1]
a[2] 50
[0]
a[2] 60
[1]
INITIALIZATION OF TWO DIMENSIONAL ARRAYS

Partial initialization

a[0] 1
int a[3][2]={ {1,2},
[0]
{3} a[0] 2
[1]
}; a[1] 3
[0]
a[1] 0
[1]
a[2] 0
[0]
a[2] 0
[1]
INITIALIZATION OF TWO-DIMENSIONAL
ARRAYS

• Initialization without size


The size may be omitted. In such case, the
compiler allocates enough space for all
elements a[0] 1
int a[ ][2] = {1,1,1,1,1,1}; [0]
a[0] 1
[1]
• row-size=total number of elements/col-size
a[1] 1
• row-size=6/2=3 [0]
a[1] 1
Note: [1]
column size is mandatory. a[2] 1
[0]
a[2] 1
[1]
INITIALIZATION OF TWO-DIMENSIONAL
ARRAYS (Run Time)

An array can be explicitly initialized at


run time.
int a[3][2];
printf(“enter 6 elements”);
scanf("%d%d%d%d%d%d", &a[0]
[0],&a[0][1],&a[1][0],&a[1][1],&a[2]
a[0] 10
[0],&a[2][1]); [0]
Enter 6 elements a[0] 13
[1]
10 13 14 6 90
a[1] 14
23
[0]
OR a[1] 6
[1]
a[2] 90
[0]
INITIALIZATION OF TWO-DIMENSIONAL
ARRAYS (Run Time)

This approach is usually applied for


initializing large arrays. a[0] 10
[0]
int a [3][2] ;
a[0] 13
printf(“Enter array elements”); [1]
for(i=0;i<3;i++) For rows a[1] 14
[0]
{
a[1] 6
for(j=0;j<2;j++) For [1]
{ columns a[2] 90
[0]
scanf("%d", &a[i][j]);
a[2] 23
} Enter array
[1]
} elements
10 13 14 6 90
23
for(i=0;i<3;i++)
i=0
{
j=0 j=2
for(j=0;j<2;j++) j=1 fails

{ i=1 j=2
scanf(“%d”,&a[i][j]);
j=0 fails
j=1
Tracing

j=2
} i=2 i=3
fails
Pass 1: fails
} Passj=0
2:
i=0; 0<3;
j=1i=1; 1<3;
j=0 ; 0<2 ; j=0 ; 0<2 ;
read a[i][j]---- a[0][0] read a[i][j]---- a[1][0]
j++; j=1 j++; j=1
j=1; 1<2; j=1; 1<2;
read a[i][j]---- a[0][1] read a[i][j]---- a[1][1]
j++ ; j=2 j++ ; j=2
j=2 ; 2<2 fails j=2 ; 2<2 fails
i++; i=1 i++; i=2
Tracing
Pass 3: Pass 4
i=3; 3<3 fails
i=2; 2<3;
j=0 ; 0<2 ;
read a[i][j]---- a[2]
[0]
j++; j=1
j=1; 1<2;
read a[i][j]---- a[2]
[1]
j++ ; j=2
j=2 ; 2<2 fails
i++; i=3;
• Declarationint m, n,i, j, a[10]
[10];

printf(“enter
• matrix of size m*n row size and column
size”);
scanf(“%d%d”,&m,&n);
Example

• To read elements

printf(“enter the
elements”);
m is
for(i=0;i<m;i++)
row_size
{ n is
for(j=0;j<n;j++) col_size
{

scanf(“%d”,&a[i][j]);
}
}
MODULE 3 : ARRAY(2D)
EXAMPLES

Department of
Computer Science & Engineering

[Link].
in
Program to Input and Output a matrix of
size m*n

void main() printf(“The elements


{ are”);
int m,n,i,j,a[10][10]; for(i=0;i<m;i++)
printf(“enter row size and
column size”); {
scanf(“%d%d”,&m,&n); printf(“\n”);
printf(“enter the elements”); for(j=0;j<n;j++)
for(i=0;i<m;i++) {
{
printf(“%d\
for(j=0;j<n;j++)
t”,a[i][j]);
{
}
scanf(“%d”,&a[i][j]);
} }
} }
To print array elements
To print in Matrix form
printf(“The elements
are”);
for(i=0;i<m;i++) To start new
{ line after every
row
printf(“\n”);
for(j=0;j<n;j++) To leave space
{ between values
printf(“%d\ in each row
t”,a[i][j]);
}
}
}
Output

enter row size and column size


2 2
enter the elements \t is used
11 22 33 44
The elements are
11 22 \n is used
33 44
void main() for(i=0;i<m;i++)
{ {
int m,n,i,j,a[10][10],big=0; for(j=0;j<n;j++)
printf(“enter row & column {
biggest element in the

size”); if(a[i][j]>big)
Program: to find the

scanf(“%d%d”,&m,&n); big=a[i][j];
}
printf(“enter the }
elements”);
array

printf(“ biggest element is %d


for(i=0;i<m;i++) ”,big);
{ }
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
void main()
{ for(i=0;i<m;i++)
int m,n,i,j,a[10] {
[10],sum=0; for(j=0;j<n;j++)
Program: To find the sum of

printf(“enter row & column size”); {


scanf(“%d%d”,&m,&n); sum=sum+a[i][j];
}
array elements

printf(“enter the
}
elements”);
printf(“The sum is %d
for(i=0;i<m;i++) ”,sum);
{ }
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
void main()
{ for(i=0;i<m;i++)
int m,n,i,j,a[10] {
Program: To find the sum of

[10],sum_sq=0; for(j=0;j<n;j++)
square of array elements

printf(“enter row & column {


size”);
scanf(“%d%d”,&m,&n); sum_sq=sum_sq+a[i]
printf(“enter the [j]*a[i][j];
elements”); }
for(i=0;i<m;i++) }
{ printf(“The sum is %d
for(j=0;j<n;j++) ”,sum);
}
{
scanf(“%d”,&a[i][j]);
}
}
Output:
Program to find biggest and smallest element in
2D array
Hand on Session

1) Program to Input and Output a matrix of size m*n.


2) a)Program: to find the largest/biggest element in the array.
b) Program: to find the smallest element in the array
3) Program: To find the sum of array elements.
4) Program: To find the sum of square of array elements
5) Write a c program to transpose a given matix.
Passing array to functions
MODULE 3 :
CHARACTER ARRAY &
STRINGS

Department of
Computer Science & Engineering

[Link].
in
CHARACTER ARRAYS AND STRINGS

• A string is a sequence of characters that is treated as a single data item.


STRINGS
• Any group of characters (except double quote sign) defined between
double quotations marks is a string constant.

Example:
• "Man is obviously made to think."
DECLARING AND INITIALIZING STRING VARIABLES

Example:
STRINGS
• C does not support strings as a data
type.
We are using char as data type char city [10] ;
Declaration:
• char string_name[size]; char name[30];
• The size determines the number of
characters in the string_name.
When the compiler assigns a character string to a character
array, it automatically supplies a null character ('\0 ') at the end
of the string.
DECLARING AND INITIALIZING STRING
VARIABLES
• Initialization with string constant
STRINGS
char city [9] = " NEW YORK ";
• Initialization with character constant
char city [9]={‘N’, ‘E’, ‘W’,’ ‘,‘Y', '0', 'R', 'K', '\
0'};
• Without size
char string [ ] = {‘G’, ‘O’,’O’, ‘D’ ,'\0'};
• Partial Initialization
char
G
str[10]
O O
= "GOOD";
D \0 \0 \0 \0 \0 \0
Mistakes
• char str2 [3] = "GOOD";
STRINGS
• We cannot separate the initialization from declaration
char str3[5];
str3 = "GOOD";

• char str1[4] = "abc";


char str2 [4];
str2 = str1 ;
STRINGS READING AND PRINTING STRINGS
READING from Terminal Printing to Terminal
• Using scanf Function • Using printf
• Using getchar() Function
• Using gets() • Using putchar()
function • Using puts()
Function
READING STRINGS Using scanf Function
STRINGS
• The input function scanf can be used with %s format
specification to read in a string of characters.

• In the case of character arrays, the ampersand (&) is not


required before the variable name.

• Example:
char address[10];
scanf("%s", address);
Write a program to input and output a
name
void main() • Output:
STRINGS
{
Enter a name
char name[20];
New york
printf(“Enter a name”);
Name is New
scanf(“%s”,name);
printf(“Name is
%s”,name);
}
READING STRINGS Using
getchar
STRINGS
• The getchar function is used to read a single character.

• We can use this function repeatedly to read successive single


characters from the input and place them into a character array.

• Example
char ch;
ch=getchar( ) ;
Write a program to read a line of text (use getchar)
containing a series of words from the terminal.

void main( ) while(character != '\n');


STRINGS
line[i] = '\0';
{ char line[30], character;

int i=0; printf("\n %s \n",


printf(“Enter line of line);Output:
text”);
do { Enter line of text
Hi welcome to C
character = getchar(); }Hi welcome to C
line[i] = character;
0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 …
i++; 0 1 2 3 4 5 6 7
Line H i w e l c o m e t o c \n \0
}
READING STRINGS Using gets()
function
STRINGS
• Another and more convenient method of reading a string
of text containing whitespaces is to use the library
function gets().

• gets function is available in the <stdio.h> header file

• Example
char name[20];
gets(name);
Write a program to input and output a
name
void main() Output:
STRINGS
{ Enter a name
char name[20]; bala guru
printf(“Enter a name”); Name is bala guru
gets(name);
printf(“Name is %s”,name);
}
Differences between gets() and scanf()
gets() scanf()
STRINGS
• It reads characters from the • It reads characters from the
keyboard and terminates its
keyboard until a new-line input on the first white space
character is encountered it finds. It appends a null
and then appends a null character at the end of the
character to the string. string.
• It is formatted input.
• It is unformatted input.
• It is used to input any type of
• It is used to input only data that is integers,
characters and strings characters, floating point
numbers and strings
• Syntax: gets(string) ; • Syntax: scanf(“%s”,string);
• Example: gets(name); • Example: scanf(“%s”,name);
Write a program to find the number of vowels
and consonants in a text string

#include<string.h>
STRINGS
void main() vc++;
{ else
Int i ,vc=0,cc=0; cc++;
char s[100],ch; }
printf(“\n Enter the sentence”); }
gets(s); printf(“\n Vowel count=%d\
for(i=0;i<strlen(s);i++) n”,vc);
{ if(isalpha(s[i])) printf(“\n Consonant count=
%d\n”,cc);
{ Output Enter the
}
ch=tolower(s[i]); sentence
if(ch==’a’||ch==’e’||ch==’i’|| Hi welcome to
ch==’o’||ch==’u’)
C class
Vowel count=6
Consonant
STRINGS Printing the Strings

• Using printf Function


• Using putchar Function
• Using puts Function
Printing Strings Using printf() Function
• printf("%s", name);
STRINGS
char name[]=”good girl”;
• printf(“%10.4s”,name);
g o o d

• printf(“%-10.4s”,name);
g o o d
Printing Strings Using putchar()
Function
STRINGS
char ch = ‘A’;

putchar(ch);

• This function is used repeatedly to output a string of characters


stored in an array using a loop.

• Example:
char name[6] = "PARIS";

for (i=0, i<5; i++)

putchar(name[i]);
Printing Strings Using puts()
Function
• puts ( str );
STRINGS
• Example: program to input and output a name
void main()
{
char name[20];
printf(“Enter a name”);
gets(name);
puts(“Name is”);
puts(name);
}
Differences between puts() and printf()
Puts() Printf()
STRINGS
• This prints the value of • This prints the value of the
string variable and then the
the string variable and cursor will be in the same
then moves the cursor to place after printing.
the beginning of the next • It is formatted output.
line on the screen. • It is used to output any type
• It is unformatted output. of data that is integers,
characters, floating point
• It is used to output only numbers and strings
characters and strings • Syntax:
printf(“%s”,string);
• Syntax: puts(string);
• Example:
• Example: puts(name); printf(“%s”,name);
Operations performed on character
strings
• Reading and writing strings.
STRINGS
• Combining strings together.
• Copying one string to
another.
• Comparing strings for
equality.
• Extracting a portion of a
string
STRING HANDLING FUCTIONS
• strcat( ) - Concatenates two strings
STRINGS
• strcmp( ) -Compares two strings
• strcpy( ) - Copies one string over another
• strlen( ) - Finds the length of a string
• strrev()- Reverses a string
• strncat()- Concatenates first leftmost n
characters of string2 to string1
STRING HANDLING FUCTIONS
• strncmp()- Compares first leftmost n characters in both
STRINGS
strings

• strncpy()- Copies first leftmost n characters of source string


to target

• strstr()- Searches for string2 in string1

• strchr()- Locate the first occurrence of the character

• strrchr()- Locate the last occurrence of the character


Function : strlen( )
• This function counts • Example:
and returns the • str1---- RAMA
number of characters
in a string. • strlen(str1);
• Syntax:
n = strlen(string); • Return value 4
Here n is a integer • n=strlen(str1);
variable. • n=4
This function returns • Print n value
integer value.
Example : strlen( )
#include<stdio.h>
#include<string.h>
• Output
void main()
{ Enter a string
char s1[20]; Hi hello
int n; Length of the
printf("Enter a string is 8
string:");
gets(s1);
n=strlen(s1);
It excludes null
character.
printf("Length of the
string is %d",n);
}
Function : strrev( )
• This function • Example
reverses the • str---- cake
string.
• Syntax • strrev(str);

• ekac--- >str
strrev(string
• print str
);
The reversed
string is stored
in the string
itself.
Example : strrev( )
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20]; • Output
printf("Enter a Enter a string:abcd
string:");
Reversed string is
gets(s1); dcba
strrev(s1);
printf("Reversed
string is %s",s1);
}
Function : strcpy( )
• The strcpy function • Examples:
works almost like a
string-assignment char city[20],
city2[30];
operator.

strcpy(city, "DELHI");
Syntax:
strcpy(string1, strcpy(city2, city);
string2);
The size of the array
• It assigns the city2 should be large
contents of string2 enough to receive the
to string1 contents of city.
Program to copy one string to other string

#include<stdio.h>
#include<string.h>
void main() • Output:
{ Enter a
char s1[20],s2[20]; string:hello class
printf("Enter a Copied string is
string:");
hello class
gets(s1);
strcpy(s2,s1);
printf("Copied string is
%s",s2);
}
Program to copy first 5 characters of
string1 to string2

#include<stdio.h>
#include<string.h>
void main() • Output
{
char s1[20],s2[20]; Enter a string:
printf("Enter a hello class
string:");
gets(s1);
Copied string is
hello
strncpy(s2,s1,5);
printf("Copied string
is %s",s2);
}
strcat()
• The strcat functions • Example:
joins two strings
together. srt1
H i \o
• Syntax:
strcat(string1,string2);
str2
B y e \0
• When the function
strcat is executed
string2 is appended to
string1 strcat(str1,str2);
• We must make sure that str1
H i B y e \0
the size of string1 (to
which string2 is
appended) is large str2
enough to accommodate B y e \0
the final string.
Program to concatenate two strings

#include<stdio.h> • Output
#include<string.h>
void main()
{
Enter string1:
char s1[20],s2[20];
great
printf("Enter string1:"); Enter string2:
gets(s1); day
printf("Enter string2:"); concatenated
gets(s2); string is
strcat(s1,s2); greatday
printf("concatenated
string is %s",s1);
}
strncat()
• This function will • Example:
concatenate the S1
left-most n h i
characters of s2
to the end of s1 S2
• strncat (sl, s2, f r i e n d s
n); strncat (S1, S2, 3);
S1
h i f r i
Program to concatenate two
strings(n)
#include<stdio.h>
#include<string.h> • Output:
void main() Enter
{ string1:good
char s1[20],s2[20];
Enter
printf("Enter string1:"); string2:morning
gets(s1);
concatenated
printf("Enter string2:");
string is
gets(s2); goodmor
strncat(s1,s2,3);
printf("concatenated
string is %s",s1);
}
strcmp()
• The strcmp function compares two strings and
returns value 0 if they are equal. If they are not,
it has the numeric difference between the first
non matching characters in the strings.
• Syntax:
strcmp(string1, string2);
• string1 and string2 may be string variables or
string constants.
strcmp(namel, name2);
strcmp(namel, “Sam");
strcmp("Rom", "Ram");
The strcmp( ) function returns
integer value.
return 0 If both strings are same

return If string1 is
negative alphabetically above
string2.

return If string1 is
positive alphabetically below
string2.

Prof. Bhagyashree Ambore, Dept. of CSE,


CITech, Bangalore
Program to compare 2 strings

#include<stdio.h>
#include<string.h>
void main()
{
char s1[20],s2[20]; Output:
int k;
printf("Enter string1:"); Enter string1: good
gets(s1); Enter string2: good
printf("Enter string2:");
gets(s2); same strings
k=strcmp(s2,s1);
if(k==0)
printf("same strings");
else
printf("not same");
}
strncmp()
• This function compares
the left-most n
characters of s1 to s2
and returns the integer. Example
• strncmp (sl, s2, n); • S1 ---- hello class
• S2 ---- hello world
• a) 0 if they are equal; • strncmp(s2,s1,5);
• (b) negative number, if
s1 sub-string is less
• Returns 0
than s2(alphabetically
above);
• (c) positive number,
otherwise.
Program to compare 2 sub strings

#include<stdio.h>
#include<string.h>
void main()
{ Output
char s1[20],s2[20];
int k;
Enter string1:hello
printf("Enter string1:"); class
gets(s1); Enter string2:hello
printf("Enter string2:");
gets(s2);
world
k=strncmp(s2,s1,5); Same strings
if(k==0)
printf("same strings");
else
printf("not same");
}
strstr( )
• The function strstr Example:
searches the string s2
in s1. • S1----ABCDE
• If yes, the function • S2----ABC
returns the position of • strstr(S1, S2)-----0
the first occurrence of • Strstr(S1,”ABC”)--
the sub-string. -0
Otherwise, it returns a
NULL pointer.
• strstr (s1, s2);
Program to find the substring
#include<stdio.h>
#include<string.h>
void main()
Output
{
char s1[20],s2[20]; Enter string1:good
printf("Enter string1:"); for good
gets(s1); Enter string2:for
printf("Enter string2");
gets(s2);
s2 is a substring of
if (strstr (s1, s2) == NULL)
s1
printf("substring is not
found");
else
printf("s2 is a substring of
s1");
}
Write a program to check if the input string
is palindrome or not.
#include<stdio.h>
#include<string.h>
void main()
{ Output:
char s1[20],s2[20];
printf("Enter a string:"); Enter a string:
gets(s1);
strcpy(s2,s1);
Malayalam
strrev(s2);
if(strcmp(s1,s2)==0)
string is
printf("string is a palindrome
palindrome");
else
printf("string is not a
palindrome");
}
Lab 8
Develop C
prog to find
the length,
combine
strings and
compare
strings
Lab 7 : Design and Develop a C program using pointers to compute the sum,
mean and standard deviation of all elements stored in an array of n real
numbers
Program: Write a C program to multiply two 2D matrix with all necessary conditions.
Trace:
Program to check if a string is palindrome or
not
Program to check if a number is
palindrome or not
MODULE 4 :PASSING 1D
ARRAY AS A PARAMETER ,
PASSING 2D ARRAY AS A
PARAMETER.

Department of
Computer Science & Engineering

[Link].
in
Passing Arrays to Functions

Passing One Dimensional Arrays to Functions


int a[4]={11,12,13,14};
The name of the array represents the address of its first
element. By passing the array name, we are, in fact,
passing the address of the array to the called function.
Ex: display(a);
Mention the size of the array like:
display(a,4);
Department of Computer Science &
Engineering [Link]
Passing One Dimensional Arrays to Functions

The array in the called function refers to the same array


stored in the memory. Therefore, any changes in the array
in the called function will be reflected in the original array.
1. The function must be called by passing only the name of
the array.
2. In the function definition, the formal parameter must be
an array type; the size of the array does
not need to be specified (optional).
3. The function prototype must show that the argument is
an array.
Department of Computer Science &
Engineering [Link]
Example 1
void display(int a[], int n);
void display(int a[], int n)
void main()
{
{
int i;
int i,a[10], n; printf(“ array
elements”);
printf(“enter n”);
scanf(“%d”,&n); for(i=0;i<n;i++)
printf(“enter elements”); printf(“%d \t”, a[i]);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
}
display(a,n);
}
Department of Computer Science &
Engineering [Link]
Example 2
void bubblesort(int a[], int n);
void bubblesort(int a[ ],int n)
void main() {

{ inti, j, t;
int i,a[10];
for(i=0;i<n-1;i++)
printf(“enter n”); {
for(j=0;j<n-1-i;j++)
scanf(“%d”,&n);
{
printf(“enter elements”); if(a[j] >a[j+1])
for(i=0;i<n;i++)
scanf(“%d”,&a[i]); {
t=a[j];
printf("before sorting\n");
a[j]=a[j+1];
a[j+1] = t;
for(i = 0; i< n; i++)
printf("%d\t ",a[i]); }
bubblesort (a,n); }
} [Link]
printf("after sorting\n");
Passing Two Dimensional Arrays to Functions

•The functions must be called by passing only the array


name.
•In the function definition, we must indicate that the
array has two-dimensions by including two sets of
brackets.
•The size of the second dimension must be specified
(compulsory), whereas the size of the first dimension is
optional.
•The prototype declaration should be similar to the
function header.
Department of Computer Science &
Engineering [Link]
Example
void display(int a[][], int m,
void main() int n)
{ {
int m,n,i,j,a[10][10];
int I ,j;
printf(“enter the row size and column printf(“ array elements
size”); are”);
scanf(“%d%d”,&m,&n);
for(i=0;i<m;i++)
printf(“enter elements”);
for(i=0;i<m;i++) {
{ printf(“\n”);
for(j=0;j<n;j++)
{ for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]); {
}
printf(“%d \t”,
}
a[i][j]);
display(a,m,n);
} Department of Computer Science & }
Engineering [Link]
}
Passing Strings to
functions
Basic rules:
[Link] string to be passed must be declared as a formal argument of the function
when it is defined. The size of the dimension is optional.
void display(char name[])
{

}
2. The function prototype may show that the argument is a string. The size of the
dimension is optional.
For the above definition, the prototype can be written as
void display(char name[]);
3. A call to the function must have a sting name without subscripts as its actual
argument.
display(sname); where name is a properly declared string array in the calling
function.
Department of Computer Science &
Engineering [Link]
Example

void display(char name[]); void display(char name[])


void main() {
{ printf(“the string is
char sname[20]; %s”,name);
printf(“enter name”); }
gets(sname);
display(sname);
}
Department of Computer Science &
Engineering [Link]
Thank you

You might also like