For loop is running only once [duplicate] - c

This question already has answers here:
Why for loop in C only passes once?
(2 answers)
Closed 3 years ago.
int input;
int factorial;
int half;
printf("Enter the number you wish to calculate: ");
scanf("%d", &input);
for(x=1; x<input; x++);
{
half = input - 1;
factorial = input * half;
}
printf("%d\n", factorial);
return 0;
It's running once, giving me the input number * (input number - 1), exam, input is 5 its giving out 20. What am I doing wrong that is preventing it from continuing running?

You have a ; after the for-loop. Remove that and you'll be fine:
for(x=1; x<input; x++) {
// your stuff
}
You still have to fix another error in your loop, as mentioned in the other answers.

You don't change input in your loop, so your code boils down to (for your sample input of 5):
for (i = 1; i < 5; i++) {
half = 5 - 1;
factorial = 5 * 4;
}
factorial 5 (5!) would be 5 * 4 * 3 * 2 * 1, which should be:
factorial = 1;
for (i = input; i > 1; i--) {
factorial = factorial * i;
}

What am I doing wrong?
There are many things that you are doing wrong:
Naming a variable half is wrong, unless you assign a value that is truly a half of something to it
Your loop does not use the previous value of factorial
You always multiply input by input-1, and never change the input
You do not initialize factorial to 1
P.S. The fact that your loop runs empty is the least of your troubles.
P.P.S. To do it right, consider how you do it on paper: you start with 1, and then keep multiplying the previous result by numbers from 2 to input. Now write the same algorithm as a C program: use factorial as your intermediate result, and x from the loop as your "current number between 1 and input.

You're not actually changing the state, so you should only ever get input * (input - 1). Why? Well, half will always be input - 1, and input will never change. Meanwhile the value of factorial is simply assigned to that product every time you step through the loop.
I think what you intended is
factorial = 1;
// no sense in starting from 1, factorial already is 1
for(x = 2;
// using <= so as to *include* the original input value.
x <= input; x++)
{
// the same things a factorial = factorial * x
factorial *= x;
}
BTW: You may wish to compensate for negatives too.

Your loop uses the same values each time (input and half)
try
factorial = 1;
for(x=2; x<=input; x++)
{
factorial *= x;
}

Related

Random Number generator printing a pattern

I am trying to create a Dice Roll game where the user can roll up to 6 dice at a time. I am attempting to accomplish this by integrating pointers into my code. I am getting an output, with the desired amount of rolls as given by the user, but the output is incorrect. It is printing a pattern instead of printing random numbers. Any help is appreciated.
How many dice would you like to roll?
user input: 4
output: 3 0 3 0
How many dice would you like to roll?
user input: 5
output: 4 0 4 0 4
#include <stdio.h>
#include <stdlib.h>
void tossDie(int []);
int main() {
int diceArray[6] = { 0 };
int num = 0;
int x;
do {
printf("\nHow many dice would you like to roll? Please enter here: ");
scanf_s("%d", &num);//user enters amount of dice they want to roll)
if (num < 1 || num > 6) {
printf("\n\nPlease enter a number between 1 and 6.\n\n");
}
} while (num < 1 || num > 6);
tossDie(diceArray);
//print dice roll numbers
for (x = 0; x < num; x++) {
printf("%d ", diceArray[x]);
}
return 0;
}
void tossDie(int numbers[]){
int randomNum;
int x;
srand(time(NULL));
randomNum = (rand() % 6) + 1; //random # between 1 - 6
for (x = 0; x < 6; x++){
numbers[x] += randomNum;
x++;
}
};
Move srand(time(NULL)); to main(). Only needed once.
Only call x++ only per loop, not twice, to assigned all 6 elements of the array.
Move randomNum = (rand() % 6) + 1; to inside for loop to get different values.
Check return value of scanf_s("%d", &num); against 1, before using num.
Tip: Use an auto-formatter to save time and improve code presentation.
Design: I'd expect tossDie(int numbers[]) to also receive a num to indicate numbers[] width.
Before I answer, please note that I don't program in C, so there may be some language-specific things that I am missing.
In your tossDie() function, you set the value of randomNum once, but don't reassign it after that. Therefore, your output should return the same number for all values in the array, like such:
Input: 5
Output: 3 3 3 3 3
To fix that, you should put the variable declaration in the for loop (if you want to use a variable at all).
Additionally, you initialise the random variable every time you run the method. Instead, you should declare it once, in the main method.
Also, there's a little issue in this block of code:
for (x = 0; x < 6; x++){
numbers[x] += randomNum;
x++;
}
};
You increase x twice in here: both in the first line and the third line. Instead, you should delete the x++ in the third line and have just the x++ in the first line.
Let me know if you have further questions or if there are still problems.

