Counting number 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 */