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

Introduction To Arrays: ESC101 September 6

The document provides an introduction to arrays in C programming. It discusses that arrays allow storing multiple values of the same data type in contiguous memory locations that can be individually accessed using an index. The document also demonstrates defining and initializing an integer array, accessing array elements using indexes, and using a for loop to iterate through an array. It notes that arrays are useful for storing and processing a collection of like data, and that their indexes begin from 0.

Uploaded by

Aditya Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Introduction To Arrays: ESC101 September 6

The document provides an introduction to arrays in C programming. It discusses that arrays allow storing multiple values of the same data type in contiguous memory locations that can be individually accessed using an index. The document also demonstrates defining and initializing an integer array, accessing array elements using indexes, and using a for loop to iterate through an array. It notes that arrays are useful for storing and processing a collection of like data, and that their indexes begin from 0.

Uploaded by

Aditya Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Introduction to arrays

ESC101
September 6th
Announcements
• Extra class on Friday, 8th September
– 1700-1750 in L20
– We will discuss major quiz 1
• Lab mid sem on Saturday, 16th September
– At NCL, rooms to be allotted at the time
– Sections B1-B6 10am-1pm
– Sections B7-B12 1200pm-4pm
• Remedial labs every week Fridays 2pm-5pm
Today
• Wrapping up last lecture
– Static variables
– Gentle intro to memory management
• Introduction to arrays
– Syntax
– Basic I/O
– Simple usage
Static Variables
• We have seen two kinds of variables: local variables and
global variables.
• There are static variables too.
int f () { = 0;
ncalls GOAL: count number of calls to f()
int
int f ncalls
static
() int
{ = 0;
ncalls = 0; SOLUTION: define ncalls as a static
ncalls = ncalls + 1; variable inside f().
/* track the number of It is created as an integer box the
first time f() is called.
times f() is called */
Once created, it never gets
… body of f() … destroyed, and retains its value
} across invocations of f().
Multiple initializations have no effect
• Use a local variable? within the active scope
• gets destroyed every It is like a global variable, but visible
time f returns only within f().
• Use a global variable? Static variables are not allocated on
stack. So they are not destroyed
• other functions can when f() returns.
Aug-19 change it! (dangerous) 4 ESC101, Functions
Gentle brush with pointers
• Pointers are special variables that store
memory addresses
• We will cover pointers in much greater depth
soon
Why use arrays
Example : Maximum of 3 numbers
int main(){ int max(int a, int b){
int a, b, c, m; if (a>b)
return a; How would
/* code to read else you scale
* a, b, c */ return b; this code to
} handle
if (a>b){ large
if (a>c) m = a; int main() { number
else m = c; int a, b, c, m; of inputs
} (e.g.: max
else{ /* code to read of 100
if (b>c) m = b; * a, b, c */ numbers!)
else m = c;
} m = max(a, b);
m = max(m, c);
/* print or use m */ /* print or use m */

return 0; return 0;
} }
Aug-19 6 ESC101, Functions
Operations on a list
• Take this list
• Do something to every element on this list
• Return the output for every element on the
list
These addresses contain entries from ONE list

Value Value Value Value


Value
Address Address Address Address
Address
Want to access them one after another
Arrays in C
An array in C is defined similar to defining a variable.

int a[5];

The square parenthesis [5] indicates that a is not a


single integer but an array, that is a consecutively
allocated group, of 5 integers.
It creates five integer boxes or variables
Array
elements are
consecutively
allocated in
a[0] a[1] a[2] a[3] a[4] memory.
The boxes are addressed as a[0], a[1], a[2], a[3] and a[4].
These are called the elements of the array.
include <stdio.h>
int main () { The program defines an
int i; integer variable called i and
int a[5]; an integer array with name a
of size 5
for (i=0; i < 5; i= i+1) {
a[i] = i+1; This is the notation used
to address the elements of
the array.
printf(“%d”, a[i] );
The variable i is being used
}
as an “index’’ for a.
return 0;
Similar to the math notation
}
ai

i a[0] a[1] a[2] a[3] a[4]


Max of N numbers
int max(int a, int b){
if (a>b)
return a;
else
return b;
}
Arrays and loops are the
int main() { bread and butter of basic
int a[100]; programming
/* code to read
100 numbers/
m = max(a[0],a[1]);
for (i = 1; i<100;i++){
m = max(a[i], m);
/* print or use m */

return 0;
}
include <stdio.h> Let us trace the
int main () { execution of the program.
int a[5];
int i;

for (i=0; i < 5; i= i+1) {


a[i] = i+1; i
} 5
2
0
1
3
4
return 0; }

a[0] a[1] a[2] a[3] a[4]

1 2 3 4 5

Statement becomes a[0] =0+1;


Statement becomes a[1] =1+1; Statement becomes a[3] = 3+1;
Statement becomes a[2] =2+1; Statement becomes a[4] = 4+1;
One can define an array of float or an array of char, or
array of any data type of C. For example

int main() { This defines an array called num


float num[100]; of 100 floating point numbers
indexed from 0 to 99 and named
char s[256]; num[0]… num[99]

/* some code here */ This defines an array called s


} of 256 characters indexed from
0 to 255 and named s[0]…s[255].
array
num[0] num[1] num[2] … num[99]
of
100
float

s[0] s[1] s[2] s[3] … … s[254] s[255]


array
of 256
char
Mind the size(of array)
int f() {
int x[5]; This defines an integer
… array named x of size 5.
}
Five integer variables
named x[0] x[1] … x[4] are
allocated.

x[0] x[1] x[2] x[3] x[4]

The variables x[0],x[1] … x[4] are


integers, and can be assigned and operated
upon like integers! OK, so far so good!
Mind the size(of array)
int f() { x[0] x[1] x[2] x[3] x[4]
int x[5];

}
But what about x[5], x[6], … x[55]?
Can I assign to x[5], increment it, etc.?

NO! Program may


crash!

x[5], x[6], and so on are undefined. These are names


but no storage has been allocated. Shouldn’t access them!
Q: Shouldn’t I or couldn’t I
access array elements outside
of the array range declared?
int f() {
int x[5]; Will it compile? Yes, it
x[0] =0; will compile. C compiler
x[1] =1; All may give a warning.
… good
x[4] =4; Program may give:
1) “segmentation fault: core dumped”
x[5] = 5; not 2) it may run correctly
x[6] = 6; recommended.
}

