Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 59

Programming and Data Structures

Debasis Samanta
Computer Science & Engineering
Indian Institute of Technology Kharagpur
Spring-2017
Lecture #4
Arrays and Strings

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Today’s Discussion…
*Arrays * Strings
* Basic concept * Basic concepts
* 1-Dimensional Arrays * Declaration of strings in C
* Declaration of 1-D arrays in C programs * Initialization of a string
* Initialization of 1-D arrays * C-library functions for strings
* Some C programs dealing with 1-D arrays * Some C-programs with strings
* 2-Dimensional Arrays
* Declaration of 2-D arrays in C programs
* Initialization of 2-D arrays
* Some C programs dealing with 1-D arrays

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Arrays

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Some Examples of Arrays

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Basic Concept
• Many applications require multiple data items that have common
characteristics.

• In mathematics, we often express such groups of data items in indexed


form
x1, x2, x3, …, xn

• Why are arrays essential for some applications?


• Reading some numbers from the keyboard and then
• Sort them in ascending order.
• To find the mode and standard deviation.
etc.
• How such a set of data can be stored in computer and subsequently
process them?
CS 11001 : Programming and Data Structures Lecture #04: © DSamanta
Basic Concept

1-D array

3-D array
2-D array

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


1-D Arrays

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Arrays
• Homogenous data types
• All the data items constituting the group share the same name.
int x[10];
• Individual elements are accessed by specifying the index.

x[0] x[1] x[2] x[9]

x is a 10-element one
dimensional array

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Declaring Arrays
• Like variables, the arrays that are used in a program must be declared
before they are used.

• General syntax:
type array-name [size];
• type specifies the type of element that will be contained in the array (int,
float, char, etc.)
• size is an integer constant which indicates the maximum number of
elements that can be stored inside the array.
Example
int marks[5];
Here, marks is an array containing a maximum of 5 integers.

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Examples
Examples:
int x[10];
char line[80];
float points[150];
char name[35];

• Be careful!
• If we are not sure of the exact size of the array, we can define an array of a large
size.
int marks[50];
there is no element like x[50], x[-1], x[100], etc.

• The following kind of usage is illegal:


int n;
int marks[n];
CS 11001 : Programming and Data Structures Lecture #04: © DSamanta
How an array is stored in memory?
• Starting from a given memory location, the successive array elements
are allocated space in consecutive memory locations.

x x+k x+2k
Here,
• x is the starting address of the array in memory
• The array index starts at zero. That is, the location of a[0] is at x
• Let k is the number of bytes allocated per array element
• Element a[i] is allocated at the memory location having address x + i*k

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


A Warning
• In C, while accessing array elements, array bounds are not checked.

Example:
int marks[5];
:
:
marks[8] = 75;

• The above assignment would not report any error; however, execution will fail.

• Rather, it may result in unpredictable program results.

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Initialization of Arrays
• General form
type array_name[size] = { list of values };

Examples
int marks[5] = {72, 83, 65, 80, 76};
char name[4] = {‘A’, ‘m’, ‘i’, ‘t’};

• Some special cases


• If the number of values in the list is less than the number of elements, then the
remaining elements are automatically set to zero.
float total[5] = {24.2, -12.5, 35.1};
total[0]=24.2, total[1]=-12.5, total[2]=35.1,
total[3]=0, total[4]=0

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Initialization of Arrays
• If the size declares is less than the elements in the initialization, then
the excess elements will be ignored
float total[5] = {2.2, -1.5, 3.5, 0.1, 0.2, 0.4};
The last element namely 0.4 will be ignored!

• The size may be omitted. In such cases the compiler automatically


allocates enough space for all initialized elements.
int flag[] = {1, 1, 1, 0};
char name[] = {‘A’, ‘m’, ‘i’, ‘t’};

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Example 1: Find the minimum of a Set of 10 Numbers

