Daniel Sutantyo, Department of Computing, Macquarie University
2.3 - Loop Invariant
2.3 - Loop Invariant
2.3 - Loop Invariant
2.3 - Loop Invariant
2.3 - Loop Invariant
// compute x^n
int exponentiate(int x, int n){
int i = 0, ans = 1; // initialisation
while (i < n){ // loop guard
ans = ans * x;
i = i + 1;
}
return ans;
}
2.3 - Loop Invariant
// compute x^n
int exponentiate(int x, int n){
int i = 0, ans = 1; // initialisation
while (i < n){ // loop guard
ans = ans * x;
i = i + 1;
}
return ans;
}
no, that's the loop guard
how is this relevant to what the loop is doing?
this is what the loop is doing
2.3 - Loop Invariant
// compute x^n
int exponentiate(int x, int n){
int i = 0, ans = 1; // initialisation
for(int i = 0; i < n; i++){
ans = ans * x;
}
return ans;
}
2.3 - Loop Invariant
// compute x^n
int exponentiate(int x, int n){
int i = 0, ans = 1; // initialisation
for(int i = 0; i < n; i++){
ans = ans * x;
}
return ans;
}
2.3 - Loop Invariant
// compute x^n
int exponentiate(int x, int n){
int i = 0, ans = 1; // initialisation
for(int i = 0; i < n; i++){
ans = ans * x;
}
return ans;
}
2.3 - Loop Invariant
// compute x^n
int exponentiate(int x, int n){
int i = 0, ans = 1; // initialisation
for(int i = 0; i < n; i++){
ans = ans * x;
}
return ans;
}
2.3 - Loop Invariant
void selection_sort(int arr[]){
for (int i = 0; i < n-1; i++){
int min_index = i;
for (int j = i+1; j < n; j++){
if (arr[j] < arr[min_index])
min_index = j;
}
swap(i,min_index);
}
}
2.3 - Loop Invariant
int min_index = i;
for (int j = i+1; j < n; j++){
if (arr[j] < arr[min_index])
min_index = j;
}
2.3 - Loop Invariant
int min_index = i;
for (int j = i+1; j < n; j++){
if (arr[j] < arr[min_index])
min_index = j;
}
2.3 - Loop Invariant
int min_index = i;
for (int j = i+1; j < n; j++){
if (arr[j] < arr[min_index])
min_index = j;
}
2.3 - Loop Invariant
int min_index = i;
for (int j = i+1; j < n; j++){
if (arr[j] < arr[min_index])
min_index = j;
}
2.3 - Loop Invariant
void selection_sort(int arr[]){
for (int i = 0; i < n-1; i++){
int min_index = i;
for (int j = i+1; j < n; j++){
if (arr[j] < arr[min_index])
min_index = j;
}
swap(i,min_index);
}
}
2.3 - Loop Invariant
void selection_sort(int arr[]){
for (int i = 0; i < n-1; i++){
int min_index = i;
for (int j = i+1; j < n; j++){
if (arr[j] < arr[min_index])
min_index = j;
}
swap(i,min_index);
}
}
2.3 - Loop Invariant
void selection_sort(int arr[]){
for (int i = 0; i < n-1; i++){
int min_index = i;
for (int j = i+1; j < n; j++){
if (arr[j] < arr[min_index])
min_index = j;
}
swap(i,min_index);
}
}