I'm having trouble understand how to reverse my output using the For loop. At first I thought I could just replace the ++ with --, but that obviously didn't work. I'm thinking I need to change something with my x integer equation but can't figure it out. Any help is greatly appreciated
There are also functions built into c++ to get the size of the array, but you could write a loop to find the size for you as well.
The sizeof operator works pretty well but you have to be careful with it.
Unless each element is of the same length in characters you could run into problems.
Here would be a couple of examples to maybe give you an idea.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
int main(){
char letters[] = {'a', 'b', 'c', 'd', 'e'};
for (int i = sizeof(letters); i > 0; i--){
std::cout << letters[i-1] << " ";
}
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <string>
int main(){
std::string letters[] = {"ab", "cd", "ef", "gh", "ij"};
for (int i = (sizeof(letters))/(sizeof(letters[0])); i > 0; i--){
std::cout << letters[i-1] << " ";
}
return 0;
}
(sizeof(letters))/(sizeof(letters[0]) is basically the size of the entire array divided by the size of an individual array element.
This tells you how many elements are in the array because sizeof doesn't distinguish different array elements for you, it just returns the size of the entire array even if individual elements contain different amounts of characters.