mercredi 13 mai 2020

For loop not iterating properly in c++

This is my Code

#include<iostream>
using namespace std ;
int main()
{
    int  n , k ,i=1 ,c=0;
    cin>>n>>k;
    int a[n];
    for(int l = 0 ; l<k ;l++){
        cin>>a[l] ;

    }
    i=1;
    for(int j=0;j<k;j++){
        if(a[j]>=i){
            c+=a[j]-i;
        }
        else{
            c+=n-i + a[j] ;
        }
//       printf("i = %d , j = %d , c = %d , a[i] = %d \n" ,i,j,c,a[i]) ;
       cout<<i<<" "<<j<<" "<<c<<" "<<a[j] <<endl;
        i = a[j];
    }
    cout<<c<<endl;
}

This is the output

enter image description here

Doesn't this mean my code stops iterating at 6 while it must run till 54 ? Why did it stop at 6 , can someone explain ?

Aucun commentaire:

Enregistrer un commentaire