Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

[Week 9] Programming Basics 8

Uploaded by

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

[Week 9] Programming Basics 8

Uploaded by

cbd11218
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

BASIS AND PRACTICE IN PROGRAMMING

PROGRAMMING
BASICS 8

INSTRUCTOR YOUNGHOON KIM


Recap

Arrays
- A group of contiguous memory locations
- All elements have the same type.

Declaration and initialization


- Squared brackets ([]) specifies that the variable is for an array. (with its size)
- You can initialize an array with an initializer list within curly brackets ({}) while declaring it.
- A loop is a good choice for initializing or accessing the array.
Example Program
with an Array
Rolling a Die 60,000,000 Times

Rolling a Die 60,000,000 Times and Summarizing the Results in an Array


- Roll a single six-sided die 60,000,000 times to test whether the random number generator
actually produces random numbers.
Rolling a Die 60,000,000 Times

unsigned int frequency[SIZE] = {}; // SIZE is a symbolic constant defined by '#define'.


for(unsigned int roll = 1; roll <= 60000000; roll++) {
size_t face = 1 + rand() % 6;
frequency[face]++;
}

Scaling and shifting for emulating a die


- Remainder and addition operators are used for it.
- The results are directly used as indices.
- CHECKPOINT: How should the array be declared to do that?

frequency array holds the number of occurrences of numbers


- increment operator increases the value one by one.
Rolling a Die 60,000,000 Times

for(int face = 1; face < SIZE; face++) {


printf("%4d%17d\n", face, frequency[face]);
}

Printing the result with formatting


- '%4d%17d' reserves spaces for pretty outputs.

We don't need to additional codes for summarizing results.


- Printing the values of frequency array is enough for summarization.
- CHECKPOINT: We can use 'size_t' instead of 'int' for face variable.
What's the meaning of it and where should be modified for clean compiling?
Rolling a Die 60,000,000 Times DEMO

Rolling a Die 60,000,000 Times and Summarizing the Results in an Array


- Checkpoints will be handled during demo.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 7 printf("%s%17s\n", "Face", "Frequency");

int main() for(int face = 1; face < SIZE; face++) {


{ printf("%4d%17d\n", face, frequency[face]);
unsigned int frequency[SIZE] = {}; }
srand(time(NULL));
return 0;
for(unsigned int roll = 1; roll <= 60000000; roll++) { }
size_t face = 1 + rand() % 6;
frequency[face]++;
}

.
BASIS AND PRACTICE IN PROGRAMMING

PROGRAMMING
BASICS 8

INSTRUCTOR YOUNGHOON KIM


Passing Arrays
to Functions
Passing Arrays to Functions

Arrays can be used as parameters.


- C does NOT allow us to specify the size of the array parameter with its declaration.
- Usage of a one-dimensional array as a parameter

int f(int a[]) // no length specified


{

}
void main()
{
int a1[100] = {1,2,3};
f(a1);
}

In function f, how do we know the proper length of a[]?


Passing Arrays to Functions

Since sum_array needs to know the actual length of a, we must supply it as a second argument.

int sum_array(int a[], int n) { // n: size of a


int i, sum = 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum;
}

void main() {
int a1[100] = {1,2,3};
int sum = sum_array(a1, 100);
}
Passing Arrays with Symbolic Constant

When the array size is globally known in advance and fixed during the execution,
we can use a symbolic constant for it.

#define SIZE 100


int sum_array(int a[]) {
int i, sum = 0;
for (i = 0; i < SIZE; i++)
sum += a[i];
return sum;
}
void main() {
int a1[SIZE] = {1,2,3};
int sum = sum_array(a1);
}
Passing an Array Element

Consider the following two functions and function calls for them.

void modifyArray(int a[], size_t size) {


for(size_t i = 0; i < size; i++)
a[i] *= 2;
}

void modifyElement(int e) {
e *= 2;
}

(Somewhere in the code)


modifyArray(a, SIZE); // a is an array
modifyElement(a[3]); // calling with an element
Passing Arrays to Functions DEMO

Two function calls with an array in a different manner


- We can compare the results of those two function calls.
void printArray(int a[], size_t size)
{
for(size_t i = 0; i < size; i++) {
char c;
c = (i==size-1)? '\n':' '; // for the pretty output
printf("%d%c", a[i], c);
}
}

