Understanding One-Dimensional Arrays
Understanding One-Dimensional Arrays
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
• Example:
20 12 34 56 78 28 num[6]
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
]
• 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
INITIALIZATION
(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
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
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.
n 4
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.
} 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
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
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
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
{ 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
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(“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
Department of
Computer Science & Engineering
[Link].
in
CHARACTER ARRAYS AND STRINGS
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";
• 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.
• Example
char ch;
ch=getchar( ) ;
Write a program to read a line of text (use getchar)
containing a series of words from the terminal.
• 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
• printf(“%-10.4s”,name);
g o o d
Printing Strings Using putchar()
Function
STRINGS
char ch = ‘A’;
putchar(ch);
• Example:
char name[6] = "PARIS";
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
• 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.
#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
{ 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