0% found this document useful (0 votes)
2 views

Arrays

The document provides an overview of arrays in programming, defining them as fixed-size collections of elements of the same data type, and discussing their advantages and disadvantages. It includes examples of one-dimensional and two-dimensional arrays, as well as character arrays (strings) and their handling in C programming. Additionally, it covers common string manipulation functions and their usage.
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)
2 views

Arrays

The document provides an overview of arrays in programming, defining them as fixed-size collections of elements of the same data type, and discussing their advantages and disadvantages. It includes examples of one-dimensional and two-dimensional arrays, as well as character arrays (strings) and their handling in C programming. Additionally, it covers common string manipulation functions and their usage.
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
You are on page 1/ 34

Introduction

Why arrays?

The fundamental data types namely char, int, float are constrained by the fact
that a variable of these types can store only one value at any given time. In order
to handle a large volume of data in terms of reading, processing and printing we
need a derived data type known as array.

Def:

An array is a fixed-size sequenced collection of elements of the same data type.

Examples where the concept of an array can be used:


• List of temperatures recorded every hour in a day, or a month, or a year.
• List of employees in an organization.
Memory Representation of Array
Introduction…..

• List of employees in an organization.

• List of products and their cost sold by a store.

• Test scores of a class of students.

For instance, we can use an array name salary to represent a set of salaries of a
group of employees in an organization. We can refer to the individual salaries by
writing a number called index or subscript in brackets after the array name.

e.g. salary[10][2]

represents the salary of 10th employee.


Introduction…..

Advantages and Disadvantages of Array

Advantages
• It is used to represent multiple data items of same type by using only single
name.

• It can be used to implement other data structures like linked list, stacks,
queues, trees, graphs, etc.

• 2D arrays are used to represent matrices.

• The elements of arrays are stored in consecutive memory locations so


searching an element is easy.
Introduction…..

Disadvantages
• We must know in advance that how many elements are to be stored in array.

• Array is static structure. It means that array is of fixed size. The memory which
is allocated to array can not be increased or decreased.
• Since array is of fixed size, if we allocate more memory than requirement then
the memory space will be wasted. And if we allocate less memory than
requirement, then it can create problem.

• As the elements are stored in consecutive memory locations so insertions and


deletions are very difficult and time consuming.
Introduction…..

The ability to use a single name to represent a collection of items and to refer to
an item by specifying the item number enables us to develop concise and
efficient programs.

We can use arrays to represent not only simple lists of values but also tables of
data in two, three or more dimensions. We have the following types of arrays:
• One-dimensional array

• Two- dimensional array

• Multi- dimensional array


Example…..
// Program to take 5 values from the user and store them
in an 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]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
Example…..
Bounds Checking

Data entered with a subscript exceeding the array


size will simply be placed in memory outside the
array; probably on top of other data, or on the
program itself.
Out of Bound
MCQ - 1

1. Which of these best describes an array?

A. A data structure that shows a hierarchical behaviour

B. Container of objects of similar types

C. Arrays are immutable once initialized

D. Array is not a data structure

Answer: B.
Two - Dimensional Array

int x[3][3];
2D Array
Two-Dimensional Array
#include<stdio.h>
void main(){
int disp[2][3];
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
}
MCQ - 2

2. What are the advantages of arrays?

A. Objects of mixed data types can be stored

B. Elements in an array cannot be sorted

C. Index of first element of an array is 1

D. Easier to store elements of same data type

Answer: D.
Character Arrays / Strings
Characters Arrays/Strings

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

Declaring and Initializing String Variables

• C does not support strings as a data type.

• C, however, allows us to represent strings as character arrays.

General form:
char string_name[size];
The ‘size’ determines the number of characters in the string_name.
e.g. char city[10];
char name[30];
Characters Arrays/Strings…..

when the compiler assigns a character string to a character array, it


automatically supplies a null character(\’0’) at the end of the string. Therefore,
the size should be equal to the maximum number of characters in the string plus
one.
Initialization
char city[9] = “NEW YORK”;
char city[9] = {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};

• C also permits us to initialize a character array without specifying the number


of elements. In such cases, the size of the array will be determined
automatically, based on the number of elements initialized.

e.g. char city[ ] = {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};


