Scripting Error

gagandeeps123
Giga Contributor

I am facing one issue in this script. My output should be 's', 'r', 'i', but in this script . I am getting error having infinite loop
var i;
var str1 ="servicenow";
for(i=0;i<6;i+2){
gs.print(str1[i]);
}
Please let me know Where am I doing the error.

1 ACCEPTED SOLUTION

Basudeb Mishra
Tera Expert

Hello Gagandeep,
Error found is i+2, It should be i+=2 or i = i+2 otherwise you can use i++ inside the for loop and again inside the loop block you can use i=i+1

 

var i;
var str1 ="servicenow";
for(i=0;i<6;i=i+2){
    gs.print(str1[i]);
}

Output is 's', 'r', 'i'.

I have attached the screenshot for better understanding.

BasudebMishra_1-1697368518857.png

 

If you like my solution please do like and follow me on LinkedIn for better connection

Regards

Basudeb Mishra

 

View solution in original post

2 REPLIES 2

Basudeb Mishra
Tera Expert

Hello Gagandeep,
Error found is i+2, It should be i+=2 or i = i+2 otherwise you can use i++ inside the for loop and again inside the loop block you can use i=i+1

 

var i;
var str1 ="servicenow";
for(i=0;i<6;i=i+2){
    gs.print(str1[i]);
}

Output is 's', 'r', 'i'.

I have attached the screenshot for better understanding.

BasudebMishra_1-1697368518857.png

 

If you like my solution please do like and follow me on LinkedIn for better connection

Regards

Basudeb Mishra

 

Danish Bhairag2
Tera Sage
Tera Sage

Hi @gagandeeps123 ,

 

The issue in your script is with the loop's increment statement. In your loop, you are using `i+2`, which calculates the new value of `i + 2` but doesn't update the `i` variable itself. As a result, the loop never reaches its termination condition (`i<6`) because `i` is always 0.

 

To fix this, you should update the `i` variable inside the loop by adding 2 to its current value. Here's the corrected version of your script:

 

var i;

var str1 = "servicenow";

for (i = 0; i < 6; i = i + 2) {

    gs.print(str1[i]);

}

 

In this corrected script, `i = i + 2` updates the value of `i` in each iteration, allowing the loop to progress correctly. With this change, the output of the script will be `'s', 'r', 'i'` as expected.

 

Mark my answer helpful & accepted if it helped u resolve your issue.

 

Thanks,

Danish