StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Program #18 (U2): Count Digits in an Integer
Download
  1. C Programming
  2. C Programming Practice
Program #17 (U2): Pattern Printing — Pyramids : Program #19 (U3): Linear Search in 1-D Array (function)
C Programming Practice

Task: Read an integer and count its digits by repeated division by 10. Handle zero (1 digit) and negative numbers correctly.

 
/* 

  Program: Count Digits in an Integer (U2)

  What it does:

    - Reads an integer n; counts how many digits it has.

    - Treats 0 as a 1-digit number; handles negatives by ignoring sign.

*/

 
#include <stdio.h>

 
int main(void) {

    int n, tmp, count = 0;

 
    printf("Enter an integer: ");

    if (scanf("%d", &n) != 1) {

        printf("Invalid input.

");

        return 0;

    }

 
    if (n == 0) {

        count = 1;

    } else {

        tmp = (n < 0) ? -n : n;

        while (tmp > 0) { tmp /= 10; ++count; }

    }

 
    printf("Digits = %d

", count);

 
    return 0;

}

 

 

Program #17 (U2): Pattern Printing — Pyramids Program #19 (U3): Linear Search in 1-D Array (function)
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website