0% found this document useful (0 votes)
6 views61 pages

CS112 Programming Languages 1 (Lecture 2 - Spring 2020)

This document outlines the content of a Level 1 programming course focused on C/C++ arrays, including one-dimensional and two-dimensional arrays, constants, and the #define directive. It covers data types, array declaration, initialization, accessing elements, and passing arrays to functions, along with practical coding examples. The course is based on materials from renowned institutions like Harvard and MIT, aimed at teaching fundamental programming concepts in a structured manner.

Uploaded by

zeyadzzzzsss
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)
6 views61 pages

CS112 Programming Languages 1 (Lecture 2 - Spring 2020)

This document outlines the content of a Level 1 programming course focused on C/C++ arrays, including one-dimensional and two-dimensional arrays, constants, and the #define directive. It covers data types, array declaration, initialization, accessing elements, and passing arrays to functions, along with practical coding examples. The course is based on materials from renowned institutions like Harvard and MIT, aimed at teaching fundamental programming concepts in a structured manner.

Uploaded by

zeyadzzzzsss
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/ 61

CS112 – Level 1

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

char - a single character like ‘a’, ‘?’, or ‘2’

float - a real number with a decimal value/point

double - a floating-point value with even more


digits

int - integers up to a certain size, or number


of bits, & their negatives

long - integers with more bits, so they can


count higher

string - a(n) string/array of characters

...
Recap
Inside our computers, we have chips called RAM, random-
access memory, that stores data for short-term use.

We might save a program or file to our hard drive (or SSD)


for long-term storage, but when we open it, it gets copied to
RAM first. Though RAM is much smaller, and temporary
(until the power is turned off), it is much faster.
We can think of bytes, stored in RAM, as though they Recap
were in a grid:

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>

int main( void )


{
// Scores
int score1 = 72;
int score2 = 73;
int score3 = 33;

// Print average
printf("Average: %f\n", (score1 + score2 + score3) / 3.0);
}

What if we have 5 numbers entered by the user?


2.2: Write a C program to calculate the average
of 5 numbers, and read those numbers from
the user.
#include <stdio.h>

int main( void )


{
// Scores
int score1, score2, score3, score4, score5;
printf("\nEnter 1st score:"); scanf("%d", &score1);
printf("\nEnter 2nd score:"); scanf("%d", &score2);
printf("\nEnter 3rd score:"); scanf("%d", &score3);
printf("\nEnter 4th score:"); scanf("%d", &score4);
printf("\nEnter 5th score:"); scanf("%d", &score5);
// Print average
printf("Average: %f\n", (score1 + score2 + score3 + score4 + score5) / 5.0);
}
2.3: Write a C program to calculate the
average of an arbitrary number of scores?
We can print the average of 3 or 5 numbers,
#include <stdio.h> BUT now we need to make one variable for
every score we want to include! And we
int main( void ) can’t easily use them later!
{
// Scores
int score1, score2, score3, score4, score5 .. ?
printf("\nEnter 1st score:"); scanf("%d", &score1);
printf("\nEnter 2nd score:"); scanf("%d", &score2);
printf("\nEnter 3rd score:"); scanf("%d", &score3);
printf("\nEnter 4th score:"); scanf("%d", &score4);
printf("\nEnter 5th score:"); scanf("%d", &score5);
.. ?
// Print average
printf("Average: %f\n", (score1 + score2 + score3 + score4 + .. ? ) / .. ?);
}
Arrays
Arrays
It turns out, in memory, we can store variables one after another, back-to-
back. And in C, a list of variables stored, one after another in a contiguous
chunk of memory, is called an array ..

0 1 2 3 4 5

Arrays are data structures that allow us to store data of the


same type in contiguous memory locations ..

Note that array indices in C always start at 0!


Arrays .. Why?

Various problems in life need arrays, for example:

o A group of grades for a student needs to be saved


