Hi!
I'm very new to C and was given a problem to solve by my lecturer. Well, 3 problems actually. I got the first part to work, but I'm having a lot of trouble with the second part. Here's what the assignment is:
"
1. Write a program that creates an array of twenty doubles, then sets every even element of the array (beginning with 0) to the value '1.0' and every odd element to '2.0'. The program should then print all of the elements in the array, with each element on a new line.
Such that:
1st element: 1.0
2nd element: 2.0
3rd element: 1.0
4th element: 2.0
...
etc.
2. Modify a copy of the program from Task 1, so that every third element is set to the value '4.0' and every fourth element set to the value '8.0'; and the contents of the array printed as before.
Such that:
1st element: 1.0
2nd element: 2.0
3rd element: 4.0
4th element: 8.0
5th element: 1.0
6th element: 2.0
...
etc.
3. Modify a copy of the program from Task 2 such that the array elements are multiplied by their index and the results printed as before. This may be done in an additional loop after the previous tasks.
Such that:
1st element: 0.0 (index 0 multiplied by value 1.0)
2nd element: 2.0 (index 1 multiplied by value 2.0)
3rd element: 8.0 (index 2 multiplied by value 4.0)
4th element: 24.0 (index 3 multiplied by value 8.0)
5th element: 4.0 (index 4 multiplied by value 1.0)
6th element: 10.0 (index 5 multiplied by value 2.0)
...
etc.
"
Here's what I have so far:
Code:
#include <stdio.h>
int main ()
{
double n[ 20 ]; /* n is an array of 20 doubles */
int i,someInt; /*someInt will store values as it increments through the array*/
/* Run someInt through array using this for loop */
for ( someInt = 0; someInt <= 20; someInt++ )
{
if(someInt==0) /* If the remainder of someInt divided by 2 is 0, then it must be even*/
{
n[someInt] = 1.0;
}
else if(someInt%4==0)
{
n[someInt] = 8.0;
}
else if(someInt%3==0)
{
n[someInt] = 4.0;
}
else if(someInt%2==0)
{
n[someInt] = 1.0;
}
else /* If the remainder of someInt divided by 2 is NOT 0, then it must be odd*/
{
n[someInt] = 2.0;
}
}
// i will be used to loop through the array again to print each new element value in the array
for (i = 0; i <= 20; i++)
{
printf("Element %d: %f\n", i, n[i]);
}
return 0;
}
I know that it involves using a modulo operator, but I can't get it to work so that the number order is exactly as the example in the question stated. Can anyone help?