i have one set of numbers many numbers start with '1' and start with '2' and start with '3'. i seperate these numbers how i identified which numbers start with '1','2' and '3'?
This is a discussion on simple c question within the C Programming forums, part of the General Programming Boards category; i have one set of numbers many numbers start with '1' and start with '2' and start with '3'. i ...
i have one set of numbers many numbers start with '1' and start with '2' and start with '3'. i seperate these numbers how i identified which numbers start with '1','2' and '3'?
Well if you read them in as strings, then you do
Code:if ( num_in_a_string[0] == '1' )
Or...
Next poster, come up with your version of it.Code:if( strchr( num_in_a_string, '1' ) == num_in_a_string )
Quzah.
Last edited by quzah; 12-02-2004 at 01:16 PM. Reason: Where's my coffee?
Hope is the first step on the road to disappointment.
Probably :
unless he wants to find SOHCode:if( strchr( num_in_a_string, '1' ) == num_in_a_string )
*slaps forehead* Yeah. I should have just used the strstr version. That's what I get for not having some coffee right when I get up. Be right back.
Quzah.
Hope is the first step on the road to disappointment.
Without using any functions prototyped in string.h!
Code:#include <stdio.h> int main(void) { int num = 123984; int i; int is_a_one = 0; for(i = 1;i < num && i > 0;i *= 10) if(num/i < 10) { if(num/i == 1) is_a_one = 1; break; } printf("It's%s a one!\n", is_a_one ? "" : " not"); return 0; }
Last edited by itsme86; 12-02-2004 at 01:44 PM. Reason: Oops! Needed to start loop at 1 instead of 10
If you understand what you're doing, you're not learning anything.
Without weird nested ifs
Code:#include <stdio.h> int main() { int num = 123984; int i; int last_digit; while(num > 0) { last_digit = num % 10; num /= 10; } printf("Number starts with a %i.\n", last_digit); }
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
Just add the other half-dozen or so cases and you'll have all the numbers which begin with a '1'Code:if ( num == 1 || ( num >= 10 && num <= 19 ) || ( num >= 100 && num <= 199 ) )
Code:int first_digit(int number) { if (number < 0) number = -number; while (number >= 10) number /= 10; return number; }