int a[4];int) int a[4], b[5]; #define SIZE 10
...
int a[SIZE], b[SIZE+1];a[i]
i é o índice (inteiro)a[i] pode ser usado tal como uma variável simples:
a[i] = 1;
printf("%d", a[i]);
++ a[i];for são convenientes para processar elementos de variáveis indexadasN:for(i = 0; i < N; i++) // Colocar zeros
a[i] = 0;
for(i = 0; i < N; i++) // Ler valores
scanf("%d", &a[i]);
soma = 0;
for(i = 0; i < N; i++) // Somar elementos
soma += a[i];a[N] duma variável com tamanho Nint main(void) {
int a[10], i;
for(i = 0; i <= 10; i++)
a[i] = 0;
...
}a[0], a[1], ..., a[10]a[0], a[1], ..., a[9] a[i+j*10] = 0; i = 0;
while (i < N)
a[i++] = 0; int a[5] = {1, 2, 3, 4, 5}; int a[10] = {1, 2, 3, 4, 5};
/* valores iniciais são
{1, 2, 3, 4, 5, 0, 0, 0, 0, 0} */ int a[10] = {0};
/* valores iniciais são
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0} int a[] = {1, 2, 3, 4, 5};
// equivalente a declarar a[5]Qual o problema?
i = 0;
while (i < N)
a[i] = b[i++];a[i] = b[i++]; é indefinida:
i++ pode ocorrer antes da atribuição a a[i]Evitamos o problema separando o incremento da indexação.
i = 0;
while (i < N) {
a[i] = b[i];
i++;
}Em alternativa podemos usar um ciclo for:
for (i = 0; i < N; i++)
a[i] = b[i];| Decimal | Binário |
|---|---|
| 2 | 10 |
| 6 | 110 |
| 16 | 10000 |
| 20 | 10100 |
| 64 | 1000000 |
n |
o inteiro positivo dado |
bit[] |
variável indexada para guardar algarismos binários (bits) |
size |
número de bits usados (0, 1, 2, ... etc) |
#include <stdio.h>
#define NUM_BITS 32 // número máximo de bits
int main(void) {
unsigned n, size, bit[NUM_BITS] = {0};
scanf("%u", &n); // inteiro sem sinal
/* obter os algarismos binários */
size = 0;
while (n > 0) {
bit[size++] = n%2;
n = n/2;
}
/* imprimir por ordem contrária */
while(size > 0) {
printf("%u", bit[--size]);
}
putchar('\n'); // terminar a linha
} NUM_BITS é 32, logo podemos guardar até 32 bits int fun(int a[]) {
// tamanho de a[] não especificado
...
} int somar_vec(int a[], unsigned size) {
int i, soma = 0;
for (i = 0; i < size; i++)
soma += a[i];
return soma;
}somar_vecPara usar esta função devemos passar dois argumentos:
int v[100];
...
s = somar_vec(v, 100);
// somar todos os valores:NB: na chamada passamos apenas o nome da variável (sem parêntesis rectos)
somar_vecTambém podemos usar somar_vec para somar apenas um segmento inicial:
int v[100];
// ...
s = somar_vec(v, 50);
// somar os primeiros 50 valoresDesta forma podemos:
void colocar_zeros(int a[], unsigned size) {
int i;
for(i = 0; i < size; i++) {
a[i] = 0;
}
}colocar_zeros modifica a variável indexada passada como argumento: int v[100];
// ...
colocar_zeros(v, 100);
// v[0], v[1], ... v[99] são agora 0Vamos rever o exemplo de conversão para binário e decompô-lo em duas funções:
compute_bitsobter os algarismos binários usando divisões sucessivas
print_bitsimprimir os algarismos binários por ordem inversa
Vamos começar pela segunda função.
print_bitsvoid print_bits(unsigned b[], unsigned size) {
while(size > 0) {
printf("%u", b[--size]);
}
putchar('\n');
}compute_bitsint compute_bits(unsigned n, unsigned b[]) {
unsigned size = 0;
while(n > 0) {
b[size++] = n%2;
n = n/2;
}
return size;
}n é o inteiro a decompor#define NUM_BITS 32
...
int main(void) {
unsigned n, size, bit[NUM_BITS];
scanf("%d", &n);
// ler um inteiro; deve ser positivo
size = compute_bits(n, bit);
// preencher "array" com algarismos de n
// valor retornado é o número de bits
print_bits(bit, size);
// imprimir algarismos
}