c language, multiples of 5 being saved on a prime vector

I'm a newbie and i'm currently making a program that asks the user a number and if the number is a prime it gets stored in a vector, if the vector isn't completed the code doesn't stop. The only problem is that it stores multiples of 5, like 15, 25, 35, etc in it. How can i make it stop storing these multiples of 5? Here is the code:
#include <stdio.h>
int main()
{
int primes[5], num, i, count = 0, x = 0;
do
{
printf ("Type a number: ");
scanf("%d", &num);
for (i = 1; i <= num; i++)
{
if (num % i == 0)
{
count++;
}
}
if (count = 2)
{
primes[x] = num;
x++;
}
}
while (x < 5);
for (x = 0; x < 5; x++)
{
printf("%d ", primes[x]);
}
}
= is the assignment operator, not the equality check operator. You should use == to check if the count is 2:
if (count = 2)
You write
for (i = 1; i<= num; i++)
a prime number is a number that is divisible only by one and itself, your primality test divides your number by all numbers (includind 1 and num itself) so every number (prime or not) will probe to be compound.
Your primality test must start at 2 and end at most at num - 1 to avoid dividing the number by one and by itself (all numbers are divisible by themselves and by one) as in
for (i = 2; i < num; i++)
this should solve your problem... but it will be very inefficient, as you are dividing by all the even numbers, and it is not necessary to divide it by all the even numbers (except for 2 itself) Also, you can stop at a number that is below or equal to sqrt(num), rounded down to the previous integer, because if the number has a factor above that number, for sure you have already found a factor below it (and both multiply pairwise to give you the number).
Also, there's a problem here:
if (count = 2)
This is a valid C statement, but it most probably don't do what you intend, as the = operator is the Assignment Operator, and not the logical equal operator (which is spelled ==) You need to change, because as shown, you are assigning count the value 2, and this is always true, by definition of the assignment operator, if you assign something different than zero, it will result in a true result, so your if will execute allways the body of its true part.
Anyway, many variables it's not clear what you are using them for, (count is one of these) as you assign, increment it, but you don't use its value anywhere (except the if statement above, and in a wrong way)

How to print decreasing odd numbers starting from scanf input integer in C?

If you input even numbers, only the odd numbers will be printed until it reaches 0. (0 will not be printed). For example, if you input 10, the output would be 9, 7, 5, 3, 1.
This is what I came up with. I'm wondering what should I decrement x by to get the desired output.
int x;
scanf("%d", &x);
while (x >= 0) {
printf("%d", x);
x = x - 2;
}
I'm wondering what should I decrement x by to get the desired output.
Subtracting 2 is fine, as long as you always start from an odd number. So you could change the loop into something like this:
for ( int i = x % 2 ? x : x - 1; // Is x odd? good.
// Otherwise, start from the previous one.
i > 0;
i -= 2 ) {
printf("%d\n", i);
}
int x, n;
printf("Give N: ");
scanf("%d", &n);
printf("odd numbers from 1 to %d are: \n", n);
x=n;
while(x<=n && x>0)
{
if(x%2!=0)
{
printf("%d\n", x);
}
x--;
}
return 0;
}
Your code was almost correct (indeed, it is a pity that you have selected as the correct question such a bad response) I will show you where is your error:
int x;
scanf("%d", &x);
if (x % 2 == 0) /* if the number is even */
x = x - 1; /* decrement it to convert it in an odd number */
while (x >= 0) {
printf("%d", x);
x = x - 2;
}
The thing is that you start your question with exactly that assert (if you input even numbers...)
Another problem is that you don't say what should happen when you introduce an odd number. Anyway, the code printed it, and all the odd numbers until we reach 0.
Why your code is better than the selected one? because your code only wastes time in the loop with the valid results, and doesn't get into the loop to decide that it has nothing to do. This saves a lot of loop executions (almost half of them) which, if your number is very large, can do your program a lot more efficient.

