C - reverse a number - c

I am coding in C on linux, and I need to reverse a number. (EG: 12345 would turn into 54321), I was going to just convert it into a string using itoa and then reverse that, as it's probably a lot easier with string manipulation, however it turns out itoa is non standard and isn't included in gcc. Is there a way of doing a binary rotation style thing on decimal numbers and if not what approach should I take?

int n;
scanf("%d",&n);
int rev=0,rem;
while(n>0)
{
rem=n%10; //take out the remainder .. so it becomes 5 for 12345
rev=rev*10+rem; //multiply the current number by 10 and add this remainder.
n=n/10; //divide the number. So it becomes 1234.
}
printf("%d",rev);

#include<stdio.h>
main()
{
int rev=0,n;
scanf("%d",&n);
while(n)
{
rev=10*rev+n%10;
n/=10;
}
printf("result=%d",rev);
}

Do it without strings.
fkt()
{
int i = 12345;
int n = 0;
int x;
char nr[10];
char *p = &nr[0];
while(i != 0)
{
x = i % 10;
i = i/10;
n = n * 10 + x;
*p = x+'0';
p++;
}
*p = 0;
printf("%d %s\n", n, nr);
return 0;
}

If you really want to use strings, you can use sprintf to do what itoa does.
int k = 12345;
char str[40];
sprintf(str,"%d",k);
Then reverse the string and convert it back to int using atoi or sscanf.

you can use stack to do this,
struct node
{
char character;
struct node *next;
};
struct node *list_head,*neos;
main()
{
list_head=NULL;
char str[14];
int number,i;
scanf("%d",&number);
sprintf(str,"%d",number); //here i convert number to string
for(i=0;i<strlen(str);i++) //until the end of the string
{
add_to_stack(str[i]); //i take every character and put it in the stack
}
print_the_number();
}
attention here,in stack the item
which is added last,
it taken out first,
that why it works..
void add_to_stack(char charac)
{
neos=(struct node*)malloc(sizeof(struct node));
neos->character=charac;
neos->next=list_head;
list_head=neos;
}
void print_the_number()
{
struct node *ptr;
ptr=list_head;
while(ptr!=NULL)
{
printf("%c",ptr->character);
ptr=ptr->next;
}
}

iota() is not a standard C function, but snprintf() serves the purpose just as well.
/* assume decimal conversion */
const char * my_itoa (int input, char *buffer, size_t buffersz) {
if (snprintf(buffer, sz, "%d", input) < sz) return buffer;
return 0;
}
Since the input cannot be negative, you can use an unsigned type:
unsigned long long irev (unsigned input) {
unsigned long long output = 0;
while (input) {
output = 10 * output + input % 10;
input /= 10;
}
return output;
}
Reversing the input may result in a value that no longer fits the input type, so the return result attempts to use a wider type. This may still fail if unsigned and unsigned long long have the same width. For such cases, it is probably easiest to use a string to represent the reversed value. Or, if the only goal is to print the number, you can just use a loop to print the digits in reverse order.
void print_irev (unsigned input) {
if (input) {
do {
putchar('0' + input % 10);
input /= 10;
} while (input);
} else {
putchar('0');
}
putchar('\n');
}

