I couldn't share the original code but the below program is as similar to my problem.
#include<stdio.h>
#include<conio.h>
void clrscr(void);
int reverse_of(int t,int r)
{
int n=t;
r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n",n); /*displays the input*/
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
return r; /*returns the value to main function*/
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
};
int main()
{
int n,r;
void clrscr();
printf("Enter a number: ");
scanf("%d",&n);
//while (n!=0) /*Use this for any number of digits*/
/* {
int z=n%10;
r=r*10+z;
n=n/10;
} */
r=reverse_of(n,r);
printf("The reverse of your number is: %d\n",r);
return 0;
};
This program displays the reverse of a 4 digit number. it works perfect when my first input is a 4 digit number. The output is as below.
(Keep in mind that i dont want this program to display the reverse of
a number unless its 4 digit)
Enter a number: 1234
Your number is: 1234
The reverse of your number is: 4321
Now when i give a non 4 digit number as the first input the program displays that it is not a 4 digit number and asks me for a 4 digit number. Now when i give a 4 digit number as the second input. It returns the correct answer along with another answer which is supposed to be the answer for the first input. (since the program cannot find the reverse value of a non 4 digit number the output always return 0 in that particular case). If i give 5 wrong inputs it displays 5 extra answers. Help me get rid of this.
Below is the output when i give multiple wrong inputs.
Enter a number: 12
The number you entered is 2 digit so please enter a four digit number
Enter a number: 35
The number you entered is 2 digit so please enter a four digit number
Enter a number: 455
The number you entered is 3 digit so please enter a four digit number
Enter a number: 65555
The number you entered is 5 digit so please enter a four digit number
Enter a number: 2354
Your number is: 2354
The reverse of your number is: 4532
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
Help me remove these extra outputs btw im using visual studio code and mingw compiler.
The problem lies here:
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
You're calling main() from reverse_of().
Try replacing the main(); with return 0; and in main(), do this:
int n,r;
do{
printf("Enter a number: ");
scanf("%d",&n);
r=reverse_of(n,r);
}while(r==0);
printf("The reverse of your number is: %d\n",r);
This happens because of the multiple recursion caused by the call of main() inside of the reverse_of function.
To avoid such thing you can move the printf("The reverse of your number is: %d\n", r); to the inside of the if(count==4){} and your problem is solved!
Also, note that your reverse_of functions does not need to receive the int r, instead it can be written like this:
#include <stdio.h>
int reverse_of(int t)
{
int n = t;
int r = 0;
int count = 0;
while (t != 0) /*Loop to check the number of digits*/
{
count++;
t = t / 10;
}
if (count == 4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n", n); /*displays the input*/
while (n != 0) /*This loop will reverse the input*/
{
int z = n % 10;
r = r * 10 + z;
n = n / 10;
}
printf("The reverse of your number is: %d\n", r);
return 1;
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n", count);
return 0;
}
};
int main()
{
int n, r=0;
while (r!=1){
printf("Enter a number: ");
scanf("%d", &n);
r=reverse_of(n);
}
return 0;
};
Hope it helped!
Well, your program has some ambiguity: If you stop as soon as you get 0, then the reverse of 1300, 130 and 13 will be the same number, '31'.
So, first of all you need two parameters in your function, to deal with the number of digits you are considering, so you don't stop as soon as the input number is zero, but when all digits have been processed. Then you extract digits from the least significant, and add them to the result in the least significant place. This can be done with this routine:
int reverse_digits(int source, int digits, int base)
{
int i, result = 0;
for (i = 0; i < digits; i++) {
int dig = source % base; /* extract the digit from source */
source /= base; /* shift the source to the right one digit */
result *= base; /* shift the result to the left one digit */
result += dig; /* add the digit to the result on the right */
}
return result;
}
The extra parameter base will allow you to operate in any base you can represent the number. Voila!!!! :)
#include <stdio.h>
int main()
{
int src;
while (scanf("%d", &src) == 1) {
printf("%d => %d\n",
src,
reverse_digits(src, 5, 10));
}
}
will provide you a main() to test it.
In contrast to C++, in C, it is allowed to call main recursively. But it is still not recommended. There are only a few situations where it may be meaningful to do this. This is not one of them.
Recursion should only be used if you somehow limit the depth of the recursion, otherwise you risk a stack overflow. In this case, you would probably have to call the function main recursively several thousand times in order for it to become a problem, which would mean that the user would have to enter a value that is not 4 digits several thousand times, in order to make your program crash. Therefore, it is highly unlikely that this will ever become a problem. But it is still bad program design which may bite you some day. For example, if you ever change your program so that it doesn't take input from the user, but instead takes input from a file, and that file provides bad input several thousand times, then this may cause your program to crash.
Therefore, you should not use recursion to solve this problem.
The other answers have solved the problem in the following ways:
This answer solves the problem by making the function reverse_of not return the reversed value, but to instead directly print it to the screen, so that it does not have to be returned. Therefore, the return value of the function reverse_of can be used for the sole purpose of indicating to the calling function whether the function failed due to bad input or not, so that the calling function knows whether the input must be repeated. However, this solution may not be ideal, because normally, you probably want the individual functions to have a clear area of responsibility. To achieve this clear area of responsibility, you may want the function main to handle all the input and output and you may want the function reverse_of to do nothing else than calculate the reverse number (or indicate a failure if that is not possible). The fact that you defined your function reverse_of to return an int indicates that this may be what you originally intended your function to do.
This answer solves the problem by reserving a special return value (in this case 0) of the function reverse_of to indicate that the function failed due to bad input, so that the calling function knows that the input must be repeated. For all other values, the calling function knows that the function reverse_of succeeded. In this case, that solution works, because the value 0 cannot be returned on success, so the calling function can be sure that this value must indicate a failure. Therefore, in your particular case, this is a good solution. However, it is not very flexible, as it relies on the fact that a return value exists that unambiguously indicates a failure (i.e. a value that cannot be returned on success).
A more flexible solution, which keeps a clear area of responsibility among the two functions as stated above, would be for the function reverse_of to not always return a single value, but rather to return up to two values: It will return one value to indicate whether it was successful or not, and if it was successful, it will return a second value, which will be the result (i.e. the reversed value).
However, in C, stricly speaking, functions are only able to return a single value. However, it is possible for the caller to pass the function an additional variable by reference, by passing a pointer to a variable.
In your code, you are declaring your function like this:
int reverse_of(int t,int r)
However, since you are not using the argument r as a function argument, but rather as a normal variable, the declaration is effectively the following:
int reverse_of( int t )
If you change this declaration to
bool reverse_of( int t, int *result )
then the calling function will now receive two pieces of information from the function reverse_of:
The bool return value will indicate whether the function was successful or not.
If the function was successful, then *result will indicate the actual result of the function, i.e. the reversed number.
I believe that this solution is cleaner than trying to pack both pieces of information into one variable.
Note that you must #include <stdbool.h> to be able to use the data type bool.
If you apply this to your code, then your code will look like this:
#include <stdio.h>
#include <stdbool.h>
bool reverse_of( int t, int *result )
{
int n=t;
int r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
*result = r;
return true;
}
else /*This will execute when the input is not a 4 digit number */
{
return false;
}
};
int main()
{
int n, result;
for (;;) //infinite loop
{
//prompt user for input
printf( "Enter a number: " );
//attempt to read number from user
if ( scanf( "%d",&n ) != 1 )
{
printf( "Invalid input!\n" );
//discard remainder of line
while ( getchar() != '\n' )
;
continue;
}
printf( "Your input is: %d\n", n );
//attempt to reverse the digits
if ( reverse_of( n, &result) )
break;
printf( "Reversing digits failed due to wrong number digits!\n" );
}
printf("The reverse of your number is: %d\n", result );
return 0;
};
Although the code is now cleaner in the sense that the area of responsibility of the functions is now clearer, it does have one disadvantage: In your original code, the function reverse_of provided error messages such as:
The number you entered is 5 digit so please enter a four digit number
However, since the function main is now handling all input and output, and it is unaware of the total number of digits that the function reverse_of found, it can only print this less specific error message:
Reversing digits failed due to wrong number digits!
If you really want to provide the same error message in your code, which specifies the number of digits that the user entered, then you could change the behavior of the function reverse_of in such a way that on success, it continues to write the reversed number to the address of result, but on failure, it instead writes the number of digits that the user entered. That way, the function main will be able to specify that number in the error message it generates for the user.
However, this is getting a bit complicated, and I am not sure if it is worth it. Therefore, if you really want main to print the number of digits that the user entered, then you may prefer to not restrict input and output to the function main as I have done in my code, but to keep your code structure as it is.
I want to print sum of the first 1000 prime numbers. I don't know if the following implementation is right and where it is wrong. Moreover, how can I optimize this implementation, which is required for extra off course?
#include<stdio.h>
#include<math.h>
int prime(int no,int lim)
{
int i=2,flag=0;
for(;i<=lim;i++)
{
if(no%i==0)
{
flag=1;
}
}
return flag ;
}
int main()
{
int i=4,count=2,j,k,l,n=4;
double sum=5.0;
for(;count<=1000;)
{
j=sqrt(i);
k=prime(i,j);
if(k==0)
{
//printf("\n%d",i);
sum+=(double)i;
//for(l=0;l<100000;l++);//just to reduce speed of the program
count++;
}
i++;
}
printf("\n%f",sum);
return 0;
}
I don't know if the following implementation is right and where it is wrong.
The implementation is correct except for an off-by-one error: Since count is the number of primes that were already taken into account, the loop condition count<=1000 causes the loop to be run one more time when 1000 primes have already been summed, adding the 1001. prime. Correct is: count<1000.
To optimize your code you better use Sieve of Eratosthenes to generate prime up to your limit, then add these primes. To know how sieve works, read this article.
Here is the code for "The Next Palindrome" which I wrote in C:
#include<stdio.h>
int main(void)
{
int check(int); //function declaration
int t,i,k[1000],flag,n;
scanf("%d",&t); //test cases
for(i=0; i<t; i++)
scanf("%d",&k[i]); //numbers
for(i=0; i<t; i++)
{
if(k[i]<=9999999) //Number should be of 1000000 digits
{
k[i]++;
while(1)
{
flag=check(k[i]); //palindrome check
if(flag==1)
{
printf("%d\n",k[i]); //prints if it is palindrome and breaks
break;
}
else
k[i]++; //go to the next number
}
}
}
return 0;
}
int check(int n)
{
int rn=0;
int temp=n;
while(n!=0)
{
rn=rn*10+n%10; //reversing
n=n/10;
}
if(rn==temp) //number is palindrome
return 1;
else //number is not a palindrome
return 0;
}
It is a beginner level problem from SPOJ.
I tried to run this code on Codeblocks and it ran fluently.
In SPOJ, why is it showing wrong output?
In SPOJ, why is it showing wrong output?
This is nice solution and it works for small inputs, however it will not pass SPOJ for several reasons.
The requirement is:
A positive integer is called a palindrome if its representation in the
decimal system is the same when read from left to right and from right
to left. For a given positive integer K of not more than 1000000
digits, write the value of the smallest palindrome larger than K to
output. Numbers are always displayed without leading zeros.
Input:
The first line contains integer t, the number of test cases.
Integers K are given in the next t lines.
So which requirements are broken in your program?
1) Your assumption is that only 1000 numbers will be given for processing since
you declared
k[1000]
wrong, the number of lines is given in first line. It could be much more than 1000. You have to dynamically assign the storage for the numbers.
2)
The line
if(k[i]<=9999999)
assumes that input is less than 9999999
- wrong, the requirement says positive integer K of not more than 1000000 digits which imply that much larger numbers e.g. 199999991 also have to be accepted.
3) The statement
For a given positive integer K of not more than 1000000 digits
as well as warning
Warning: large Input/Output data, be careful with certain languages
leads us to conclusion that really big numbers should be expected!
The int type is not a proper vehicle for storing such big numbers. The int will fail to hold the value if the number is bigger than INT_MAX +2147483647. (Check C Library <limits.h>)
So, how to pass SPOJ challange?
Hint:
One of the possible solutions - operate on strings.
So i got the following task in C : the user input two integers, let's call them n1 and n2, so that n1<=n2.
The programm must print all the possible integers between n1 and n2 (n1 and n2 included),and that all the digits in the number are increasing in their value.
For example, if the user input 1234 and 1260, the programm will print 1236,1237,1238,1239, but not 1240, since 0 is smaller than 4.
Then it will print 1356,1357,1358,1359.
I'm not allowed to use arrays (otherwise it would be very easy), functions, even the power function.
So I came up with the next pseudo code:
Make a loop that takes the number n1, and counts the number of digits it has.
Then make a loop that divides n1 (number of digits-1) times, and then with the remainder of the result of it, it will do % .
at this point you are left with some digit.
Then take n1 again, and divide it (number of digits-2) times, and then with the remainder of the result, it will do %.
at this point you are left with some another digit.
Compare the two digits. if first digit is smaller then the second digit, continue compairing digits by promotion of the digits location ( digitsNum--) .
do in loop steps 2-3-4.
if everything checks out, prints n1;
promote n1 (n1++), (up to n2)
loop everything again.
The problem is that with all the restricions on what I can use, I find my solution very hard to implement, and once I start, I just get one big mess .
Any suggestion on how can I improve it?
Hope it helps you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int num;;
int num2;
int flag=-1;
int i=0,j=0;
int rem,rem2;
printf("Enter First Number\n");
scanf("%d",&num);
printf("Enter Second Number\n");
scanf("%d",&num2);
if(num>num2)
{
printf("Wrong inputs have given\n");
exit(0);
}
int div=num2-num;
for(i=0;i<=div;i++)
{
num2=(num+i);
rem=(num2)%10;
num2/=10;
rem2=(num2)%10;
if(rem>rem2)
{
printf("....%d\n",num+i);
}
}
return 0;
}
I am writing a program which have to generate N random not repeating numbers
the prototype should be voidrandom_int(int array[], int N);
it is not having any errors but it is not working. Not even giving any number
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void random_init(int array[], int N)
{
srand(time(NULL));
int i, j;
array[0]=rand()%N;
for(i=1;i<N;i++)
{
array[i]=rand()%N;
if(array[i]==0)
array[i]=1;
for(j=0;j<i;j++)
{
if(array[i]==array[j])
break;
}
if((i-j)==1)
continue;
else
i--;
}
}
int main(void)
{
int a[5], i, N;
N=5;
random_init(a,N);
for(i=0;i<N;i++)
printf("%d ", a[i]);
return 0;
}
This part makes no sense:
if(array[i]==0)
array[i]=1;
It will limit your choices to N-1 numbers (1 to N-1), out of which you try to find N numbers without repetition - leading to an infinite loop.
if((i-j)==1)
continue;
Here you probably want if (i==j) instead, to check if the previous loop ran to completion.
A faster and simpler way to generate the numbers 0..N-1 in a random order, is to put these numbers in an array (in sequential order), and then use Fisher-Yates Shuffle to shuffle the array.
This method is biased. Do not use it other than for educational purposes.
Other than Ficher-Yates, which uses another array, you can use the method of going through all the available numbers and find a "random" spot for them (effectively "initializing" the array twice). If the spot is taken, choose the next one. Something like this, in pseudo-code:
fill array with N
for all numbers from 0 to N-1
find a random spot
while spot is taken (value is N) consider next spot /* mind wrapping */
set value in current spot