What's wrong with my program which reverses a given integer? - c

Codechef isn't accepting the following code. Can anyone tell me what's wrong in it as I'm unable to point any mistake ?
//This program reverses a given integer.
#include<stdio.h>
int main(void)
{
int t,n,l;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
while(n>0){
l=n%10;
n=n/10;
printf("%d",l);
}
printf("\n");
}
return 0;
}
t is no. of test cases.
n is the input integer.
l is some random variable to get the print job done.
This program is supposed to reverse a positive integer only.
Example:- Input - 1234
Output - 4321

try this code (I'm agree with molbdnilo's comment):
//This program reverses a given integer.
#include<stdio.h>
#include <math.h>
int main(void)
{
int i,j,t,n,l,r = 0;
char d[1024]; // stock digits
scanf("%d",&t);
while(t--){
scanf("%d",&n);
i = 0;
while(n>0){
l=n%10;
n=n/10;
d[i] = l;
i++;
}
for(j=0;j<i;j++)
r+= d[i-j-1] * pow(10,j); // r is the reversed number
printf("%d\n",r);
}
return 0;
}

I got it. You must not print the non-significant '0'. For example 1230 gives 321. Here is my working code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/* strrev reverses a given string */
char *strrev(char *str)
{
char tmp;
size_t i = 0,
len = strlen(str);
for (; i < len / 2 ; ++i)
{
tmp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = tmp;
}
return str;
}
int main(void)
{
char buff[32],
*s;
size_t i,
len;
scanf("%zu", &len);
for (i = 0 ; i < len ; ++i)
{
scanf("%s", buff);
s = strrev(buff);
while (*s == '0')
++s; /* discarding '0' */
printf("%s\n", s);
}
return EXIT_SUCCESS;
}

Related

Doing reverse of a number in C language

While doing reverse program in C,I am getting issue with number 01 & 10 because its reverse is not showing in the output. Here is my code:
#include<stdio.h>
int main(){
int i,n,rev=0;
printf("Enter the number:");
scanf("%d",&n);
while(n>0){
i=n%10;
rev=rev*10+i;
n=n/10;
}
printf("Reverse of that number:%d",rev);
return 0;
}
I am expecting that if I give 01 as input, its reverse must be shown as 10.
If obliged to still use "%d":
Detect the input offset with "%n", which stores the character offset of the scan at that point.
int offset1 = 0;
int offset2 = 0;
if (scanf(" %n%d%n", &offset1, &n, &offset2) == 1) {
while (offset1 < offset2) {
offset1++;
i = n%10;
rev = rev*10+i;
n = n/10;
}
offset2 - offset1 will be the character count of the number and input "01" has a character count of 2.
This still gets fooled if the text input includes a sign character. Additional, and not so clear, code needed to handle that.
As suggested in comments, this is trivial if approached from a string perspective.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char input[100] = {0};
if (scanf("%99s", input) != 1) {
printf("Invalid input.\n");
return 1;
}
size_t len = strlen(input);
char *output = malloc(len + 1);
size_t i;
for (i = 0; i < len; i++) {
output[i] = input[len-i-1];
}
output[i] = '\0';
printf("%s\n", output);
free(output);
return 0;
}
You could add in validation code that determines that the input actually is a valid integer, and if you actually need an int back, there are library functions like strtol that will accomplish this.

Every k-th digit cyclic problem using strings in C

