The program is supposed to display the days of the week from saturday to sunday using an array, which it does, but I get an error afterwards and the program has to exit. What is causing this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
usingnamespace std;
int main() {
constint SIZE = 7;
string daysOfWeek[SIZE] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" } ;
cout << "Here are the days of the week: \n" ;
for (int count = 6; count < SIZE; count--)
cout << daysOfWeek[count] << endl;
return 0;
}
IN the beginning count is equals to 6. 6 is less than SIZE (7) so daysOfWeek[6] (Saturday) is outputted.
count is decremented
...
count is equal to 0. 0 is less than 6, so daysOfWeek[0] (Sunday) is outputted
count is decremented.
count is equal to -1. -1 is less than 6, so program tries to output daysOfWeek[-1];
I just tried changing count's initialization to 7 instead of 6 and then to 7 with count <= SIZE. First time I didnt get an error but I didnt get any of the days of the week, second time I didnt get any of the days and the program had to stop running right away.
I tell you that your condition is always true and useless. You need to capture moment when count becomes negative, not uselessly wait when constantly decreasing variable suddenly become larger than something.
for (int iterator = 6; iterator >=0; iterator--)
cout << daysOfWeek[iterator] << (some end-line thing like endl) ;
Look at MiiNiPaa's first comment; THERE CANNOT BE any negative numbers for an array. Array[lessThan0] will never work. So make it stop at 0, and in future reference, make it so that the loop stops. Otherwise, it will keep going.