together. If you save these grades – for example 5 grades
– without using an array, you have to define 5 different
variables. But if you use arrays, you can define just one
variable as an array that contains 5 values.

o Thus, when we need a way to hold different homogenous


values in order to apply some sort of processing on all of
these values. Varying processing types may be applied,
such as calculating the average of these values, or the
total summation of the values, … etc.
Arrays
Declare an array by specifying the data type it will store, its name,
as well as its size.
<data type> name[<size>];
Arraydeclaration

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

(memory locations), all those constituting


variables have the same type, and share a
common name.
o Array a:
o int a[3] = { 4, 7, 2 }; 4
o In this case, a place in the memory is 7 a
2
located for this array.
o The name of this place is a.
o The values in this place are 4, 7, and 2.
o The type of the values is integer.
o The size of this place is (3 * 4) bytes, where
3 is the number of integers.
Arrays
Another Example .. Here, we declare an array of 3 integers called
temperature and load it with values.

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

Notice that arrays are zero-indexed, meaning


that the first element, or value, has index 0.
}
Arrays Example
RAM
#include <stdio.h>

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

o Two important precautions should be taken into


consideration:
o You can not define the size of an array using
variables
o int x = 3;
o int a[ x ];  array size cannot be a variable
o You can not access an element outside the array
(i.e., calling an index that is out of the array size).
o int a[ 3 ];
o a[ 4 ] = 5;  array-index-out-of-bound
Passing Arrays to Functions

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)

Arrays are: c[0] -45


o Structures of related data items c[1] 6

o Static entity – same size throughout the c[2] 0


c[3] 72
program c[4] 1543
o Group of consecutive memory locations c[5] -89

o Same name and type c[6] 0


c[7] 62
o To refer to an element, specify c[8] -3
o Array name c[9] 1

o Position number c[10] 6453


c[11] 78
o Format:
o arrayname[ position number ]
Position number of
o First element at position 0 the element within
o n element array named c: array c
c[ 0 ], c[ 1 ], .., c[ n – 1 ]
Arrays: Key Points

Array elements are like normal variables


o c[ 0 ] = 3;
o printf( "%d", c[ 0 ] );
o Perform operations in subscript. If x equals 3
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
Arrays: Key Points

When defining arrays, specify:


o Name
o Type of array
o Number of elements
o arrayType arrayName[ numberOfElements ];
o Examples:
o int c[ 10 ];
o float myArray[ 3284 ];
o Defining multiple arrays of same type:
o Format similar to regular variables.
o For example:
o int b[ 100 ], x[ 27 ];
Arrays Multi-
Dimensional
Two-Dimensional
Arrays
Multidimensional Arrays
Arrays can be multidimensional.
You can think of multidimensional
arrays as "arrays of arrays." 0,0 0,1 0,2

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

Here, we declared and initialized


o
a 2-dimensional array tic-tac-toe 2,0 2,1 2,2
board.
o
Multidimensional Arrays
Accessing Multidimensional Array Elements
This code uses nested for loops to print out all elements of the
tic-tac-toe board array.

// print out all elements


for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%c", board[i][j]);
printf("\n");
}
}
2 Dimensional Arrays
A 2-dimentional array a which contains three rows and four
columns can be represented as:
2 Dimensional Arrays

A two dimensional array is the same as several identical arrays


put together. It is a matrix that consists of a certain number of
rows and columns.

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

An one-dimensional array is usually processed via a for loop.


Similarly, a two-dimensional array may be processed using
two nested loops.
0 1 2 3 4 5 6
const int NumCols = 7; 0 0 0 0 0 0 0 0
int Array[ NumCols ];
for ( int Col = 0; Col < NumCols; Col++ )
{
Array[ Col ] = 0;
}
2 Dimensional Arrays
A one-dimensional array is usually processed via a for loop.
Similarly, a two-dimensional array may be processed using two
nested loops. 0 1 2 3 4 5 6
0 0 0 0 0 0 0 0
const int NumRows = 3; 1 0 0 0 0 0 0 0
const int NumCols = 7;
int Array[ NumRows ][ NumCols ]; 2 0 0 0 0 0 0 0
for ( int Row = 0; Row < NumRows ; Row++ )
{
for ( int Col = 0; Col < NumCols; Col++ )
{
Array[ Row ][ Col ] = 0;
}
}
2 Dimensional Arrays

