Im a beginner programmer and i needed some help with making the result of the following exercise look a bit better. As i said in the title i want to make the exercise look nicer by removing the 0-s from the array and leaving just the numbers.
The exercise goes like this:
We enter an array of integers and we copy into the 2nd array the integers that are positive and negative and multiples of 3 and in the 3rd array the negative elements that are odd and not multiples of 3. This is the code that I did:
#include <stdio.h>
#include <stdlib.h>
#define N 5
int main()
{
int v[N];
int v2[N] = {0, };
int v3[N] = {0, };
int i;
printf("Please enter the elements of the 1st array: ");
for (i = 0; i < N; i )
{
scanf("%d", &v[i]);
}
printf("\nThe elements of the 2nd array are: ");
for (i = 0; i < N; i )
{
if ((v[i] >= 0 || v[i] <= 0) && v[i] % 3 == 0)
{
v2[i] = v[i];
}
}
for (i = 0; i < N; i )
{
printf("%d ", v2[i]);
}
printf("\nThe value of the 3rd array are : ");
for (i = 0; i < N; i )
{
if (v[i] <= 0 && v[i] % 2 != 0 && v[i] % 3 != 0)
{
v3[i] = v[i];
}
}
for (i = 0; i < N; i )
{
printf("%d ", v3[i]);
}
return 0;
}
For future use if possible how to do I post a code copied for code blocks directly into here without using space 4 times on every line? Thanks in advance
CodePudding user response:
Another option is to insert a condition in the output loop:
for (i = 0; i < N; i )
{
if (v2[i] != 0)
{
printf("%d ",v2[i]);
}
}
CodePudding user response:
If you only want to add relevant numbers of the first array to the second one, you have to use two counters. One that works as index in the source array, i.e. the numbers that were inputted, and a second counter that works as the index for the target array. And maybe you still need a number for every target array, because the count of number in these arrays may vary (and could be less than 5).
As a hint, the counters of the source and target array would show up like this in your example source target comment
0 0 no new number entered
1 0 no new number entered
2 1 number 3 at index 2 is a valid number for the first target array
3 1 again no new number for the target array
4 2 number 5 at index 4 is valid again.
So, now you know the first target array has a count of 2 valid numbers, and then you can output those first two numbers of the array.