06 - Theory of A Computer and Arrays
06 - Theory of A Computer and Arrays
Fundamentals
Week 3 - Lecture 6
What did we learn last lecture?
Code Style and Code Reviews
Introduction of Functions
Arrays
● Maintains a “state”
● Works based on a current set of instructions
● Can read and write from/to memory
In our C Programming
● From registers (tiny bits of memory on the CPU) through Random Access
Memory (RAM) and to the Hard Disk Drive. All of these are used to store
information
CPU
RAM Hard Drive
Registers
Let’s take a look at our current capability (and why we need arrays) . . .
An Example
Let’s record everyone’s marks at the end of the term
0 1 2 3 4 5 6 7 8 9
arrayOfMarks 55 70 44 91 82 64 62 68 32 72
The trick then becomes looping to access all individual elements one by one
User input/output with Arrays
Using printf and scanf with Arrays
https://xkcd.com/844/
A Basic Program using Arrays
Let's make a program to track player scores in a game
#include <stdio.h>
#define NUM_PLAYERS 4
int main(void) {
int scores[NUM_PLAYERS] = {0};
int counter;
scores 55 84 32 61
● The lowest
● The highest
● And the total
Finding particular values in an array
If we see all the values, we can easily find the highest
We just add all the values to a variable we're keeping outside the loop
int total = 0;
counter = 0;
while (counter < NUM_PLAYERS) {
total += scores[counter];
counter++;
}
printf("Total points scored across the players is %d", total);
Wait, what was that new syntax?
+= is another shorthand operator
int a = 0;
int b = 0;
Arrays