0% found this document useful (0 votes)
4 views41 pages

L4 1 Array

Uploaded by

tanvimishraoct
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)
4 views41 pages

L4 1 Array

Uploaded by

tanvimishraoct
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/ 41

Arrays in C

Basic Concept

• Many applicatons require multple data items


that have common characteristcs.
– In mathematcs, we ofen express such groups of data
items in indexed form:
x1, x2, x3, …, x n
• Why are arrays essental for some applicatons?
– Take an example.
– Finding the minimum of a set of numbers.

Programming and Data Structure


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

Programming and Data Structure


The Problem

• Suppose we have 10 numbers to handle.


• Or 20.
• Or 100.

• How to tackle this problem?


• Soluton:
– Use arrays.

Autumn Semester 2019 Programming and Data Structure


Using Arrays
• All the data items consttutng 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

Programming and Data Structure


• The name of the array also denotes the startng
address of the array in memory.
– Example:
int x[10];

x[0], x[1], x[2], … indicates the contents of the


successive array locatons.
x indicates the startng address in memory for the array.

• NOTE: Indexing starts at zero

Programming and Data Structure


An Example
#include <stdio.h>
main()
{
int x[10];
x[0] = 15;
x[1] = x[0] + 5;
printf (”\n%d %d %d %u \n”, x[0], x[1], x[2], x);
}

Output: The name of the array


15 20 1107384350 3221224640 holds the address of the
zeroth element.

Garbage Address
Programming and Data Structure
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 data type (Homogeneous) 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];
– marks is an array containing a maximum of 5 integers.

Programming and Data Structure


• 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 partcular run we may only be using, say, 10
elements.

Programming and Data Structure


How an array is stored in memory?

• Startng from a given memory locaton, the successive array


elements are allocated space in consecutve memory
locatons. int a[10];

Array a
x x+k x+2k

x: startng address of the array in memory


k: number of bytes allocated per array element
– Element a[i]:: allocated memory locaton at address x + i*k

Programming and Data Structure


Accessing Array Elements

• A partcular element of the array can be accessed by


specifying two things:
– Name of the array.
– Index (relatve positon) 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.

Programming and Data Structure


Contd.

• The array index must evaluate to an integer between 0


and n-1 where n is the number of elements in the array.
• Any integer expression can be given as the index.
a[x+2] = 25;
b[3*x-y] = a[10-x] + 5;

Programming and Data Structure


In Lab you may get
A Warning segmentation fault (core
dumped) error

• 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.

Programming and Data Structure


Initalizaton 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
automatcally 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

Programming and Data Structure


Contd.

– The size may be omited. In such cases the compiler


automatcally allocates enough space for all initalized
elements.

int flag[] = {1, 1, 1, 0};


char name[] = {’A’, ’m’, ’i’, ’t’};

Programming and Data Structure


Example 1: Find the minimum of a set of 10 numbers
#include <stdio.h>
main()
{
int a[10], i, min;

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


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

min = 99999; /* or, min=a[0] */


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

Programming and Data Structure


Example 1: Find the minimum of a set of 10 numbers
#include <stdio.h>
main()
{
int a[10], i, min;

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


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

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

Programming and Data Structure


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

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

Change only one for (i=0; i<size; i++)


line to change the scanf ( %d , &a[i]);
problem size
min = a[0];
for (i=0; i<size; i++)
{
if (a[i] < min)
min = a[i];
}
printf ( \n Minimum is %d , min);
}

Programming and Data Structure


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

scanf ( %d , &n);
/* Number of elements */
for (i=0; i<n; i++)
Define an array of
scanf ( %d , &a[i]);
large size and use
only the required min = a[0];
number of elements for (i=0; i<n; i++)
{
if (a[i] < min)
min = a[i];
}
printf ( \n Minimum is %d , min);
}

Programming and Data Structure


#include <stdio.h>
Example 2: #define nsub 6
Computng gpa
main()
{
int grade_pt[nsub], cred[nsub], i,
gp_sum=0, cred_sum=0;
float gpa;

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


scanf ( %d %d , &grade_pt[i],&cred[i]);
Handling two arrays
at the same tme for (i=0; i<nsub; i++)
{
gp_sum += grade_pt[i] * cred[i];
cred_sum += cred[i];
}
gpa = (float) gp_sum / cred_sum;
printf ( \n GPA is: %f , gpa);
}
Programming and Data Structure
Things you can’t do
int a[20], b[20];

• 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 print arrays:
printf (”……”, a);

Programming and Data Structure


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];

Programming and Data Structure


How to read the elements of an array?

• By reading them one element at a tme.

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.

Programming and Data Structure


How to print the elements of an array?

• By printng them one element at a tme.

for (j=0; j<25; j++)


printf ( \n %d , a[j]);

– The elements are printed one per line.

for (j=0; j<25; j++)


printf ( %d , a[j]);

– The elements are printed all in one line (startng with


a new line).

Programming and Data Structure


Passing Arrays to a Functon
How to pass arrays to a functon?

• An array name can be used as an argument to a


functon.
– Permits the entre array to be passed to the functon.
– The way it is passed differs from that for ordinary
variables.
• Rules:
– The array name must appear by itself as argument,
without brackets or subscripts.
– The corresponding formal argument is writen in the same
manner.
• Declared by writng the array name with a pair of empty brackets.

Programming and Data Structure


An Example with 1-D Array

main()
{
We can also write int n;
float list[100], avg;
float x[100]; :
But the way the functon avg = average(n,list);
is writen makes it :
general; it works with }
arrays of any size.
float average(int a, float x[])
{
:
sum = sum + x[i];
}