#include <stdio.h>
Array
main()
{
declaration
int a[10], i, min;

for (i=0; i<10; i++) Reading array


scanf (“%d”, &a[i]);
element
min = 99999;

for (i=0; i<10; i++)


{ Assessing array
if (a[i] < min) element
min = a[i];
}
printf (“\n Minimum is %d”, min);
}

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Alternate Version #1

• Change only one line to change the problem size.


#include <stdio.h>
#define size 10

main()
{
int a[size], i, min;

for (i=0; i<size; i++)


scanf (“%d”, &a[i]);

min = 99999;
for (i=0; i<size; i++)
{
if (a[i] < min)
min = a[i];
}
printf (“\n Minimum is %d”, min);
}

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Alternate Version #2

• Define an array of large size and use only the required number of elements.
#include <stdio.h>

main()
{
int a[100], i, min, n;

scanf (“%d”, &n); /* Number of elements */


for (i=0; i<n; i++)
scanf (“%d”, &a[i]);

min = 99999;
for (i=0; i<n; i++)
{
if (a[i] < min)
min = a[i];
}
printf (“\n Minimum is %d”, min);
}

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Example 2: Computing GPA

• Handling two arrays at the same time.


#include <stdio.h>
#define nsub 6

main()
{
int grade_pt[nsub], cred[nsub], i,
gp_sum=0, cred_sum=0, gpa;

for (i=0; i<nsub; i++)


scanf (“%d %d”, &grade_pt[i], &cred[i]);

for (i=0; i<nsub; i++)


{
gp_sum += grade_pt[i] * cred[i];
cred_sum += cred[i];
}
gpa = gp_sum / cred_sum;
printf (“\n Grade point average: is %d”, gpa);
}

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Things You Cannot Do
• You cannot
• Suppose, a and b are two array names.

• They cannot be used as ordinary variables


• use = to assign one array variable to another is not possible
a = b; /* a and b are arrays */

• use == to directly compare array variables is not allowed


if (a == b) ………

• directly scanf or printf arrays is not possible


printf (“……”, a);

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Accessing Array
int a[25], b[25];

• How to copy the elements of one array to another?


• By copying individual elements
for (j=0; j<25; j++)
a[j] = b[j];

• By reading them one element at a time


for (j=0; j<25; j++)
scanf (“%f”, &a[j]);

The ampersand (&) is necessary.


Note:
•The elements can be entered all in one line or in different lines.
CS 11001 : Programming and Data Structures Lecture #04: © DSamanta
Accessing Array
int a[25];
• Printing Array (array elements)

• By printing them one element at a time.


for (j=0; j<25; j++)
printf (“\n %f”, a[j]);

•The elements are printed all in one line (starting with a new line).
printf (“\n”);
for (j=0; j<25; j++)
printf (“%f”, a[j]);

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


2-D Arrays

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Two Dimensional Arrays
• Many applications require us to store a table of values.
Subject 1 Subject 2 Subject 3 Subject 4 Subject 5
Student 1 75 82 90 65 76
Student 2 68 75 80 70 72
Student 3 88 74 85 76 80
Student 4 50 65 68 40 70

• The table contains a total of 20 values, five in each line.

• The table can be regarded as a matrix consisting of four rows and five columns.

• C allows us to define such tables of items by using 2-D arrays.

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Declaring 2-D Arrays
• General form:-
type array_name [row_size][column_size];

• Examples
int marks[4][5];
float sales[12][25];
double matrix[100][100];

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Accessing Elements of a 2-D Array
• Similar to that for 1-D array, but use two indices.
• Examples
x[m][n] = 0;
c[i][k] += a[i][j] * b[j][k];

• First indicates row, second indicates column.

• Both the indices may be expressions which would evaluate to integer


values.
x = sqrt (a[j*3][k+2]);

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Storing a 2-D Array in Memory
• Starting from a given memory location, the elements are stored row-
wise in consecutive memory locations.
x: starting address of the array in memory
c: number of columns
Column
k: number of bytes allocated per array element
0 1 2 3
0

• a[i][j]

Row
:: is allocated memory location at 1