Ans: You can but shouldn’t.


Program may crash.
Reading directly into array
Read N numbers from user directly into an array

#include <stdio.h> scanf can be used


directly, treat an
int main() { array element like
int num[10]; variable of the same
data type.
for (i=0; i<10; i=i+1) {
scanf(“%d”, &num[i]); 1. For integers, read as
} scanf(“%d”, &num[i]);
2. For reading elements
return 0; of a char array s[],
} use scanf(“%c”, &s[j]).
In the previous slide, we had scanf(“%d”, &num[i] );
the statement:

&num[i]: two operators & and [].


What does &num[i] mean? gives address of array element num[i].

& is the “address-of’’ operator.


1. It can be applied to any defined [ ]
variable. array indexing operator
2. It returns the location (i.e., e.g, num[i].
address) of this variable in the
program’s memory.

&num[i] is evaluated as:


&(num[i])
NOT as : (&num)[i]
Array Example: Print backwards
Problem:
1. Define a character array of size 100 (upper limit)
2. read the input character by character and store in
the array until either
• 100 characters are read or
• EOF (End Of File) is encountered
3. Now print the characters backwards from the
array.

Example Input 1 Output 1


Me or ooM
Moo ro eM

Example Input 2 Output 2


Eena Meena Dika akiD aneeM aneE
EOF (end of file)
• EOF is a distinctive value that is a non-
character. This is to distinguish “an input”
from “no more input”.

• In integers, it’s -1. Not to be confused with


“\n” or “ ” (space).

• stdio.h contains the integer value of EOF.