#include<iostream>
using namespace std;
int main()
{
int dig,n,rev=0;`
cout<<"enter number";
cin>>n;
while(n!=0)
{
dig=n%10;
rev=rev*10+dig;
n=n/10; }
if(n==0){
cout<<"palindrome of zeros ";
}
if(rev==1)
{
cout<<"reverse of 10 is 01";
}
//since exception occurs when user inputs 10 or 0s
else
{
cout<<"reverse of the number is ";
cout<<rev;
}
getch();
}

their are two methods
method 1 :
int n;
cin>>n;
int rev=0,rem;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
cout<<rev;
method 2:
cin>>n; // size of array
int a[n+1]={0};
for(i=1;i<=n;i++)
cin>>a[i];
for(i=n;i>0;i--)
cout<<a[i];

Related

How to stop infinite looping the output?

I have code with a function that returns the biggest digit from a number. The requirement is to enter numbers until something that is not a number is entered. When something that isn't a number is entered, the program is supposed to stop, but in my case it just starts an infinite loop that prints the last result that the function returned. Here is the code:
#include <stdio.h>
int maxDigit(int n){
int temp = n, maxDig = 0;
while(temp){
int digit = temp % 10;
if(digit > maxDig){
maxDig = digit;
}
temp /= 10;
}
return maxDig;
}
int main()
{
int n = 1, broj;
while(n){
if(scanf("%d", &broj));
printf("%d\n", maxDigit(broj));
}
return 0;
}
What might be the problem?
You can look at the return value of scanf to see if you read a valid integer, and you can use break to terminate your loop. The n variable in your main function just had a constant value so I got rid of it, and cleaned up the function in a few other ways. Here is my resulting code:
...
int main() {
while (1) {
int input;
if (scanf("%d", &input) != 1) { break; }
printf("%d\n", maxDigit(input));
}
}

Print string shows symbols

I'm trying to write an ITOA (integer to array) function using pointers.
So this is what I got so far. I debugged and it works just fine. The thing is, the printing itself doesn't work. I'm adding two screenshots.
Would appreciate some help.
int num_length(int number)
{
int count = 0;
while (number > 0)
{
count++;
number /= 10;
}
return count;
}
void itoa(int number, char *strptr)
{
int number_len = num_length(number);
char *start = strptr;
strptr += number_len - 1;
while (strptr >= start)
{
*strptr = number % 10;
number /= 10;
strptr--;
}
}
void print_string(char *strptr)
{
while (*strptr != '\0')
{
printf("%c", *strptr);
strptr++;
}
}
void main(void)
{
int number;
char number_in_string[N] = { '\0' };
char *strptr = &(number_in_string[0]);
printf("Enter a number: ");
scanf_s("%d", &number);
itoa(number, strptr);
print_string(number_in_string);
getch();
}
If you're trying to get an array of numeric characters (as seems evident by your print_string(a) function), you'll need to adjust the values appropriately:
*strptr = number % 10 + '0';
As per your debugging output ('\x2', '\x5', '\x5') , you're correctly getting the individual digits of the number but those are binary values, not the character representations.
Turning the former into the latter involves adding '0' (0x30 if you're using ASCII, for example). C guarantees that the numeric values are contiguous so this is safe.
(a) ... which could, by the way, be replaced with a simple:
printf("%s", number_in_string);
in your main function.

Assignment makes pointer from integer without a cast and vice versa in c

I'm trying to write a program that gets a string, and a number, and calculates the length of it and shifting all the elents right.
I have 2 errors:
1.assignment makes pointer from integer without a cast.
2.assignment makes integer from pointer without a cast.
#include <stdio.h>
#include <string.h>
#define N 10
int myStrlen(char*);
void shiftRight(char*, int);
int main() {
char str[N] = {0};
int num = 0;
int len;
/* input of the string */
scanf("%s",str);
scanf("%d",&num);
len=myStrlen(str);
if(num>=0) {
shiftRight(str, num);
printf("%s\n",str);
}
else
{
printf("%s\n", str);
}
return 0;
}
int myStrlen(char*str)
{
int my_len=0;
while (str[my_len] != '\0')
{
my_len++;
}
return my_len;
}
void shiftRight(char* str, int num)
{
int i;
char* j;
int count;
j=(str[N-1]);
for(count=0;count<num;count++)
{
for(i=N-1;i>0;--i)
{
str[i]=str[i-1];
}
str[0]=j;
}
}
Your answers are welcome,anf if you anything wrong with this code,please mention it.
As your compiler will have told you, pointer from integer without a cast is at
j=(str[N-1]);
And integer from pointer is at
str[0]=j;
You should have declared j as char j;
But now when i run it, and typing lets say ball as a string and 1 to
be a number, i get nothing from the program instead of getting "lbal"
You have all the correct elements but that's not enough. Writing a program is telling a story, you need to set the scene, describe what happens along the way and conclude your narrative. A story with elements out of order is nonsense, as is a program.
Specific issues with your code: you're saving of the last character (to restore it to the beginning of the string) is in the wrong place; you're using the allocation of the string when you should be using it's length (and conveniently, you have a function for that!); this is really more of a rotation than a shift; use the most descriptive variable names you can, not the shortest you can get away with; pick one indentation style and stick with it -- it can change between programs you write but shouldn't change within an individual program.
Below is a rework of your code addressing some of the issues above:
#include <stdio.h>
#define STRING_SIZE 10
int myStrlen(char *string)
{
int length = 0;
while (string[length] != '\0')
{
length++;
}
return length;
}
void rotateRight(char *string, int number)
{
int length = myStrlen(string);
for (int count = 0; count < number; count++)
{
char j = string[length - 1];
for (int i = length - 1; i > 0; i--)
{
string[i] = string[i - 1];
}
string[0] = j;
}
}
int main()
{
char string[STRING_SIZE] = {0};
int number = 0;
/* input of the string */
scanf("%s", string);
scanf("%d", &number);
if (number > 0)
{
rotateRight(string, number);
printf("%s\n", string);
}
else
{
printf("%s\n", string);
}
return 0;
}
OUTPUT
% ./a.out
elephant
3
anteleph
%

Decimal to Binary Program

I am working on an assignment for a C Programming course in regards to converting a decimal to binary using a function that takes in an unsigned char as its input and has a void output. The function will print the binary code of the unsigned char. A hint for the assignment is to create an array of exponents starting with 128 and going down to 1.
I started working on the assignment and ran the debugger, but my program is not working and I am getting a run time error message: Run-Time Check Failure #2 - Stack around the variable userInput was corrupted.
I would appreciate some suggestions on how I can fix my code and if there is a much simple way to write it in order to make the code easier to understand.
#include <stdio.h>
#include <stdlib.h>
unsigned char DecimalToBinary(unsigned char decimalInput);
void main() {
unsigned char userInput = ' ';
unsigned char resultOfUserInput = DecimalToBinary(userInput);
printf("Enter a number less than 256: ");
scanf_s("%u", &userInput);
printf("%u in binary: %u", userInput, resultOfUserInput);
system("pause");
}
unsigned char DecimalToBinary(unsigned char decimalNumber) {
int arrayOfExponents[128] = {}, i = 1, j;
while (decimalNumber > 0) {
arrayOfExponents[i] = decimalNumber % 2;
i++;
decimalNumber = decimalNumber / 2;
}
for (j = i - 1; j > 0; j--) {
printf("%i", arrayOfExponents[j]);
}
return 0;
}
%u reads an unsigned int (say 4 bytes) and you are trying to read it into variable userInput (1 byte)
Few things
1) scanf_s("%u", &userInput); please change it to scanf_s("%c", &userInput);
2) You are calling DecimalToBinary before reading user input
#include <stdio.h>
#include <stdlib.h>
unsigned DecimalToBinary(unsigned char decimalInput);
int main(void) {//void is invalid as a return value.
unsigned userInput = 256;
unsigned resultOfUserInput;//DecimalToBinary(userInput);userInput did not input at this point.
printf("Enter a number less than 256: ");
if(1 != scanf_s("%u", &userInput)){
printf("invaid input!\n");
return EXIT_FAILURE;
}
if(userInput >= 256){
printf("More than 256 of the value has been entered.\n");
return EXIT_FAILURE;
}
resultOfUserInput = DecimalToBinary((unsigned char)userInput);
printf("%u in binary: %u\n", userInput, resultOfUserInput);
system("pause");
return 0;
}
unsigned DecimalToBinary(unsigned char decimalNumber) {
unsigned bin = 0, exp = 1;//assert(sizeof(unsigned) >= 4);
while (decimalNumber > 0) {
bin += (decimalNumber & 1) * exp;
decimalNumber >>= 1;
exp *= 10;
}
return bin;
}
This is an easy way to convert numbers from base 10 to any other base using recursion. I have shared one example with you. You can have any other number as your base.
#include <stdio.h>
void baseconvert(int number,int base)
{
if(number > 0)
{
int digit = (number % base);
baseconvert(number / base, base);
printf("%d",digit);
}
else
{
printf("\n");
}
}
int main()
{
baseconvert(1023,2);
return 0;
}

How to extract numbers from string in c?

Say I have a string like ab234cid*(s349*(20kd and I want to extract all the numbers 234, 349, 20, what should I do ?
You can do it with strtol, like this:
char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
// Found a number
long val = strtol(p, &p, 10); // Read number
printf("%ld\n", val); // and print it.
} else {
// Otherwise, move on to the next character.
p++;
}
}
Link to ideone.
A possible solution using sscanf() and scan sets:
const char* s = "ab234cid*(s349*(20kd";
int i1, i2, i3;
if (3 == sscanf(s,
"%*[^0123456789]%d%*[^0123456789]%d%*[^0123456789]%d",
&i1,
&i2,
&i3))
{
printf("%d %d %d\n", i1, i2, i3);
}
where %*[^0123456789] means ignore input until a digit is found. See demo at http://ideone.com/2hB4UW .
Or, if the number of numbers is unknown you can use %n specifier to record the last position read in the buffer:
const char* s = "ab234cid*(s349*(20kd";
int total_n = 0;
int n;
int i;
while (1 == sscanf(s + total_n, "%*[^0123456789]%d%n", &i, &n))
{
total_n += n;
printf("%d\n", i);
}
here after a simple solution using sscanf:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str[256]="ab234cid*(s349*(20kd";
char tmp[256];
int main()
{
int x;
tmp[0]='\0';
while (sscanf(str,"%[^0123456789]%s",tmp,str)>1||sscanf(str,"%d%s",&x,str))
{
if (tmp[0]=='\0')
{
printf("%d\r\n",x);
}
tmp[0]='\0';
}
}
Make a state machine that operates on one basic principle: is the current character a number.
When transitioning from non-digit to digit, you initialize your current_number := number.
when transitioning from digit to digit, you "shift" the new digit in:
current_number := current_number * 10 + number;
when transitioning from digit to non-digit, you output the current_number
when from non-digit to non-digit, you do nothing.
Optimizations are possible.
If the numbers are seprated by whitespace in the string then you can use sscanf(). Since, it's not the case with your example,
you have to do it yourself:
char tmp[256];
for(i=0;str[i];i++)
{
j=0;
while(str[i]>='0' && str[i]<='9')
{
tmp[j]=str[i];
i++;
j++;
}
tmp[j]=0;
printf("%ld", strtol(tmp, &tmp, 10));
// Or store in an integer array
}
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
char *str ="ab234cid*(s349*(20kd", *ptr = str;
while (*ptr) { // While there are more characters to process...
if ( isdigit(*ptr) ) {
// Found a number
int val = (int)strtol(ptr,&ptr, 10); // Read number
printf("%d\n", val); // and print it.
} else {
// Otherwise, move on to the next character.
ptr++;
}
}
}
Or you can make a simple function like this:
// Provided 'c' is only a numeric character
int parseInt (char c) {
return c - '0';
}

Resources