// program to check if a number is a perfect square or not.
#include<stdio.h>
double perfect_square(double number)
{
step:
for (int i = 1; i<=number; i++)
{
if (i*i == number)
{
return number;
}
else
{
goto step;
}
}
return 0;
}
int main ()
{
double N;
printf("Enter a number: ");
scanf("%lf", &N);
double cube_decision = perfect_square(N);
if (cube_decision == 0)
{
printf("It is not a perfect cube");
}
else
printf("It is a perfect cube.");
return 0;
}
The above program lets me input a number but I it just kind of freeze and doesn't do anything onward. I tried replacing every double variables with int variable and made the function to return int type and it worked but my question here is why does this program suddenly freezes when I use double???
Note: This might not be the best program to check perfect square but still it would be of great help if anyone can find the mistake in this program! :)
Because if the condition i*i == number is false, then you start the loop all over again, from the very beginning (with the int i = 1 part). The goto will give you an infinite loop.
You don't nee the goto here, the loop will automatically iterate anyway:
double perfect_square(double number)
{
for (int i = 1; i<=number; i++)
{
if (i*i == number)
{
return number;
}
}
return 0;
}
And as a general rule, never use goto and labels.
Related
Basically the title, I am in a beginners C++ class and am trying to do an assignment but have been having trouble learning without the hands on teaching due to covid. I am trying to sum and average numbers using a while loop, but have it stop when a character or string is entered instead of a double. I think all of my code except the conditionals work, any help would be greatly appreciated.
#include <stdio.h>
int main(int argc, const char* argv[])
{
double userNum, numSum, numAvg;
int i; //iterations for calculating average
userNum = 0.0;
numSum = 0.0;
numAvg = 0.0;
i = 0;
while (1)
{
if (1) {
printf("Enter a score (or stop to quit):\n");
scanf("%lf", &userNum);
}
else // I thought this would break the loop if any nun double value was entered but I was wrong?
{
break;
}
numSum = numSum + userNum;
i++;
}
if (i == 0) // if no ittereations done, gives no sum message
{
printf("No sum and average calculated!");
}
else
{
// otherwise calculates and prints sum and avg
}
{
numAvg = numSum / i;
printf("The sum is: %0.2lf, average is: %0.2lf", numSum, numAvg);
}
return 0;
}
if(1) is redundant and by adding it, you are never going to reach else.
It is equivalent to if (1 != 0) which is always true.
You can achieve what you are asking by checking the return value of scanf(). You can modify your code like so:
while (1)
{
printf("Enter a score (or stop to quit):\n");
if (scanf("%lf", &userNum) != 1) // should return 1 if 1 double is read
{
break;
}
numSum = numSum + userNum;
i++;
}
For large inputs, I would suggests that you switch to fgets() and later parse the string with sscanf(). scanf() doesn't provide any protection from arithmetic overflow, which is undefined behavior.
so i'm practicing c and i built a program that says if its prime number or not and i tried to execute it but it wont work it doesnt shows me the output oh and im still new to this i started learning c one week ago.
i dont know how to fix this.
#include <stdio.h>
void Num();
int main()
{
void Num();
return 0;
}
void Num()
{
int n, i, flag = 0;
printf("Enter a num: ");
scanf("%d", &n);
for(i = 1; i <= 10; i++)
{
for(n = 1; n <= 10; n++)
{
flag = 1;
}
}
if( flag == 1)
{
printf("its not the prime num ");
} else{
printf("its the prime num" );
}
}
it wont even show the printf output
You need to go back to the basics (this means: reading a good C book before diving in). You are confusing declaration and calling of functions.
int main()
{
void Num();
return 0;
}
main contains two statements:
A local (re)declaration of Num as a function without return value.
A return statement.
Since you want to call Num rather than redeclaring it, you need to use the function call syntax:
int main()
{
Num();
return 0;
}
This is just the first step, however. Your Num function does not perform the correct actions to determine primality.
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 4 years ago.
Improve this question
#include <stdio.h>
int checkiffactorial();
int factorial(int n);
int number;
int main()
{
int answer, n, i;
printf("Enter a number: ");
scanf("%d", &number);
answer = checkiffactorial();
if (answer == 1)
{
printf("It's a factorial");
}
else
{
printf("It's not a factorial");
}
}
int checkiffactorial()
{
static int whichnumber = 1;
int currnumber;
if (whichnumber > number)
{
return 0;
}
if(whichnumber <= number)
{
currnumber = factorial(whichnumber);
if (currnumber == factorial(number))
{
return 1;
}
whichnumber++;
checkiffactorial();
}
}
int factorial(int n)
{
int i;
int fac;
for(i=1; i<=n; ++i)
{
fac = fac * i;
}
}
Why is this code not working?
My C code is meant for you to input a number and check if that number can be a factorial.
Like for example: if you enter 6 it should be Yes because 3! = 6 but if you enter 8 it would not work.
I d'ont think it's a duplicate because the method i did it was different.
Please note i'm not really good at C so any extra tips could be appreciated.
You need to correct 3 mistakes to make this program work.
You're comparing factorial of whichnumber with factorial of number that's wrong.
currnumber = factorial(whichnumber);
if (currnumber == factorial(number)) //<----never be true
{
return 1;
}
You should compare factorial of whichnumber with number
currnumber = factorial(whichnumber);
if (currnumber == number) //<----should check whether it's same with the number
{
return 1;
}
2 . You should initialize fac variable in factorial function otherwise it will take some garbage value.
int fac=1; //<-----initialize this variable
3. You should return the value of fact after calculating the factorial.
return fac; //<-----should return value
Here is the modified code:
#include <stdio.h>
int checkiffactorial();
int factorial(int n);
int number;
int main()
{
int answer, n, i;
printf("Enter a number: ");
scanf("%d", &number);
answer = checkiffactorial();
if (answer == 1)
{
printf("It's a factorial");
}
else
{
printf("It's not a factorial");
}
}
int checkiffactorial()
{
static int whichnumber = 1;
int currnumber;
if (whichnumber > number)
{
return 0;
}
if(whichnumber <= number)
{
currnumber = factorial(whichnumber);
if (currnumber == number) //<----should check whether it's same with the number
{
return 1;
}
whichnumber++;
checkiffactorial();
}
}
int factorial(int n)
{
int i;
int fac=1; //<-----initialize this variable
for(i=1; i<=n; ++i)
{
fac = fac * i;
}
return fac; //<-----should return value
}
It has been pointed out to you that you don't return value from your functions and use uninitialsed values. These errors are easy to make, but they are also easy to catch: Enable warnings for your compiler and they will tell you about these things.
Suvojit's answer tells you what is wrong with your factorial function. Unfortunately, more things are wrong with your factorial check:
You make the number you check a global variable. This should really be an argument to the function, so that you can call it like you should: is_factorial(n).
You make your counter a static variable. This is like a global variable, but with the restriction that it is only known in this function, which means that you cannot change it from outside. If your program want to check several numbers, the second call starts where you left off earlier, which leads to wrong results.
Of course that's what you want in your implementation, because you use a recursive algorithm. In this case, that's not a good choice; use a loop.
Your condition when to stop the iteration (or when to break the loop) checks the number against the number you took the factorial of. You should test this against the factorial itself.
Note that a typical int has 32 bits and can represent positive values up to 2³¹. The factorial 13! already exceeds this limit. So you must check your number against 12 values.
You don't need the factorial function for this, you can build these values as you go, because n! = (n − 1)! · n. (You can use the factorial function, but will do the same calculations over and over again, which is wasteful. It doesn't matter for this toy problem, but it is worth bearing such things in mind.)
So here's your function, completely rewritten:
int is_factorial(int n)
{
int fact = 1;
int k = 1;
while (k < 13 && fact <= n) {
fact *= k;
if (n == fact) return k;
k++;
}
return 0;
}
It returns 0 when the n isn't a factorial, otherwise it returns the number that n is a factorial of. (This information is used anyway, so why not provide it? The caller can choose whether to use this infor or just use it as truth value.)
While we're at it, let's adjust the main function so that the program checks for bad input and prints out the extra information we return:
int main(void)
{
int n;
printf("Enter a number: ");
if (scanf("%d", &n) < 1) {
printf("Illegal input!\n");
} else {
int m = is_factorial(n);
if (m) {
printf("%d is the factorial of %d!\n", n, m);
} else {
printf("%d is not a factorial!\n", n);
}
}
return 0;
}
The things to take away here are that you should use the compiler warning to tell you about simple errors, that you should avoid global and static variables for closed problems like these and that loops are often simpler than recursion.
How can I run this program without any crash #C #CoFactors
This program is about finding cofactors of a number it is working but at the same time this program crashes after showing the output. Please take a look.
Here is the program.
int coFactors(int number,int divisor)
{
if(number%divisor==0)
{
printf("%d ",divisor);
number /= divisor;
coFactors(number,divisor);
}
else if(number==divisor-1)
{
return;
}
else
{
coFactors(number,++divisor);
}
}
int main()
{
int num;
printf("Enter number:");
scanf("%d",&num);
coFactors(num,2);
return 0;
}
seems below condition is wrong:
else if(number==divisor-1)
it should be:
else if(number < (divisor))
My earlier post would have avoided crashed but to get correct Co factor condition should have been like edited.
BLUEPIXY has suggested correctly.
I wrote this program to build a number diamond. The issue is that when I compile the program, it throws the error
build2.c:(.text+0x5): undefined reference to `get_input'
collect2: error: ld returned 1 exit status
I've tried for hours to figure out what exactly the problem is (e.g. if there is a spelling mistake or something similar), but the function call looks identical. I have attempted to rename it, write it as both a prototype and as an implementation, and nothing seems to work. Is there an issue that I'm not seeing?
//Define prior to main
int is_valid(int);
int get_input(void);
void print_pattern(int);
//Main
int main(void){
int diamond_size;
//diamond_size = get_input();
//value from get imput method used for diamond size
print_pattern(get_input());
return 0;
}
void print_pattern(int size){
int length, num, i, j;
//beginning of new diamond
printf("\n");
//Define each integer to work in layout of diamond
//First for loop fans out
for(i=1; i <= size; i += 2){
length = size-i+1;
num = 1;
printf("%*s", length," ");
for(j = 0; j < i; j++){
printf("%d ", num);
num++;
}
printf("\n");
}
//second for loop fans in
for(i=size-2; i >= 1; i -= 2){
length = size-i+1;
num = 1;
printf("%*s", length," ");
for(j = 0; j < i; j++){
printf("%d ", num);
num++;
}
printf("\n");
}
int is_valid(int value){
int rem;
//uses remainder to determine if it is odd or even; an even number will not have a reaminder in this case
rem = value % 2;
if (rem == 0){
printf("You've entered a even number. Please try again.\n");
return (0);
}
//greater than 9 cnd
if (value > 9){
printf("You have entered a number greater than 9. Please try again.\n");
return (0);
}
//less than 1 cnd
if (value < 1){
printf("You have entered a number less than 1. Please try again.\n");
return (0);
}
return (1);
}
int get_input()
{
int cont, number, valid;
cont = 1;
while (cont = 1)
{
printf("Enter an odd number less than 9 and greater than 0 < ");
scanf("%d", &number);
valid = is_valid(number);
if (valid == 1)
{
cont = 0;
}
}
return number;
}
}
You seem to have nested functions; this is (a) a non-standard GCC extension, and (b) I presume the scope of the nested get_input() function is the enclosing function, not the file scope. The solution is to move get_input() to file scope. At the end of print_pattern() add an extra }, and delete the final } at the end of the file.
Also, please format your code - most IDEs these days have options to tidy it up, and with correct indentation you may have seen your problem earlier.
Oh, and as a bonus bug fix, you also have in get_input():
while (cont = 1)
This will always be true - use this instead:
while (cont == 1)
The function print_pattern is not terminated at proper place but instead at the very end of the file:
void print_pattern(int size){
...
... end of the loop
}
... more functions
...
... end of print_pattern
}
This results into defining nested functions instead of global level.
It's generally good habit to indent the blocks, in which case you would realized the mistake very quickly.