address x + (i * c + j) * k 2

a[0]0] a[0][1] a[0]2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3]
Row 0 Row 1 Row 2

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Reading the Elements of a 2-D Array
• By reading them one element at a time.
for (i=0; i < nrow; i++)
for (j=0; j < ncol; j++)
scanf (“%f”, &a[i][j]);

• The ampersand (&) is necessary.

Note:
• The elements can be entered all in one line or in different lines.

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Printing the Elements of a 2-D Array
• By printing them one element at a time.
for (i=0; i<nrow; i++)
for (j=0; j<ncol; j++)
printf (“\n %f”, a[i][j]);

• The elements are printed one per line.


for (i=0; i<nrow; i++)
for (j=0; j<ncol; j++)
printf (“%f”, a[i][j]);

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Printing the Elements of a 2-D Array
• The elements are printed nicely in matrix form.

for (i=0; i<nrow; i++)


{
printf (“\n”);
for (j=0; j<ncol; j++)
printf (“%f ”, a[i][j]);
}

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Example 1: Reading a Matrix Amxn
• Read the element of a matrix of integers of size mxn

#include <stdio.h>
#define M 10;
#define N 15;
#include <stdio.h>
main ()
main
{ ()
{ int n;
int a[M][N];
scanf("%d",&n);
for (i=0; i<M; i++)
printf("%d\n",n);
} for (j=0; j<N; j++)
scanf("%d",&a[i][j]);
}

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Example 2: Matrix Addition
• Find the sum of two matrix amxn and bmxn anddtore the result in cmxn
#include <stdio.h>
#define m 10;
#define n 15;
#include <stdio.h>
main ()
main ()
{
{
int a[m][n];
int n;
int b[m[n];
scanf("%d",&n);
// Read the array a
printf("%d\n",n);
// Read the array b
}
for (i=0; i<m; i++)
for (j=0; j<m; j++)
c[i][j] = a[i][j]+ b[i][j];
}
CS 11001 : Programming and Data Structures Lecture #04: © DSamanta
Example 3: Matrix Multiplication
• Find the product of two matrices amxp and bpxn and store the result in cmxn
#include <stdio.h>
#define m 10;
#define p 5;
#define n 15;
#include <stdio.h>
main ()
main ()
{
{
int a[m][p]; int b[p[n];
int n;
int c[m][n];
scanf("%d",&n);
// Read the array a, b
printf("%d\n",n);
for (i=0; i<m; i++)
}
for (j=0; j<n; j++)
c[i][j] = 0;
for (k=0; k<p; k++)
c[i][j] = c[i][j]+ a[i][j]* b[i][j];
}

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Arrays Beyond 2-D
• C language allows arrays of three or more dimensions. The general form of a
multi-dimensional array is
type array_name[s1][s2][s3]…[sn];
Here, si is the size of the i-th dimension.

• Examples.
int rainFall [day][month][city];
will store the rainfall data for each day in a year and for a number of cities.

float table[2][3][4] = {{{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}},


……};
declares a 3-D array table with 24 float values and initialize the first and second
rows of the first entries in the third dimension.

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Strings

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Introduction
• A string is an array of characters.
• Individual characters are stored in memory in ASCII code.
• A string is represented as a sequence of characters terminated by the null
(‘\0’) character.

“Hello”  H e l l o ‘\0’

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Character Arrays and Strings
• char C[8] = {‘d',‘e',‘b',‘a',‘s',‘i',‘s','\0'};

• C[0] gets the value ‘d', C[1] the value ‘e', and so on. The last (7th) location
receives the null character ‘\0’.

• Null-terminated character arrays are also called strings.

• Strings can be initialized in an alternative way. The last declaration is


equivalent to
char C[16] = “India is great!";

• The trailing null character is missing here. C automatically puts it at the end.

• Note also that for individual characters, C uses single quotes, whereas for
strings, it uses double quotes.
CS 11001 : Programming and Data Structures Lecture #04: © DSamanta
Declaring String Variables
• A string is declared like any other array:
char string-name [size];

Here, size determines the number of characters in string_name


(including for null character ‘\0’)

• When a character string is assigned to a character array, it


automatically appends the null character (‘\0’) at the end of the string.
char C[16] = “India is great!";

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Examples
char name[30];
char city[15];
char dob[11];

• A string may be initialized at the time of declaration. Equivalent


char city[15] = “Calcutta”;
char city[15] ={‘C’,‘a’,‘l’,’c’,‘u’,‘t’,’t’,‘a’};
char dob[] = “12-10-1975”;

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Reading Strings from the Keyboard
• Two different cases will be considered

• Reading words

• Reading an entire line

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Reading “words”
• scanf can be used with the “%s” format specification.
char name[30];
:
:
scanf (“%s”, name);

• The ampersand (&) is not required before the variable name with “%s”.

• The problem here is that the string is taken to be upto the first white space
(blank, tab, carriage return, etc.)
• If we type “Debasis Samanta”
• name will be assigned the string “Debasis”!

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Reading a “line of text”
• In many applications, we need to read in an entire line of text
(including blank spaces).

• We can use the getchar() function for the purpose.

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Reading a “line of text”

char line[81], ch;


int c=0;
:
:
do Read characters
{ until CR (‘\n’)
ch = getchar();
line[c] = ch; is encountered
c++;
}
while (ch != ‘\n’);

c = c – 1; Make it a valid
line[c] = ‘\0’; string

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Reading a line :: Alternate Approach
Reads a string containing uppercase characters and blank spaces

char line[81];
:
:
scanf (“%[ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line);

Reads a string containing any characters:

char line[81];
:
:
scanf (“%[^\n]”, line);

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Writing Strings to the Screen
• We can use printf with the “%s” format specification.
printf (“\n %s”, name);

• Alternatively, we can use printf with the “%c” format and each
character one after another.

i = 0;
while (name[i++] !=‘\0’)
printf(“%c”, name[i]);

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Processing Character Strings
• There exists a set of C library functions for character string
manipulation.
strcpy :: string copy
strlen :: string length
strcmp :: string comparison
strtcat :: string concatenation

• It is required to add the line.


#include <string.h>

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


strcpy()
• Works very much like a string assignment operator.
strcpy (string1, string2);
• Assigns the contents of string2 to string1.

• Examples:
strcpy (city, “Calcutta”);
strcpy (city, mycity);

• Warning:
• Assignment operator do not work for strings.
city = “Calcutta”; -> INVALID

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


strlen()
• Counts and returns the number of characters in a string.
len = strlen (string);/* Returns an int */

• The null character (‘\0’) at the end is not counted.


• Counting ends at the first null character.

char city[15];
int n; n is assigned 8
:
:
strcpy (city, “Calcutta”);
n = strlen (city);

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


strcmp()
• Compares two character strings.
int strcmp (string1, string2);
• Compares the two strings and returns 0 if they are identical; non-zero
otherwise.
• Examples:-
if (strcmp (city, “Delhi”) = = 0)
{ …… }

if (strcmp (city1, city2) ! = 0)


{ …… }

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


strcat()
• Joins or concatenates two strings together.
strcat (string1, string2);
• string2 is appended to the end of string1.
• The null character at the end of string1 is removed, and string2 is joined at
that point.
• Example:-
A m i t ‘\0’
strcpy (name1, “Amit “);
strcpy (name2, “Roy“);
R o y ‘\0’
strcat (name1, name2);
A m i t R o y ‘\0’

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Example 2: Page Statistics
/* Read a line of text and count the number of uppercase in the text */

#include <stdio.h>
#include <string.h>

main()
{
char line[81];
int i, n, count=0;
scanf (“%[^\n]”, line);
n = strlen (line);
for (i=0; i<n; i++)
{
if (isupper (line[i])
count++;
}
printf (“\n The no. of uppercase ltr in the str %s is %d”,line, count);
}

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Example 1: Upper Case Counting
/* Read a text and count the number of uppercase letters */

#include <stdio.h>
#include <string.h>
#define MAX 1000;

main()
{
char myText[MAX];
int i, n, wCount=0; lCount = 0;
while ((c=getchar()) != 0) myText[i++] = c;
myText[i] = ‘\0’;

n = strlen (myText);
for (i=0; i<n; i++)
{
switch(myText[i]){
case ‘ ‘: wCount++; break;
case ‘\.’ :lcount++; break;
}
printf (“\n The number of words is %d and sentences is %d”,wCount, lCount);
}
CS 11001 : Programming and Data Structures Lecture #04: © DSamanta
Any question?

You may post your question(s) at the “Discussion


Forum” maintained in the course Web page.
CS 11001 : Programming and Data Structures Lecture #04: © DSamanta
Problems for Ponder…
1. An array of integer of size 10 is declared. Compiler then allocate memory for it
a) In which memory (cache, main memory, secondary memory) the memory is allocated?

b) If it is stored in maim memory, then in which part of the memory (data area, heap area or instruction area) it is stored?

c) How much memory (in Bytes), usually it will take?

d) Are they stored in contagious locations or distributed at random thorough the entire memory available?

2. Two arrays x and y are declared as follows.

float x[100] ; double y [100];

Which would take more amount? Why?

3. Suppose, you have declared an array long x[100]; Assume that the word size of the memory is 2
bytes. If the starting location of the array (i.e., the location of x[0]) in the memory is 1124, then what will be
the memory location of x[8]?

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Problems for Ponder…
4. Suppose, we want to store the following data into an array, which is declared as char a2z [100];

11, 0, A, a, -1, 55, *

Is it possible to store them? If not, why?

5. What will be the memory location of a[i][j] in memory, if the starting location of the array is x and the
2-D array is stored in column major order? Assume, each element of the array needs w words of the memory.
Column
0 1 2 3
0
Row

6. What should be the memory locations in (a) row-major and (b) column major order of any non-zero
elements of the following diagonal matrices.

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Problems for Ponder…
7. Assume that array A and B are declared as follows:
int A[5][4];
int B[4];

Find the errors (if any), in the following program segments


a) for (i=1; i<4; i++)
scanf(“%f”, B[i]);

b) for (i=1; i<=5; i++)