Characters Arrays/Strings…..

• We can also declare the size much larger than the string size in the initialize.
e.g. char str[10] = “GOOD”;

G O O D \0 \0 \0 \0 \0 \0
Characters Arrays/Strings…..

Reading Strings from Terminal


1. Using scanf() Function
char address[10];
scanf(“%s”,address);
Here, scanf() is used with %s format specification to read a string of
characters.
Characters Arrays/Strings…..

NOTE: that unlike previous scanf calls, in the case of character arrays, the
ampersand (&) is not required before the variable name.

• The problem with the scanf( ) function is that it terminates its input on the first
white space it finds.
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Characters Arrays/Strings…..

Reading a Line of Text


C supports a format specification known as the edit set conversion code%[ ] that
can be used to read a line containing a variety of characters, including
whitespaces.
e.g. char line[80];
scanf(“%[\n]”,line);
printf(“%s”, line);

The above program segment reads a line of input from the keyboard and display
the same on the screen.
Characters Arrays/Strings…..

1. Using getchar() and gets() Functions

a. getchar()

This function is used to repeatedly read successive single characters


from the input and place them into a character array.
An entire line of text can be read and stored in an array. The
reading is terminated when the newline character(‘\n’) is entered and
the null character is then inserted at the end of the string.
General format:
char ch;
ch = getchar();
Characters Arrays/Strings…..

Code Segment:
char line[80],ch;
int c = 0;
printf(“Enter text:”);
do
{
ch=getchar();
line[c] = ch;
c++;
} while(ch !=’\n’);
Characters Arrays/Strings…..

a. gets()
This function is available in the <stdio.h> header file.
General format:
gets(str);
where str is a string name.
This function reads characters into the character array from the
keyboard until a new-line character is encountered and then adds a null
character to the string.

Code Segment:
char line[80];
gets(line);
Characters Arrays/Strings…..

Writing Strings to Screen


1. Using printf() Function
The format %s can be used to display an array of characters that is
terminated by the null character.
printf(“%s”,name);

2. Using putchar() and puts() Functions


a. putchar()
C supports another character handling function putchar() to output the
values of character variables. It takes the following form:
char ch = ‘A’;
putchar(ch);
Characters Arrays/Strings…..

Code Segment:
char name[6] = “ARNAV’;
for(i=0; i<6; i++)
putchar(name[i]);

b. puts()
The function puts() is defined in the header file <stdio.h>.
General format:
puts(str);
where str is a string name.
Characters Arrays/Strings…..

Code Segment:
char line[80];
gets(line);
puts(line);

STRING HANDLING FUNCTIONS


All the string handling functions are prototyped in:
#include <string.h>
The common functions are described below:
Characters Arrays/Strings…..

• Strcpy

This library function is used to copy a string and can be used like this:
strcpy(destination, source)
(It is not possible in C to do this: string1 = string2).

Take a look at the following example:

str_one = "abc"; str_two = "def"; strcpy(str_one , str_two); // str_one


becomes "def“

Note: strcpy() will not perform any boundary checking, and thus there is a risk of
overrunning the strings.
Characters Arrays/Strings…..

Strcmp

This library function is used to compare two strings and can be used like
this:
strcmp(str1, str2)

• If the first string is greater than the second string a number greater than null
is returned.

• If the first string is less than the second string a number less than null is
returned.

• If the first and the second string are equal a null is returned.
Characters Arrays/Strings…..

Take look at an example:


printf("Enter you name: ");
scanf("%s", name);
if( strcmp( name, "jane" ) == 0 )
printf("Hello, jane!\n");

Note: strcmp() will not perform any boundary checking, and thus there is a
risk of overrunning the strings.

Strcat
This library function concatenates a string onto the end of the other string.
The result is returned.
Characters Arrays/Strings…..

Take a look at the example:


printf("Enter you age: ");
scanf("%s", age);
result = strcat( age, " years old." ) == 0 )
printf("You are %s\n", result);

Note: strcat() will not perform any boundary checking, and thus there is a risk of
overrunning the strings.

strlen
This library function returns the length of a string. (All characters before the null
termination.)
Take a look at the example:
name = "jane";
result = strlen(name); //Will return size of four.

You might also like