A one dimensional array can be initialized while declared as


follows:

int Array[ 7 ]={ 0, 0, 0, 0, 0, 0, 0 };

Also a two dimensional array can be initialized while


declared as follows:

int Array[ 3 ][ 7 ] = { { 0, 0, 0, 0, 0, 0, 0 }, {0, 0, 0, 0, 0, 0, 0 },


{ 0, 0, 0, 0, 0, 0, 0 } };
2 Dimensional Arrays

If you define a two dimensional array as follows:


int grades[ 3 ][ 6 ];
What is the size of this array in the memory?
There is in an operator in C++ that can yield the size of the
array:
printf("%d", sizeof( grades ) );
The output of this method in this case is:
sizeof( grades ) = 4 * 3 * 6 = 72
where 4 is the size of an integer, 3 is the number of rows,
and 6 is the number of columns.
2.4: Exercise: Calculating the Average

Let’s try to find the average of the grades for a group of students
(not a single student as in the previous problem).

If you have a set of 6 grades per student, for three students:


• The grades of the 1st student are: 73, 35, 63, 81, 12, and 70.
• The grades of the 2nd student are: 63, 56, 31, 31, 52, and 58.
• The grades of the 3rd student are 53, 45, 73, 31, 12, and 20.

o Calculate the average value of the grades for each student.


o Print this average.
2.4: Solution: Calculating the Average

Thus we have 3 students * 6 subjects


Therefore, we need a two dimensional array:
• with 3 rows, one for each student.
• with 6 columns, one for each subject.
0 1 2 3 4 5
0 73 35 63 81 12 70
1 63 56 31 31 52 58
2 53 45 73 31 12 20
2.4: Solution: Calculating the Average
#include <stdio.h>
int main() {
int grades[3][6] = { { 73, 35, 63, 81, 12, 70 }, { 63, 56, 31, 31, 52, 58 },
{ 53, 45, 73, 31, 12, 20 } };
for ( int i = 0; i < 3; i ++) {
int sum = 0; float average;
for ( int j = 0; j < 6; j++ ) {
sum = sum + grades[ i ][ j ];
}
average = (float) sum / 6;
printf( "Average of the grades for student %d is: ", i + 1 );
printf( "%f\n", average );
}
}
The output is :
Average of the grades for student 1 is 55
Average of the grades for student 2 is 48
Average of the grades for student 3 is 39
Passing 1-D Array to a function
#include <stdio.h>
int getMax(int arr[], int R)
{
int max = 0;
for(int i = 0; i < R; i++)
if(max < arr[ i ])
max = arr[ i ];
return max; This is called a function call
} getMax(array, 2)
int main() { The first parameter is a 1
int array[2]; dimensional array, and the
for(int i = 0; i < 2; i++) second parameter is an integer
scanf("%d", &array[ i ]); just like the function defined
printf("%d", getMax(array, 2) ); above.
}
Passing a 2-D Array to a function
#include <stdio.h> We can also pass C as we pass R, or
const int C = 4; make them both constants too (but
these constants should be global, i.e.
int getMax(int arr[][C], int R) {
can be accessed by both the main
int max = 0; and the getMax functions).
for(int i = 0; i < R; i++)
for(int j = 0; j < C; j++)
if(max < arr[i][j])
max = arr[i][j];
This is called a function call
return max;
} getMax(array, 3)
int main(){ The first parameter is a 2
int array[3][C]; dimensional array, and the
for(int i = 0; i < 3; i++) second parameter is an integer
for(int j = 0; j < C; j++) just like the function defined
scanf("%d", &array[ i ][ j ]);
above.
printf("%d", getMax( array, 3 ) );
}
Multiple-Subscripted Arrays: Key Points

