04 Loops, Arrays, and Pointers
04 Loops, Arrays, and Pointers
• Conditional loops
• Counter-controlled loops
• break and continue
3
Previous lesson recaps
4
To succeed in this course…
5
if statement – do it or skip it
Statement(s)
Syntax: if (condition) statement
6
Comparison and logical operators
Operator Description • Comparison operators yield 1 for true and 0
== Equal to for false
!= Not equal to
Greater than
>
• We use logical operators to combine “logical
Greater than or
>= clauses” Operator Description
equal to
< Less than ! Negation (NOT)
Less than or && AND
<=
equal to || OR
7
Other important points
• Short-circuit evaluation
• Computation cost savings
• Preventing unwanted execution
• Be careful with equality == and assignment = operators
• Never directly compare floating-points for equality
• Defensive programming where possible – always guard against
potential invalid/malicious inputs
8
Type conversion
• When operands’ types are different, one of the operand will automatically be
promoted to the larger/wider type (if possible)
• Roughly, byte à short à int à long à float à double
• Conversion from a large int to float, or a large long to float or double is
potentially lossy
• Conversion between signed and unsigned where the source value is out of
the target type range is lossy 9
Blocks are treated as single statements
• You’ve seen an example of blocks (or compound statements, enclosed in {
… }) in the previous example
• Use blocks when more than one statement are being executed together
• Without using blocks, the return statement will always be executed
if (choice < 0 || choice > 9)
printf("Invalid choice (%d)\n", choice);
return -1; 10
if … else statement – do this or do that
Syntax:
if (condition) statement1 else statement2 Condition
False
True
int n = 123;
Statement(s)1 Statement(s)2
if (n % 2 == 0)
printf("%d is even.\n", n);
else
printf("%d is odd.\n", n);
C reference: https://en.cppreference.com/w/c
Still, I recommend getting a book – your life will be easier that way
17
Let’s continue with the lesson
18
Let’s start with problems again
• Many problems require us to do things repeatedly
• What is the value of 10! (factorial of 10)?
• If we sum up integers from 1 to N, what are the largest N such that the sum is
less than 1,000?
return 0;
}
22
Problem: sum of a series
• If we sum up integers from 1 to N, what is the largest N such that the
sum is less than 50?
• Understanding the problem
• What is the expected output?
• What are the inputs?
• What is the condition?
• Thinking about loops:
• What should each iteration do?
• What is the terminating condition?
23
Sum of a series
#include <stdio.h>
Result:
int main() N that sums up to 45 = 9
{
int target = 50;
int n = 1, sum = 0;
More concise version
while (sum + n < target) {
while (sum + n < target)
sum += n;
sum += n++;
n++;
}
return 0;
}
24
do … while loop – act first, then check
Statement(s)
• Keep reading the user input until the input is within the range 1-100
26
Input validation
#include <stdio.h> Result:
Enter your guess (1-100): 0
int main() Enter your guess (1-100): 101
{ Enter your guess (1-100): 100
int guess; You guessed 100.
do {
printf("Enter your guess (1-100): ");
scanf("%d", &guess);
} while (guess < 1 || guess > 100);
return 0;
}
27
Can we use while loop for that?
#include <stdio.h>
int main()
{
int guess;
return 0;
}
28
Counter-controlled loops
29
Factorial of 10
#include <stdio.h>
int main()
{
int n = 10;
int fact = 1;
int i = 1; Result:
while (i <= n) {
fact *= i; 10! = 3628800
i++;
}
return 0;
}
30
From while loop to for loop
int main()
{
int n = 10;
int fact = 1; Compared with
int i = 1;
for (int i = 1; i <= n; i++) while (i <= n) {
fact *= i; fact *= i;
i++;
printf("%d! = %d\n", n, fact); }
return 0;
}
32
Scope of the initialized variable
• The for loop here: • If we move the declaration out:
34
Sum of a series with skipping
#include <stdio.h>
return 0;
}
35
When to use which?
• while is more commonly used for conditional loops
• You have an action p that needs to be done on every iteration, and the
condition c depends on the result of action p
• In this case, if you use while, you will need to duplicate p both before the
while clause and within the body of the while, so do … while is a better fit
36
Sequential data structures
Arrays and strings
Arrays
Value 5 3 1 2 4 10 7 4 6 11
Index 0 1 2 3 4 5 6 7 8 9
int main()
{
int arr[] = { 3, 4, 2, 0, 1 }; Result:
int num_elems = 5;
Sum = 10
int sum = 0;
return 0;
}
40
Finding the maximum
#include <stdio.h>
#define NUM_SCORES 5
Result:
int main()
{ 5 7 2 9 6
int scores[NUM_SCORES]; Max = 9
// Read user inputs into array
for (int i = 0; i < NUM_SCORES; i++)
scanf("%d", &scores[i]); // array element needs &
return 0;
}
41
Address Memory Variable
Variables, memory, and addresses
0xBC04 A0
• Variables are stored in memory 0xBC05 86
exp
0xBC06 01
• Memory is a collection of byte-addressable cells
0xBC07 00
0xBC08 42
int exp = 100000; // 0x186A0 0xBC09 65
char name[8] = "Beck"; // 0x42 0x65 0x63 0x6B 0x00 0xBC0A 63
int *ptr = &exp; // 0xBC04 0xBC0B 6B
name
0xBC0C 00
0xBC0D ?
• Pointers are variables that store addresses – they point 0xBC0E ?
to data stored in memory 0xBC0F ?
• Note that actual in-memory ordering of variables is not 0xBC10 04
ptr
0xBC11 BC
guaranteed to be the same as the declaration order
42
Pointers
• Pointer variable declaration: type *name;
int *ptr;
• “Address of” operator (&) is used to get the address of a variable
ptr = &exp;
• Array and string variable names represent their memory addresses – we can
get their addresses directly without using & operator
• “Pointer dereference” operator (*) is used to get the value stored at the
memory address pointed to by the pointer
*ptr = *ptr + 1000;
• It is also used for assigning a value to that memory address
43
Pointers in action Result:
Value at 00000000005FFE80 = 3
int arr[] = { 3, 4, 2, 0, 1 }; Value at 00000000005FFE84 = 4
Value at 00000000005FFE88 = 2
int *ptr = arr; Value at 00000000005FFE8C = 0
Value at 00000000005FFE90 = 1
Address of the pointer = 00000000005FFE78
for (int i = 0; i < 5; i++) {
printf("Value at %p = %d\n", ptr, *ptr);
ptr++;
}
printf("Address of the pointer = %p\n", &ptr);
• Not used in most other languages (including C++ which has another
string type)
45
Null-terminated strings
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
0xA10D
0xA10C
0xA10B
0xA110
0xA111
0xA112
0xA113
0xA114
0xA115
0xA116
0xA10E
0xA10F
Address
48
Counting string length
#include <stdio.h> Result:
Enter a word: Hello!
int main() Length of "Hello!" = 6
{
char str[20];
int i = 0;
while (str[i] != '\0')
i++;
return 0;
}
49
Counting string length (pointer version)
#include <stdio.h>
int main()
{
char str[20];
return 0;
}
50
Problem: copying a string
• Given a source string variable and a destination string variable, copy the
content of the source string to the destination string
51
Copying a string
#include <stdio.h> Result:
int main() Enter a word: Hello!
{ Content of dest = "Hello!"
char src[20];
char dest[20] = "1234567890123456789";
return 0;
}
52
Copying a string (using for loop)
#include <stdio.h>
int main()
{
char src[20];
char dest[20] = "1234567890123456789";
return 0;
}
53
Copying a string (pointer version)
#include <stdio.h>
int main()
{
char src[20];
char dest[20] = "1234567890123456789";
return 0;
}
54
Problem: concatenating two strings
55
Concatenating two strings
char src[20];
char dest[25] = "12345";
Result:
Enter a word: Hello!
printf("Enter a word: "); Content of dest = "12345Hello!"
scanf("%19s", src);
int i = 0, j = 0;
dest[j] = '\0';
*q = '\0';
58
That’s it for today!
59