Read and print in reverse
1. We will design the program in a top down fashion,
using just main() function.
2. There will be two parts to main: read_into_array and
print_reverse.
3. read_into_array will read the input character-by-
character up to 100 characters or until the end of
input.
4. print_reverse will print the characters in reverse.

Overall design
int main() {
char s[100]; /* to hold the input */
/* read_into_array */
/* print_reverse */
return 0;
}
Let us design the program fragment read_into_array.
Keep the following variables:
1. int count: count the number of characters read so far.
2. int ch: to read the next character using getchar().

Note that getchar() has prototype int getchar()


since getchar() returns all the 256 characters and the
integer EOF
int ch;
int count = 0;
read the next character into ch using getchar();
while (ch is not EOF AND count < 100) {
s[count] = ch;
count = count + 1;
read the next character into ch using getchar();
}

An initial design (pseudo-code)


int ch;
int count = 0;
read the next character into ch using getchar();
while (ch is not EOF AND count < 100) {
s[count] = ch;
count = count + 1;
read the next character into ch using getchar();
}
int ch; Overall design
int count = 0; int main() {
ch = getchar(); char s[100];
while ( ch != EOF && count < 100) { /* read_into_array */
s[count] = ch; /* print_reverse */
count = count + 1; return 0;
ch = getchar(); }
} What is the value of
Translating the read_into_array count at the end of
pseudo-code into code. read_into_array?
Let us trace the execution.
INPUT HELLO<eof>
We will do this for part
read_into_array
i ch `H’
`O’
eof
`L’
`E’
#include <stdio.h>
int main() {
char s[100]; s[0] `H’
int count = 0;
int ch, i; s[1] `E’
ch = getchar(); s[2] `L’
s[3] `L’
while ( ch != EOF &&
count < 100) { s[4] `O’
s[count] = ch;
count = count + 1; count 1
5
0
3
2
4
ch = getchar(); s[99]
}

Now let us design the code fragment print_reverse

Suppose input is: HELP<eof>

`H’ `E’ `L’ `P’


s[100]
s[0] s[1] s[2] s[3] s[99]
i
count 4
index i runs backwards in array

int i;
set i to the index of last character read.

while (i >= 0) {
print s[i]
i = i-1; /* shift array index one to left */
}
The
array `H’ `E’ `L’ `P’
char
s[100] s[0] s[1] s[2] s[3] s[99]
i
count 4
index i runs backwards in array

int i; int i;
set i to index of the last character read. i = count-1;

while (i >= 0) { while (i >=0) {


print s[i] putchar(s[i]);
i = i-1; i=i-1;
} }
Code for printing
Translating pseudo code to
characters read in
C code: print_reverse
array in reverse
Overall design Putting it together
int main() {
char s[100];
/* read_into_array */ The code
/* print_reverse */ fragments we
return 0; have written
} so far.

read_into_array code.
print_reverse code
int count = 0;
int ch; int i;
ch = getchar(); i = count-1;
while ( ch != EOF && count < 100) { while (i >=0) {
s[count] = ch; putchar(s[i]);
count = count + 1; i=i-1;
ch = getchar(); }
}
#include <stdio.h>
int main() {
char s[100]; /* the array of 100 char */
int count = 0; /* counts number of input chars read */
int ch; /* current character read */
int i; /* index for printing array backwards */
ch = getchar();
while ( ch != EOF && count < 100) {
s[count] = ch; /*read_into_array */
count = count + 1;
ch = getchar();
}
i = count-1;
while (i >=0) {
putchar(s[i]);
/*print_in_reverse */
i=i-1;
}
return 0;
}
#include <stdio.h>
int main() {
char s[100];
int count = 0;
int ch;
int i; /*read_into_array */
while ( (ch=getchar()) != EOF &&
count < 100 )
{ s[count] = ch;
count = count + 1;
}

i = count-1;
while (i >=0) {
putchar(s[i]); /*print_in_reverse */
i=i-1;
}
return 0;
}
Next class
• More about arrays

You might also like