Multiple subscripted arrays


Tables with rows and columns (m by n array)
Like matrices: specify row, then column
Column 0 Column 1 Column 2 Column 3

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

o Initializers grouped by row in braces


o If not enough, unspecified elements set to zero
o int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 1 0
3 4
o Referencing elements
o Specify row, then column
o printf( "%d", b[ 0 ][ 1 ] );
2.5: Write a program in C to print an array’s
elements using recursion.

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;

printf("\n\n Recursion: Print the array elements :\n");


printf(" Input the number of elements to be stored (max. 100) : ");
scanf("%d", &n );
printf(" Input %d elements in the array :\n", n );
for( i = 0; i < n; i++ )
{
printf(" Element - %d : ", i );
scanf("%d", &arr1[ i ] );
}
printf(" The elements in the array are : ");
ArrayElement( arr1, 0, n ); // call the function ArrayElement
printf("\n\n");
return 0;
}
void ArrayElement( int arr1[], int st, int length )
{
if( st >= length )
return;
//Prints the current array element
printf( "%d ", arr1[ st ] );
/* Recursively call ArrayElement to print next element in the array */
ArrayElement( arr1, st + 1, length ); // calling the function ArrayElement again
}
2.6: Write a Program in C to Add two Matrices
of the Same Size.
Sample Output:
Input the size of the square matrix (max. 5): 2

Input the elements of the First Matrix :


Element - [0],[0] : 1
Element - [0],[1] : 2
Element - [1],[0] : 3
Element - [1],[1] : 4

Input the elements of the Second Matrix :


Element - [0],[0] : 5
Element - [0],[1] : 6
Element - [1],[0] : 7
Element - [1],[1] : 8
2.6: Write a Program in C to Add two Matrices
of the Same Size.
Sample Output:
The First Matrix is :
1 2
3 4

The Second Matrix is :


5 6
7 8

The Addition of the Two Matrices is :


6 8
10 12
#include <stdio.h>
int main()
{
int arr1[ 5 ][ 5 ], brr1[ 5 ][ 5 ], crr1[ 5 ][ 5 ], i, j, n;

printf("\n\nAddition of two Matrices :\n");


printf("------------------------------\n");
printf("Input the size of the square matrix (max. 5): ");
scanf("%d", &n);

/* Stored values into the array*/


printf("Input the elements of the First Matrix :\n");
for( i = 0; i < n; i++ )
{
for( j = 0; j < n; j++ )
{
printf("Element - [%d],[%d] : ", i, j );
scanf("%d", &arr1[ i ][ j ] );
}
}
printf("Input the elements of the Second Matrix :\n");
for( i = 0; i < n; i++ ) {
for( j = 0; j < n; j++ )
{
printf("Element - [%d],[%d] : ", i, j );
scanf("%d", &brr1[ i ][ j ] );
}
}

printf("\nThe First Matrix is :\n");


for( i = 0; i < n; i++ ) {
for( j = 0; j < n; j++ )
printf("%d\t", arr1[ i ][ j ] );
printf("\n");
}
printf("\nThe Second Matrix is :\n");
for( i = 0; i < n; i++ ) {
for( j = 0; j < n; j++ )
printf("%d\t", brr1[ i ][ j ] );
printf("\n");
}
/* calculate the sum of the matrix */
for( i = 0; i < n; i++ )
for( j = 0; j < n; j++ )
crr1[ i ][ j ] = arr1[ i ][ j ] + brr1[ i ][ j ];

printf("\nThe Addition of the Two Matrices is : \n");


for( i = 0; i < n; i++ )
{
for( j = 0; j < n; j++ )
printf("%d\t", crr1[ i ][ j ] );
printf("\n");
}
}
Thanks! .. Questions?

You might also like