Joe
Joe

Reputation: 37

For-loop error in c

I've downloaded a program which seems to have an error at the line:

for(i=0; i<SIZE_OF_DATA; i--){ 

in main.c, however as a newbie programmer I'm not too sure how to resolve it.

Here's main.c :

#include <stdio.h>
#include "util.h"

#define SIZE_OF_DATA 10

int main(void) {
    int data[SIZE_OF_DATA];

    generateRandomData(data, SIZE_OF_DATA);


    int i;
    for(i=0; i<SIZE_OF_DATA; i--){
        printf("%d: %d\n",i,data[i]);
    }

    return 0;
}

Upvotes: 1

Views: 87

Answers (3)

Nitin Pandey
Nitin Pandey

Reputation: 719

Choose any one

1.for(i=0; i<SIZE_OF_DATA; i++)

2.for(i=SIZE_OF_DATA -1 ; i>=0; i--)

1.You are starting your loop from 0 to SIZE_OF_DATA. Since you are progressing towards your size so you should increment your iterator i.

2.You are doing the opposite here ; i is set to the last position i.e SIZE_OF_DATA - 1 and now you have to decrement your iterator i till you reach 0.

Note In your code , you are starting from 0 and going towards negative side with i--. Your exit condition for for loop i<SIZE_OF_DATA will remain true always. This can cause you serious issues

1.Segmentation fault (accessing a negative index in the array data[] i.e data[i] and i is going towards negative integers).

2.Infinite loop as your termination condition will is always true. (It has to be false to come out of the loop).

Upvotes: 1

bytecode77
bytecode77

Reputation: 14860

Your problem is that you use i--. So the loop will count backwards, i.e. 0, -1, -2, -3 and so on and will always be smaller than SIZE OF DATA

The correct code would be

for(i=0; i<SIZE_OF_DATA; i++) {

Otherwise you'll have a perfect infinite loop :)

Upvotes: 4

Rahul Tripathi
Rahul Tripathi

Reputation: 172588

You probably need

for(i=0; i<SIZE_OF_DATA; i++)

instead of

for(i=0; i<SIZE_OF_DATA; i--)

i-- means that the value of i will be 0 then -1,-2... which you dont want. SIZE_OF_DATA will be a positive value and hence the for loop will result in an infinite loop and hence your problem.

Upvotes: 2

Related Questions