int main()
{
int nums[SIZE];
for( size_t i = 0; i < SIZE; i++ )
nums[i] = i; // initializing the array
printArray(nums, SIZE);
modifyArray(nums, SIZE); // The same function defined before. nums is an array
printArray(nums, SIZE);
modifyElement(nums[3]); // The same function defined before. calling with an element
printArray(nums, SIZE);

return 0;
}
Passing an Array Element

(Somewhere in the code)


modifyArray(a, SIZE); // a is an array
modifyElement(a[3]); // calling with an element

We can see that the array is modified with the first function call, but no modification occurs with
the second one.
Call-by-reference or pass-by-reference
- When we pass an array to a function, we can modify elements of the array, and this mechanism is called as 'call-by-
reference'.
- It is about the addresses of variables, which is related to pointers. (will be discussed later.)
Call-by-value or pass-by-value
- Other data types rather than arrays or pointers, only values are copied into the function via parameters, which are local
variables for functions.
- Values in the callers' variables cannot be modified with this mechanism.
Searching
Arrays
Searching Arrays

Searching
- It may be necessary to determine whether an array contains a value that matches
a certain key value.
- The process of finding a particular element of an array is called searching.

Searching an Array with Linear Search


- The linear search compares each element of the array with the search key.
- Because the array is not in any particular order,
it’s just as likely that the value will be found in the first element as in the last.
- On average, therefore, the program will have to compare the search key with half the elements
of the array.
Searching Arrays

for(size_t i = 0; i < size; i++) {


if(array[i] == key) {
return i;
}
}

Linear Searching is done by visiting all elements of the target array.


- for loop is a well-match for it.
- We have to check the current value is our key or not.
- CHECKPOINT: The loop can end without returning a value. What does it imply?
Searching Arrays Example DEMO

Linear search for an array


- A function prototype declares the function and the compiler makes a link to its definition.
- Check the message when the linearSearch function returns -1.

printf("Enter integer search key: ");


#include <stdio.h>
int searchKey;
#define SIZE 100
scanf("%d", &searchKey);
int index = linearSearch(a, searchKey, SIZE);
int linearSearch(const int array[], int key, size_t size);

if(index != -1) {
int main()
printf("Found value at index %d\n", index);
{
} else {
int a[SIZE];
puts("Value not found");
}
for(size_t x = 0; x < SIZE; x++) {
a[x] = 2 * x;
return 0;
}
}
Searching Arrays Example DEMO

Linear search function


- When the loop ends not returning a value, the key is not in the array.
- We need to return an error code or any value that can indicate the situation.
- -1 is used in the code, because indices are positive numbers.

int linearSearch(const int array[], int key, size_t size)


{
for(int i = 0; i < size; i++) {
if(array[i] == key) {
return i;
}
}

return -1;
}

.
BASIS AND PRACTICE IN PROGRAMMING

PROGRAMMING
BASICS 8

INSTRUCTOR YOUNGHOON KIM


Character
Arrays
printf("%s", "Hello\n"); (re-visited)

C string can be printed out using printf function with a conversion specifier '%s’.
- %s: a conversion specifier for string data
- You can use '%s' with C strings or variables with string data.

String variables in C are with 'char array' data type.


- Use squared brackets after the variable name to specify the string length.
They are called 'arrays' which will be dealt later.
- The size of the string MUST be greater than the actual string length.

char hello[10] = "Hello"; // A string variable


char name[10] = "Mike";
printf("%s, %s!\n", hello, name); // Printing string variables with %s
printf("%s", "Hello\n"); // Weird, but ok.
Using Character Arrays to Store and Manipulate Strings

A string such as "Hello" is an array of individual characters in C.


A character array can be initialized using a string literal only when declaring it.

char string1[] = "first"; // The size is determined by the length of "first"

Above code initializes the elements of array string1 to the individual characters in the string
literal "first".
Array string1 contains six elements.
- Five characters from "first" and a special string-termination character called the null character ('\0')
- All strings in C end with this character.
- You MUST define a string variable to be large enough to hold the number of characters in the string and the terminating
null character.
Using Character Arrays to Store and Manipulate Strings

The preceding definition is equivalent to

char string1[] = {'f', 'i', 'r', 's', 't', '\0'};

We can access individual characters in a string directly using array index notation.
- string1[0]: the character 'f', string1[3]: the character 's'

char string2[20];

