Thursday, 15 July 2010

Algorithms for deleting multiple elements in arrays in C -



Algorithms for deleting multiple elements in arrays in C -

i trying larn c , trying write piece of code following:

take user input of natural number n take user input of n elements , store them in array x delete negative numbers array x print new array, length n - number of deleted elements

here code:

#include <stdio.h> int main(void) { int n, i, count=0; double x[1000]; scanf("%d", &n); (i=0; i<n; i++) scanf("%lg", &x[i]); (i=0; i<n; i++) { if (x[i] < 0) { count++; continue; }; x[i-count]=x[i]; }; n -= count; (i=0; i<n; i++) printf("%d: %g\n", i, x[i]); homecoming 0; }

i have been told should replace sec loop next code:

int j=0

...

(i=0; i<n; i++) { if (x[i] < 0) { count++; continue; }; if (i > j) x[j] = x[i]; j++; };

could please explain why latter code better?

if i==j, you're assigning element itself: not wrong, (small) waste of effort.

if want improve this, avoid putting negative values in array in first place.

c arrays algorithm

No comments:

Post a Comment