CS112 Programming Languages 1 (Lecture 2 - Spring 2020)
CS112 Programming Languages 1 (Lecture 2 - Spring 2020)
Programming Languages 1
( General Division – Software Engineering Program – Medical Informatics Program )
Lecture 2
One-Dimensional, Two-Dimensional Arrays,
Constants, .. and .. the #define Directive
Spring 2020 (Semester 2)
Week 3
Course & Lectures are based on their counterparts in the following courses:
o Harvard University's CS50; An introduction to the intellectual enterprises of
computer science and the art of programming, Harvard School of
Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New
South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++
(2011), and 6.S096 Introduction to C and C++ (2013), MIT (Massachusetts
1
Institute of Technology) OpenCourseWare.
• Data Types in C/C++
• Write a C program to calculate the average2
of
an arbitrary number of scores?
• Arrays
• Arrays .. Why?
• Precautions when using an Array
• Arrays Example
O • Passing Arrays to Functions
u • Arrays: Key Points
t
• Multi-Dimensional Arrays
Outline l
i
n
• Two-Dimensional Arrays
• Exercise: Calculating the Average
e • Passing 1-D Array to a function
• Passing a 2-D Array to a function
• Multiple-Subscripted Arrays: Key Points
• Write a program in C to print an array’s
elements using recursion.
• Write a Program in C to Add two Matrices
of the same size.
Recap
Data Types in C/C++ ..
bool - a Boolean expression of either true or
false
...
Recap
Inside our computers, we have chips called RAM, random-
access memory, that stores data for short-term use.
5
A character or a boolean, stored in 1 byte .. Recap
6
An integer or a float, stored in 4 bytes .. Recap
7
A double, in 8 bytes .. Recap
2.1: Write a C program to calculate the average
of 3 numbers.
#include <stdio.h>
// Print average
printf("Average: %f\n", (score1 + score2 + score3) / 3.0);
}
0 1 2 3 4 5
The number of
values in this array
are three values.
Declare that the
values in this The name of the
array are going to array is a. To read
be integers. This any value in this
means that every array, you are
value is going to going to use this
be an integer. name.
Arrays
Arraydeclarationandinitialization:
You can set all values of the array in just one line.
The number of
values in this array
are three values.
Declare that the
values in this The name of the The values in this array.
array is going to array is a. To read You will notice that they
be integers. This any value in this are 3, and they are all
means that every array, you are integers. The first value
value is going to going to use this is 4, the second value is
be integer. name. 7, the third value is 2.
Arrays
o An Array is a consecutive group of variables RAM
int temperature[3];
temperature[0] = 65;
0 1 2
temperature[1] = 87;
temperature[2] = 30; 65 87 30
To access any value of an array,
you have to know its index.
The index is the position of the
value in the array. The index of
the first element is zero.
OR .. Alternatively, you can declare and initialize the array in a single step (in
which case stating the size is optional).
int temperature[] = { 65, 87, 30 };
Arrays
Accessing Array Elements
0 1 2
65 87 30
for (int i = 0; i < 3; i++)
{
printf("%d\n", temperature[i]);
}
Arrays Example
RAM
#include <stdio.h>
int main(){
int a[3];
Define an array a
of 3 integers
}
Arrays Example
RAM
#include <stdio.h>
int main(){
int a[3];
a[0] = 4;
Set the first 4
a
value by 4
int main(){
int a[3];
a[0] = 4;
a[1] = 7; Set the 4
second 7 a
value by 7
}
Arrays Example
RAM
#include <stdio.h>
int main(){
int a[3]; Set the
a[0] = 4; third value
by 2 4
a[1] = 7; 7 a
a[2] = 2; 2
}
Arrays Example
RAM
#include <stdio.h>
int main(){
int a[3]; You can not access an element
a[0] = 4; outside the array. If you do so,
4
a[1] = 7; the program will not run, and 7 a
a[2] = 2; give an error saying :
2
a[3] = 5;
array-index-out-of-bound error
} where this index in not included
in your array
Arrays Example
Use a for loop to
set the values of an
#include <stdio.h> array by the user
int main(){
int a[3];
for ( int i = 0; i < 3; i++ )
{
scanf("%d", &a[i]);
}
Notice that a 3 is the
} limit of the for loop
2.3: Write a C program to calculate the
average of an arbitrary number of grades?
Lets try to solve this problem by using arrays and for loops:
#include <stdio.h>
int main()
{
//declare and initialize the array, an array of 5 grades
int grades[5] = { 73, 35, 63, 81, 12 };
float avg; int sum = 0;
for ( int i = 0; i < 5; i++ )
{
sum = sum + grades[ i ];
}
avg = (float) sum / 5;
printf("The average is: %f", avg);
}
2.3: Write a C program to calculate the
average of an arbitrary number of grades?
Lets try to solve this problem by using arrays and for loops:
#include <stdio.h>
int main()
{
//declare and initialize the array, an array of 5 grades
int grades[5] = { 73, 35, 63, 81, 12 };
float avg; int sum = 0; Notice that we repeated
for ( int i = 0; i < 5; i++ ) the value 5,
{ representing the length
sum = sum + grades[ i ]; of our array, in three
different places. So we
} can use a constant, or
avg = (float) sum / 5; fixed value, to indicate it
printf("The average is: %f", avg); should always be the
} same in those places.
Arrays Example
#include <stdio.h>
int main() {
When declaring an
const int x = 5;
array, the number of
int grades[x]; //declare the array
values in the array
for ( int i = 0; i < x; i++ ) {
should be a constant
printf("\nEnter garde %d: ", i);
variable. That is
scanf("%d", &grades[i]);
because the size of
}
the array should be
float avg; int sum = 0;
predefined and can
for ( int i = 0; i < x; i++ ) {
not be changed
sum = sum + grades[ i ];
during the running of
}
the program.
avg = (float) sum / x;
printf("The average is: %f", avg);
}
Remarks
const int x = 5;
The const keyword specifies that the object or variable is not modifiable
(i.e., specifies that a variable's value is constant and tells the compiler to
prevent the programmer from modifying it.)
#define PI 3.14
A Pre-processor directive (#define identifier replacement) ... When the pre-
processor encounters this directive, it replaces any occurrence of identifier
in the rest of the code by replacement.
• Here's an example of the usage of an array to keep track of student scores.
• This code prompts the user to enter a score for each student.
• Scores are stored in scores_array.
#include <stdio.h>
#define CLASS_SIZE 30
int main(void)
{
// declare array
int scores_array[CLASS_SIZE];
// populate array
for (int i = 0; i < CLASS_SIZE; i++)
{
printf("Enter score for student %d: ", i + 1);
scanf("%d: ", &scores_array[i]);
}
}
Precautions when using an Array
Passing arrays:
o To pass an array argument to a function, specify the name
of the array without any brackets:
o int myArray[ 24 ];
o myFunction( myArray, 24 );
o Array size usually passed to function
o Function prototype:
o void modifyArray( int b[], int arraySize );
o Parameter names are optional in prototypes:
o int b[] could be written int [].
o int arraySize could be simply int.
Passing Arrays to Functions
#include <stdio.h>
double getAverage( int arr[], int size )
{
int i, sum = 0; double avg;
for ( i = 0; i < size; ++i )
{ sum += arr[ i ]; }
avg = (double) sum / size;
return avg;
}
int main()
{
const int size = 6;
int grades[] = { 73, 35, 63, 81, 12, 70 };
printf("Average: %f ", getAverage( grades, size ) );
return 0;
}
Name of array (Note
that all elements of
this array have the
Arrays: Key Points same name, c)
char board[3][3];
board[1][1] = 'o';
board[0][0] = 'x';
x x
board[2][0] = 'o'; 1,0 1,1 1,2
board[0][2] = 'x';
For example:
const int NumRows = 3; 0 1 2 3 4 5 6
const int NumCols = 7; 0
int Array[NumRows][NumCols]; 1
2
Where:
Array[2][5] is the 3rd value (row) in 6th column ..
2 Dimensional Arrays
Let’s try to find the average of the grades for a group of students
(not a single student as in the previous problem).
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript
Array name
Row subscript
Multiple-Subscripted Arrays: Key Points
o Initialization
1 2
o int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 3 4
Sample Output:
Recursion : Print the array elements :
Input the number of elements to be stored (max. 100) : 6
Input 6 elements in the array :
Element - 0 : 2
Element - 1 : 4
Element - 2 : 6
Element - 3 : 8
Element - 4 : 10
Element - 5 : 12
The elements in the array are : 2 4 6 8 10 12
#include <stdio.h>
#define MAX 100
void ArrayElement( int arr1[], int st, int length );
int main()
{
int arr1[ MAX ]; int n, i;