1. ## Arrays.

I'm just thinkering around with arrays. I've coded the following:

Code:
```#include <stdio.h>

int main()
{
int array[6];
int a;
int b = 1;
while (b == 1)
{
printf("Enter: ");
scanf("%d", &a);
if (a == 1)
{
array[0] = 1;
}
else if (a == 2)
{
array[1] = 1;
}
else if (a == 3)
{
array[2] = 1;
}
else if (a == 4)
{
array[3] = 1;
}
else if (a == 5)
{
array[4] = 1;
}
else if (a == 6)
{
array[5] = 1;
}

printf("%d\n",a);
printf("[%d]\n",a,array[0]);
printf("[%d]\n",a,array[1]);
printf("[%d]\n",a,array[2]);
printf("[%d]\n",a,array[3]);
printf("[%d]\n",a,array[4]);
printf("[%d]\n",a,array[5]);
}

}```
What I expect this to do is: you fill in a value of one to six, and then it will print the values of all arrays. When you enter 5 for example, it will put 1 in array[4] and print that together wil the values in the others. The only problem is, it's not working. If you enter i.e. 3 it will output 3 and it will output [3] 6 times. I'm guessing the syntax is not correct here. How should I do it?

Thank You.

2. Code:
`                printf("[%d]\n",a,array[0]);`
This prints a instead of array[0].
try
Code:
`                printf("[%d]\n",array[0]);`
Kurt

3. Code:
```                   if (a == 1)
{
array[0] = 1;
}
else if (a == 2)
{
array[1] = 1;
}
else if (a == 3)
{
array[2] = 1;
}
else if (a == 4)
{
array[3] = 1;
}
else if (a == 5)
{
array[4] = 1;
}
else if (a == 6)
{
array[5] = 1;
}```
Consider replacing the code above with:
Code:
`array[a-1]=1;`
Now you can expend your array as much as you want without having to write the same code over and over again.
Don't forget to validate the input to avoid unexpected results.

Regards
Doron Moraz

4. Thanks!

Code:
```#include <stdio.h>

int main()
{
int a;
int b = 1;
int c;
int d = 0;
int array[d];

for (c = 0; c < 6; c++)
{
array[d] = c;
d = d + 1;
}

while (b == 1)
{

printf("Enter a value to put one into that slot: ");
scanf("&#37;d", &a);
array[a-1] = 1;
printf("%d\n",a);
printf("[%d]\n",array[0]);
printf("[%d]\n",array[1]);
printf("[%d]\n",array[2]);
printf("[%d]\n",array[3]);
printf("[%d]\n",array[4]);
printf("[%d]\n",array[5]);
}

}```
It works very well now!

5. Would you use the same code for 100, 1000, 10000000 items?
Probably not, the same rule goes to your output, so instead of using:
Code:
```             printf("[%d]\n",array[0]);
printf("[%d]\n",array[1]);
printf("[%d]\n",array[2]);
printf("[%d]\n",array[3]);
printf("[%d]\n",array[4]);
printf("[%d]\n",array[5]);```
Use
Code:
```for (c = 0; c < 6; c++)
printf("[%d]\n",array[c]);```
Regards
Doron Moraz

Popular pages Recent additions