array's

Ok so I have an assignment that i'm having a rough time with. Now I have the array outputting correctly but I need to use an if statement to add in the (\n) or space between every 10 numbers. I know i'm close I just can not figure out what i am missing.

Here is the assignment:

Write a main function that declares an array of 100 doubles.

In a for loop, assign each of the doubles a random number between 0.50 and 50.00. Here’s how.

array[i] = (double) (rand() % 100 + 1) / 2.0;


Output the elements of the array in 10 columns that are each 6 spaces wide.
Each row in the output will have 10 values. The doubles will be printed with 2 places of accuracy past the decimal.

The output of this one-dimensional array requires a single for loop with an if statement inside.
Use the if statement to decide when it’s time to output \n
Even though the 100 numbers are going to be presented as a table of numbers, they are still just a list in memory.

Here is my code so far. Now I'm not asking for anyone to do the assignment for me but to guide me in the right direction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  #include<stdio.h>
#include<stdlib.h>

main()	{

	double totalNumbers[100];
	int i;
	int col;

	for (i = 0; i < 100; i++)	{
		totalNumbers[i] = (double)(rand() % 100 + 1) / 2.0;
		printf("%.2lf      ", totalNumbers[i]);
		
		col = 10;


		if (col < 10)	{
			printf("\n");
		}
	}



	system("pause");
}
You can use the modulus operator % on 100 and the current value of i to figure out if the current loop iteration is a multiple of 10. If it is, add a newline.

i = 0 - 9 first row
i = 10 - 19 second row
i = 20 - 29 third row
and so on....

You can initialize col to 1 before the loop and increment it inside the loop.

Then if col == 10 you can print a newline and reset col to one.

That's not the complete solution so you'll need to play around a bit, but it's a good start :)
Topic archived. No new replies allowed.