Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Is this implementation of random number generation wrong?
int random_number(int l, int u)
{
int num;
num = rand()%u;
if (num<l && num>u)
{
while(num<l && num>u)
{
num = rand()%u;
}
}
return num;
}
This is not giving me the correct answer.
If I try random_number(4,8); it generates numbers like 0,1,2 etc.
Assuming u means upper and l means lower, then it is wrong. Try this:
int random_number(int l, int u) {
int num = rand() % (u - l);
return num + l;
}
Consider the lines.
int random_number(int l, int u)
num = rand()%u // result 0, 1, 3, .... 7
if (num<l && num>u)
random_number(4,8);
Code needs to follow the if() when num <4 and num > 8. An int cannot both be less than 4 and greater than 8 at the same time.
The usual idiom is
int random_number(int lower, int upper) {
int num;
num = rand()%(upper - lower + 1) + lower;
return num;
}
Extra code is needed to cope/detect upper < lower, upper - lower >= RAND_MAX
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This might be simple but I'm new to recursion in c. I want to find the sum of odd integers based on user's input. For example if user inputs 3, function returns 9 (1 + 3 + 5 = 9)
int recursiveSumNOdd(int n)
{
int start = -2; //later start = start+2, so it starts at 0
int n1 = n*2; //total number of digits with rec
int num = 0;
int sum=0;
int count=0;
if(start>=n1)
{
return 0;
}
else
{
start = start+2;
count++;
sum = sum +recursiveSumNOdd(start);
}
return sum;
}
Explanations in comment:
int recursiveSumNOdd(int n) {
if (n == 1 || n == 0)// first "if" in a recursive is its stop condition
return n;
return 2 * n - 1 + recursiveSumNOdd(n-1); // formula for 2->3, 3->5 etc
}
int main(void) {
printf("%d\n", recursiveSumNOdd(3));
return 0;
}
NB: You may want to handle integer overflow
NB2: You can have a mathematics formula to return instantly the result, it is way better, but I guess it was to understand better recursion?
return n * n; // the sum of odd numbers is the square of user's input
You are over-complicating things.
You cannot have the sum of negative elements.
int sum_n_odd(unsigned n)
{
What is the sum of 0 (zero) elements?
if (n == 0) return 0;
If you knew the sum of n - 1 numbers, what is the sum of n numbers?
return sum_n_odd(n - 1) + something; // something is easy to figure out
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm receiving Output: 1. I should count the number of times a digit appear in an integer, for example, for number 1222345 and n = 2 Should appear 3 times.
int countOccurrences(int n, int num)
{
int i,k;
i=0;
while(num!=0)
{
k=num%10;
num=num/10;
if(k==n)
{
i++;
}
}
}
// Main
void main()
{
int num= 1222345;
int n = 2;
printf("Occurance of a number: %d", countOccurrences(n,num));
}
You have undefined behavior in the code. The function is supposed to return an int and it didn't.
Solution is to add return i in the end of other function. This will give you correct result. In the countOccurrences() function
...
if(k==n)
{
i++;
}
}
return i;
}
I was skipping the discussion of error check and all that. As chux mentioned for n<=0 case you might want to add a different way of handling it but you didn't add it. Atleast consider those case and put an error message on whatever input you need.
Some corner cases are
n=0,m=0.
Negative value of n or m.
Put a return on your countOccurrences function please
int countOccurrences (int n, int num) {
int i, k;
i = 0;
while (num! = 0)
{
k = num% 10;
num = num / 10;
if (k == n)
{
i ++;
}
}
return i; }
As other have pointed out, there are important issues with your code.
Here is a recursive solution that you may find interesting:
int countOccurrences(int n, int num)
{
int count = ((num % 10) == n);
return (num < 10) ? count : count + countOccurrences(n, num / 10);
}
Few general remarks about your code:
When using printf(), you should #include <stdio.h>.
main() should return int.
Place spaces around operators and format your code consistently. This k = num % 10; is more readable than k=num%10;. (There's more to code formatting than a matter of taste; without spaces you create areas full of characters which are more difficult to parse for our visual system.)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is the program I wrote. I get a blank output when I execute it. Can't figure out what's wrong with it.
#include <stdio.h>
void main() {
int a, b = 0, s, n;
printf("The armstrong numbers are-");
for (n = 1; n <= 10000; n++) {
s = n;
while (n > 0) {
a = n % 10;
b = b + a * a * a;
n = n / 10;
}
if (b == s)
printf("%d ", s);
}
}
As others have suggested Don't change n inside the for loop as your loop depends on the variable n. you have to set b back to 0 for each iteration.
Your program is not very much readable as others might not understand what does a,b,n and s mean. So, always use meaningful variable names like this: (see comments for more description)
#include<stdio.h>
int main(void) //correct signature for main function
{
int digit; //instead of a
int sum=0; //instead of b
int number; //instead of n
printf("The armstrong numbers are-");
for(number = 1; number <= 10000; number++)
{
int temporary = number; //temporary integer to store number value
sum = 0; //sum must be reset to 0 at the start of each iteration
while(temporary > 0)
{
digit = temporary % 10;
sum = sum + (digit * digit * digit);
temporary = temporary / 10;
}
if(sum == number) //if sum obtained == number, print it!
printf("%d ",number);
}
return 0;
}
output:
The armstrong numbers are-1 153 370 371 407
Don't change n inside the for loop.
you have to set b back to 0 for every n.
Hope I helped
The loop variable n was getting modified in the loop. So use the temporary variable s to do the inner while loop. And variable b must be initialized to zero every time you check for a new number. It's a good practice to define the variable within block that you use rather than defining everything globally or in the start of main.
#include <stdio.h>
int main() {
int n;
printf("The armstrong numbers are-");
for (n=1; n<=10000; n++) {
int a, b=0, s=n;
while (s > 0) {
a = s % 10;
b = b + (a*a*a);
s = s / 10;
}
if (b == n)
printf("%d ", n);
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Imagine we've got an int number = 1040 or int number = 105 in a C program, and we want to know if this number contains a 0 and in which position/s are they. How could we do it?
Examples
1040 -> position 0 and 2.
1000 -> position 0, 1 and 2.
104 -> position 1.
56 -> NO ZEROS.
Thanks!
I would divide by 10 and check the remainder. If remainder is 0, then last position of the number is 0. Then repeat the same step until number is less than 10
#include<iostream>
int main(void)
{
long int k = 6050404;
int iter = 0;
while (k > 10) {
long int r = k % 10;
if( r == 0) {
std::cout << iter << " ";
}
k = k / 10;
iter++;
}
}
I would convert it to a string; finding a character in a string is trivial.
As a rule of thumb, if you are doing maths on something, it's a number; otherwise, it's probably (or should be treated as) a string.
Alternatively, something like:
#include <stdio.h>
int main(void) {
int input=1040;
int digitindex;
for (digitindex=0; input>0; digitindex++) {
if (input%10==0) {
printf("0 in position %i\n",digitindex);
}
input/=10;
}
return 0;
}
This basically reports if the LAST digit is 0, then removes the last digit; repeat until there is nothing left. Minor modifications would be required for negative numbers.
You can play with this at http://ideone.com/oEyD7N
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Using C Language:
How can I generate random numbers in the [pi, 2pi] range?
How can I generate random numbers in the [-1, 0] range?
This is a pseudo random integer generator, but has only been tested for positive numbers, you would have to modify it to use with negatives:
int randomGenerator(int min, int max)
{
int random=0, trying=0;
trying = 1;
srand(clock());
while(trying)
{
random = (rand()/32767.0)*(max+1);
(random >= min) ? (trying = 0) : (trying = 1);
}
return random;
}
EDIT (last method did not produce randoms due to srand() not being updated enough)
For a range spanning positive and negative numbers you could modify it like this: (but ratio of pos to neg would be same)
int randomGenerator(int min, int max)
{
int random=0, trying=0;
int i=0;
trying = 1;
srand(clock());
while(trying)
{
random = (rand()/32767.0)*(max+1);
(random >= min) ? (trying = 0) : (trying = 1);
}
return (i++%2==0)?(random):(-1*random);
}