Reputation: 15
I have a quick question. Trying to create a method to print out an array, however, the compiler is telling me that it isn't declared in the scope.
Here's my code:
int main() {
int theArray[10] = {41, 23, 43, 12, 43, 23, 12, 41, 29, 102};
printArray(theArray, 10);
}
Here's my printArray method:
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i ++) {
std::cout <<" "<< arr[i];
std::cout << std::endl;
}
}
Any clue what I'm doing wrong?
Upvotes: 1
Views: 2913
Reputation: 20311
Your code is perfectly fine. Just make sure that necessary includes
are exist. And the order of the methods:
#include <iostream>
#include <string>
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
std::cout << " " << arr[i];
std::cout << std::endl;
}
}
int main() {
int theArray[10] = { 41, 23, 43, 12, 43, 23, 12, 41, 29, 102 };
printArray(theArray, 10);
return 0;
}
Or use forward declaration
:
#include <iostream>
#include <string>
void printArray(int arr[], int size);
int main() {
int theArray[10] = { 41, 23, 43, 12, 43, 23, 12, 41, 29, 102 };
printArray(theArray, 10);
return 0;
}
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
std::cout << " " << arr[i];
std::cout << std::endl;
}
}
However, you may write it in more C++ modern Style:
1) Using templated function :
#include <iostream>
#include <string>
#include <array>
template<std::size_t N> void printArray(std::array<int, N> x) {
for (auto const& item:x){
std::cout << " " << item << std::endl;
}
}
int main() {
std::array <int, 10> theArray{ { 41, 23, 43, 12, 43, 23, 12, 41, 29, 102 } };
printArray<10>(theArray);
return 0;
}
2)The better by using iterators:
#include <iostream>
#include <string>
#include <array>
template<typename Iterator> void printArray(Iterator beg, Iterator end) {
for (auto it = beg; it != end; it = std::next(it)){
std::cout << " " << *it << std::endl;
}
}
int main() {
std::array <int, 10> theArray{ { 41, 23, 43, 12, 43, 23, 12, 41, 29, 102 } };
printArray(std::begin(theArray), std::end(theArray));
return 0;
}
Upvotes: 3