I am making a program to find prime factorials of a given number.
Although the program works fine, I have two problems.
1. when i enter an odd number, it prints 2 in the result although 2 should not be in it.
2. After 15 seconds , it turns into an infinite loop , Which is really creepy.
#include<stdio.h>
#include<conio.h>
int num(int); // Making a function for finding prime factors
int main()
{
int i,j;
printf("Enter any number");
scanf("%d",&i);
num(i);
getch();
}
int num(int i)
{
int a=2;
while(a<=i)
{
if(i%a==0) //if the number is divisible then divide it
i=i/a;
printf(" %d",a);
if(i%a!=0)
{
i%a;
while(i%a!=0)// If it is not divisible by 2 then increment it until it is
a++;
}
}
}
It always prints 2 because the print statement is not part of the if which tests for mod 0. It goes into an infinite loop because once a passes i, the second while loop will never exit.
The infinite loop is your second while loop, while(i%a!=0). For a prime number, this will continue endlessly. There are smart ways to fix that, but at the very least, change it to
while(i%a!=0 && a<=i)
I'm not sure why 2 is coming up on odd numbers, still thinking that part through.
EDIT As Fred mentioned, the printout is not part of the if statement, causing 2 to always show up. Personally, I recommend getting into the habit of always putting { } after an if statement. Even if you've been coding for decades, this will make sure you get the right statements in your condition.
Related
#include<stdio.h>
int main()
{
int i,n;
int arr[10]={};
printf("\n print all the entered elements in array");
printf("\n enter the value of n");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
printf("\n element no %d",n);
scanf("%d",arr[i]);
}
printf("\n the reversed elements are");
for(i=n-1;i<=0;i--)
{
printf("\n the numbers are %d",arr[i]);
}
return 0;
}
hey there this is my c program code and i have first enter the no of elemnts as how many element i want in that array and the have to print it in reverse order and i am facing some problem with this as when my first loop starts after 1 complete cycle or after taking one input on element i=0 it stops. i dont have any idea whats going on here so pls help me..
You want the address of the array element, not its value.
So, change
scanf("%d",arr[i]);
to
scanf("%d",&arr[i]);
(And, for your own sake, learn to not ignore the return value of scanf().)
Also, if you enter N as number of elements, then your code will need N+1 numbers entered, hoping that N+1 is less than 10.
This is because for(i=0;i<=n;i++) will need numbers entered for 0,1,2, ...N, because of the <=, you probably want <. You will then be asked one number less, which should fix the problem you describe. I.e. you should then see the "the reversed elements are" output after entering N elements. Your program currently seems to "stop" because it waits for another number being entered.
When you fixed that the next problem you encounter will be the one described in the comment by Tom Karzes. It prevents the output of "the numbers are".
Your continuation test is backwards. You want i >= 0, not i <= 0, since i is counting down to zero.
This means that, with your code as is, the body of the second loop will never be executed because with any meaningful n value, i<=0 for i==n-1 will already be false for the first check and the loop is immediatly done.
Hi i have a project for tommorrow which i want to finish but im stuck. Im pretty new at this so don't be harsh.Basicly i want my program to ask how many numbers did the user play. How much money, after it asks for the lottery numbers and puts then in a border,then it asks for the users numbers,puts in on a second border and then i want to compare the 2 of them and if they have a same number it will add to 'sum'.
#include <stdlib.h>
int main()
{
int k[20],i;
int k2[12],f;
int numbers,sum,n,l,num;
float money,winnings;
l=0;
sum=0;
printf("How many numbers from 1 to 12?\n");
scanf("%d",&num);
printf("How much money?\n");
scanf("%f",&money);
for (i=0;i<19;i++)
{printf("Give lottery numbers\n");
scanf("%d",&k[i]);}
while (l<num){
printf("Give your numbers\n");
scanf("%d", k2 + f); !!fixed!!
l++;}
for (f=0;f<num;f++){
for (i=0;i>19;i++){ !!fixed!!
if ((k[i])==(k2[f])) !!! and here i think its a mistake.
{
sum=sum+1;
}
}
}
printf("You got %d numbers out of %d",sum,num);
if ((sum=1) && (num=1));
{winnings=(money*2,5);
printf("Won %f",winnings);}
if ((sum=1) && (num=2));
{winnings=(money*1);
printf("won %f",winnings);}
if ((sum=2) && (num=2));
{winnings=(money*5);
printf("Won %f",winnings);}
system("pause");}
It doesn't appear that f has ever been initialized to anything. Therefore,
scanf("%d",k2[f]);
Will result in undefined behavior, and is the likely cause of the crash.
Additionally, you need to fix your indentation. Furthermore, your loop is off by one. You initialize l to 1, then execute the following loop, whose apparent purpose is reading num numbers:
while (l<num){
So, if, for example, "1" was entered, in order to read only one number, the body of the loop will never execute, since the comparison "1<1" will be false.
It's likely there are other problems with this code, hard to analyze it due to bad indentation.
This loop
for (i=0;i=19;i++){
will never end since i=19 will evaluate to always true.
I think that the intention was:
for (i=0;i<19;i++){
Instead of l, what you probably intended, you are using f, which, as Sam Varshavchik spotted already, is not initialized.
Additionally, you are not passing a pointer to scanf: scanf("%d", k2[f]);. You need scanf("%d", k2 + l); instead, or scanf("%d", &k2[l]), if you prefer.
// C program to print reverse of a number using for loop
#include<stdio.h>
int main()
{
long int num,i;
int d;
printf("\n enter number");
scanf("%ld",&num);
printf("\n the reverse of number %ld is ",num);
for(i=0;num>0;i++)
{
d=num%10;
num=num/10;
printf("%d",d);
}
return 0;
}
I think there is no terminating given in this code as the for loop will run infinte times, but this code is working fine, so can someone explain this code?
In order to understand the loop you need to understand the working of % 10 and /= 10 operations.
The first one, the remainder of division by ten, chops off the last decimal digit. The second one drops that digit from the number, because the division is done in integers.
Dividing a number by ten repeatedly will make it a zero aftre a number of iterations equal to the number of digits in the number, so that is when your loop is going to stop.
I've been looking into this simple piece of code for 1.5 hrs now and do not find the mistake. I start going crazy ;)
Could anyone of you with a fresh mind and view give me a little hint, where I might have the mistake in? (I am relatively new to C)
The problem is: The code works fine for most of the numbers I entered and tested, but accidentically I found a number that does not work: 3486118 (or 55777888 which is a multiple of it) It goes right for the first loop(s), but after factor 2 it becomes an endless loop.
Here is my code: (any help is greatly appreciated)
// Program calculates prime factors of entered number and returns them
#include <stdio.h>
int main() {
long int num, num_cp;
long int product=1;
/*prime number array up to 100.000*/
long int prime[] = {2, 3, **[...cut out MANY numbers...]** 99971, 99989, 99991};
printf("Please enter a positive integer:\n");
scanf("%li", &num);//55777888 or 3486118 not working... why?
//copy the entered number to keep the original for comparison with "product" and "break;" if equal
num_cp=num;
printf("prime factorization of %li:\n\n", num);
for (int i=0; i<sizeof(prime); i++) {
if (num_cp%prime[i]==0) {
num_cp/=prime[i];
product*=prime[i];
if (product==num) {
printf("%li\n\n", prime[i]);
break;
}
printf("%li*", prime[i]);
//If prime factor found but "product" is still not equal to "num" reset loop counter "i" to -1 (==0 in next loop)
i=-1;
}
}
printf("END");
return 0;
}
"I've been looking into this simple piece of code for 1.5 hrs now and do not find the mistake. I start going crazy ;)"
Don't. Leave it. Go away and eat a pizza. Veg out in front of your favourite movie. Have a shower. Aim for a new high-score on 2048 (or whatever). Your brain gets stuck in a rut and you are no longer seeing your code. You are only seeing what you think your code is.
When you get your brain out of the rut, then -- and only then -- go back and actually read the code you wrote. Not the code you think you wrote, but the code you actually wrote. Yes, they are different.
The prime factors of 55777888 are 2·2·2·2·2·1743059, where the last factor is too large to be contained in your list.
You can fix this in your code: When the product is equal to the product of the prime factors you have found, num_cp is 1. If num_cp is greater than one after you have exhausted your prime list, it is a factor of num. If num/num_cp is smaller than the largest prime you have checked, you can assume that the remaining value of num_cp is a prime. If it wasn't you'd have found more factors earlier.
You can fix this by adding an additional check after your main loop:
if (num_cp > 1) printf("%li\n\n", num_cp);
(If long int is a 64-bit number on your system, you're still not safe: The remaining factor might be made up of several numbers that are not in your array.)
Finally: Resetting the for loop counter so that the loop starts over isn't a good idea. It always starts from the beginning and re-checks primes that you have already checked. And it just isn't natural program flow, which makes it hard to read. A while loop instead of the inner if block would be more natural in my opinion.
Edit: To illustrate:
#include <stdio.h>
int main() {
long int num;
/* prime number array up to 100.000 */
long int prime[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
int nprime = sizeof(prime) / sizeof(*prime);
num = 55;
printf("%li == ", num);
for (int i = 0; i < nprime; i++) {
long int p = prime[i];
if (num <= 1) break;
while (num % p == 0) {
num /= prime[i];
printf("%li", p);
if (num > 1) printf(" * ");
}
}
if (num > 1) printf("%li", num);
printf("\n");
return 0;
}
Things to note:
Instead of resetting the main loop counter i, a while loop is used, which consumes all repetitions of the same factor. If a prime p doesn't divide the number, the while loop isn't entered, just like an if clause.
I've removed the copy of num and used num throughout, mainly to remove clutter. I've also removed the product. Your logic that all prime factors should multiply to the original number, is good. But it also works the other way round: After dividing the number by all primes, we are left with 1. And we have to divide the number anyways. By removing the product, we have to keep track of only one variable instead of two.
I've moved the break condition to the front, so we catch negative numbers and 0 early.
That said, your way to code isn't wrong, just maybe a bit unusual in places.
I want to write a c program that prints the sum of the squares of a given number.
For example, if the given number is 456, the output would be 4^2+5^2+6^2=16+25+36=77.
So i have written this code and i want to know why it doesn't work if the user gives a number like 100,101,102 or 200,300 etc. It works fine for other numbers. I guess it has something to do with the dowhile loop. Please help me.
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int n,t=0,r,q;
printf("Enter the number to be tested: ");
scanf("%d",&n);
q=n;
do
{
r=q%10;
t=t+pow(r,2);
q=q/10;
}
while(q%10!=0);
printf("%d",t);
getch();
}
Your stopping condition is wrong: q%10!=0 will become "true" as soon as you reach the first zero in a decimal representation. For example, for a number 6540321 your program would add 32+22+12, and stop, because the next digit happens to be zero. Squares of 6, 5, and 4 would never be added.
Use q != 0 condition instead to fix this problem. In addition, consider replacing
t=t+pow(r,2);
with a more concise and C-like
t += r*r;
Change
while(q%10!=0);
To
while(q);
Which is the short for
while(q!=0);
This is done to prevent to loop from ending once the value of q is a multiple of 10.