Computer Programming for
Engineering Applications
ECE 175
Intro to Programming
02/13/2021 ECE 175 1
Lecture Set Overview
• Array in C
• Declaration, initialization, and sequential access
• Arrays and function in C
• Pointer with Arrays
02/13/2021 ECE 175 2
Why array?
• What if we want to write the program to keep the homework score
- for 100 students?
declare variables x1, x2, x3, …., x100
Note: there is a better way!
- for 1000 students?
• What if we want to write a program dealing with paragraphs (statements)
in the text file? such as counting number of every alphabet in the text file,
search for a specific word in the text file.
• What if we want to write the code to do a calculation on a vector or a
matrix (linear algebra)?
Efficient handling of multiple variables of same data type where
those variables are related to each other.
02/13/2021 ECE 175 3
Arrays
A collection of two or more adjacent memory cells, called array elements
associated with a single symbolic name.
array_name[array_subscript]
First memory cell 2 x[0]
5 x[1]
6 x[2]
1 x[3]
7 x[4]
9 x[5]
8 x[6]
2 x[7]
02/13/2021 ECE 175 4
Declaring arrays
Declaration specifies array name and the number of elements in the array
Syntax: data_type array_name[# of elements];
Examples: int counters[26];
double temp[10];
char initial[20];
#define NUM 8
int x[NUM];
double score[NUM];
The number of elements must be defined (may use constant variables)
C does not check for array boundaries; so be careful in accessing arrays
02/13/2021 ECE 175 5
Accessing an array
Each element of the array (location) can be accessed using an array subscript.
The subscript always starts from 0.
Example:
int x[8] = {10, 5, 2, -3, 25, 1001, -1,
23}
x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]
10 5 2 -3 25 1001 -1 23
Every element of the array may be viewed as an independent variable
6
02/13/2021 ECE 175
Exercise 1 (3 mins):
1) For the declaration: int number[20];
- how many memory cells are allocated for data storage?
- How do we refer to the first element of this array?
the last element of this array?
2) Declare
- an array to store the square root of the integers from 0 to 10
- an array to store the cube of the square of the integers from 2 to 15.
02/13/2021 ECE 175 7
Array Initialization
You can declare more than one array on a single declaration:
Example:
int scores[30], x, pins[10];
double temp[10], limit;
char initial[20];
Initialization – Can be done at declaration
Example:
int scores[]={0, 0, 0, 0, 0};
char vowels[]={'a', 'e', 'i', 'o', 'u', 'y'};
Notice that the size of an array that is fully initialized can be omitted
since the size can be deduced from the initialization list.
02/13/2021 ECE 175 8
Exercise 2 (5 mins): Array subscripts
As a group on the table, write on the whiteboard what get printed by the
following printf statements and content of array x
float x[ ]={10.5, 30.2, 20.23, 50.6, 90, 100};
int i=1, j=2;
printf("%.2f\n", x[0]); x[0]
printf("%.2f\n", x[i]); x[1]
printf("%.2f\n", x[2*i+1]); x[2]
x[3]
x[i] = x[i] + x[++j];
x[4]
printf("%.2f\n", x[i]);
x[5]
printf("%.2f\n", x[j]);
x[3*i]=x[i]/2;
printf("%.2f\n", x[i++]);
printf("%.2f\n", x[++i]);
02/13/2021 ECE 175 9
Using (for) loop to sequentially access an array
Arrays can be sequentially accessed using a counting for loop whose
loop control variable runs from 0 to (size of array -1).
Example:
float scores[]={10.5, 30.2, 20.23, 50.6, 90 100};
int i;
for (i=0; i < 6; i++)
printf{“%d\t%f”, i, scores[i]);
• The loop can also be used for array initialization
#define SIZE 100
int scores[SIZE], i;
for (i=0; i < SIZE; i++)
scores[i]=0;
02/13/2021 ECE 175 10
Exercise 3 (6 mins):
#include <stdio.h>
#define SIZE 10
int main(void){
int i=0, sum=0;
int x[SIZE];
for(i=0; i < SIZE; i++){
x[i] = (i+1)*10;
}
//Q1: complete the code to sum all even-index elements of
//the array => x[0] +x[2] + ... +
for( _____________________________ ){
_____________________________
}
printf("ans is %d\n", sum); //Q2: what get printed?
return 0;
}
02/13/2021 ECE 175 11
Exercise 4 (8 mins): Work as a group at your table, write a program(on whiteboard) that
lets a user enter 8 numbers (stored in an array x) and then finds 1) the maximum value and
its location and 2) average. Your code MUST use a loop structure.
#include <stdio.h>
#define MAX_SIZE 8
int main(void)
{
int x[MAX_SIZE];
int i;
printf("Enter %d numbers separated by space: ", MAX_SIZE);
Sample code execution:
Enter 8 numbers separated by space: 10.1 20.2 89 76 30.3 40.4 54 65
max = 89.00 at index = 2 and average = 48.13
02/13/2021 ECE 175 12
Activity 1: Letter Frequency
Develop an algorithm (5 mins) that counts and display the occurrence frequency
of every letter (both lowercase and UPPERcase) in a text file “[Link]”
e.g., “In the emerging Internet of Things (IoT) ecosystem, an unprecedented
volume of data will be collected through the deployment of Internet-enabled
smart devices.”
Sample code execution
Total characters in a text file: 160
a: 5 0.03%
b: 2 0.01%
…
z: 0 0.00%
Others: 28 0.17%
Work with your group, develop an algorithm to accomplish this task.
Q: how will you keep number of times that each alphabet occurs?
13
Activity (cont): Letter Frequency
Input: Text file
Output: fa , f b … fz and fother
Algorithm:
• Determine and initialize all variables (including arrays)
• open file “[Link]” to read
• read from the file character by character
update the corresponding counter
• when finished, display number occurrences of each character.
First way (INefficient way):
int num_a = 0, num_b = 0, num_c = 0, num_d = 0, …, num_z = 0, num_other = 0;
27 variables!
Second way:
int counter[27];
a b c d e f g h i j k l m n o p q r s t u v w x y z other
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
02/13/2021 ECE 175 14
(10 mins) Write (modify/add to the code below) a program to count and display the
occurrence frequency of every letter (both lowercase and UPPERcase) in a text file
“[Link]”
#include <stdio.h>
int main(void) {
FILE *inp = fopen("[Link]", "r");
char alp;
if (inp == NULL) {
printf("file not found");
}
else {
while (fscanf(inp, "%c", &alp) != EOF) {
printf("%c", alp);
}
fclose(inp);
}
return 0;
}
02/13/2021 ECE 175 15
Array and Pointer
• Array in C: elements of an array are stored in successive
memory locations with the first element (index 0) stored at
the lowest memory address.
• An array name with no subscript is a
pointer to the first array element
ex: int x[6] = { 10, 20, 30, 40, 50, 60 };
x is an address of the first element of the array ( &x[0])
02/13/2021 ECE 175 16
Array and Pointer
int main(void) {
double *ptr;
double a[] = { 10.1, 20.3, 30.3, 40.4, 50.5 };
ptr = a;//ptr = &a[0];
printf("%.1lf\n", *ptr);
ptr = ptr + 1;
printf("%.1lf\n", *ptr);
printf("%.1lf\n", *(ptr+2));
printf("%.1lf\n", *ptr+2);
ptr = &a[2];
for (i = 0; i < 3; i++) {
printf("%.1lf ", *(ptr + i));
}
return 0;
}
02/13/2021 ECE 175 17
Pointer Arithmetic
• Pointers can be incremented or decrement by integer.
Q: if p is a pointer, what does p++ or p = p + 1 mean?
A: let p contain the address of an array’s n th element, then
p + 1 is the address of an array’s (n + 1) th element.
=> It increments the value of a pointer by the number of bytes associated
with the data type that the pointer points to.
e.g. if p is a pointer of type char (1 byte), p++ will increment p by 1
if p is a pointer of type integer (4 bytes), p++ will increment p by 4
if p is a pointer of type double (8 bytes), p++ will increment p by 8
02/13/2021 ECE 175 18
Exercise 4 CONTINUED (8 mins): Work as a group at your table, rewrite the following code
using a pointer px given below.
Sample code execution:
Enter 8 numbers separated by space: 10.1 20.2 89 76 30.3 40.4 54 65
#include <stdio.h> max = 89.00 at index = 2 and average = 48.13
#define MAX_SIZE 8
int main(void){
double x[MAX_SIZE];
double *px = x;
int i, maxloc;
double sum = 0, max;
printf("Enter %d numbers separated by space: ", MAX_SIZE);
for (i = 0; i < MAX_SIZE; i++) {
scanf("%lf", &x[i]);
}
max = x[0]; maxloc = 0;
for (i = 0; i < MAX_SIZE; i++) {
sum = sum + x[i];
if (x[i] > max) {
max = x[i];
maxloc = i;
}
}
printf("max = %.2lf at index = %d and average = %.2lf\n", max, maxloc, sum/MAX_SIZE);
}
02/13/2021 ECE 175 19
Arrays and Functions
Using array elements as function arguments:
Example: double x[ ] = {16.0, 12.5, 6.0, 8.1, 2.5, 12.0, 14.0,-54.5};
• used as an input argument to function printf.
printf("%.2f %.2f\n", x[0],x[1]);
• used as an input argument to functions defined in standard libraries
y1 = sqrt(x[0]);
y2 = pow(x[2],2);
• used as an output argument of scanf.
scanf("%lf", &x[i]);
=> We can also use array as arguments to user-defined functions. In other words,
we can pass individual array elements to a function just like other variables.
02/13/2021 ECE 175 20
Array arguments
an array name with no subscript is a pointer to the first array element
Ex: function print_int_array displays all elements of a type int
array.
void print_int_array( int list[ ] , int n) {
int i;
for (i = 0; i < n; ++i)
printf("%d\t%d\n", i, list[i]);
}
function call
int id[10];
print_int_array(id, 10);
21
Example: Arrays and Functions
Calling the init and print_ar function
#include<stdio.h>
void init(float x[], int size)
{ // initialization of an array to zeros
int main(void) int i;
{ for (i=0; i<size; ++i)
int i, totalChars=0; x[i]=0;
float counters[27]; }
char letter;
// array initialization void print_ar(float *x, int size)
{ // printing of the elements of an array
init(counters,27); int i;
for (i=0; i<size; ++i)
// printing array elements printf("%.3f\n", x[i]);
print_ar(&counters[0],27); printf("\n");
}
an array name with no subscript is a pointer to the first array element
02/13/2021 ECE 175 22
Exercise 5 (8 mins): write a user-defined function vectorcalc
Given two vectors: A = [A1 A2 … An] and B = [B1 B2 … Bn]
- Sum of the two arrays = [A1+B1 A2+B2 … An+Bn]
- Dot product of the two arrays = (A1×B1) + (A2×B2) + … + (An×Bn)
#include<stdio.h>
#define SIZE 6
int vectorcalc(int x[], int y[], int sum[], int size);
int main(void){ Sample code execution:
int a[SIZE] = {2, 3, 5, -2, 8, 4 };
dot product = 66
int b[SIZE] = {-1, 4, 2, 7, 6, 3 };
int sum[SIZE]; //sum = a + b sum of a and b = [ 1 7 7 5 14 7]
int dotp = 0; //keep a.b
int i;
Note: dot product = a.b =
(2)(-1)+ (3)(4)+ (5)(2)+ (-2)(7)+
//call function here
(8)(6)+ (4)(3) = 66
printf("dot product = %d\n", dotp);
printf("sum of a and b = [");
for (i = 0; i< SIZE; i++){
printf(" %d", sum[i]);
}
printf("]\n");
return(0);
}
02/13/2021 ECE 175 23
Exercise 6 (8 mins):
Write the twoMax function that returns the locations of the
two maximum values in array x
#include<stdio.h>
#define SIZE 9
void twoMax(int x[], int size, int *max1_pt, int *max2_pt);
int main(void){
int max1,max2, arr[]={-10, 45, 15,-12, 30, 28, -1, 27, 38};
twoMax(arr, SIZE, &max1, &max2);
printf("Max 1 = %d is at index %d\n", arr[max1], max1);
printf("Max 2 = %d is at index %d\n", arr[max2], max2);
return 0;
}
02/13/2021 ECE 175 24
Array and Pointer in Functions
• Array in C: elements of an array are stored in successive
memory locations with the first element (index 0) stored at
the lowest memory address.
• An array name with no subscript is a
pointer to the first array element
Ex: int x[6] = { 10, 20, 30, 40, 50, 60 };
x is an address of the first element of the array ( &x[0])
02/13/2021 ECE 175 25
Example:
void simple(int *arr){
#include <stdio.h>
arr[0] = 0;
arr[3] = 100;
void simple(int arr[])
}
{
arr[0] = 0;
arr[3] = 100; void simple(int *arr){
} *arr = 0;
*(arr+3) = 100;
int main(void){ }
int i;
int x[5] = {10, 20, 30, 40, 50};
simple(x); simple(&x[0]);
for(i=0;i<5;i++)
printf("%d ", x[i]);
printf("\n");
return 0;
}
array name with no subscript is a pointer to the first array element
02/13/2021 ECE 175 26
Example: To write code using pointer arithmetic
void mean_fun(const int x[], int size, double *s)
{
int i=0, sum=0;
for (i=0; i<size; i++){ function call
sum = sum + x[i]; int data[10];
} double avg;
*s = 1.0*sum/ size; mean_fun(data, 10, &avg);
}
void mean_fun(int *x, int size, double *s)
{
int *p;
for (p = x; p < x + size; p++){
*s = *s + *p;
}
*s = *s/ size;
}
ECE 175 27
Activity 2: Product Codes
Develop algorithm to store up to 50 unique product codes into an array i.e.
Unique product codes that got sold in one day
Program analysis
Input: A file containing integer product codes. Product code cannot be zero
Output: The unique product codes (up to 50) – if a code is a duplicate, it is not stored.
Input file:
4564 3456 3234 4564 3467 1234 3456 3210 …
Output:
4564 3456 3234 3467 1234 3210 …
02/13/2021 ECE 175 28
#include<stdio.h>
int main(void){
// declare and initialize relevant variables
// initialize array
// opening the file for reading
(assume the file is called “[Link]”)
// read the file one integer (one product code) at a time
// if the product code does not exist, add it to array
// print the array of the unique code products
// close the text file.
}
02/13/2021 ECE 175 29
void init(int x[], int size){
#include<stdio.h> // array initialization to 0
int main(void) }
{
// initialize relevant variables void print(int x[], int size){
// array printing (only elements != 0)
// initialize array
// opening the file for reading
(assume the file is called “[Link]”)
}
// read file one integer at a time int findCode(int x[],int code, int size){
int flag = 0;
// if code product does not exist, add // return flag = 0, if code is not found
// it to array // size keeps numbers of unique codes
// found (and stored in array) x so far
// print the array of unique code
products
} return flag;
}
02/13/2021 ECE 175 30
Activity 2 (12 mins): Write a C program
that stores up to 50 unique product codes
into an array by separating into two groups
at your table and do the following
Team 1: write main and init functions
Team 2: write findCode and print functions
#include<stdio.h>
int main(void){ void print(int x[], int size){
// initialize relevant variables // array printing (only elements != 0)
// initialize array
// opening the file for reading
(assume the file is called “[Link]”)
// read file one integer at a time }
// if code product does not exist,
int findCode(int x[],int code, int size){
//add it to array int flag = 0;
// print the array of unique code // return flag = 0, if code is not found
products // size keeps numbers of unique codes
} // found (and stored in array) x so far
void init(int x[], int size){
// array initialization (to 0) return flag;
}
02/13/2021 ECE 175 31
}
Additional Exercises
02/13/2021 ECE 175 32
Exercise: Given each function call below, decide whether it will cause an error when compiled.
If yes, explain why.
If not, what are values of z after it is executed?
Assume that the main function declare the followings:
double x[]={11.1, 12.2, 13.3, 14.4, 15.5, 16.6};
double y[]={1.2, 2.4, 3.6, 4.8, 5.0, 6.0};
double z[6]={0,0,0,0,0,0};
a) add_arrays(x[0], y[0], z[0], 6);
b) add_rays(&x[0], &y[0], &z[0], 6);
c) add_arrays(x, y, z, 6);
d) add_arrays(x, y, z, 4);
e) add_arrays(x, y, z, 7);
f) add_arrays(x, y, z, y[2]);
g) add_arrays(&x[2], &y[2], &z[2], 4);
void add_arrays(const double a[], const double b[], double sum[],int n){
/* n- number of elements*/
int i;
for (i = 0; i < n; i++)
sum[i] = a[i] + b[i];
}
02/13/2021 ECE 175 33
#include <stdio.h> Exercise: What will get printed?
int main(void){
int *pint, array_int[] = {1,2,3};
double *pdouble;
double array_double[]= {0.125, 5.234, 100.678, 9.846};
char *pchar, array_char[] = "Hello";
pint = array_int;
pdouble = array_double;
pchar = array_char;
printf("%d\t%d\n", *pint, array_int[0]);
printf("%.3lf\t%.3lf\n", *pdouble, array_double[0]);
printf("%c\t%c\n", *pchar, array_char[0]);
pint++;
printf("%d\t%d\n", *pint, array_int[1]);
pdouble = pdouble+1;
printf("%.3lf\t%.3lf\n", *pdouble, array_double[1]);
pchar++;
printf("%c\t%c\n", *pchar, array_char[1]);
}
02/13/2021 ECE 175 34