APS105 L17 - Midterm Review
#APS105 Slides Lecture Link to web notes
Question 10
Write a C main function that takes in the number of lines, and prints the following pattern depending on the number of lines entered.
Example input:
Enter number of lines: 5
*****
* *
*
* *
*****
#include <stdio.h>
int main(void) {
int numLines;
printf("Enter number of lines: ");
scanf("%d", &numLines);
for (int row = 1; row <= numLines; ++row) {
for (int col = 1; col <= numLines; ++col) {
// print a * or a space
if (row == 1 || row == numLines || row == col || col == numLines - row + 1) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Question 11
Write a complete C function called arrayInArray, the prototype of which is given below. The function accepts two arrays of type int as parameters, named a and b. The sizes of b and a are unknown, but the last element in both array is always -1. All other elements in the arrays are positive integers. The function must return true if the sequence of numbers in array b is found in array a excluding the last element in the array, which is always -1.
For example, if a = {6, 8, 7, 6, 1, 7, 4, -1} and b = {6, 1, -1}, the function returns true as the sequence of {6, 1} is available in a at index 3. Another example, if a = {6, 8, 7, 6, 1, 7, 4, -1} and b = {7, 8, -1}, the function returns false as the sequence of {7, 8} is not available in a.
bool arrayInArray(int a[], int b[]) {
#include <stdio.h>
#include <stdbool.h>
int arrayLength(int arr[]) {
int length = 0;
for (int i = 0; arr[i] != -1; ++i) {
++length;
}
}
bool arrayInArray(int a[], int b[]) {
int aLength = arrayLength(a);
int bLength = arrayLength(b);
for (int i = 0; i < aLength; ++i) {
bool matches = true;
for (int j = 0; j < bLength; ++j) {
if (a[i+j] != b[j]) {
matches = false;
}
}
return matches;
}
}
int main(void) {
int a[] = {[0]=6, [1]=8, [2]=7};
int b[] = {[0]=8, [1]=7};
}