Counting the amount of odd numbers in an integer vector:
#include <stdio.h>
#include <stdlib.h>
/* Macro para calcular quantidade de elementos dentro de um vetor */
#define sizeof_vector(_vec) (sizeof(_vec) / sizeof(_vec[0]))
/* Vetores para teste */
int g_vetor_a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int g_vetor_b[] = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };
int g_vetor_c[] = { 2, 4, 6, 8, 10, 12, 14, 16, 18 };
int contarImpares( int * vet, int qtd )
{
int n = 0;
int i = 0;
for( i = 0 ; i < qtd ; i++)
if( vet[i] % 2 )
n++;
return n;
}
int main( int argc, char * argv[] )
{
/* Testando */
printf( "Vetor A: %d\n", contarImpares( g_vetor_a, sizeof_vector(g_vetor_a) ) );
printf( "Vetor B: %d\n", contarImpares( g_vetor_b, sizeof_vector(g_vetor_b) ) );
printf( "Vetor C: %d\n", contarImpares( g_vetor_c, sizeof_vector(g_vetor_c) ) );
return 0;
}
/* fim */
Calculating the largest odd number contained in a vector:
#include <stdio.h>
#include <stdlib.h>
/* Macro para calcular quantidade de elementos dentro de um vetor */
#define sizeof_vector(_vec) (sizeof(_vec) / sizeof(_vec[0]))
/* Vetores para teste */
int g_vetor_a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int g_vetor_b[] = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };
int g_vetor_c[] = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
int maiorImpar( int * vet, int qtd )
{
int i = 0;
int max = -1;
for( i = 0 ; i < qtd ; i++)
if( vet[i] % 2 )
if( vet[i] > max )
max = vet[i];
return max;
}
int main( int argc, char * argv[] )
{
/* Testando */
printf( "Vetor A: %d\n", maiorImpar( g_vetor_a, sizeof_vector(g_vetor_a) ) );
printf( "Vetor B: %d\n", maiorImpar( g_vetor_b, sizeof_vector(g_vetor_b) ) );
printf( "Vetor C: %d\n", maiorImpar( g_vetor_c, sizeof_vector(g_vetor_c) ) );
return 0;
}
/* fim */
boot
int qtde_impar
,int qtde_impar = 0
not to pick up memory junk.– BrTkCa
Do you have the exercise statement? I’ve seen the error, but this code can be greatly improved.
– Maniero
If this is the statement, it is bad, it does not seem to be complete or clear. Your question implies that you want something else. The first thing to do a correct code is to interpret the text correctly. You have to pass the vector as well?
– Maniero
Thanks, Lucas. That’s all that’s solved my problem :)
– Victor Souza
else continue
is unnecessary.– Oralista de Sistemas
@Victorsouza actually has much more serious problems. That would be one of the problems if the exercise were to count how many odd.
– Maniero
Another way of writing
vetor[cont]%2 == 1
, which I believe is more understandable and simple isvetor[cont] & 1 == 1
.– Nexus
@Victorsouza Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already done so. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero