Contents
Arrays
⮚ Introduction to Arrays:
⮚ 2-D Arrays:
⮚ Strings:
⮚ Basic Algorithms using Arrays: Numerical Algorithms:
1
INTRODUCTION OF ARRAYS
▪ Definition: An array is a collection of elements of the same type that are
referenced by a common name.
▪ Compared to the basic data type (int, float & char) it is an aggregate or
derived data type.
▪ All the elements of an array occupy a set of contiguous memory locations.
▪ Why need to use array type?
▪ Consider the following issue:
"We have a list of 1000 students' marks of an integer type. If using the
basic data type (int), we will declare something like the following…"
int studMark0, studMark1, studMark2, ..., studMark999;
ARRAYS
▪ Can you imagine how long we have to write the declaration part
by using normal variable declaration?
int main(void)
{
int studMark1, studMark2, studMark3, studMark4, …, …, studMark998,
stuMark999, studMark1000;
…
…
return 0;
}
ARRAYS
▪ By using an array, we just declare like this,
int studMark[1000];
▪ This will reserve 1000 contiguous memory locations for storing the students’ marks.
▪ Graphically, this can be depicted as in the following figure.
ARRAYS
▪ This absolutely has simplified our declaration of the variables.
▪ We can use index or subscript to identify each element or location in the
memory.
▪ Hence, if we have an index of jIndex, studMark[jIndex] would refer to
the jIndexth element in the array of studMark.
▪ For example, studMark[0] will refer to the first element of the array.
▪ Thus by changing the value of jIndex, we could refer to any element in the
array.
▪ So, array has simplified our declaration and of course, manipulation of the
data.
// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
} 6
printf("Displaying integers: ");
// printing elements of the array
for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
// Program to find the average of n numbers using arrays
#include <stdio.h>
int main() {
int marks[10], i, n, sum = 0;
double average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i < n; ++i) {
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the7 user to the sum variable
sum += marks[i];
}
// explicitly convert the sum to double
// then calculate average
average = (double) sum / n;
printf("Average = %.2lf", average);
return 0;
ARRAYS- One Dimensional Array: Declaration
▪ Dimension refers to the array's size, which is how big the array is.
▪ A single or one-dimensional array declaration has the following form,
array_element_data_type array_name[array_size];
▪ Here, array_element_data_type define the base type of the array, which is the
type of each element in the array.
▪ array_name is any valid C / C++ identifier name that obeys the same rule for
the identifier naming.
▪ array_size defines how many elements the array will hold.
ARRAYS- 1D
▪ For example, to declare an array of 30 characters, that
construct a people name, we could declare,
char cName[30];
▪ Which can be depicted as follows,
▪ In this statement, the array character can store up
to 30 characters with the first character occupying
location cName[0] and the last character
occupying cName[29].
▪ Note that the index runs from 0 to 29. In C, an
index always starts from 0 and ends with array's
(size-1).
▪ So, take note the difference between the array size
and subscript/index terms.
ARRAYS- 1D
▪ Examples of the one-dimensional array declarations,
int xNum[20], yNum[50];
float fPrice[10], fYield;
char chLetter[70];
▪ The first example declares two arrays named xNum and yNum of type int. Array xNum can
store up to 20 integer numbers while yNum can store up to 50 numbers.
▪ The second line declares the array fPrice of type float. It can store up to 10 floating-point
values.
▪ fYield is basic variable which shows array type can be declared together with basic type
provided the type is similar.
▪ The third line declares the array chLetter of type char. It can store a string up to 69
characters.
▪ Why 69 instead of 70? Remember, a string has a null terminating character (\0) at the end, so
we must reserve for it.
ARRAYS - 1D Array Initialization
▪ An array may be initialized at the time of declaration.
▪ Giving initial values to an array.
▪ Initialization of an array may take the following form,
type array_name[size] ={a_list_of_value};
▪ For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};
▪ The first line declares an integer array idNum and it immediately assigns the values 1, 2, 3, ..., 7 to
idNum[0], idNum[1], idNum[2],..., idNum[6] respectively.
▪ The second line assigns the values 5.6 to fFloatNum[0], 5.7 to fFloatNum[1], and so on.
▪ Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to chVowel[1], and so
on. Note again, for characters we must use the single apostrophe/quote (') to enclose them.
▪ Also, the last character in chVowel is NULL character ('\0').
▪ Initialization of an array of type char for holding strings may take the following form,
char array_name[size] = "string_lateral_constant";
▪ For example, the array chVowel in the previous example could have been written more compactly as
follows,
char chVowel[6] = "aeiou";
▪ When the value assigned to a character array is a string (which must be enclosed in double quotes), the
compiler automatically supplies the NULL character but we still have to reserve one extra place for the
NULL.
▪ For unsized array (variable sized), we can declare as follow,
char chName[ ] = "Mr. Dracula";
1-D Array Representation
Char Address 100 101 102 103 104
Arr[5]
Data Item A B C D E
Array
Arr[0] Arr[1] Arr[2] Arr[3] Arr[4]
Index
Int Address
A[5]
Unit 1. Introduction
100 102
13
104 106 108
Data Item 10 20 30 40 50
Array
A[0] A[1] A[2] A[3] A[4]
Index
1D Array Address Calculation
• Address of A[I] = B + W * (I – LB)
• I = Element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LB = Lower Limit/Lower Bound of subscript(If not specified assume zero).
14
1D Array Address Calculation
• Address of A[I] = B + W * (I – LB)
• Given the base address of an array A[1……50] as 1000 and the size of each element is 2 bytes in the
memory, find the address of A[20]?
Solution: Given:
Base address B = 1000
Lower Limit/Lower Bound of subscript LB = 1
Storage size of one element store in any array W = 2 Byte
Element whose address to be found I = 20
Unit 1. Introduction 15
• Formula:
Address of A[I] = B + W * (I – LB)
• Solution: Address of A[20] = 1000 + 2 * (20 – 1)
= 1000 + 2 * (19) = 1000 + 38
Address of A[20] = 1038
1D Array Address Calculation
• Address of A[I] = B + W * (I – LB)
• Given the base address of an array A[100……200] as 2000 and the size of each element is 2 bytes in the
memory, find the address of A[115]?
Solution: Given:
Base address B = 2000
Lower Limit/Lower Bound of subscript LB = 100
Storage size of one element store in any array W = 2 Byte
Element whose address to be found I = 115
• Formula:
Address of A[I] = B + W * (I – LB)
• Solution: Unit 1. Introduction 16
Address of A[115] = 2000 + 2 * (115 – 100)
= 2000 + 2 * (15)
= 2000 + 30
Address of A[115] = 2030
1D Array Address Calculation
• Address of A[I] = B + W * (I – LB)
• Given the base address of an array A[1300…………1900] as 1020 and the size of each element is 2
bytes in the memory, find the address of A[1700]?
1D Array Address Calculation
• Address of A[I] = B + W * (I – LB)
• Given the base address of an array A[1300…………1900] as 1020 and the
size of each element is 2 bytes in the memory, find the address of A[1700]?
Given:
Base address B = 1020
Lower Limit/Lower Bound of subscript LB = 1300
Storage size of one element store in any array W = 2 Byte
Subset of element whose address to be found I = 1700
• Formula:
Address of A[I] = B + W * (I – LB)
• Solution:
Unit 1. Introduction 18
Address of A[1700] = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * (400)
= 1020 + 800
Address of A[1700] = 1820
Programs on ARRAYS- 1D
▪ Arrays allow programmers to group related items of the same data type in one variable.
▪ However, when referring to an array, one has to specify not only the array or variable
name but also the index number of interest.
▪ Program example 1: Sum of array’s element.
▪ Notice the array's element which is not initialized is set to 0 automatically.
Programs on ARRAYS- 1D
▪ Program example 2: Searching the smallest value.
▪ Finding the smallest element in the array named fSmallest.
▪ First, it assumes that the smallest value is in fSmallest[0] and assigns it to the variable
nSmall.
▪ Then it compares nSmall with the rest of the values in fSmallest, one at a time.
▪ When an element is smaller than the current value contained in nSmall, it is assigned to
nSmall. The process finally places the smallest array element in nSmall.
Programs on ARRAYS- 1D
▪ Program example 3:
▪ Program example 4: Searching the
Searching the
location for the given value in an array
biggest value. By
modifying the
previous example we
can search the
biggest value.
Programs on ARRAYS- 1D
▪ Program example ▪ Program example 6:
5: Storing and Storing and reading array
reading a string content and its index
ARRAYS- Two Dimensional/2D Arrays
▪ A two dimensional array has two subscripts/indexes.
▪ The first subscript refers to the row, and the second, to the column.
▪ Its declaration has the following form,
data_type array_name[1st dimension size][2nd dimension size];
▪ For examples,
int xInteger[3][4];
float matrixNum[20][25];
▪ The first line declares xInteger as an integer array with 3 rows and 4 columns.
▪ Second line declares a matrixNum as a floating-point array with 20 rows and 25
columns.
ARRAYS- 2D
▪ If we assign initial string values for the 2D array it
will look something like the following,
char Name[6][10] = {"Mr. Bean", "Mr.
Bush", "Nicole", "Kidman", "Arnold",
"Jodie"};
▪ Here, we can initialize the array with 6 strings,
each with maximum 9 characters long.
▪ If depicted in rows and columns it will look
something like the following and can be
considered as contiguous arrangement in the
memory.
ARRAYS- 2D
▪ Take note that for strings the null character (\0) still needed.
▪ From the shaded square area of the figure we can determine the size of the array.
▪ For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the number of the
colored square. In general, for
array_name[x][y];
▪ The array size is = First index x second index = xy.
▪ This also true for other array dimension, for example three dimensional array,
array_name[x][y][z]; => First index x second index x third index = xyz
▪ For example,
ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.
▪ And if you want to illustrate the 3D array, it could be a cube with wide, long and height
dimensions.
2D Array Representation
Column 0 Column 1 Column 2
Int X[3][3]={1,2,3,4,5,6,7,8,9} Row 0 X[0][0] X[0][1] X[0][2]
Row 1 X[1][0] X[1][1] X[1][2]
Row 2 X[2][0] X[2][1] X[2][2]
1 2 3
4 5 6
7 8 9
2D String Array Representation
Col0 Col1 Col2 Col3 Col4
char X[5][5]={COEP, PICT, VIT,
SCOE,SITS}
Row 0 C O E P
Row 1 P I C T
Row 2 V I T
Row 3 S C O E
Row 4
27
S I T S
Address Calculation of any element in the 2-D array:
• To find the address of any element in a 2-Dimensional array there
are the following two ways-
–Row Major Order
• The elements of an array are being stored in a Row-Wise
fashion.
–Column Major Order
• The elements of an array are being stored in a Column-Wise
fashion.
Address Calculation of any element in the 2-D array:- Row Major
• Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
• I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as
zero),
N = Number of column given in the matrix.
Address Calculation of any element in the 2-D array:
• Example: Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1 Byte in memory. Find
the address of arr[8][6] with the help of row-major order?
• Solution:
• Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix ,LR = 1
Lower Limit of column/start
Unit 1. column
Introduction index of matrix,LC = 1 30
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1 = 15
• Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Address Calculation of any element in the 2-D array:
• Solution:
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210
Address Calculation of any element in the 2-D array:
• Example: Given an array, arr[0…15][0………20] with base value 500 and the size of each element is 2 Bytes in memory. Find the
address of arr[8][9] with the help of row-major order?
• Solution:
• Given:
Base address B = 500
Storage size of one element store in any array W = 2 Bytes
Row Subset of an element whose address to be found, I = 8
• Column Subset of an element whose address to be found, J = 9
Lower Limit of row/start
Unit 1.
rowIntroduction
index of matrix ,LR = 0 32
Lower Limit of column/start column index of matrix, LC = 0
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 20 – 0 + 1 = 21
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Address Calculation of any element in the 2-D array:
• Solution:
Address of A[8][9] = 500 + 2 * (( 8– 0) * 21 + (9 – 0))
= 500 + 2 * ((8) * 21 + (9))
= 500 + 2 * (177)
Address of A[I][J] = 854
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Address Calculation of any element in the 2-D array:- Column Major
• Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
• I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume
it as zero),
LC = Lower Limit of column/start column index of matrix(If not given
Unit 1. Introduction 34
assume it as zero),
M = Number of rows given in the matrix.
Address Calculation of any element in the 2-D array:- Column Major
• Example: Given an array arr[1………10][1………15] with base value 100 and the size of each element
is 2 Bytes in memory find the address of arr[7][7] with the help of column-major order.
• Solution:
• Given:
Base address B = 100
Storage size of one element store in any array W = 2 Bytes
Row Subset of an element whose address to be found I = 7
Column Subset of an element whose address to be found J = 7
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
• Number of rows given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
• Formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address of A[7][7] = 100 + 2 * ((7 – 1) * 10 + (7 – 1))
= 100 + 2 * ((6) * 10 + (6))
= 100 + 2 * (66)
Address of A[I][J] = 232
Address Calculation of any element in the 2-D array:- Column Major
• Example: Given an array arr[5………15][1………15] with base value 200 and the size of each element
is 2 Bytes in memory find the address of arr[10][10] with the help of column-major order.
• Solution:
• Given:
Base address B = 200
Storage size of one element store in any array W = 2 Bytes
Row Subset of an element whose address to be found I = 10
Column Subset of an element whose address to be found J = 10
Lower Limit of row/start row index of matrix LR = 5
Lower Limit of column/start column index of matrix = 1
• Number of rows given in the matrix M = Upper Bound – Lower Bound + 1
= 15– 5 + 1
= 11
• Formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address of A[10][10] = 200 + 2 * ((10 – 1) * 11 + (10 – 5))
= 200 + 2 * ((9) * 11 + (5))
= 200 + 2 * (104)
Address of A[I][J] = 408
Programs on 2D ARRAYS
▪ Program example 7: ▪ Program example 8:
Storing and reading array Swapping iIndex (iRow) with
content and its index jIndex (iColumn) in the
previous program example
Programs on 2D ARRAYS
1. Program example 9: Strings are read in by the rows.
2. Each row will have one string. Enter the following data:
“you”, “are”, “cat” for the following example.
3. Remember that after each string, a null character is added.
4. We are reading in strings but printing out only characters.
Contents
⮚ Strings:
⮚ Basic Algorithms using Arrays: Numerical Algorithms:
39
Strings Basics
• Strings are defined as an array of characters.
• The difference between a character array and a string is the
string is terminated with a special character ‘\0’.
• Eg.
• char arr[ ] =“Hello”;
Declaration of strings
• Declaring a string is as simple as declaring a one-dimensional array.
Below is the basic syntax for declaring a string.
char str_name[size];
e.g.
char stud_marks[60];
Initializing a String
□ char string1[ ]=“Hello”
□ char string1[ 6]=“Hello”
□ char string1[
]={‘H’,’e’,’l’,’l’,’o’,’\0’}
□ char
string2[10]={‘H’,’e’,’l’,’l’,’o’,’\0’}
NULL terminated Strings
□ When the compiler encounters a sequence of characters enclosed in the double
quotation marks, it appends a null character \0 at the end by default.
□ For example –
char c[ ] = "c string";
□ ‘\0’ is null character , it tells where string
ends .
□ ‘\0’ and ‘0’ are different.
Reading and Writing String
getchar( ) and putchar( )
function
• int getchar(void); • int putchar(int c);
• This function reads only • This function prints only
single character at a time. single character at a time
• function reads the character • function puts the passed
from the screen and returns it character on the screen and
as an integer. returns the same character.
Sample Program
#include <stdio.h>
int main( )
{
Enter a value :
int c;
this is test
printf( "Enter a value :");
You entered: t
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
return 0;
}
gets( ) and puts( )
function
Puts()
•Gets() □ It displays single or multiple characters of
□ It accepts single or multiple characters of string including spaces to the standard
Input device.
string including spaces from the standard Input device.
□ Syntax:
□ Syntax:
puts(variable_name);
• gets(variable_name);
e.g. char
• e.g. char ch[10]; gets(ch);
ch[10]=“Welcome";
• □ It reads any characters ,space , tabs from standard puts(ch);
input device.
□ It display string to the screen.
Sample Program
#include <stdio.h>
int main( )
{
char str[100]; Enter a value : This is VIT
printf( "Enter a value You entered: This is VIT
:"); gets( str );
printf( "\nYou entered:
"); puts( str );
return 0;
}
getch( ) and putch( )
function
• getch() is a nonstandard function • putch() is a nonstandard function
and is present in conio.h header file and is present in conio.h header file
which is mostly used by MS-DOS which is mostly used by MS-DOS
compilers like Turbo C compilers like Turbo C
• This function is used to Accept one • This function is used to print one
character , from keyboard ,without character ,on the screen
echo to the screen
• Without echo means when we type
on screen it is not visible.
#include<stdio.h>
#include<conio.h>
void main()
{
Press any character:
char ch; Pressed character is: e
printf(“Press any character:
”); ch = getch();
Note: while using getch() pressed character is not
printf(“\nPressed character echoed. Here pressed character is e and it is displayed
is:”); putch(ch); by putch().
getch(); /* Holding output */
}
getche( ) Function
• This function is used to Accept one character , from keyboard ,echo
to the screen
• This Function also takes One Character as an input
#include<stdio.h>
Output:
void main Enter the Character:
B Character was B
{
char var1;
printf("Enter The Character:");
var1 = getche(); // echo to the screen
printf("Character was %c",var1");
}
Reading and printing string using scanf and
printf
#include<stdio.h>
int main()
• Scanf is not capable of receiving multiple-word
{ strings
char name[30]; • Therefore we cannot use string which contains spaces
printf(“enter your and multiple words
• Hello Welcome to VIT //not acceptable
name:”); scanf(“%s”,
&name);
printf(“%s”,
name); return 0;
}
String library functions
□ The C library offers a wide array of functions for string operations.
□ Library function are define in string.h header file.
Functions
strcat( ) Function to concatenate(merge) strings.
strcmp( ) Function to compare two strings.
strcpy( ) Function to copy a string to another string.
stricmp( ) Function to compare two strings ignoring their case.
strlen( ) Function to calculate the length of the string.
strlwr( ) Converts the given string to lowercase.
strrev( ) Function to reverse the given string.
Functions
•strupr( ) Converts the given strrchr(
string to uppercase. strdup( ) ) strstr(
Duplicates a string. ) strset(
)
•strnicmp( ) Compares the first n characters of one string to another
without being case sensitive.
strncat( ) Adds the first n characters at the end of second
strncpy( string. Copies the first n characters of a string into
strchr( ) Finds the first occurrence of the
) another.
character. Finds the last occurrence of the character.
Finds the first occurrence of string in another string.
strnset ( Sets all the characters of the string to a given
) character.
Sets first n characters of the string to a given
character.
strlen( ) function
• The strlen() function calculates the length of a given string.
• The strlen() function is defined in string.h header file. It doesn’t count null
character ‘\0’.
□ Syntax:
int no=strlen(s1)
□ Ex:
char s1[12] = "Hello";
strlen(s1);
Sample
program
#include<stdio.h>
#include <string.h>
int main() Output :
{ Length of string is:
char ch[]={‘h', 'e', ‘l', ‘l', ‘o', '\0'}; 5
printf("Length of string is: %d",
strlen(ch)); return 0;
}
strcat( ) function
• The strcat() function is used for string concatenation. It concatenates
the specified string at the end of the another string
□ Syntax:
strcat(s1, s2)
It Concatenate string s2 onto the end of string s1
□ char str1[12] =
Ex: "Hello"; char str2[12] =
"World"; strcat(str1,
str2);
Sample program
#include <stdio.h>
#include <string.h>
int main ( ) Output: strcat( str1,
{ str2): HelloWorld
char str1[12] =
"Hello"; char str2[12]
= "World"; strcat( str1, %s\n", str1 );
str2); printf("strcat(
str1, str2): return 0;
}
strcpy( ) function
• strcpy() is used to copy one string to another. In C it is present in string.h header
file
□ Syntax:
strcpy(destinationstring,
sourcestring) It Copies sourcestring into
destinationstring
□ Ex: char str1[12] =
"Hello"; char str3[12];
strcpy(str3, str1);
Sample program
#include <stdio.h>
#include <string.h>
int main ( )
{
char str1[12] = Output: strcpy( str3, str1) :
"Hello"; char str2[12]
Hello
= "World"; char
str3[12];
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3
); return 0;
strcmp( ) function
• This function takes two strings as arguments and compare these two strings
□ strcmp(s1, s2): Returns 0 if s1 and s2 are the same; less
than 0 if s1<s2;
greater than 0 if s1>s2.
□ Syntax:
int no = strcmp(s1,s2);
□ Ex: char str1[12] = "Hello";
char str2[12] = "World";
strcmp(str1, str2);
This will return difference of ASCII value of first unmatched characters in both
strings.
#include <stdio.h>
#include <string.h>
int main () {
char str1[15];
char str2[15];
int ret;
strcpy(str1, "abcdef"); strcpy(str2,
"ABCDEF"); ret = strcmp(str1, str2); Output: str2 is less than
if(ret < 0) { str1
printf("str1 is less than str2");
} else if(ret > 0) {
printf("str2 is less than str1");
} else {
printf("str1 is equal to str2");
}
THANK YOU
64
Vishwakarma Institute of Technology, Pune