-2

I got this for-loop:

for(int k=4;k<0;k--){
    if(k == 0){
        test[k] = 5;
        break;
    }
    else{
        test[k] = test[k-1];
    }
}

it should shift the elements of the array to the right, but nothing happens. To my knowledge it should work just fine, but the compiler says, that the for-loop statement has no effect: statement with no effect [-Wunused-value]

can anyone help me solve this problem?

Tomas0206
  • 77
  • 1
  • 7

3 Answers3

1

The loop initializes k to a positive value (k=4) and then loops while k is negative (k<0).

Since k is never negative, the loop has no effect.

Did you mean to write k >= 0?

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

The condition expression of the loop is wrong.

for(int k=4;k<0;k--){

You initialized k with 4 and then are checking whether it is less than 0. As 4 is obviously greater than 0 then the loop will iterate never.

I think you mean the following

for(int k = 4; k >= 0; k-- ) {

But in any case the code looks badly. For example it is not clear what the magic number 5 means and there is no need to use the break stztement.

You could write a function. Here is an example of the corresponding program

#include <stdio.h>

void shift_right( int a[], size_t n )
{
    if ( n > 1 )
    {
        size_t i = n - 1;
        int last = a[i];

        for ( ; i != 0 ; --i ) a[i] = a[i - 1];

        a[i] = last;
    }
}

int main(void) 
{
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    const size_t N = sizeof( a ) / sizeof( *a );
    size_t i;

    for ( i = 0; i < N; i++ ) printf( "%d ", a[i] );
    puts( "" );

    shift_right( a, N );

    for ( i = 0; i < N; i++ ) printf( "%d ", a[i] );
    puts( "" );

    return 0;
}

The output is

0 1 2 3 4 5 6 7 8 9 
9 0 1 2 3 4 5 6 7 8
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

In your loop you use condition k<0 -> 4<0 -> false. so your condition fails in first time itself.so your loop has not executed.so change your conditional statement to k>0 instead of k<0. use the printf statement to find the loop is executes or not.

 for(int k=4;k>=0;k--){
        if(k == 0){
            test[k] = 5;
            break;
        }
        else{
            test[k] = test[k-1];
        }
    }

The above code works as you expected.

Selva
  • 1,620
  • 3
  • 33
  • 63