Soluções da aula prática 10



1a.
/* Edgar Alan Poe */
#include <stdio.h>

void main()
{
  FILE *f;
  char c;
  int ci;
  int cont[91];
  int i;

  for (i=65; i<=90; i++)
    cont[i] = 0;
  f = fopen("theraven.txt", "r");
  while (!feof(f))
  {
    c=fgetc(f);              /* get a single character from file */
    printf("%c", c);         /* show it on screen */
    if ((c>=97) && (c<=122)) /* convert ot uppercase */
      c=c-32;
    if ((c>=65) && (c<=90))  /* count it in our histogram 'cont' */
      cont[c] = cont[c] + 1;
  }
  fclose(f);
  for (i=65; i<=90; i++)
    printf("%c : %d\n", i, cont[i]);
}

output (ecrã)

A  339
B  94
C  71
D  194
E  618
F  94
G  122
H  290
I  318
J  2
K  32
L  225
M  158
N  374
O  370
P  95
Q  9
R  336
S  278
T  437
U  121
V  66
W  79
X  3
Y  100
Z  0



1b.
/* Edgar Alan Poe output to file */
#include <stdio.h>

void main()
{
  FILE *f;
  char c;
  int ci;
  int cont[91];
  int i;

  for (i=65; i<=90; i++)
    cont[i] = 0;
  f = fopen("theraven.txt", "r");
  while (!feof(f))
  {
    c=fgetc(f);
    printf("%c", c);
    if ((c>=97) && (c<=122))
      c=c-32;
    if ((c>=65) && (c<=90))
      cont[c] = cont[c] + 1;
  }
  fclose(f);
  f = fopen("contas.txt", "w");
  for (i=65; i<=90; i++)
    fprintf(f, "%c : %d\n", i, cont[i]);
  flcose(f);
}



1c.
/* Edgar Alan Poe */
#include <stdio.h>

void main()
{
  FILE *f;
  char c;
  int ci;
  int cont[91];
  int i;
  int maxn;

  for (i=65; i<=90; i++)
    cont[i] = 0;
  f = fopen("theraven.txt", "r");
  while (!feof(f))
  {
    c=fgetc(f);
    printf("%c", c);
    if ((c>=97) && (c<=122))
      c=c-32;
    if ((c>=65) && (c<=90))
      cont[c] = cont[c] + 1;
  }
  fclose(f);
  maxn=0;
  maxc=0;
  for (i=65; i<=90; i++)
    if (cont[i]>maxn)
      {
        maxc = i;
        maxn = cont[i];
      }
  printf("Max: %c  %d\n", maxc, maxn);
}

output (ecrã)

Max: E  618