I have a remainder function that finds that modulo of a number then a divider function to divide that number. My program isn't working the way I need it to. For example if I put in 2502 as my number, I should get the output of : 2 5 0 2.
I need to be able to store the value through each iteration, so for example:
number: 123
123 % 10 = 3 //last digit
Number: 123 / 10 = 12
12 % 10 = 2 //second digit
Number: 12 / 10 = 1
1 % 10 = 1 //first digit
int Rem(int num);
int Div(int num);
int main() {
int num;
printf("Enter an integer between 1 and 32767: ");
scanf("%d", &num);
Rem(num);
Div(num);
printf("%d","The digits in the number are: ");
}
int Rem(int num) {
while(num != 0){
int rem = num % 10;
return rem;
}
}
int Div(int num){
while(num != 0){
int div = num / 10;
return div;
}
}
The idea here is pretty simple, but there are some subtleties. Here's some pseudo code. You'll need to convert to C.
num = 9934; // or get it from input
do {
rem = num % 10; // this gives you the lowest digit
num = num / 10; // divide by 10 to get rid of that lowest digit
print rem;
} while (num != 0);
I use a do ... while loop so the output will be correct if the user enters 0.
If you code this up and run it, you'll notice that it prints the digits in reverse order: 4 3 9 9. So you'll need some way to reverse the digits before you output them. Three possible ways are:
Store the digits in an array, and then reverse the array before outputting.
Push each digit onto a stack. When you're done, pop each digit off the stack and output it.
Write a recursive function. That would eliminate the need for an explicit stack or array.
Also you could convert it to a string and then convert back the elements of that string, but keep '\0' in mind
You can simply use this function , it return the number of digits passing by argument
size_t ft_cnbr(int n)
{
size_t count;
count = 1;
if (n < 0)
{
count++;
n = -n;
}
while (n > 9)
{
n = n / 10;
count++;
}
return (count);
}
Related
I'm trying to create a program that breaks down a number into its component digits.
The code I've written so far is as follows:
#include <stdio.h>
int main() {
int num;
int digits;
int count = 1;
printf("Insert a positive number: ");
do {
scanf("%d", &num);
} while (num <= 0);
printf("In digits... \n");
// Number in digits
while (num != 0) {
digits = num % 10;
printf("Digit %d --> %d \n", count, digits);
num /= 10;
count++;
}
}
The digits of the number are printed correctly, but in reverse order!
Insert a positive number: 345
In digits...
Digit 1 --> 5
Digit 2 --> 4
Digit 3 --> 3
I can't figure out how to fix this, can anyone help me?
You're printing the number mod 10, which is the last digit, then dividing the number by 10 and repeating until the number is zero. So it prints the digits from right to left.
If you want to print from left to right, you need to print the digit that has the highest power of ten first. Here's a naive way to do that, by first finding the highest power of ten the number has a digit for and then using a for loop to go from that power to one to print the digits from left to right:
void print_digits(int n) {
int mask = 1;
for(int n2 = n; n2; n2 /= 10) mask *= 10; // find the left-most power of ten
for(int i = 1; mask > 1; mask /= 10) // loop over the mask to 1
printf("Digit %d --> %d\n", i++, (n % mask) * 10 / mask);
// print the digit number and increment the digit counter
// extract and print the digit:
// `n % mask` gets rid of everything to the left
// `* 10 / mask` gets rid of everything to the right
}
You could also make a simpler solution using the standard library function sprintf (string print formatted) to put the int into a string and then print from that, like so:
void print_digits(int n) {
char num[11]; // 32-bit int up to 9 digits, possible '-', and \0 -> 11
sprintf(num, "%d", n);
for (int i = 0; num[i]; i++)
printf("Digit %d --> %c\n", i + 1, num[i]);
}
The second might also be a tiny bit more performant due to not involving division, but I'm not certain of that and such minor differences don't matter for a problem like this anyway
Your code prints them in reverse because you are starting with the right-most digit (by taking the modulo by 10) each time, then dividing by 10.
To print from left to right, you could have:
#include <stdint.h>
void print_uint32_digits(uint32_t val)
{
int started = 0; // Flag to say we have started printing digits
// Special case for when val is zero
if (val == 0u)
{
printf("0\n");
return;
}
for (uint32_t divider = 1000000000u; divider != 0u; divider /= 10u)
{
uint32_t num = val / divider;
if (num > 0u || started)
{
printf("%c", num + '0');
started = 1;
val -= (num * divider);
}
}
printf("\n");
}
Some notes - I've used uint32_t because it is unsigned and a nice length. To make it work with plain "ints" would involve handling the case of negative numbers, which is more complex. I don't know if you need to handle negative numbers. (Also, ints on your platform could be 64-bit, so the initial divider would have to be adjusted accordingly.)
The 'started' flag is used to signal when we have output at least one digit, to ensure zeros get printed correctly. Until that flag is set, leading zeros are not printed.
A very simple recursive solution looks like this:
void print_num(int num)
{
if (num < 10)
fputc('0' + num, stdout);
else {
print_num(num/10);
print_num(num%10);
}
}
I am trying to determine a function to extract the individual digits of a long data type which the user enters.
int remain(int digit)
{
while(number != 0)
{
digit = number % 10;
number = number / 10;
}
return digit;
}
In this code the number variable is the number entered by user.
I want to extract all the digits of the number (e.g. a 16 digit number). So when I print remain(16) it prints 16 instead of 16th digit or prints 1 if I print remain(1). And also it prints the first digit if the number is less than 13 or greater than 16 and prints the 1 or 2 or 3 if i print remain(1) or remain(2) or remain(3) instead of printing the 1st or 2nd or 3rd digit, if the number is 13 digit long or 16 digit long or 15 digit long.
Okay, after your edit, I understand you want to print the return of the function and have all digits print. While you can simply use printf(), extracting with % and / is another way to extract digits. But, as you have found, when you extract digits with % and /, the digits will end up in reverse order. The solve that problem, you simply fill an array with digits, working from the end of the array back to the beginning.
Now before looking at a solution, if you want to "... extract the individual digits of a long data..." -- you will need to change the type in your function from int to long or you will experience a mismatch of type-size on systems where int and long are different sizes (like on x86_64).
In order for the array to survive the return of your function, you can either pass in an array to fill using another parameter, or you can declare your array with static storage duration so it survives return (but not that make the function not thread_safe in multithreaded programs -- not a concern here)
You can do something like the following:
#include <stdio.h>
#include <stdlib.h>
#define NCHR 32 /* if you need a constant, #define one (or more) */
#define BASE 10
char *extract_digits (long n)
{
static char digits[NCHR]; /* static, so digits survives return */
char *p = digits + NCHR - 1; /* pointer to last char in digits */
int sign = n < 0; /* check sign of n (negative, sign == 1) */
if (sign) /* process positive number */
n = -n;
if (!n) { /* handle zero case, sign irrelevant */
*--p = '0';
return p;
}
do { /* convert each digit to char */
*--p = n % BASE + '0'; /* fill from end of digits array */
n /= BASE;
} while (n);
if (sign) /* if sign, add '-' at front */
*--p = '-';
return p; /* return ptr to start of digits in digits[] */
}
int main (int argc, char **argv) {
long v = argc > 1 ? strtol(argv[1], NULL, BASE) : -2381;
printf ("digits: %s\n", extract_digits(v));
}
(note: I have change the function name to extract_digits(), you can rename it as you please)
The program prints the extracted digits directly using the function return -- which is what I take was your intent from the question.
Example Use/Output
Using default value:
$ ./bin/extractdigits_fnc
digits: -2381
Passing value:
$ ./bin/extractdigits_fnc 54823
digits: 54823
Passing zero:
$ ./bin/extractdigits_fnc 0
digits: 0
Passing negative zero:
$ ./bin/extractdigits_fnc -0
digits: 0
Your '16' example:
$ ./bin/extractdigits_fnc 16
digits: 16
Look things over and let me know if I understood your question correctly.
If you are looking for a function that can extract the n'th digit in a number, it can be something like:
int extract_digit(unsigned long long number, unsigned digit)
{
int res = -1;
if (digit > 0)
{
unsigned count = 1;
unsigned long long tmp = number;
while(tmp/10 > 0)
{
++count;
tmp /= 10;
}
if (digit <= count)
{
tmp = number;
while ((count - digit) > 0)
{
--count;
tmp /= 10;
}
res = tmp % 10;
}
}
return res;
}
Notice that the function assumes that the left-most digit is digit 1.
The function will return a -1 if the requested "digit" doesn't exists. Otherwise the function returns the digit.
The function can be used like:
int main(void){
unsigned long long number = 31415926535ULL;
printf("number: %llu\n", number);
for (unsigned i = 0; i < 13; ++i)
{
int n = extract_digit(number, i); // Get i'th digit
if (n < 0)
{
printf("Digit %u is out of range\n", i);
}
else
{
printf("Digit %u is %d\n", i, n);
}
}
return 0;
}
Output
number: 31415926535
Digit 0 is out of range
Digit 1 is 3
Digit 2 is 1
Digit 3 is 4
Digit 4 is 1
Digit 5 is 5
Digit 6 is 9
Digit 7 is 2
Digit 8 is 6
Digit 9 is 5
Digit 10 is 3
Digit 11 is 5
Digit 12 is out of range
I can't elaborate a program with arrays language C.
The console received 4 numbers. I want to change the first number digits and multiply with the other.
Example input: 1260
Desire output: Change 12 to 21 and them multiple by 60 -> so output will be 1260 (as 21 * 60)
This is my current code:
int main() {
int number, temp;
int newnumber[4];
int n = 3;
printf("put the number");
scanf("%d", &number);
do {
newnumber[n] = number % 10;
number = number / 10;
n--;
} while (n >= o);
temp = newnumber[1];
newnumber[1] = newnumber[2];
newnumber[2] = temp;
}
know how i do 21 multiply with 60?
If we look at your example:
1260 => change 2 with 1, and multiply 21 with 60.
The permutation in your main function is wrong, cause you changed numbers at the index 1 (second position) and 2 (third position).
Back to your question, you can get the result you're looking for by doing the oppisite of what you did to get the units, tens and hundreds...
int main() {
int number, temp1, temp2;
int newnumber[4];
int n = 3;
printf("put the number");
scanf("%d", &number);
do {
newnumber[n] = number % 10;
number = number / 10;
n--;
} while (n >= 0);
temp1 = newnumber[0];
newnumber[0] = newnumber[1];
newnumber[1] = temp1;
temp1 = newnumber[0] * 10;
temp1 += newnumber[1];
temp2 = newnumber[2] * 10;
temp2 += newnumber[3];
printf("%d", temp1 * temp2);
}
I would have go with slightly different approach: first separate the numbers. Then call function to change the number order.
If you always get numbers with 2 digit you can do this:
int first = number / 100;
int second = number % 100;
And a function to swap the digit:
function swapDigits(int num) {
int ans = 0;
while (num > 0) {
ans = ans * 10 + num % 10;
num /= 10;
}
return ans;
}
Now just do second * swapDigits(first) to get your result.
I'm not c expert so verify my code before use...
If your conditions always hold you can keep it simple and do something like this:
int main() {
int number;
int newnumber[4];
int n = 3;
printf("put the number");
scanf("%d", &number);
do {
newnumber[n] = number % 10;
number = number / 10;
n--;
} while (n >= 0);
printf("And the result: %d\n", (newnumber[1] * 10 + newnumber[0]) * (newnumber[2] * 10 + newnumber[3]));
}
Then you are not getting the individual digits, but pairs and the like. Just get the last two digits in one shot:
int rem = number % 100; /* last two digits */
number /= 100;
int msd = number % 10; /* next, third digit */
number /= 10;
int lsd = number % 10; /* most significant digit */
/* I don't assume you have more digits, because you are doing different
* operations with them, no pattern up to here, but you should continue
* your approach here. */
int out = (msd * 10 + lsd) * rem;
should give you a solution. No arrays needed.
I need to extract the odd number out and give the output, but when I execute the code, it gives me in reverse order (e.g. expected output is1234 = 13 but my code gave me 31).
int digit, num;
while (num > 0)
{
digit = num % 10;
if(digit % 2 != 0)
{
printf("%d" , digit);
}
num /= 10;
}
That is because you are first printing the remainder from the division operation in the following statement:
digit = num % 10;
You have to store it in an array and after all the divisions are complete only print it.
you're printing the units first. So you need either to store the data, or to use a recursive approach so last numbers are printed first:
#include <stdio.h>
void podd(int num)
{
if (num > 0)
{
int digit = num % 10;
if (digit % 2)
{
printf("%d" , digit);
}
podd(num / 10);
}
}
int main()
{
podd(1234);
printf("\n");
return 0;
}
(variation of the classic int to string conversion problem described here: Convert integer to string without access to libraries)
Obviously, It will output 31.
Coz,
1st iteration in while loop =>
num is 1234
digit = num % 10; digit = 1234 % 10 ( It's 4)
if(digit % 2 != 0)
{
printf("%d" , digit);
}
4 will not print coz 4 % 2 != 0 will return false.
num /= 10; num = 1234 / 10 ( num is now 123)
2nd iteration in while loop =>
num is 123
digit = num % 10; digit = 123 % 10 ( It's 3)
if(digit % 2 != 0)
{
printf("%d" , digit);
}
3 will be printed coz 4 % 2 != 0 will return true.
num /= 10; num = 123 / 10 ( num is now 12)
So ... we got our first number 3.
So, if you continue this process (it's called debugging ) for the next while loop iterations you will find the final output ... that's 31.
The direct answer as follows:
int num = 1234, digit = 0;
do {
digit = num % 10; // Assigns the extracted digit to a variable named digit (ex: 4).
if (digit % 2 != 0) // Applies the formula to get the odd number.
printf("%d\n", digit); // Prints the odd number.
num /= 10; // Extracts one digit each time (ex: 1234 / 10 = 123).
} while (num > 0); // Has reached the end of the number 'num'.
The Result:
3
1
I'm doing a homework assignment for my course in C (first programming course).
Part of the assignment is to write code so that a user inputs a number up to 9 digits long, and the program needs to determine whether this number is "increasing"/"truly increasing"/"decreasing"/"truly decreasing"/"increasing and decreasing"/"truly decreasing and truly increasing"/"not decreasing and not increasing". (7 options in total)
Since this is our first assignment we're not allowed to use anything besides what was taught in class:
do-while, for, while loops, else-if, if,
break,continue
scanf, printf ,modulo, and the basic operators
(We can't use any library besides for stdio.h)
That's it. I can't use arrays or getchar or any of that stuff. The only function I can use to receive input from the user is scanf.
So far I've already written the algorithm with a flowchart and everything, but I need to separate the user's input into it's distinct digits.
For example, if the user inputs "1234..." i want to save 1 in a, 2 in b, and so on, and then make comparisons between all the digits to determine for example whether they are all equal (increasing and decreasing) or whether a > b >c ... (decreasing) and so on.
I know how to separate each digit by using the % and / operator, but I can't figure out how to "save" these values in a variable that I can later use for the comparisons.
This is what I have so far:
printf("Enter a positive number : ");
do {
scanf ("%ld", &number);
if (number < 0) {
printf ("invalid input...enter a positive integer: ");
continue;
}
else break;
} while (1);
while (number < 0) {
a = number % 10;
number = number - a;
number = number / 10;
b = a;
}
Why not scan them as characters (string)? Then you can access them via an array offset, by subtracting the offset of 48 from the ASCII character code. You can verify that the character is a digit using isdigit from ctype.h.
EDIT
Because of the incredibly absent-minded limitations that your professor put in place:
#include <stdio.h>
int main()
{
int number;
printf("Enter a positive number: ");
do
{
scanf ("%ld", &number);
if (number < 0)
{
printf ("invalid input...enter a positive integer: ");
continue;
}
else break;
} while (1);
int a = -1;
int b = -1;
int c = -1;
int d = -1;
int e = -1;
int f = -1;
int g = -1;
int h = -1;
int i = -1;
while (number > 0)
{
if (a < 0) a = number % 10;
else if (b < 0) b = number % 10;
else if (c < 0) c = number % 10;
else if (d < 0) d = number % 10;
else if (e < 0) e = number % 10;
else if (f < 0) f = number % 10;
else if (g < 0) g = number % 10;
else if (h < 0) h = number % 10;
else if (i < 0) i = number % 10;
number /= 10;
}
/* Printing for verification. */
printf("%i", a);
printf("%i", b);
printf("%i", c);
printf("%i", d);
printf("%i", e);
printf("%i", f);
printf("%i", g);
printf("%i", h);
printf("%i", i);
return 0;
}
The valid numbers at the end will be positive, so those are the ones you validate to meet your different conditions.
Since you only need to compare consecutive digits, there is an elegant way to do this without arrays:
int decreasing = 2;
int increasing = 2;
while(number > 9)
{
int a = number % 10;
int b = (number / 10) % 10;
if(a == b)
{
decreasing = min(1, decreasing);
increasing = min(1, increasing);
}
else if(a > b)
decreasing = 0;
else if(a < b)
increasing = 0;
number /= 10;
}
Here, we walk through the number (by dividing by 10) until only one digit remains. We store info about the number up to this point in decreasing and increasing - a 2 means truly increasing/decreasing, a 1 means increasing/decreasing, and a 0 means not increasing/decreasing.
At each step, a is the ones digit and b is the tens. Then, we change increasing and decreasing based on a comparison between a and b.
At the end, it should be easy to turn the values of increasing and decreasing into the final answer you want.
Note: The function min returns the smaller of its 2 arguments. You should be able to write your own, or replace those lines with if statements or conditionals.
It's stupid to ask you to do loops without arrays --- but that's your teacher's fault, not yours.
That being said, I would do something like this:
char c;
while (1) {
scanf("%c", &c);
if (c == '\n') /* encountered newline (end of input) */
break;
if (c < '0' || c > '9')
break; /* do something to handle bad characters? */
c -= '0';
/*
* At this point you've got 0 <= c < 9. This is
* where you do your homework :)
*/
}
The trick here is that when you type numbers into a program, you send the buffer all at once, not one character at a time. That means the first scanf will block until the entire string (i.e. "123823" or whatever) arrives all at once, along with the newline character ( '\n' ). Then this loop parses that string at its leisure.
Edit For testing the increasing/decreasing-ness of the digits, you may think you need to store the entire string, but that's not true. Just define some additional variables to remember the important information, such as:
int largest_digit_ive_seen, smallest_digit_ive_seen, strict_increasing_thus_far;
etc. etc.
Let us suppose you have this number 23654
23654 % 10000 = 2 and 3654
3654 % 1000 = 3 and 654
654 % 100 = 6 and 54
54 % 10 = 5 and 4
4
This way you can get all the digits. Of course, you have to know if the number is greater than 10000, 1000, 100 or 10, in order to know the first divisor.
Play with sizeof to get the size of the integer, in order to avoid a huge if...else statement
EDIT:
Let us see
if (number>0) {
// Well, whe have the first and only digit
} else if (number>10) {
int first_digit = number/10;
int second_digit = number % 10;
} else if (number>100) {
int first_digit = number/100;
int second_digit = (number % 100)/10;
int third_digit = (number % 100) % 10;
} ...
and so on, I suppose
// u_i is the user input, My homework asked me to extract a long long, however, this should also be effective for a long.
int digits = 0;
long long d_base = 1;
int d_arr[20];
while (u_i / d_base > 0)
{
d_arr[digits] = (u_i - u_i / (d_base * 10) * (d_base * 10)) / d_base;
u_i -= d_arr[digits] * d_base;
d_base *= 10;
digits++;
}
EDIT: the extracted individual digit now lives in the int array d_arr. I'm not good at C, so I think the array declaration can be optimized.
Here's a working example in plain C :
#include <stdio.h>
unsigned long alePow (unsigned long int x, unsigned long int y);
int main( int argc, const char* argv[] )
{
int enter_num, temp_num, sum = 0;
int divisor, digit, count = 0;
printf("Please enter number\n");
scanf("%d", &enter_num);
temp_num = enter_num;
// Counting the number of digits in the entered integer
while (temp_num != 0)
{
temp_num = temp_num/10;
count++;
}
temp_num = enter_num;
// Extracting the digits
printf("Individual digits in the entered number are ");
do
{
divisor = (int)(alePow(10.0, --count));
digit = temp_num / divisor;
temp_num = temp_num % divisor;
printf(" %d",digit);
sum = sum + digit;
}
while(count != 0);
printf("\nSum of the digits is = %d\n",sum);
return 0;
}
unsigned long alePow(unsigned long int x, unsigned long int y) {
if (x==0) { return 0; }
if (y==0||x==1) { return 1; }
if (y==1) { return x; }
return alePow(x*x, y/2) * ((y%2==0) ? 1 : x);
}
I would suggest loop-unrolling.
int a=-1, b=-1, c=-1, d=-1, e=1, f=-1, g=-1, h=-1, i=-1; // for holding 9 digits
int count = 0; //for number of digits in the given number
if(number>0) {
i=number%10;
number/=10;
count++;
}
if(number>0) {
h=number%10;
number/=10;
count++;
}
if(number>0) {
g=number%10;
number/=10;
count++;
}
....
....
/* All the way down to the storing variable a */
Now, you know the number of digits (variable count) and they are stored in which of the variables. Now you have all digits and you can check their "decreasing", "increasing" etc with lots of if's !
I can't really think of a better soltion given all your conditions.