Professional Documents
Culture Documents
BY MRS.C.GEETHA,ASST.PROF IN CS
Common uses of a Computer
As a tool for storing and retrieving information
◦ Extracting and storing information regarding students
entering IIT
MEMORY
Arrays
• Array Basics
• Arrays in Classes and Methods
• Programming with Arrays and
Classes
• Sorting Arrays
• Multidimensional Arrays
Motivation
• How to organize 100 Student objects?
• 100 different Student object names?
• Organize data for efficient access
– Class: different data types in one object
– Array: multiple objects of the same type
Overview
• An array
– a single name for a collection of data values
– all of the same data type
– subscript notation to identify one of the values
• A carryover from earlier programming languages
• More than a primitive type, less than an object
– like objects when used as method parameters and return
types
– do not have or use inheritance
• Accessing each of the values in an array
– Usually a for loop
Creating Arrays
• General syntax for declaring an array:
• Examples:
80-element array with base type char:
char[] symbol = new char[80];
pressure[3] = keyboard.nextInt();
System.out.println("You entered" + pressure[3]);
Some Array Terminology
Array name
temperature[n + 2]
Index - also called a subscript
- must be an int,
- or an expression that evaluates to an int
temperature[n + 2]
Indexed variable - also called an
element or subscripted variable
temperature[n + 2]
Value of the indexed variable
- also called an element of the array
temperature[n + 2] = 32;
Programming Tip:
Do not count on default initial values for array elements
– explicitly initialize elements in the declaration or in a loop
Arrays, Classes, and Methods
An array of a class can This excerpt from the Sales Report program
be declared and the in the text uses the SalesAssociate class
class's methods applied
to the elements of the to create an array of sales associates:
array.
public void getFigures()
create an array of {
SalesAssociates System.out.println("Enter number of sales associates:");
numberOfAssociates = SavitchIn.readLineInt();
SalesAssociate[] record =
each array element is new SalesAssociate[numberOfAssociates];
a SalesAssociate for (int i = 0; i < numberOfAssociates; i++)
variable {
record[i] = new SalesAssociate();
System.out.println("Enter data for associate " + (i + 1));
use the readInput record[i].readInput();
method of System.out.println();
SalesAssociate }
}
Arrays and Array Elements
as Method Arguments
• Arrays and array elements can be
– used with classes and methods just like other
objects
– be an argument in a method
– returned by methods
public static void main(String[] arg)
Indexed {
Scanner keyboard = new Scanner(System.in);a
Variables System.out.println("Enter your score on exam 1:");
int firstScore = keyboard.nextInt();
as Method int[ ] nextScore = new int[3];
int i;
Arguments double possibleAverage;
for (i = 0; i < nextScore.length; i++)
nextScore[i] = 80 + 10*i;
nextScore is
for (i = 0; i < nextScore.length; i++)
an array of ints {
possibleAverage = average(firstScore, nextScore[i]);
System.out.println("If your score on exam 2 is "
an element of + nextScore[i]);
nextScore is System.out.println("your average will be "
+ possibleAverage);
an argument of
}
method }
average public static double average(int n1, int n2)
{
average return (n1 + n2)/2.0;
method definition } Excerpt from ArgumentDemo
program in text.
• In this example, the output from the command line above will be:
Hello Josephine Student
Using = with Array Names:
Remember They Are Reference Types
A value changed in a
The output for this code will be:
is the same value
2 2 obtained with b
10 10
Using == with array names:
remember they are reference types
int i; a and b are both
3-element arrays of ints
int[] a = new int[3];
int[] b = new int[3];
all elements of a and b are
for(i=0; i < a.length; i++)
assigned the value 0
a[i] = 0;
for(i=0; i < b.length; i++) tests if the
b[i] = 0; addresses of a
if(b == a) and b are equal,
System.out.println("a equals b"); not if the array
else values are equal
System.out.println("a does not equal b");
The output for this code will be " a does not equal b"
because the addresses of the arrays are not equal.
Behavior of Three Operations
Primitive Class Entire Array
Type Type Array Element
Assignment Copy content Copy Copy Depends on
(=) address address primitive/
class type
Equality Compare Compare Compare Depends on
(==) content address address primitive/
class type
Parameter Pass by Pass by Pass by Depends on
Passing value reference reference primitive/
(content) (address) (address) class type
Testing Two
public static boolean equals(int[] a,
Arrays for {
int[] b)
• The text shows an example of creating a wrapper class for an array of objects
of type OneWayNoRepeatsList
– the wrapper class defines two constructors plus the following methods:
addItem, full, empty, entryAt, atLastEntry, onList,
maximumNumberOfEntries, numberOfEntries, and
eraseList
Partially Filled Arrays
• Sometimes only part of an array has been filled with data
• Sequential search:
– start at the beginning of the array and proceed in sequence until either
the value is found or the end of the array is reached*
• if the array is only partially filled, the search stops when the last
meaningful value has been checked
– it is not the most efficient way
– but it works and is easy to program
* Or, just as easy, start at the end and work backwards toward the beginning
Example: Sequential Search of an Array
public boolean onList(String item)
{
boolean found = false;
int i = 0;
while ((! found) &&
(i < countOfEntries))
The onList method of {
OneWayNoRepeatsList if (item.equals(entry[i]))
sequentially searches the found = true;
array entry to see it the else
i++;
parameter item is in the }
array
return found;
}
www.cs.fit.edu/~pkc/classes/cse1001/Search.java
Gotcha: Returning an
Array Attribute (Instance Variable)
• Access methods that return references to array instance variables cause
problems for information hiding.
Example: class …
{
private String[] entry;
…
public String[] getEntryArray()
{
return entry;
}
Even though entries is declared private, a method outside the class
can get full access to it by using getEntryArray.
• In most cases this type of method is not necessary anyhow.
• If it is necessary, make the method return a copy of the array instead of
returning a reference to the actual array.
Sorting an Array
• Sorting a list of elements is another very common problem (along with
searching a list)
– sort numbers in ascending order
– sort numbers in descending order
– sort strings in alphabetic order
– etc.
• There are many ways to sort a list, just as there are many ways to
search a list
• Selection sort
– one of the easiest
– not the most efficient, but easy to understand and program
Selection Sort Algorithm
for an Array of Integers
To sort an array on integers in ascending order:
1. Find the smallest number and record its index
2. swap (interchange) the smallest number with the first
element of the array
– the sorted part of the array is now the first element
– the unsorted part of the array is the remaining
elements
3. repeat Steps 2 and 3 until all elements have been placed
– each iteration increases the length of the sorted part
by one
Key:
Selection Sort Example smallest remaining value
sorted elements
1st iteration: smallest value is 3, its index is 4, swap a[0] with a[4]
before: 7 6 11 17 3 15 5 19 30 14
after: 3 6 11 17 7 15 5 19 30 14
2nd iteration: smallest value in remaining list is 5, its index is 6, swap a[1] with a[6]
3 6 11 17 7 15 5 19 30 14
3 5 11 17 7 15 6 19 30 14
10 33 100 1,024
• Arrays with more than two dimensions are a simple extension of two-
dimensional (2-D) arrays
Indexes 0 1 2 3 4 5
0 $1050 $1055 $1060 $1065 $1070 $1075
1 $1103 $1113 $1124 $1134 $1145 $1156
2 $1158 $1174 $1191 $1208 $1225 $1242
3 $1216 $1239 $1262 $1286 $1311 $1335
Row Index 3 4 $1276 $1307 $1338 $1370 $1403 $1436
(4th row) … … … … … … …
balance method in
class InterestTable
public static int balance(double startBalance, int years,
double rate)
{
double runningBalance = startBalance;
int count;
for (count = 1; count <= years; count++)
runningBalance = runningBalance*(1 + rate/100);
return (int) (Math.round(runningBalance));
}
Processing a 2-D Array:
for Loops Nested 2-Deep
• To process all elements of an n-D array nest n for loops
– each loop has its own counter that corresponds to an index
• For example: calculate and enter balances in the interest table
– inner loop repeats 6 times (six rates) for every outer loop iteration
– the outer loop repeats 10 times (10 different values of years)
– so the inner repeats 10 x 6 = 60 times = # cells in table
• Example: create a 2-D int array named b with 5 elements in the first
row, 7 in the second row, and 4 in the third row:
int[][] b = new int[3][];
b[0] = new int[5];
b[1] = new int[7];
b[2] = new int[4];
Programming Example:
Employee Time Records
• Definition of a structure:
struct <struct-type>{
<type> <identifier_list>; Each identifier
<type> <identifier_list>; defines a member
... of the structure.
} ;
• Example:
struct Date {
int day;
The “Date” structure
int month; has 3 members,
int year;
} ; day, month & year.
3
struct examples
• Example:
struct StudentInfo{
int Id; The “StudentInfo”
int age;
char Gender; structure has 4 members
double CGA; of different types.
};
• Example:
struct StudentGrade{
char Name[15];
char Course[9]; The “StudentGrade”
int Lab[5]; structure has 5
int Homework[3];
int Exam[2]; members of
}; different array types.
4
struct examples
• Example:
struct BankAccount{
char Name[15];
The “BankAcount”
int AcountNo[10]; structure has simple,
double balance; array and structure
Date Birthday;
}; types as members.
• Example:
struct StudentRecord{ The “StudentRecord”
char Name[15];
int Id; structure has 4
char Dept[5]; members.
char Gender;
};
5
struct basics
• Declaration of a variable of struct type:
<struct-type> <identifier_list>;
• Example:
StudentRecord Student1, Student2;
Name Name
Student1 Student2
Id Gender Id Gender
Dept Dept
6
Ex. 1: struct basics
• The members of a struct type variable are accessed with the dot (.) operator:
<struct-variable>.<member_name>;
• Example:
strcpy(Student1.Name, "Chan Tai Man"); Student1
Student1.Id = 12345;
strcpy(Student1.Dept, "COMP");
Student1.gender = 'M';
cout << "The student is ";
switch (Student1.gender){ Name
case 'F': cout << "Ms. "; break;
case 'M': cout << "Mr. "; break;
}
cout << Student1.Name << endl; Id Gender
Dept
12345 M
COMP
7
8
Ex. 2: struct-to-struct assignment
• The values contained in one struct type variable can be
assigned to another variable of the same struct type.
• Example: Student1
strcpy(Student1.Name,
"Chan Tai Man");
Student1.Id = 12345; Chan Tai Man
strcpy(Student1.Dept, "COMP");
Student1.gender = 'M';
12345 M
Student2 = Student1;
COMP
12345 M
Student2 COMP 9
10
Ex. 3-5: Nested structures
• We can nest structures inside structures.
• Examples:
struct point{
double x, y;
};
point P; (P.x, P.y)
struct line{
point p1, p2;
};
line L; (L.p2.x, L.p2.y)
struct triangle{
point p1, p2, p3;
};
triangle T;
(L.p1.x, L.p1.y)
(T.p2.x, T.p2.y)
(T.p3.x, T.p3.y)
(T.p1.x, T.p1.y)
11
Ex. 3-5: Nested structures
• We can nest structures inside structures.
• struct line{
point p1, p2;
}; (L.p2.x, L.p2.y)
line L;
(L.p1.x, L.p1.y)
line
p1 p2
x y x y
12
Ex. 3-5: Nested structures
• Assign values to the variables P, L, and T
using the picture: (4, 11)
point P; (10, 9)
line L;
triangle T; (2, 7)
(6, 5)
Ex. 3: Graph a point
Ex. 4: Graph a line
(8, 3)
Ex. 5: Graph a triangle
(2, 0)
13
Ex. 3-5: Nested structures
point P;
line L;
triangle T; (4, 11)
P.x = 4;
P.y = 11; (10, 9)
L.p1.x = 2;
L.p1.y = 7; (2, 7)
L.p2.x = 10;
L.p2.y = 9; (6, 5)
T.p1.x = 2;
T.p1.y = 0;
T.p2.x = 6; (8, 3)
T.p2.y = 5;
T.p3.x = 8;
(2, 0)
T.p3.y = 3; 14
Ex. 3: Graphing a Point
0 1 2 3 4 5 6 7 8 0 10 11 12 13 14 15
1
2 * (x1, y1)
y
3
4
5
15
struct point {int x, y;};
void user_input(point&);
void graph_point(char grid[NUMBER_ROWS][NUMBER_COLS], point);
void print_grid(char grid[NUMBER_ROWS][NUMBER_COLS]);
void set_background(char grid[][NUMBER_COLS]);
0 1 2 3 4 5 6 7 8 0 10 11 12 13 14 15
1 * (x1, y1)
2 *
y
3 *
4 *
(x2, y2)
5 *
• The equation of a line going through two points
(x1, y1) & (x2, y2) can be represented by:
(y-y1)/ (x-x1) = (y2-y1)/(x2-x1)
or y = ((y2-y1)/(x2-x1)) (x-x1) + y1
where (y2-y1)/(x2-x1) is called the slope. 17
// use struct to graph line between two points
#include <ctype> // for tolower
#include <iostream>
using namespace std;
//A function to get user input and check that it is on the grid.
void user_input(line& line1){
do{
cout << "Enter column (x<" << NUMBER_COLS
<< ") & row (y<" << NUMBER_ROWS
<< ") coordinates of the 1st point: ";
cin >> line1.p1.x >> line1.p1.y;
} while ((line1.p1.y<0) ||
(line1.p1.y>=NUMBER_ROWS) ||
(line1.p1.x<0) ||
(line1.p1.x >= NUMBER_COLS));
// use another do-while loop for the 2nd point, col2 and row2
} 20
More on Graphing Line
void graph_line(char grid[][NUMBER_COLS], line line1){
int row, col;
double rise, run, slope;
// one point
if((line1.p1.y==line1.p2.y)&&(line1.p1.x==line2.p2.x))
grid[line1.p1.y][line1.p1.x] = '*';
else if(line1.p2.x==line1.p1.x){ // infinite slope
if (line1.p1.y < line1.p2.y){
for(row=line1.p1.y; row <= line1.p2.y; row++)
grid[row][line1.p1.x] = '*';
}
else{
for(row=line1.p1.y; row >= line1.p2.y; row--)
grid[row][line1.p1.x] = '*';
}
}
21
More on Graphing Line
else{
rise=line1.p2.y-line1.p1.y; run=line1.p2.x-line1.p1.x;
slope = (double)rise / run; // run cannot = 0
if (run >0){
for(col = line1.p1.x; col <= line1.p2.x; col++){
// line1.p1.y is offset for starting point
row=(int)(slope*(col–line1.p1.x)+line1.p1.y);
grid[row][col] = '*';
}
}
else{
for(col=line1.p1.x; col >= line1.p2.x; col--){
row=(int)(slope*(col–line1.p1.x)+line1.p1.y);
grid[row][col] = '*';
}
}
}
}
22
23
Arrays of structures
• An ordinary array: One type of data
0 1 2 … 98 99
0 1 2 … 98 99
24
Arrays of structures
• We often use arrays of structures.
• Example:
StudentRecord Class[100];
strcpy(Class[98].Name, "Chan Tai Man");
Class[98].Id = 12345;
strcpy(Class[98].Dept, "COMP");
Class[98].gender = 'M';
Class[0] = Class[98]; Chan Tai Man
12345 M
COMP
...
0 1 2 … 98 99 25
Arrays inside structures
• We can use arrays inside structures.
• Example: (4, 3) (10, 3)
struct square{
point vertex[4];
};
(4, 1) (10, 1)
square Sq;
26
Pointers
A pointer is a reference to another variable (memory
location) in a program
– Used to change variables inside a function (reference
parameters)
– Used to remember a particular member of a group (such
as an array)
– Used in dynamic (on-the-fly) memory allocation
(especially of arrays)
– Used in building complex data structures (linked lists,
stacks, queues, trees, etc.)
Outline
Pointers
Basics
Variable declaration, initialization, NULL pointer
& (address) operator, * (indirection) operator
Pointer parameters, return values
Casting points, void *
Arrays and pointers
1D array and simple pointer
Passing as parameter
Dynamic memory allocation
calloc, free, malloc, realloc
Dynamic 2D array allocation (and non-square arrays)
Pointer Basics
Variables are allocated at addresses in computer memory
(address depends on computer/operating system)
Name of the variable is a reference to that memory address
A pointer variable contains a representation of an address of
another variable (P is a pointer variable in the following):
Name V P
Address v (some value) p (some value)
int V = 101;
Abstract
101
Representation
int *P = &V;
Concrete 4 bytes for 4 bytes for
Representation int value 101 mem address v
Pointer Variable Definition
Basic syntax: Type *Name
Examples:
int *P; /* P is var that can point to an int var */
float *Q; /* Q is a float pointer */
char *R; /* R is a char pointer */
Complex example:
int *AP[5]; /* AP is an array of 5 pointers to ints */
– more on how to read complex declarations later
Address (&) Operator
The address (&) operator can be used in front of any
variable object in C -- the result of the operation is
the location in memory of the variable
Syntax: &VariableReference
Examples:
int V;
int *P;
int A[5];
&V - memory location of integer variable V
&(A[2]) - memory location of array element 2 in array A
&P - memory location of pointer variable P
Pointer Variable Initialization/Assignment
NULL - pointer lit constant to non-existent address
– used to indicate pointer points to nothing
Can initialize/assign pointer vars to NULL or use the
address (&) op to get address of a variable
– variable in the address operator must be of the right
type for the pointer (an integer pointer points only at
integer variables)
Examples:
int V;
int *P = &V;
int A[5];
P = &(A[2]);
Indirection (*) Operator
A pointer variable contains a memory address
To refer to the contents of the variable that the
pointer points to, we use indirection operator
Syntax: *PointerVariable
Example:
int V = 101;
int *P = &V;
/* Then *P would refer to the contents of the variable V
(in this case, the integer 101) */
printf(“%d”,*P); /* Prints 101 */
Pointer Sample
int A = 3; Q = &B;
int B; if (P == Q)
int *P = &A; printf(“1\n”);
int *Q = P; if (Q == R)
int *R = &B; printf(“2\n”);
if (*P == *Q)
printf(“Enter value:“); printf(“3\n”);
scanf(“%d”,R); if (*Q == *R)
printf(“%d %d\n”,A,B); printf(“4\n”);
printf(“%d %d %d\n”, if (*P == *R)
*P,*Q,*R); printf(“5\n”);
Reference Parameters
To make changes to a variable that exist after a
function ends, we pass the address of (a pointer to)
the variable to the function (a reference parameter)
Then we use indirection operator inside the function
to change the value the parameter points to:
void changeVar(float *cvar) {
*cvar = *cvar + 10.0;
}
float X = 5.0;
changeVar(&X);
printf(“%.1f\n”,X);
Pointer Return Values
A function can also return a pointer value:
float *findMax(float A[], int N) {
int I;
float *theMax = &(A[0]);
for (I = 1; I < N; I++)
if (A[I] > *theMax) theMax = &(A[I]);
return theMax;
}
void main() {
float A[5] = {0.0, 3.0, 1.5, 2.0, 4.1};
float *maxA;
maxA = findMax(A,5);
*maxA = *maxA + 1.0;
printf("%.1f %.1f\n",*maxA,A[4]);
}
Pointers to Pointers
A pointer can also be made to point to a pointer
variable (but the pointer must be of a type that
allows it to point to a pointer)
Example:
int V = 101;
int *P = &V; /* P points to int V */
int **Q = &P; /* Q points to int pointer P */
free(nums);
• Concept of files
Files
fp = fopen(“filename”, “mode”);
/*opens file with name filename , assigns identifier to fp */
• fp
– contains all information about file
– Communication link between system and program
• Mode can be
– r open file for reading only
– w open file for writing only
– a open file for appending (adding) data
Different modes
• Writing mode
– if file already exists then contents are deleted,
– else new file with specified name created
• Appending mode
– if file already exists then file opened with contents safe
– else new file created
• Reading mode
– if file already exists then opened with contents safe
– else error occurs.
• Ensures
– All outstanding information associated with file flushed out from
buffers
– All links to file broken
– Accidental misuse of file prevented
• If want to change mode of file, then first close and open again
Closing a file
Syntax: fclose(file_pointer);
Example:
fclose(f1);
} /*end main */
fscanf() and fprintf()
• similar to scanf() and printf()
• in addition provide file-pointer
• given the following
– file-pointer f1 (points to file opened in write mode)
– file-pointer f2 (points to file opened in read mode)
– integer variable i
– float variable f
• Example:
fprintf(f1, “%d %f\n”, i, f);
fprintf(stdout, “%f \n”, f); /*note: stdout refers to screen */
fscanf(f2, “%d %f”, &i, &f);
• fscanf returns EOF when end-of-file reached
getw() and putw()
fp = fopen(“input.dat”, “r”);
if (fp == NULL)
printf(“File could not be opened \n ”);
Random access to files
$ cc args.c -o args.out
$ ./args.out 2 join leave 6
6
leave
join
2
./args.out
$