i started to learn C a few days ago through the cs50 course and i'm trying to write a program as a side project where the user inputs a multi-digit integer, and the program will break it apart into seperate integers, but im having trouble. Here is my code:

//program that will take the integer the user inputs and will output the digits added together.
#include <stdio.h>
#include <cs50.h>
int main(void)

int n = get_int ("Please enter an integer:\n");
int d = 0;

while(n >= 0) //terminate loop when n reaches zero

d = n % 10; //takes the last number off and assigns it to digit variable

printf("%i\n", d); //should print the digit one after another 

n = n / 10; //divides original number by 10 

The output comes as "123" and then waits for another input. I know that i'm probably making a really dumb mistake but i can't figure out where i've gone wrong, help would be appreciated, PS this is my first post on here so sorry if i did not post the code the correct way


Here's the problem:

while(n >= 0)

What happens when you get to the most significant digit in the number? It integer divides by 10, leaving 0. Since 0 makes the test true, it just goes into an infinite loop.

Maybe if you change ">=" to just">", it will solve your problem.

  • Thank you so much!! this fixed it – Jordan Emmett Jun 1 '20 at 22:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .