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

Array1

The document covers the basics of data structures, specifically focusing on arrays and character strings in programming. It explains how to declare, initialize, access, and manipulate arrays, as well as the differences between character arrays and strings. Additionally, it includes examples of finding the minimum value in an array and reading strings from user input.

Uploaded by

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

Array1

The document covers the basics of data structures, specifically focusing on arrays and character strings in programming. It explains how to declare, initialize, access, and manipulate arrays, as well as the differences between character arrays and strings. Additionally, it includes examples of finding the minimum value in an array and reading strings from user input.

Uploaded by

21bcs008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Unit 4

Data Structures

1
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?
– Take an example.
– Finding the minimum of a set of numbers.

2
3 numbers 4 numbers

if ((a <= b) && (a <= c)) if ((a <= b) && (a <= c) && (a <= d))
min = a; min = a;
else else
if (b <= c) if ((b <= c) && (b <= d))
min = b; min = b;
else else
min = c; if (c <= d)
min = c;
else
min = d;

3
The Problem
• Suppose we have 10 numbers to handle.
• Or 20.
• Or 100.

• How to tackle this problem?


• Solution:
– Use arrays.

4
Using Arrays
• 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

5
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.
int marks[5];
• marks is an array containing a maximum of 5 integers.

6
• Examples:
int x[10];
char line[80];
float points[150];
char name[35];
• If we are not sure of the exact size of the array,
we can define an array of a large size.
int marks[50];
though in a particular run we may only be using,
say, 10 elements.
7
How an array is stored in memory?
• Starting from a given memory location, the
successive array elements are allocated space in
consecutive memory locations.
Array a
x x+k x+2k
• Let
x: starting address of the array in memory
k: number of bytes allocated per array element
– Element a[i] :: allocated memory location at address
x + i*k
• First array index assumed to start at zero.

8
Accessing Array Elements
• A particular element of the array can be accessed
by specifying two things:
– Name of the array.
– Index (relative position) of the element in the array.
• In C, the index of an array starts from zero.
• Example:
– An array is defined as int x[10];
– The first element of the array x can be accessed as
x[0], fourth element as x[3], tenth element as x[9],
etc.

9
Contd.
• The array index must evaluate to an integer
between 0 and n-1 where n is the number of
elements in the array.
a[x+2] = 25;
b[3*x-y] = a[10-x] + 5;

10
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 necessarily cause an
error.
– Rather, it may result in unpredictable program results.
11
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, 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

12
Contd.
– 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’};

13
Example 1: Find the minimum of a set of 10 numbers
#include <stdio.h>
main()
{
Array
int a[10], i, min;
declaration printf(“Give 10 values \n”);
for (i=0; i<10; i++) Reading
scanf (“%d”, &a[i]); Array Element
min = 99999;
for (i=0; i<10; i++)
{
if (a[i] < min)
Accessing
min = a[i];
} Array Element
printf (“\n Minimum is %d”, min);
}

14
Alternate
#include <stdio.h>
Version 1 #define size 10

main()
{
int a[size], i, min;
printf(“Give 10 values \n”);
for (i=0; i<size; i++)
Change only one scanf (“%d”, &a[i]);
line to change the
problem size min = 99999;
for (i=0; i<size; i++)
{
if (a[i] < min)
min = a[i];
}
printf (“\n Minimum is %d”, min);
}

15
#include <stdio.h>
Alternate
Version 2 main()
{
int a[100], i, min, n;

printf(“Give number of elements (n) \n”);


scanf (“%d”, &n); /* Number of elements */
Define an array of
printf(“Input all n integers \n”);
large size and use
for (i=0; i<n; i++)
only the required
scanf (“%d”, &a[i]);
number of elements
min = 99999;
for (i=0; i<n; i++)
{
if (a[i] < min)
min = a[i];
}
printf (“\n Minimum is %d”, min);
} Programming and Data Structure 16
Things you cannot do
• You cannot
– use = to assign one array variable to another
a = b; /* a and b are arrays */
– use == to directly compare array variables
if (a = = b) ………..
– directly scanf or printf arrays
printf (“……”, a);

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

