mercredi 1 juillet 2020

C language exercise

Here is my other question. I don't understand those pieces of code. The output of the provided code is:

N
O
R
c
u
y
z

My questions are:

  1. a[i] > a[i + 1] They're characters, not numbers. Why should we compare two characters? It doesn't make sense. or should I expect they yield boolean value?
  2. printf ("%c\n", a[i] + 2);--> a[i] + 2 It seems like something is happening with orders of array elements one by one. How and why? I understand the output should be 7lines of single characters.
#include <stdio.h>
int main (void)
{
  char a[] = { 'w', 's', 'x', 'a', 'P', 'L', 'M' };
  int i, tmp, flag;
  do
    {
      flag = 0;
      for (i = 0; i < 7; i++)
    {
      if (a[i] > a[i + 1])
        {
          tmp = a[i];
          a[i] = a[i + 1];
          a[i + 1] = tmp;
          flag = 1;
        }
    }
    }
  while (flag == 1);
  for (i = 0; i < 7; i++)
    printf ("%c\n", a[i] + 2);
  printf ("\n");
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire