C language: three methods are used to output each digit of an integer.

Source: Internet
Author: User

C language: three methods are used to output each digit of an integer.
Output each digit of an integer. Solution: Method 1:

# Include <stdio. h> # include <string. h> int main () {int I, len; char num [100]; printf ("enter an integer:"); scanf ("% s", num ); len = strlen (num); for (I = 0; I <= len-1; I ++) {printf ("% c \ n ", num [I]);} if (num [0]! = 45) // 45 indicates the ASCII Value of "-" {printf ("bits: % d \ n", len);} else {len = len-1; printf ("digits: % d \ n", len);} return 0 ;}

 

Result 1: Enter an integer: 7235672356 digits: 5. Press any key to continue... result 2: enter an integer-2378-2378 bits: 4. Press any key to continue... method 2: Program:
# Include <stdio. h> int main () {int num = 0; printf ("enter a non-negative integer:"); scanf ("% d", & num); while (num) {printf ("% d \ t", num % 10); num/= 10;} return 0 ;}

 

Result: enter a non-negative integer: 9877 8 9. Press any key to continue... method 3: Program:
# Include <stdio. h> int print (int num) // Recursive Implementation {if (num> 9) {print (num/10);} printf ("% d \ t ", num % 10) ;}int main () {int num = 0; printf ("enter an integer:"); scanf ("% d", & num ); print (num); return 0 ;}

 

Result: enter an integer: 876548 7 6 5 4. Press any key to continue...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.