Programming and Data Structure


main()
{
int n, i;
float list[100], avg;
scanf (“%d”, &n);
for (i=0; i<n; ++)
scanf ( %f , &list[i]);
avg = average (n, list);
printf ( \nAverage is: %d , avg);
}

float average(int a, float x[])


{
float sum = 0; int index;
for (index=0; index<a; index++)
sum = sum + x[i];
return sum;
}

Programming and Data Structure


The Actual Mechanism

• When an array is passed to a functon, the values of the


array elements are not passed to the functon.
– The array name is interpreted as the address of the
first array element.
– The formal argument therefore becomes a pointer to
the first array element.
– When an array element is accessed inside the
functon, the address is calculated using the formula
stated before.
– Changes made inside the functon are thus also
reflected in the calling program.

Programming and Data Structure


Contd.

• Passing parameters in this way is called


call-by-reference.
• Normally parameters are passed in C using
call-by-value.
• Basically what it means?
– If a functon changes the values of array elements, then
these changes will be made to the original array that is
passed to the functon.

Programming and Data Structure


Example: Parameter passed as a value
#include <stdio.h> main()
{
void swap (int a, int b) int x,y;
{
int temp; x=10; y=15;
temp=a; printf( x=%d y=%d \n , x, y);
a=b; swap(x,y);
b=temp; printf( x=%d y=%d \n , x, y);
} }

Output:
x=10 y=15
x=10 y=15

Programming and Data Structure


Example: Minimum of a set of numbers

#include <stdio.h> int minimum (int x[], int


int minimum (int x[], int y); size)
{
main()
{ int i, min = x[0];
int a[100], i, n;
for (i=0;i<size;i++)
scanf ( %d , &n); if (min > x[i])
for (i=0; i<n; i++) min = x[i];
scanf ( %d , &a[i]); return (min);
}
printf ( \n Minimum is
%d ,minimum(a,n));
}

Parameter x passed by reference, size by value.

Programming and Data Structure


Example: Square each element of array
#include <stdio.h>
void square (int a[], int b); void square (int x[], int
size)
main() {
{ int i;
int a[100], i, n;
for (i=0;i<size;i++)
scanf ( %d , &n);
for (i=0; i<n; i++) x[i] = x[i] * x[i];
scanf (”%d”, &a[i]);
return;
square (a, n); }

printf ( \nNew array is: );


for (i=0; i<n; i++)
printf ( %d , a[i]);

}
Programming and Data Structure
Introducton to Pointers

• What is the concept?


– Pointer is a variable which stores the address of memory
locaton of another variable.
– When declared, we must specify the data type of the
variable being pointed to.
– Examples:
int *p;
float *x, *y;
char *flag;

Programming and Data Structure


• A pointer variable can be assigned the address of
another variable.
int a, *p;
a=10;
p = &a; /* Address of ‘a’ assigned to ‘p’ */
printf (”%d %d”, a, *p);
/* Will print “10 10” */
• Point to note:
– Array name indicates pointer to first array element.
int num[10], *xyz;
xyz = num; /* Points to x[0] */

Programming and Data Structure


– When an integer expression E is added to or subtracted
from a pointer, actually scale factor tmes E is added or
subtracted.
• Scale factor indicates size of the data item being pointed to in
number of bytes.
• Scale factor for char is 1, int is 4, float is 4, double is 8, etc.

int a, *p;
p = &a; /* p is assigned address of ‘a’
(say, 2500) */
p++; /* p will become 2504 */
p = p – 10; /* p will become 2464 */

Programming and Data Structure


• Consider the declaraton:
int x[5] = {1, 2, 3, 4, 5};
int *p;
– Suppose that the base address of x is 2500, and each
integer requires 4 bytes.
Element Value Address
x[0] 1 2500
x[1] 2 2504
x[2] 3 2508
x[3] 4 2512
x[4] 5 2516

Programming and Data Structure


Contd.

Both x and &x[0] have the value 2500.

p = x; and p = &x[0]; are equivalent.

• Relatonship between p and x:


p = &x[0] = 2500
p+1 = &x[1] = 2504
*(p+i) gives the
p+2 = &x[2] = 2508 value of x[i]
p+3 = &x[3] = 2512
p+4 = &x[4] = 2516

Programming and Data Structure


• An example:

int x[ ] = {1,2,3,4,5,6,7,8,9,10};
int *p;
p = x + 3; /* Point to 4th element of x */

printf ( %d , *p); /* Will print 4 */

printf ( %d , *(p+5));
/* Will print 9 */

printf ( %d %d , p[3], p[-1]);


/* Will print 7 and 3 */

Programming and Data Structure


Example: functon to find average

#include <stdio.h> float avg (int array[], int


main() size)
{ {
int x[100], k, n; int *p, i , sum = 0;

scanf (”%d”, &n); p = array;

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


scanf (”%d”, &x[k]); sum = sum + *(p+i);

printf (”\nAverage is %f”, return ((float) sum / size);


avg (x, n)); }
}

Programming and Data Structure


Example: SWAP revisited
#include <stdio.h> main()
{
void swap (int *a, int *b) int x, y;
{
int temp; x=10; y=15;
printf ( x=%d y=%d \n , x,y);
temp = *a;
swap (&x, &y);
*a = *b;
printf ( x=%d y=%d \n , x,y);
*b = temp;
}
}

Output:
x=10 y=15
x=15 y=10

Programming and Data Structure

You might also like