Given some number in a form of string, I want to extract every k-th number from it. Then I go through the remaining string and extract every k-th number again. The thing I get as a result should be the number formed by these extracted ones(in a proper order). Example: 123456789, k = 3 --> 369485271
My algorithm is as follows: While the lenght of the string allows extracting every k-th number, I go through the string and store every k-th element in another string. Then I delete the extracted elements from the original string by tracking the proper index of an element and proceed forvard while the lenght of my str is sufficient.
I can't figure out what's the problem with my code. And maybe my approach isn't that good and there are some better/simpler ways of diong this?
#include <stdio.h>
#include <string.h>
void remove(char *str, unsigned int index) {
char *src;
for (src = str+index; *src != '\0'; *src = *(src+1),++src) ;
*src = '\0';
}
int main() {
char number[100];
char result[100];
int k;
printf("Enter a string: ");
scanf("%s",number);
printf("Enter a key: ");
scanf("%d",&k);
while (strlen(number)>k-1) {
for (int i = 0, p = 0; number[i] != '\0'; i++) {
if (i % k == (k-1)) {
result[p] = number[i];
p++;
}
}
for (int j = 0; number[j] != '\0'; j++){
if (j % k == (k-1)) {
remove(number, j);
j+=1; /*since the index was shifted due to removing an element*/
}
}
}
puts(result);
return 0;
}
You some issues:
You start writing your output from scratch again in each iteration of your while loop.
You do not handle the last digits
You do not treat the input as a cyclic input.
You do not terminate your output string.
remove is already a name of standard library function.
A shorter version could be this (untested):
#include <stdio.h>
#include <string.h>
void remove_digit(char *str, unsigned int index) {
char *src;
for (src = str+index; *src != '\0'; *src = *(src+1),++src)
;
}
int main() {
char number[100];
char result[100];
int k;
printf("Enter a string: ");
scanf("%s",number);
printf("Enter a key: ");
scanf("%d",&k);
int p = 0;
int i = 0;
int skip = k-1; // We remove 1 digit and skip k-1 digits
while (number[0] != 0) {
i = (i + skip) % strlen(number);
result[p] = number[i];
p++;
remove_digit(number, i);
}
number[p] = 0;
puts(result);
return 0;
}
The following code seems to be what you want:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void remove_(char *str, unsigned int index) {
char *src;
for (src = str+index; *src != '\0'; *src = *(src+1),++src) ;
*src = '\0';
}
int main(int argc, const char * argv[]) {
char number[100];
char result[100];
int tmp[100];
int k;
printf("Enter a string: ");
scanf("%s",number);
printf("Enter a key: ");
scanf("%d",&k);
int p = 0;
for (int tp = 0; strlen(number) > k-1; tp = 0) {
for (int i = 0; number[i] != '\0'; i++)
if (i % k == (k-1))result[p++] = number[i];
for (int j = 0; number[j] != '\0'; j++)
if (j % k == (k-1)) tmp[tp++] = j;
for (; tp; --tp) remove_(number, tmp[tp-1]);
}
// The newly added code
for (int index; strlen(number); ) {
index = (k-1) % strlen(number);
result[p++] = number[index];
remove_(number, index);
}
puts(result);
return 0;
}
The most important thing is that every while loop, you need to remove the elements in number at once. While ensuring the integrity of your original code, I made some changes. Unfortunately, the main idea of ​​the original code is wrong.
It should circulate from the tail (including the rest) to the head after one round. But I found that the function of the code you provided is that after each round, the next round starts from the 0th element of the head.
By the way, your algorithm is similar to the Josephus problem

C program to find frequency of a character from a string

why the code doesn't work?? anything wrong with that loop?? if then what should be answer? and why it can't be. Please make me clear. :)
#include<stdio.h>
#include<string.h>
int main()
{
char s[1000];
int i,j=1,x,y; char k,l;
gets(s);
l = strlen(s);
scanf("%c",&k);
for(s[i]=0; s[i]<l; i++)
{
if(s[i]=='k')
j++;
}
printf("\n%c is %d time(s) in string",k,j);
return 0;
}
First use l = strlen(s)+1; instead of l = strlen(s);. Then change s[i]=0 in for loop to i = 0; and use i<l instead of s[i]<l.
Also, change if(s[i]=='k') to if(s[i]==k).
Full example:
#include<stdio.h>
#include<string.h>
int main()
{
char s[1000];
int i,j=0,l;
char k;
gets(s);
l = strlen(s)+1;
scanf("%c",&k);
for(i=0; i<l; i++)
{
if(s[i]== k)
j++;
}
printf("\n%c is %d time(s) in string",k,j);
return 0;
}
please check this way. you are matching letter 'k' instead of variable.
if(s[i]==k)
The datatype of the variable l is char.It should be declared of the type int.
You have initialised j with value 1 when it should have been initialised with 0 .
The for loop is incorrect. Instead of s[i] use i and check the condition i < l .
And finally in the if condition replace 'k' by k
I hope this will help you get desired result
I can see you made many mistakes, I will list them up:
if(c[i] == 'k') should be if(c[i] == k)
You should use fgets instead of gets, gets is not stable or safe
Please do use MACRO for 1000 in char s[1000]
for(s[i]=0; s[i] < l; i++) is wrong because you should be iterating with i so it should be for( i = 0; i < length; ++i)
The code example:
#include <stdio.h> /* printf */
#include <stdlib.h> /* fgets */
#include <string.h> /* strlen */
#define MAX_LINE_LENGTH 1000
int main()
{
char k;
char line[MAX_LINE_LENGTH];
size_t count, length, i;
/* Reading a line/string */
printf("Please enter a line : ");
if (!fgets (line, MAX_LINE_LENGTH, stdin))
{
/* handle error */
printf("Failed to read input\n");
return 1;
}
/* calculating the length */
length = strlen(line) + 1;
/* Reading the letter to count its occurences */
printf("Please enter a letter : ");
scanf("%c",&k);
/*
* Counting the occurences of k in a string/line
*/
count = 0;
for(i = 0; i < length; ++i)
{
if(line[i] == k)
{
++count;
}
}
printf("%c is %d time(s) in string\n", k, count);
return 0;
}

