+ 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

28th Nov 2017, 7:57 PM
Ali Hashemi
Ali Hashemi - avatar
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; }
28th Nov 2017, 8:20 PM
AgentSmith
+ 9
can also do it recursively instead of loops 😬
28th Nov 2017, 11:11 PM
Burey
Burey - avatar
+ 2
thanks Burey but one thing you have used loops
28th Nov 2017, 8:08 PM
Ali Hashemi
Ali Hashemi - avatar
+ 2
@Ali You're more than welcome bro! Hope that helped you out with your problem.
28th Nov 2017, 8:39 PM
AgentSmith
+ 1
thanks a lot man Im an amateur , and I dont know c funcs but I will search for them. thanks again
28th Nov 2017, 8:29 PM
Ali Hashemi
Ali Hashemi - avatar
+ 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.
28th Nov 2017, 9:57 PM
Zeke Williams
Zeke Williams - avatar
+ 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.
28th Nov 2017, 10:59 PM
Jakub Stasiak
Jakub Stasiak - avatar
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.
29th Nov 2017, 9:54 AM
Timon Paßlick