'How can I get 2nd digit of a number manually
#include <stdio.h>
int main(int argc, char *argv[]) {
int n = 234;
// Gets first digit
int digit = n / 100;
putchar('0' + digit);
// gets 3rd digit
digit = n % 10;
putchar('0' + digit);
}
How can I get "3" aka 2nd digit?
Also If the n was something like 245836 how could I extract each digit one by one?
Solution 1:[1]
As an expansion on the answer you already got: In general, you can get the ith digit from the right with:
int digit = (n / (int) pow(10, i)) % 10;
where i is a zero-based index. You can get the index of the most significant digit with i = log10(n) and loop your way down to 0. pow and log10 are floating-point functions, which should be used carefully in integer calculations.
Alternatively, you can get at the powers of 10 in decreasing order by sequential division by 10 of an initial value d, which also must be a power of 10. You can find this value d by repeatedly multiplying 1 with 10 until the next multiplication would exceed your number.
Here's a simple program that prints all digits of a positive integer in order:
#include <stdio.h>
int main(int argc, char *argv[])
{
unsigned int n = 0;
unsigned int d = 1;
while (d <= n / 10) d *= 10;
while (d) {
unsigned int digit = (n / d) % 10;
putchar('0' + digit);
d /= 10;
}
putchar('\n');
return 0;
}
The example uses unsigned int, because it works only with non-negative numbers.
Solution 2:[2]
This is a simple program to print a digit in tenth position.
import java.util.*;
public class Main{
public static void main(String []args){
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
if(n>0)
{
n=n%100;
n=n/10;
}
System.out.println(n);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Eric Aya |
