So i have an Array{4,7,5,8,1,3,9,2,6,0} need to write a continuous loop | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

So i have an Array{4,7,5,8,1,3,9,2,6,0} need to write a continuous loop

I need to print an output 0 So the loop condition is that it should start with position 0.So 0 position has value 4 so now the position should shift to 4 which has value 1 then again to position 1 which has value 7 and so on......and finally it need to print 0 which is in position 9

6th Jun 2018, 8:05 AM
Rohit Reddy Ch
Rohit Reddy Ch - avatar
3 Antworten
+ 7
Rohit Reddy Ch I added some comments in the code and verbose output to explain what happens in the loop, hope it helps. Thank you ; )
6th Jun 2018, 2:38 PM
Ipang
+ 4
This is my noob way to it in C++ #include <iostream> int main() { int arr[] {4,7,5,8,1,3,9,2,6,0}; unsigned int index {0}; // The loop is infinite, but with the help // of 'if' condition in loop body the loop // will stop when arr[index] equals zero while(true) { // print the value of arr[index] // *** Commented temporarily *** //std::cout << arr[index] << " "; // This section will show what is // happening during the loop std::cout << "Current index: " << index << " arr[" << index << "] = " << arr[index] << "\n " << "Next index to be used: " << arr[index] << "\n"; // Exit the loop if the arr[index] // value is zero if(!arr[index]) break; // Use the value of arr[index] // for the next referred index index = arr[index]; } return 0; } Hth, cmiiw
6th Jun 2018, 8:51 AM
Ipang
+ 1
Hi Rohit, I wrote this in Javascript, and hope this is what you're asking for. please note that the "document.write()" is only for testing. you can replace it with "console.log()" or whatever you need. var x = [4,7,5,8,1,3,9,2,6,0]; for (var i = 0; i < x.length; i) { document.write("<br> i is now " + i); i = x[i]; document.write("<br> i is now " + i); if (i == 0) { document.write("<br> i is now ZERO... END"); break; } }
6th Jun 2018, 8:22 AM
Ridwan Abrash
Ridwan Abrash - avatar