Junk values while reversing a string?

My program is to reverse, even though the reverse is being generated but the problem is there is an unwanted junk values too.
I am not able to understand where the problem is.
#include <stdio.h>
#include<string.h>
int main()
{
char ar[100],b[100];
int i,j;
scanf("%s",ar);
j=strlen(ar);
printf("%d",j);
j-=1;
for(i=0;j>=0;i++)
{
b[i]=ar[j];
j--;
}
printf("\n %s",b);
}
This is the output:
You need to add
b[i] = 0;
at the end to terminate the string.
The function printf() depends on the NUL-terminating character as a marker to stop printing, so you should terminate your array with the character '\0'. Also it would be better to make a function to reverse a string:
#include <stdio.h>
#include <string.h>
void m_strrev(char *str, char *output);
int main(void)
{
char ar[100], b[100];
//int i, j;
scanf("%s", ar);
/*j = strlen(ar) - 1;
for (i = 0; j >= 0; i++)
{
b[i] = ar[j];
j--;
}
b[i] = '\0';
printf("%s\n", b);*/
m_strrev(ar, b);
printf("%s\n", b);
}
void m_strrev(char *str, char *output)
{
char *e = str;
while (*e) {
e++;
}
e--;
while (e >= str) {
*output++ = *e--;
}
*output = '\0';
}

string reverse program in C

i have written a program to reverse a string.. But it is not working.. It is printing the same string which is scanned.. What is the problem with the code?
#include <stdio.h>
#include <stdlib.h>
char *strrev(char *s)
{
char *temp = s;
char *result = s;
char t;
int l = 0, i;
while (*temp) {
l++;
temp++;
}
temp--;
for (i = 0; i < l; i++) {
t = *temp;
*temp = *s;
*s = t;
s++;
temp--;
}
return result;
}
int main()
{
char *str;
str = malloc(50);
printf("Enter a string: ");
scanf("%s", str);
printf("%s\n\n", strrev(str));
return 0;
}
for (i = 0; i < l; i++)
You're walking through the entire string, so you're reversing it twice - it won't be reversed after all. Walk only halfways:
for (i = 0; i < l / 2; i++)
Also, try using int len = strlen() instead of the while-not-end-of-string loop, if you're permitted to do so.
You swap the string's content twice.
Use the following code ..
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
char *strrev(char *s)
{
char *temp = s;
char *result = s;
char t;
while (*temp)
temp++;
while (--temp != s)
{
t = *temp;
*temp = *s;
*s++ = t;
}
return result;
}
int main()
{
char *str;
str = (char*)malloc(50);
printf("Enter a string: ");
scanf("%s", str);
printf("%s\n\n", strrev(str));
return 0;
}
The logic is to swap characters from start upto first half with the characters from last of second half, i.e, upto len/2. Just modify your for loop as below & it will work fine for you
for (i = 0; i < l/2; i++) {
you can use this simple code
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int str_len (char *str)
{
char *ptr = str;
while (*str)
str++;
return str - ptr;
}
int main ()
{
char *str;
int length;
str = (char*)malloc(50);
printf("Enter a string: ");
scanf("%s", str);
length = str_len(str) - 1;
for (int i = length ; i >= 0 ; i--)
printf ("%c", str[i]);
return 0;
}
you can use this code to reverse the string
#include<stdio.h>
#include<string.h>
int main()
{
int n,i;
char str2[100],str1[100];
printf("enter teh string 1\n");
gets(str1);
n = strlen(str1);
for(i=0;i<n;i++)
{
str2[n-1-i]=str1[i];
}
printf("%s\n",str2);
}
Actually you are reversing the string twice...so after come to middle of the string, you should terminate the loop that is your loop should be run for half of the string length that is l/2 (in this case). so your loop should be like
for(i = 0; i < i / 2; i++)
swapping the string content twice..
swapping it once will help..
for (i = 0; i < l/2; i++)

Resources