[Week 9] Programming Basics 8
[Week 9] Programming Basics 8
PROGRAMMING
BASICS 8
Arrays
- A group of contiguous memory locations
- All elements have the same type.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 7 printf("%s%17s\n", "Face", "Frequency");
.
BASIS AND PRACTICE IN PROGRAMMING
PROGRAMMING
BASICS 8
Since sum_array needs to know the actual length of a, we must supply it as a second argument.
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.
Consider the following two functions and function calls for them.
void modifyElement(int e) {
e *= 2;
}
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
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.
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
return -1;
}
.
BASIS AND PRACTICE IN PROGRAMMING
PROGRAMMING
BASICS 8
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.
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
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.
#include <stdio.h>
#define SIZE 20
int main() {
char string1[SIZE];
char string2[] = "string literal";
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
int m[5][9];
Multidimensional arrays
can have more than two indices.
Initializing a Multidimensional Array
If there are not enough initializers for a given row, the remaining elements of that row
are initialized to 0.
If there are not enough initializers, the remaining elements are initialized to 0.
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}};
printf("%d\n", noo);
return 0;
}
Multidimensional Arrays as Arguments
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
#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;
}
}
#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;
}
}