carraysloopslogicordinals

How do I print ordinal indicators in a C program? Can't print numbers with 'st', 'nd', 'rd'. (Beginner)


#include <stdio.h>

main()
{
    int i, num, sum=0; //declaration
    printf("How many numbers do you want to calculate average of?\n");
    scanf("%d", &num); //how many numbers are to be calculated
    printf("Enter %d numbers\n", num);

    int a[num]; //array to store data
    for(i=1;i<=num;i++) //loop to take input 
    {
        if(i==1) //for 1st
            printf("1st value : ");
        else if (i<=2) //2nd
            printf("2nd value : ");
        else if (i<=3) //3rd
            printf("3rd value : ");
        else //else print th ordinal
            printf("%dth value : ", i);
        scanf("%d", &a[i]);
    }

    for(i=1;i<=num;i++)
        sum+=a[i];

    float avg;
    avg=sum/num;
    printf("Average : %f", avg);

    return 0;
}

A program to take out the average of n numbers. Now, this code does what it should, but if the size of the array goes beyond 20, it prints 21th, 22th, 23th and so on, which is wrong. I can't think of how to fix this problem. Any help would be great. I am new to programming, so pardon my ignorance. Output depicting what needs to be fixed


Solution

  • You can mod by 10 to get the last digit. Then based on that you can use "st", "nd", "rd", or "th". You'll also need special cases for 11, 12, and 13.

        if ((i % 10 == 1) && (i % 100 != 11))
            printf("%dst value : ", i);
        else if ((i % 10 == 2) && (i % 100 != 12))
            printf("%dnd value : ", i);
        else if ((i % 10 == 3) && (i % 100 != 13))
            printf("%drd value : ", i);
        else
            printf("%dth value : ", i);