In: Computer Science
Input: An array of non-negative integers, where each element in the array represents your maximum jump length at that position.
Output: A boolean value if you are able to reach the last index starting if you start at the first spot in the array.
Example 1:
Example 2:
#include<iostream>
using namespace std;
int main()
{
int a[100],n=0,i=0,sum=0;
cout<<endl<<"Enter a non negative
number(-ve number to terminate input)";
//infinite loop to input non negative
numbers
while(1)
{
cin>>a[n];//stor ethe number
if(a[n]<0) //validate the number
{
n--;//if -ve discard the
number and decrease the index n
break;//terminate the
loop
}
n++;//increase the index
}
//loop to process the array values
for(i=0;i<n;)
{
//update the value of i by adding the jump lengt
i=i+a[i];
if(i==(i+a[i])) //if value of i and
i+a[i] equal then stop the loop because
//you will be unable to movce
forward
break;
}
if(i==n) //if v;alue of i match with value of n then
return n
cout<<endl<<"TRUE";//display true
else
if(i>n) //if value of i exceeds to n then you are
out of array
cout<<endl<<"FALSE(You will go out of
range)";//display false with error message
else //display the message because you will be unable
tomove forward
cout<<endl<<"FALSE(You
will always arrive at, and get stuck at index
"<<i<<")";
}
OUTPUT