The point of my code is to print all the odd numbers inputted each array using function.
#include<stdio.h>
void printOdd(int arr1[], int arr2[], int s1, int s2) {
int count = 0;
for (int i = 0; i < s1; i ) {
if (arr1[i] % 2 != 0) {
printf("%d", arr1[i]);
count ;
if(count<(s1 s2)/2)
{
printf(", ");
}
}
}
for (int i = 0; i < s2; i ) {
if (arr2[i] % 2 != 0) {
printf("%d", arr2[i]);
if(count<(s1 s2)/2-1)
{
printf(", ");
}
}
}
}
int main(void)
{
int s1, s2;
printf("Enter first array size: ");
scanf("%d", &s1);
int arr1[s1];
printf("Enter second array size: ");
scanf("%d", &s2);
int arr2[s2];
printf("Enter first array values: ");
for(int x = 0; x < s1; x )
{
scanf("%d", &arr1[x]);
}
printf("Enter second array values: ");
for(int y = 0; y < s2; y )
{
scanf("%d", &arr2[y]);
}
printOdd(arr1, arr2, s1, s2);
}
These are the expected outputs
Enter first array size: 5 Enter second array size: 5 Enter first array values: 1 2 3 4 5 Enter second array values: 6 7 8 9 10 1, 3, 5, 7, 9
Enter first array size: 3 Enter second array size: 3 Enter first array values: 5 6 10 Enter second array values: 12 41 36 5, 41
Enter first array size: 4 Enter second array size: 3 Enter first array values: 1 2 3 5 Enter second array values: 3 2 1 1, 3, 5, 3, 1
My problem is everytime I input numbers, the result is that there is always a comma at the end, here's my output
Enter first array size: 3 Enter second array size: 3 Enter first array values: 5 6 10 Enter second array values: 12 41 36 5, 41,
https://gyazo.com/9d544951a3572666a3b6b0dc8620d9cc
the link is a picture of expected output and my output
CodePudding user response:
The simplest thing to do is to print the comma before printing your value, and only when count
is non-zero. The reason is that you never know if there will be a next odd number, but you do know when there was a previous one. So you should always leave your output with no trailing comma.
void printOdd(int arr1[], int arr2[], int s1, int s2) {
int count = 0;
for (int i = 0; i < s1; i ) {
if (arr1[i] % 2 != 0) {
if (count > 0) printf(", ");
printf("%d", arr1[i]);
count ;
}
}
for (int i = 0; i < s2; i ) {
if (arr2[i] % 2 != 0) {
if (count > 0) printf(", ");
printf("%d", arr2[i]);
count ;
}
}
}