+ 2
How to print an array by its pointer ?
I mean is it possible not to use loops to print an array ? maybe by its pointer
9 Answers
+ 1
@Ali
Here you go. Not sure if it's what you're looking for, but it's done without using a "loop." I mean technically it's a loop by concept, but it's not a loop in terms of the official programming functions.
Let me know if you were looking for something diff and I'll help out if I can.
https://code.sololearn.com/cdlHVezPeCON/#cpp
int main() {
int arr[5] = {1,2,3,4,5};
int i = 0;
printArr:
printf("Index (%d) is %d \n", i, arr[i]);
i++;
if(i < 5){
goto printArr;
}
return 0;
}
+ 9
can also do it recursively instead of loops đŹ
+ 2
thanks Burey
but one thing you have used loops
+ 2
@Ali
You're more than welcome bro! Hope that helped you out with your problem.
+ 1
thanks a lot man
Im an amateur , and I dont know c funcs but I will search for them.
thanks again
+ 1
Generally, you never want to use 'goto' in C++. You must use loops to iterate over an array otherwise. Learning to code with goto will NOT teach you how to think about C++ code structure in the right way.
+ 1
Well if you don't wanna loops you might do it like:
Put the last index in "last" place.
std::ostream_iterator<int> out_it (std::cout,", ");
std::copy ( arr, &arr[last], out_it );
You create ostream_iterator object (first argument: stream that we will throw output to. Second argument: separator between elements.), then you use copy function to copy all elements from array to our ostream iterator.
0
You could modify the memory of the output buffer directly, but a loop will be used implicitly to flush it. Unless you want to print a giga byte of text to the console, I wouldn't recommend you to do so. And a console isn't well suited to view a giga byte of text.