I'm going to take a wild stab in the dark here and guess that every single one of us has made a programming error, and when you finally figured out the problem, you thought to yourself 'what an idiot I am!'.
Well...that was me this week.
I'm going to share the course project I worked on, and what mistake I made which had me face palming.
My project was to write a function which took an array and array size and return the length of the longest sequence of increasing values.
It didn't matter if they were consecutive or any other pattern, as long as they were increasing. e.g. for array[] = {1,2,3,0,8,50,55,70). The longest sequence of increasing values would be 5 (0, 8,50,55,70).
My code succeeded with all the test parameters passed to it until it came to grading time where it failed.
This was my failed code.
`#include
int maxSeq(int *array, int n) {
int counter = 1;
int max = 0;
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
for (int i = 1; i < n; i++) {
if (array[i] > array [i-1]) {
counter++;
if (counter > max) {
max = counter;
}
}
else {
counter = 1;
}
}
return max;
}`
It took me a long time to figure out the problem. Even then, only by re-writing the programs in Clion IDE and running through numerous test cases.
I discovered that I had not accounted for situations where the program had not entered into the first if statement of the for loop. In that situation, max remains at its initialized value of 0. e.g. array [] = {2,2,2,2}
Corrected code
`#include
int maxSeq(int *array, int n) {
int counter = 1;
int max = 0;
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
for (int i = 1; i < n; i++) {
if (array[i] > array [i-1]) {
counter++;
if (counter > max) {
max = counter;
}
}
else {
counter = 1;
}
}
if (counter > max) {
max = counter;
}
return max;
}`
When I finally figured it out, I felt like a complete idiot. I had to remind myself that hindsight is 20/20 and that it's all part of the learning curve. Also, I could have put more effort into testing with all the corner cases I could think of. Be thorough, even when the code seems simple enough.
Top comments (0)