Andrew Lu
Andrew Lu

Reputation: 35

How do I print out something different at the last item of a loop, C programming

Please enter an integer: 1234
Digit: 4
Digit: 3
Digit: 2
Digit: 1

I have a program right now that prints out an integer's digits in reverse. Instead of the output above, I'd like to have:

Please enter an integer: 1234
Digit: 4
Digit: 3
Digit: 2
Last Digit: 1

How do i make that happen? Here's my code by the way:

#include <stdio.h>
int main()
{
int input;
    printf("Please enter an integer: ");
    scanf("%d", &input);
int num = input;
int i = 0;
while(num > 0)
{
    int remainder = num % 10;
    num = num /10;
    i++;
    printf("Digit: %d\n", remainder );
}
return 0;
}

How do I print something else at the last item of the loop?

Upvotes: 0

Views: 190

Answers (2)

ryanpattison
ryanpattison

Reputation: 6251

Testing to see if the while condition will fail is one way.

 while (num > 0) {
    int remainder = num % 10;
    num = num / 10;
    i++;
    if (num > 0) {
        printf("Digit: %d\n", remainder);
    } else {
        printf("Last Digit: %d\n", remainder);
    }
 }

Or change the while condition...

 while (num > 9) {
    int remainder = num % 10;
    num = num / 10;
    i++;
    printf("Digit: %d\n", remainder);   
 }
 printf("Last Digit: %d\n", num);

Upvotes: 1

bit
bit

Reputation: 4487

Use

if (num > 0) //Indicates that there are more digits to come
{
    printf("Digit: %d\n", remainder );
} 
else // Otherwise, it is the last digit
{
    printf("Last Digit: %d\n", remainder);
}

Instead of just

printf("Last Digit: %d\n", remainder);

Upvotes: 2

Related Questions