The question is as follows.
Q) Develop a function f1 to accept an integer argument, reverse the digits and return the reversed value. Also, develop another function f2 to accept two integer arguments x and n and to return the value of x raised to the power n. The return value of f2 should be passed on to f1 and the return value of f1 must be checked whether it is prime or not by another function f3. The result must be printed in the program.
The control does not flow beyond the 45th line in this code. I do not really know what it the issue here because when i run the code in code blocks, the output screen displays the output of f2 and then it remains idle. for example, if i give the input as 8 and 2, then the output returns a value of 81 and then it does not do anything beyond that.
#include <stdio.h>
#include <math.h>
int f1(int npow)
{
int ret=0;
while (npow>0)
{
ret=(ret*10)+(npow%10);
}
return ret;
}
int f2(int x,int n)
{
int res;
res=pow(x,n);
return res;
}
int f3(int resrev)
{
int i,check;
for (i=2;i<resrev;i++)
{
if (resrev%i==0)
{
check =1;
break;
}
else
{
check=0;
break;
}
}
return check;
}
void main()
{
int resrev,x,n,npow,prime;
printf("Enter two numbers x and n\n");
scanf("%d %d",&x,&n);
npow=f2(x,n);
printf("x to the power n is %d\n",npow);
resrev=f1(npow);
printf("Reversed value of x to the power n is %d \n",resrev);
prime=f3(resrev);
if (prime==1)
printf("It is not a prime number \n");
else
printf("It is a prime number\n");
}
Problem is in function f1. It is an infinite loop.
Loop condition is until npow>0 but you are not updating value of npow in the loop.
Following is corrected code:
int f1(int npow)
{
int ret=0;
while (npow>0)
{
ret=(ret*10)+(npow%10);
npow = npow/10;
}
return ret;
}
Loop inside f1 is infinite as condition to exit while loop is unaltered.
snippet has to be updated as follows,
int f1(int npow)
{
int ret=0;
while (npow>0)
{
ret=(ret*10)+(npow%10);
npow /= 10; // divide to remove lsb digit
}
return ret;
}
Related
I am wroting two program that calculates a factorial. The program #1 is to have the return value type to be void, and the program #2 is to have the return value type to be int.
But I lack knowledge, so I don't know which one is right.
Which one is correct?
program #1 - return value type: void
#include <stdio.h>
void calculateFactorial(int count, int *sum);
int main()
{
int number;
int sum = 1;
printf("factorial number: ");
scanf(" %d", &number);
calculateFactorial(number, &sum);
printf("result: %d\n", sum);
return 0;
}
void calculateFactorial(int count, int *sum)
{
if (count == 0)
{
return;
}
*sum *= count;
calculateFactorial(--count, sum);
}
program #2 - return value type: int
#include <stdio.h>
int calculateFactorial(int count, int *sum);
int main()
{
int number;
int sum = 1;
printf("factorial number: ");
scanf(" %d", &number);
calculateFactorial(number, &sum);
printf("result: %d\n", sum);
return 0;
}
int calculateFactorial(int count, int *sum)
{
if (count == 0)
{
return *sum;
}
*sum *= count;
calculateFactorial(--count, sum);
}
The first one is correct, and the second one is wrong. In the second one, you don't return anything even though the function type is int. You are supposed to return an int. E.g.,
int func() {//Whatever code}
is wrong. It needs to return an int. The correct version is:
int func() {
return 0; //Or whatever int
}
If you don't want to return anything, then you need to have type void.
void func() {
return 0;
}
This is wrong. You can't return anything, and you need to do:
void func {
return; //Not having a return won't do anything though, you can leave it blank
}
void func {} //Works, no need to return
You may be confused because:
1. void main() {} //Works and
2. int main() {} //Works as well, and
3. int main() {return 0;} //Works as well
So, no 1. is absolute rubbish. It works somehow, but it's wrong and it's rubbish. Check How does int main() and void main() work?.
In no. 2 the compiler adds return 0 for you. It only happens in main function.
No. 3 is perfectly correct.
There is no right or wrong when it comes to how you handle returning values from a function: they can be returned as a direct value, or as a secondary value through a passed pointer. There is, however, one (or more) right way(s) to DO each, and many wrong ways. In your two examples, the first one is done a right way, and the second one is done a wrong way. In the second example, there is no return for the case where count != 0, so it is a wrong way.
I general, I prefer a simple mathematical function (like factorial) to return a direct value (in this case, as an int); to do so I would write the calculateFactorial function like this:
int calculateFactorial(int num)
{
if (num <= 1) return 1;
return num * calculateFactorial(num - 1);
}
sum is not needed in this scenario, just print the returned value (which is technically a product, not a sum anyway).
#include<stdio.h>
int factorial_calculator(int n);
void main()
{
int n;
printf("Enter a number to get its factorial: ");
scanf("%d",&n);
printf("The factorial of %d is %d\n",n,factorial_calculator(n));
}//end main
int factorial_calculator(int n)
{
int factorial;
int number;
for(number=1;number<=n;number++)
{
factorial=factorial*number;
return factorial;
}
}//end factorial_Calculator
You should not return in the body of the loop:
for(number=1;number<=n;number++)
{
factorial=factorial*number;
return factorial;
}
should be
for(number=1;number<=n;number++)
{
factorial=factorial*number;
}
return factorial;
otherwise you return the value in the first iteration of the for loop.
also, as pointed out by #spartygw in comments, you need to initialize factorial:
int factorial = 1;
and use the proper signature for main: int main(void) instead of void main()
Also, since scanf can fail, initialize n
int n = 0;
and pass the absolute value of n in order to avoid an infinite loop if a negative number is entered:
printf("The factorial of %d is %d\n",n,factorial_calculator(abs(n)));
Here's the code snippet, this when run with number 4 outputs 2424242448484848288288288288576576576576. Not sure as to why would the execution would jump back to while loop after exiting the function code. Any help will be appreciated. Thank you in advance.
#include <stdio.h>
#include <string.h>
int result = 1;
void FirstFactorial(int);
void FirstFactorial(int num) {
// code goes here
while (num > 0) {
result = result * num;
num--;
FirstFactorial(num);
}
printf("%d", result);
}
int main(void) {
int var;
// keep this function call here
printf ("Enter your no.\n");
scanf("%d", &var);
FirstFactorial(var);
return 0;
}
Within the function
void
FirstFactorial(int num)
{
// code goes here
while(num > 0)
{
result = result * num;
num--;
FirstFactorial(num);
}
printf("%d", result);
}
each its iteration calls itself num times and all iterations together output the global variable result.
So for example in the first call of the function the function calls itself in the while loop for the range of values [num, 1].
Remove the while loop and do not use the global variable.
Here is a demonstrative program.
#include <stdio.h>
unsigned long long int factorial( unsigned long long int n )
{
return n < 2 ? 1 : n * factorial( n - 1 );
}
int main(void)
{
printf( "%llu! = %llu\n", 4llu, factorial( 4 ) );
printf( "%llu! = %llu\n", 20llu, factorial( 20 ) );
return 0;
}
The program output is
4! = 24
20! = 2432902008176640000
Pay attention that the maximum value you may specify is 20.
Either you implement the factorial with a loop or you do it recursively.
Both ways are feasible but your code mixes it up.
Your function mixes iterative and recursive approaches. You can correct it by removing the useless recursion which causes multiple intermediary results to be computed and printed. Defining result as a global variable is also a mistake, especially since you do not reinitialize it before the loop. Using type long long will allow for larger factorials to be computed. Adding a trailing \n after the printf conversion specifier is advisable too.
Here is a corrected version:
#include <stdio.h>
void FirstFactorial(int num) {
long long result = 1;
while (num > 1) {
result = result * num;
num--;
}
printf("%lld\n", result);
}
int main(void) {
int var;
// keep this function call here
printf("Enter your number\n");
if (scanf("%d", &var) == 1)
FirstFactorial(var);
return 0;
}
#include <stdio.h>
int multiple(int, int);
int main()
{
int i;
int x;
int y;
scanf("%d %d", &x, &y);
printf("%d", multiple(x,y));
}
int multiple(int N,int M)
{
int i;
int result;
for (i=0;i*M<N;i++)
{
result=i*M;
printf("%d", result);
}
}
When I put input (for example x=100 and y=7) the output displays all the multiple until 105 and not until 98 as it should be.
The loop does print up to 98. However, multiple is declared to return an int but doesn't actually have a return statement, so the return value is unspecified (and in practice you'll get some arbitrary value from a previous calculation). Then you print this "garbage" return value and in your case it happens to be 105.
If you don't want multiple to return a value then don't declare it to return a value, and don't print the value it returns.
I can't seem to figure out what is wrong in my code, when It comes to the first scanf in do while loop, I enter a number and it just stops there.
If I put printf("Something"); after that scanf, it isn't printed so it isn't a infinite loop. Also program does not just freeze, when I go into Task Manager, it takes up CPU, so it is doing something.
My program is supposed to load resistors and calculate their parallel equivalent, until I type in 'done', and then print out the calculated number.
#include <stdio.h>
#include <stdlib.h>
typedef struct o{char om[20];}RESISTOR;
int finish(char *s)
{
if( s[0]=='d' && s[1]=='o' && s[2]=='n' && s[3]=='e' && s[4]==0 )
return 0;
else return 1;
}
int power(int n, int pows)
{
int expo=1;
while (pows)
{
expo*=n;
pows--;
}
return expo;
}
int convert(char *s)
{
int broj,c;for(c=-1;s[c];c++);
for(int i=0;s[i];i++)
{broj+=(s[i]-0x30)*power(10,c-i);}
return broj;
}
double paralel(double old, int new)
{
double num;
num=((double)new*old)/(old+(double)new);
return num;
}
int main()
{
int n=0;double para;
RESISTOR *p=(RESISTOR *)malloc(1*sizeof(RESISTOR));
int *convertnum=(int *)malloc(1*sizeof(int));
do
{
printf("R%d= ",n+1);
scanf(" %s", (p+n)->om);
convertnum[n]=convert((*(p+n)).om);
if(n==0) para=convertnum[n];
else if (finish((*(p+n)).om)) para=paralel(para,convertnum[n]);
n++;
if(finish((*(p+n-1)).om))
{
p=(RESISTOR *)realloc(p, n*sizeof(RESISTOR));
convertnum=(int *)realloc(convertnum, n*sizeof(int));
}
}while(finish((*(p+n-1)).om));
printf("\n");printf("\n");
printf("Re= %.2f",para);
free(p);free(convertnum);
printf("\n");
return 0;
}
for(c=-1;s[c];c++); accesses s[-1], which might be 0, which means c-i in power(i,c-i) is negative, and thus the while(pows){pows--} has to go through 2^64 loops which may take a while. Your program should not take any measurable cpu time.