for (j=1; i<=4; j++)
A[i][j] = 0;

c) for (i=4; i>=0; i--)


scanf(“%d”, &B[i]);

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Problems for Ponder…
8. String variables can be assigned values in the following four ways:

i. During type declaration


a) char name[] = “India”;
b) char name [ ] = {‘I’, ‘n’, ‘d’, ‘i’, ‘a’, ‘\0’};\

ii. Using strcpy function


strcpy(aString, name);

iii. Reading-in a string using scanf function


scanf(%s”, name);

iv. Reading using gets function


gets(name);

What is the advantages and limitations in the above ways of initializing a string variable. Explain your
answers with appropriate C programs.

9. It is required to store the name of 20 cities. Assume that name of a city should not exceed 20 characters. Give
an idea how the data can be stored in a string matrix say myCities, tht is, myCity[i] will stored the
name of the i-th city.

CS 11001 : Programming and Data Structures Lecture #04: © DSamanta


Problems for Practice…
*You can check the Moodle course management system for a
set of problems for your own practice.

• Login to the Moodle system at http://cse.iitkgp.ac.in/


• Select “PDS Spring-2017 (Theory) in the link “My Courses”
• Go to Topic 4: Practice Sheet #04 : Arrays and Strings

*Solutions to the problems in Practice Sheet #04 will be uploaded


in due time.

CS 10001 : Programming and Data Structures 58 Lecture #01: © DSamanta


If you try to solve problems yourself, then you will learn
many things automatically.

Spend few minutes and then enjoy the study.

CS 10001 : Programming and Data Structures 59 Lecture #01: © DSamanta

You might also like