Brett Malmquist Brett Malmquist - 3 months ago 11
C Question

Output from Arrays in C won't format?

I'm new to this site and was looking for help. I'm trying to design a program that will take an input of numbers from a user, store it into an array, and format them correctly into three columns. However, I can't seem to figure out why my inputs aren't formatting correctly.

#include <stdio.h>
int main()
{

int x=0;
float num[100];

/* for loop for receiving inputs from user and storing it in array */
for (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;

Answer

Problems I see:

  1. Use of incorrect range in the for loop. Given

    float num[100];
    

    the maximum valid index is 99. Hence, the for loop needs to be:

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

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

    Nothing has been read into num[x+1] and num[x+2]. Hence, you are going to get garbage values.

  3. Accessing num using out of bounds array indices.

    Accessing num[x], num[x+1], and num[x+2] makes sense only if x+2 is less than or equal to 97.


My suggestion:

Use two loops. In the first loop, read the data. In the second loop, write out the data.

for (x=0; x < 100; x++)  // Using 100 here.
{
    scanf("%f", &num[x]);
}

for (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 to comment by OP

Change the print loop to:

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