Arrays, Strings, and Pointers
03603111 Programming Fundamentals I
Department of Computer Engineering, Faculty of Engineering at Sriracha
Course outline and schedule
2
Overview
3
Previous lesson recaps
4
while loop – check first, then act
#include <stdio.h>
int main()
{
int n;
printf("Number to count up to: ");
scanf("%d", &n);
int v = 1;
while (v <= n) {
printf("%d\n", v);
v++;
}
return 0;
}
5
Condition
Statement(s)
False
True
Repeat N Times
PROBLEM: Given N, repeat an action N times
SOLUTION: We need a counter variable that counts up from 0 to N-1 (idiomatic) or 1 to N (less common)
Using while:
int i = 0; // counter variable
while (i < n) {
// Perform action ...
i++;
}
However, it is more common to use the for loop, which we will discuss next week
Using for:
for (int i = 0; i < n; i++) {
// Perform action ...
}
�Counter variables are commonly named i, j, or so, but you’re welcome to use a more meaningful name
6
CODING PATTERN
PATTERN NAME
Simple Loop Invariant
This is a simple 4-step recipe to use loop invariants that works well for problems with a single-value result that can be derived directly from a list of items
However, this is not the only way to use loop invariants, but it’s a simple way to start
7
CODING RECIPE
RECIPE NAME
break and continue
8
do … while loop – act first, then check
#include <stdio.h>
int main()
{
int guess;
do {
printf("Enter your guess (1-100): ");
scanf("%d", &guess);
} while (guess < 1 || guess > 100);
printf("You guessed %d.\n", guess);
return 0;
}
9
Condition
Statement(s)
False
True
The for loop
Convenient counter-controlled style for loop
initialize;
while (condition) {
statement(s);
step;
}
for (initialize; condition; step)
statement
11
1
2
4
3
1
2
4
3
True
False
Factorial of 10 (for loop version)
#include <stdio.h>
int main()
{
int n = 10;
int fact = 1;
for (int i = 1; i <= n; i++)
fact *= i;
printf("%d! = %d\n", n, fact);
return 0;
}
12
int i = 1;
while (i <= n) {
fact *= i;
i++;
}
Compared with
Scope of the counter variable
for (int i = 1; i <= n; i++)
fact *= i;
printf("%d\n", i);
int i;
for (i = 1; i <= n; i++)
fact *= i;
printf("%d\n", i);
13
When to use which?
14
Arrays
Problem: Counting integers equal or above the average
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Help! We’re stuck!
17
Arrays
// 10-element int array (40 bytes allocated), uninitialized
int xs[10];
// 3-element float array (24 bytes allocated), with initialization
double ys[] = { 1.0, 2.5, 4.5 };
// 5-element unsigned int array (20 bytes), initialized to 1, 2, 3, 0, 0
unsigned zs[5] = { 1, 2, 3 };
18
Value | 5 | 3 | 1 | 2 | 4 | 10 | 7 | 4 | 6 | 11 |
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Operations on arrays
int arr[3];
arr[0] = 1;
arr[1] = arr[0] + 2;
arr[arr[0] + 1] = arr[0] + arr[1];
19
Value | 1 | 3 | 4 |
Index | 0 | 1 | 2 |
Reading user inputs into an array
int main()
{
int scores[10];
// Read user inputs into array
for (int i = 0; i < 10; i++)
scanf("%d", &scores[i]); // array elements need &
// Do other stuff ...
}
20
Sum of the array
#include <stdio.h>
int main()
{
int arr[] = { 3, 4, 2, 0, 1 };
int num_elems = 5;
int sum = 0;
for (int i = 0; i < num_elems; i++)
sum += arr[i];
printf("Sum = %d\n", sum);
return 0;
}
21
Sum = 10
Result:
Solution: Counting integers equal or above the average
int elems[MAX_ELEMS];
int num_elems;
scanf("%d", &num_elems);
int sum = 0;
for (int i = 0; i < num_elems; i++) {
scanf("%d", &elems[i]);
sum += elems[i];
}
float average = (float)sum / num_elems;
int count = 0;
for (int i = 0; i < num_elems; i++) {
if (elems[i] >= average) {
count++;
}
}
printf("Count of elements above %.2f: %d\n", average, count);
22
5
7 5 3 4 2
Count of elements above 4.20: 2
Result:
Mixing data types require casting, otherwise our answer will be wrong
Example: Finding the maximum
#define MAX_LEN 100
int main()
{
int scores[MAX_LEN]; // pre-allocated size must be large enough
int num_scores;
// Read number of inputs
scanf("%d", &num_scores);
// Read user inputs into array
for (int i = 0; i < num_scores; i++)
scanf("%d", &scores[i]); // array elements need &
// Find maximum score
int max = scores[0];
for (int i = 1; i < num_scores; i++)
if (scores[i] > max)
max = scores[i];
printf("Max = %d\n", max);
}
23
5�5 7 2 9 6
Max = 9
Result:
Example: Searching for an element
int elems[] = { 6, 1, 3, 0, 9, 4, 2 };
int target;
int pos = -1;
printf("Enter a number to search: ");
scanf("%d", &target);
for (int i = 0; i < 7; i++) {
if (elems[i] == target) {
pos = i;
break;
}
}
if (pos != -1) {
printf("Found %d at position %d\n", target, pos);
} else {
printf("%d not found in the array\n", target);
}
24
Enter a number to search: 9
Found 9 at position 4
// Re-run
Enter a number to search: 5
5 not found in the array
Result:
Memory addresses and pointers
Variables, memory, and addresses
26
Address | Memory | Variable |
| | |
0xBC04 | A0 | exp |
0xBC05 | 86 | |
0xBC06 | 01 | |
0xBC07 | 00 | |
0xBC08 | 42 | name |
0xBC09 | 65 | |
0xBC0A | 63 | |
0xBC0B | 6B | |
0xBC0C | 00 | |
0xBC0D | 00 | |
0xBC0E | 00 | |
0xBC0F | 00 | |
0xBC10 | 04 | ptr |
0xBC11 | BC | |
| | |
int exp = 100000; // 0x186A0
char name[8] = "Beck"; // 0x42 0x65 0x63 0x6B 0x00
int *ptr = &exp; // 0xBC04
Pointers
int *ptr;
ptr = &exp;
*ptr = *ptr + 1000;
27
Pointers in action
int arr[] = { 3, 4, 2, 0, 1 };
int *ptr = arr;
for (int i = 0; i < 5; i++) {
printf("Value at %p = %d\n", ptr, *ptr);
ptr++;
}
printf("Address of the pointer = %p\n", &ptr);
28
Value at 00000000005FFE80 = 3
Value at 00000000005FFE84 = 4
Value at 00000000005FFE88 = 2
Value at 00000000005FFE8C = 0
Value at 00000000005FFE90 = 1
Address of the pointer = 00000000005FFE78
Result:
Strings
29
Greeting with “strings”
#include <stdio.h>
int main()
{
char name[50];
char surname[50];
int age;
printf("Enter your name: ");
scanf("%s", name);
printf("Enter your surname: ");
scanf("%49s", surname);
printf("Enter your age: ");
scanf("%d", &age);
printf("Hi %s %s, you are %d years old!\n", name, surname, age);
}
30
Enter your name: John
Enter your surname: Doe
Enter your age: 25
Hi John Doe, you are 25 years old!
Result:
C strings are arrays of char
Use %s to read a string (word)
Note that string variables do not have an & in front of them
Also, use %s to print strings
String reading can be length-limited
C uses null-terminated strings
31
Null-terminated strings
char text[10] = "Hello!";
32
Content | | | 'H' | 'e' | 'l' | 'l' | 'o' | '!' | '\0' | | | | | |
Memory | | | 48 | 65 | 6C | 6C | 6F | 21 | 00 | 00 | 00 | 00 | | |
Index | | | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | | |
Address | | 0xA10B | 0xA10C | 0xA10D | 0xA10E | 0xA10F | 0xA110 | 0xA111 | 0xA112 | 0xA113 | 0xA114 | 0xA115 | 0xA116 | |
Reading strings with scanf()
char str[20];
printf("Enter a word: ");
scanf("%s", str);
scanf("%19s", word);
33
Problem: Counting string length
34
Solution: Counting string length
#include <stdio.h>
int main()
{
char str[20];
printf("Enter a word: ");
scanf("%19s", str);
� int count = 0;
while (str[count] != '\0')
count++;
� printf("Length of \"%s\" = %d\n", str, count);
return 0;
}
35
Enter a word: Hello!
Length of "Hello!" = 6
Result
Convenient function for string length
for (int i = 0; i < strlen(s); i++) {
// Do something
}
36
Problem: Find and replace characters
37
Solution: Find and replace characters
char str[50];
char src;
char dest;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Enter character to replace: ");
scanf(" %c", &src);
printf("Enter replacement character: ");
scanf(" %c", &dest);
int i = 0;
while (str[i] != '\0') {
if (str[i] == src) {
str[i] = dest;
}
i++;
}
printf("Modified string: %s\n", str)
38
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == src) {
str[i] = dest;
}
}
With for loop
That’s all for today!
39