Output from Arrays in C won't format? -


i'm new site , looking help. i'm trying design program take input of numbers user, store array, , format them correctly 3 columns. however, can't seem figure out why inputs aren't formatting correctly.

#include <stdio.h> int main() {  int x=0; float num[100];  /* loop receiving inputs user , storing in array */ (x=0; x<=100; x++) {     scanf("%f", &num[x]);     printf("%7.1lf%11.0lf%10.3lf", num[x], num[x+1], num[x+2]);      //printf("%f %f %f\n", num[0], num[1], num[2]);  } return 0; 

problems see:

  1. use of incorrect range in for loop. given

    float num[100]; 

    the maximum valid index 99. hence, for loop needs be:

    for (x=0; x < 100; x++)  // x < 100 not x <= 100 
  2. using array elements before initialized.

    printf("%7.1lf%11.0lf%10.3lf", num[x], num[x+1], num[x+2]); 

    nothing has been read num[x+1] , num[x+2]. hence, going garbage values.

  3. accessing num using out of bounds array indices.

    accessing num[x], num[x+1], , num[x+2] makes sense if x+2 less or equal 97.


my suggestion:

use 2 loops. in first loop, read data. in second loop, write out data.

for (x=0; x < 100; x++)  // using 100 here. {     scanf("%f", &num[x]); }  (x=0; x < 98; x++)  // using 98 here. {     printf("%7.1lf%11.0lf%10.3lf", num[x], num[x+1], num[x+2]); } 

update, in response comment op

change print loop to:

for (x=0; x < 98; x += 3)  // increment x 3 {     printf("%7.1lf%11.0lf%10.3lf", num[x], num[x+1], num[x+2]); } 

Comments