C code to find "Cullen's number" [closed]

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
Need to make a C code that asks of the user to input one number, and the code will check whether the number is a "Cullen's number" or not.
A number is Cullen's number as long as you can calculate it by doing "2^n * n + 1".
Examples of Cullen's numbers:
3=2^1 * 1 + 1
9=2^2 * 2 + 1
25=2^3 * 3 + 1
Here's the code I was working on, any help?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int num, brojP, potency = 0, numRepeats = 0, endResult=0, isCullen;
printf("Unesite broj");
scanf("%d", &num);
do
{
potency = potency + 1; // initializing "potency" and at the same time making it one number larger at each repeat of the loop
do
{
brojP = 2*potency;
numRepeats = numRepeats + 1;
} while (numRepeats < potency); // this entire loop is used for "2^n" part
endResult = brojP * potency + 1; // calculate the "2^n * n + 1"
numRepeats = 0;
if (endResult == num)
{
isCullen = 1;
break;
}
} while (endResult < num);
if (isCullen == 1)
printf("Number inputted is Cullen's number\n");
else
printf("Number inputted isn't Cullen't number\n");
return 0;
}
This loop is wrong:
do
{
brojP = 2*potency;
numRepeats = numRepeats + 1;
} while (numRepeats < potency); // this entire loop is used for "2^n" part
You need to multiply the result from the previous iteration by 2 each time, but you're multiplying potency by 2 instead. Since potency doesn't change, you're just doing the same assignment over and over. Do it like this:
brojP = 1;
for (numRepeats = 0; numRepeats < potency; numRepeats++) {
brojP *= 2;
}
It would maybe be more efficient if you used dichotomic search. As you store your result in an int, I assume that the max size for the entered number is 2^32 (int are most frequently coded on 32 bits).
You can try with potency = 16 and then if the entered number is bigger with 2^24, etc
If (let's say) you try for n = 6 then n = 7 and none of them is working, you know that it is not a Cullen's number.
You will at most calculate log2(32)=5 times.
EDIT: By the way, why don't you just use the math.h library?

Break a number down int array and get factorial of each number - C programming

I apologize in advance for the length of the code and how tedious it may be to follow. I am trying to break a number down into individual digits and get the factorial of each one. I have successfully done that (with the help of paxdiablo) but I want to do this all the way from 99999 to 0. In order to do that I have placed all of the code in a loop starting indx at 99999 and decreasing value until it reaches 1. The reason I am trying to do this is because I need to compare the sum of the factorial of each individual digit to the number and if they are equal then I have a match. The program runs and the first run for the number 99999 works perfectly fine but the next loop SHOULD be 99998 and do the exact same thing but instead the next number is 4. I have no idea why it would do this. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
int indx;
int fact = 1;
int individualDigit[50];
int length;
for(indx = 99999; indx > 0; indx--)
{
num = indx;
for (length = 0; num > 0; length++, num /= 10)
{
individualDigit[length] = num % 10;
}
printf ("Digit count = %d, digits =", length);
for (indx = length - 1; indx >= 0; indx--)
{
printf (" %d", individualDigit[indx]);
}
for (indx = 0; indx < length; indx++)
{
while (individualDigit[indx] > 0)
{
fact = fact * individualDigit[indx];
individualDigit[indx]--;
}
printf("\n%d ", fact);
fact = 1;
}
printf("\n");
}
return 0;
}
The value in "indx" is being used by multiple for loops. The line
for (indx = 0; indx < length; indx++)
increments indx back up to 4, which is the value used by your outer loop. Just use some new variables to count the different loops
This seems like a homework question and your code quality seems to confirm that so I'm hesitant to write you actual code but I'll give you a few pointers.
As #Cody Braun said above your index variable is getting overwritten in line 23 where you calculate the factorial.
There is a much more efficient way to calculate factorials using dynamic programming
I don't know if you just didn't want to do it in the post but learning how to properly format your code will help you catch these errors quicker and keep yourself form making them. As well as make it easier for others to read your code.
Cheers

Resources