Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out ordinals

Tags:

c

Here I'm trying to create a function which accepts n number of integers and sum them together... But I'm having trouble having it print the correct ordinals. Am I using a wrong loop?

int i, count, sum, number;
sum = 0;
count = 0;


printf("Please indicate the number of integers:");
scanf("%d", &count);

for (i=0; i<count; i++){
    printf("Please input the %dst number:", i+1);
    scanf("%d", &number);

    sum = sum + number;
}

printf("sum is %d\n", sum);
return 0;

For example if i input count = 5, it will print

Please input the 1st number:
Please input the 2st number:
Please input the 3st number:
Please input the 4st number:
Please input the 5st number:
sum is 15

It prints the correct sum, but I want it to print the correct ordinal for every line.. for example, 2nd..3rd. Possibly without having to use an array

like image 809
friedrojak Avatar asked Dec 08 '25 19:12

friedrojak


1 Answers

In English, rules for ordinals are fairly simple (note: not "simple," but "fairly simple"):

  1. Below zero, you're on your own. Some might apply positive-number rules, others say it makes no sense to try a negative ordinal.

  2. Most ordinals end with 'th':

    • fourth
    • thirty-ninth
  3. Numbers ending with 1, 2, 3 are different:

    • first
    • twenty-second
    • one hundred eighty-third
  4. Except that numbers ending in 11, 12, 13 are 'th' numbers, because English treats the teens differently (six-teen vs. twenty-six). So:

    • eleventh
    • one hundred twelfth
    • thirteenth
  5. In general, only nerds think "zeroth" is funny. But it's still a -th, so it gets the default treatment.

In code:

if (n < 0) { /* Rule 1: good luck */ }

suffix = "th"; /* Rule 2: default = th */

if (1 <= n%10 && n%10 <= 3) { /* Rule 3: 1st, 2nd, 3rd */

    if (n%100 < 10 || n%100 > 20) { /* Rule 4: 11th-13th */
        suffix = (n%10 == 1) ? "st" 
               : (n%10 == 2) ? "nd" 
               :               "rd"
               ;
    }
}
like image 89
aghast Avatar answered Dec 10 '25 10:12

aghast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!