Above code creates a character array capable of storing a string of at most 19 characters and a
terminating null character.
- If the data is not a string, we can store upto 20 bytes in string2 variable.
Using Character Arrays to Store and Manipulate Strings

char string2[20];
scanf("%s", string2);

We also can input a string directly into a character array usingscanf using a conversion
specifier %s.
Above code reads a string from the keyboard into string2.
The name of the array is passed to scanf without the preceding &.
- Remember the call-by-reference mechanism on function calls in the previous slide.
- string2 variable can be modified by the scanf function.
- An array name is the address of the start of the array, so the function can directly access the array.
Function scanf will read characters until a space, tab, newline or end-of-file indicator is
encountered not considering the size of the array. (Be cautious!!)
- The scanf() automatically appends the null character( '\0' ) to the end of the input string.
Using Character Arrays to Store and Manipulate Strings

char string2[20];
scanf("%s", string2);
printf("%s\n", string2);

A character array representing a string can be output with printf and the %s conversion specifier.
The array string2 is printed with the last statement.

The characters of the string are printed until a terminating null character is encountered.
- Function printf, like scanf, does not check how large the character array is.

The following demo demonstrates


- initializing a character array with a string literal
- reading a string into a character array
- printing a character array as a string and
- accessing individual characters of a string.
Character Array Example DEMO

A simple program with various string variable usages.


- Entering characters more than SIZE might cause a runtime error.
- scanf() automatically appends '\0' at the end of the input string.

#include <stdio.h>
#define SIZE 20

int main() {
char string1[SIZE];
char string2[] = "string literal";

printf("%s", "Enter a string (no longer than 19 characters): ");


scanf("%s", string1);

printf("string1 is: %s\nstring2 is: %s\n", string1, string2);

printf("string1 with spaces between characters is:\n");


for(size_t i=0; i<SIZE && string1[i] != '\0'; i++) {
printf("%c ", string1[i]);
}

puts("");
return 0;
}
.
Reading Materials

char string2[20];
scanf("%19s", string2);

- The string2 should be no longer than 19 characters to leave room for the terminating null
character.

- If the user types 20 or more characters, your program may crash or create a security
vulnerability. For this reason, we used the conversion specifier %19s so that scanf reads a
maximum of 19 characters and does not write characters into memory beyond the end of the
array string2.

- It’s your responsibility to ensure that the array into which the string is read is capable of holding
any string that the user types at the keyboard.

- Function scanf does not check how large the array is.
BASIS AND PRACTICE IN PROGRAMMING

PROGRAMMING
BASICS 8

INSTRUCTOR YOUNGHOON KIM


Multidimensional
Array
Multidimensional Arrays

Arrays in C can have multiple indices.


The following declaration creates a two-dimensional array
- a table or a matrix, in mathematical terminology

int m[5][9];

- m has 5 rows and 9 columns. (called 5-by-9 array)


- Both rows and columns are indexed from 0.

Multidimensional arrays
can have more than two indices.
Initializing a Multidimensional Array

Remind the initialization of an array with declaration

int m[5] = {1, 1, 1, 1, 1};

Initializing multidimensional arrays


- Similar to one dimensional arrays
- Nesting one-dimensional initializers
- The values are grouped by row in braces.

// "5 rows, 9 columns" means that each row has 9 elements.


// We have 5 one-dimensional initializers with 9 elements.
int m[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1},
{0, 1, 0, 1, 0, 1, 0, 1, 0},
{0, 1, 0, 1, 1, 0, 0, 1, 0},
{1, 1, 0, 1, 0, 0, 0, 1, 0},
{1, 1, 0, 1, 0, 0, 1, 1, 1}};
Initializing a Multidimensional Array in Detail

int b[2][2] = {{1, 2}, {3, 4}};

A two-dimensional array int b[2][2] is defined and initialized.


- The values in the first braces initialize row 0 and the values in the second braces initialize row 1.
- 1 and 2 are for b[0][0] and b[0][1], respectively.
- 3 and 4 are for b[1][0] and b[1][1], respectively.

If there are not enough initializers for a given row, the remaining elements of that row
are initialized to 0.

int b[2][2] = {{1}, {3, 4}};

This code would initialize b[0][0] to 1, b[0][1] to 0, b[1][0] to 3 and b[1][1] to 4.


Initializing a Multidimensional Array in a different way

int b[2][2] = {1, 2, 3, 4};

We can initialize a multidimensional array without inner braces.


- Arrays occupy contiguous memory space.
- The values in the initializer will be placed as in order.
- First two values are for the first row and the next two are for the second row.

If there are not enough initializers, the remaining elements are initialized to 0.

int b[2][2] = {1, 2};

Above code initializes b[0][0] to 1, b[0][1] to 2, b[1][0] to 0 and b[1][1] to 0.


Traversing Multidimensional Arrays

for loops are used for traversing arrays.


- for loops match to array operations.
- It naturally gives us indexes for traversing.

Multiples indexes for multidimensional arrays


- For rows and columns (Higher dimensional arrays needs more indexes.)

Nested for loops


- for loops inside of a for loop
Traversing Multidimensional Arrays

total = 0;
for (int row = 0; row <= 2; ++row) { // size_t can be used
for (int column = 0; column <= 3; ++column) { // instead of int
total += a[row][column];
}
}

The for statement totals the elements of the array one row at a time.

The variable 'row' and 'column' are used for fixing rows and columns to visit.

When the nested for statement terminates, total contains the sum of all the elements
in the array a.
Count 1s in the Array DEMO

With a given two-dimensional array, make a program that count the occurrences of 1.
- A nested loop can be the best choice for this problem.
- If you want to count the occurrences on each line, how can we modify the program?

#include <stdio.h>

int main()
{ int m[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1},
{0, 1, 0, 1, 0, 1, 0, 1, 0},
int m[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1}, …};
{0, 1, 0, 1, 1, 0, 0, 1, 0},
{1, 1, 0, 1, 0, 0, 0, 1, 0},
int noo = 0; {1, 1, 0, 1, 0, 0, 1, 1, 1}};

for(int i=0; i<5; i++)


for(int j=0; j<9; j++)
if(m[i][j] == 1)
noo++;

printf("%d\n", noo);
return 0;
}
Multidimensional Arrays as Arguments

Remember passing single dimensional array to functions


- The size of the array should be specified.

Similar thing happens here too.


- First dimensional size can be omitted, but with passing the number of rows.
- Subsequent sizes are mandatory.

void PrintArray (int m[][9], int rows){


for (int i = 0; i < rows; i++) {
for (int j = 0; j < 9; j++) {
printf("%d ", m[i][j]);
}
printf("\n");
}
}
Multidimensional Array Example DEMO

Example code for 'passing arrays to functions' and 'nested initializers’.


- Variation will be done on the initializers.
- printArray function is working but not properly written. What is wrong with it?

int main() {
void printArray(int a[][3])
int array1[2][3] = {{1,2,3}, {4,5,6}};
{
printArray(array1);
for (int i=0; i<=1; i++) {
for(int j=0; j<=2; j++) {
int array2[2][3] = {1,2,3,4,5};
printf("%d ", a[i][j]);
printArray(array2);
}
printf("\n");
int array3[2][3] = {{1,2}, {4}};
}
printArray(array3);

return;
return 0;
}
}
Exercise: Identity Matrix

Fill in the code to make an identity matrix.

#define N 5
double e_mat[N][N];
for (int row = 0; row < N; row++) {
for (int col = 0; col < N; col++) {
if (row == col)
e_mat[row][col] = 1.0;
else Fill in here
e_mat[row][col] = 0.0;
}
}

Initializing a two-dimensional array with nested for loops


Exercise: Identity Matrix

Fill in the code to make an identity matrix.

#define N 5
double e_mat[N][N];
for (int row = 0; row < N; row++) {
for (int col = 0; col < N; col++) {
if (row == col)
e_mat[row][col] = 1.0;
else
e_mat[row][col] = 0.0;
}
}

Initializing a two-dimensional array with nested for loops


.
Reading Materials

- Arrays in C can have multiple indices.

- A common use of multidimensional arrays is to represent tables of values consisting of


information arranged in rows and columns.

- To identify a particular table element, we must specify two indices:


The first (by convention) identifies the element’s row and the second (by convention) identifies
the element’s column.

- Tables or arrays that require two


indices to identify a particular
element are called
two-dimensional arrays.

- Multidimensional arrays can have


more than two indices.
Reading Materials

- The figure illustrates a two-dimensional array, a.


The array contains three rows and four columns, so it’s said to be a 3-by-4 array.
- In general, an array with m rows and n columns is called an m-by-n array

You might also like