• By copying individual elements


int a[25],b[25];
for (j=0; j<25; j++)
a[j] = b[j];

18
How to read the elements of an array?
• By reading them one element at a time
int a[25];
for (j=0; j<25; j++)
scanf (“%d”, &a[j]);
• The ampersand (&) is necessary.
• The elements can be entered all in one line or
in different lines.

19
How to print the elements of an array?
• By printing them one element at a time.
for (j=0; j<25; j++)
printf (“\n %d”, a[j]);
– The elements are printed one per line.
printf (“\n”);
for (j=0; j<25; j++)
printf (“ %d”, a[j]);
– The elements are printed all in one line (starting
with a new line).

20
Example: Matrix Addition
#include <stdio.h> for (p=0; p<m; p++)
for (q=0; q<n; q++)
main() c[p]q] = a[p][q] + b[p][q];
{
int a[100][100], b[100][100], for (p=0; p<m; p++)
c[100][100], p, q, m, n; {
printf (“\n”);
scanf (“%d %d”, &m, &n); for (q=0; q<n; q++)
printf (“%f ”, a[p][q]);
for (p=0; p<m; p++)
for (q=0; q<n; q++) }
scanf (“%d”, &a[p][q]); }

for (p=0; p<m; p++)


for (q=0; q<n; q++)
scanf (“%d”, &b[p][q]);

21
Character Strings

22
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’
23
Character Strings
Character vs. String
• A string constant is a sequence of characters
enclosed in double quotes.
– For example, the character string:
char s1[2]="a"; //Takes two bytes of
storage.
s1: a ‘\0’

– On the other hand, the character, in single quotes:


char s2= `a`; //Takes only one byte of
storage.
s2: a
Declaring String Variables
• A string is declared like any other array:
char string-name [size];
– size determines the number of characters in
string_name.
• When a character string is assigned to a character
array, e.g. s=“abc”;
– It automatically appends the null character (‘\0’) at
the end of the string.
– size should be equal to the number of characters in
the string plus one.
26 February 2022 26
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’,’\0’};
char dob[] = “12-10-1975”;
26 February 2022 27
Reading Strings from the Keyboard

• Two different cases will be


considered:
–Reading words
–Reading an entire line

26 February 2022 28
Reading Words
• scanf with “%s” format:
char name[30];
:
:
scanf (“%s”, name);
– The ampersand (&) is not required before the
string name.
– Point to remember here is that the string is taken
to be upto the first white space (blank, tab,
carriage return, etc.)
• If we type “Rupak Biswas”
• name will be assigned the string “Rupak”
26 February 2022 29
Reading a Line
char line[81];
:
:
scanf (“%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line);
è Reads a string containing uppercase
characters and blank spaces
char line[81];
:
scanf (“%[^\n]”, line);

è Reads a string containing any characters


26 February 2022 30
Displaying Strings on the Screen
• We can use printf with the “%s” format
specification.

char name[50];
:
:
printf (“\n %s”, name);
26 February 2022 31
Processing Character Strings
• C library functions for character string
manipulation.
– strcpy :: string copy
– strlen :: string length
– strcmp :: string comparison
– strtcat :: string concatenation
• It is required to include the following
#include <string.h>
26 February 2022 32
strcpy()
• Works very much like a string assignment
operator.
strcpy (string1, string2);
– Assigns the contents of string2 to string1.
• Examples:
strcpy (city, “Hamirpur”);
strcpy (city, mycity);
• Warning:
– Assignment operator does not work for
strings.
city = “Hamirpur”; è INVALID
26 February 2022 33
strlen()
• Counts and returns the number of
characters in a string.
len = strlen (string); /* Returns an integer
*/

–The null character (‘\0’) at the end is not


counted.
–Counting ends at the first null character.
26 February 2022 34
char city[15];
int n;
:
:
strcpy (city, “Hamirpur”);
n = strlen (city);

n is assigned 8

26 February 2022 35

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy