i am trying to find factorial by recursively.My function works but why i recieve "segmenatation fault (core dumped)" when i input -1.
#include <stdio.h>
int fak(int number);
int main(){
int i;
printf("give me an integer: ");
scanf("%d",&i);
printf("factorial: %d\n",fak(i));
return 0;
}
int fak(int number){
if(number == 1 || number == 0){
return 1;
}
return number * fak(number - 1);
}
To answer the question: you will get a stack overflow because your recursive method will never end normally (see all the comments).
If you put in -1, the method will be called again with -2.
It depends on your stack-size when it will crash.
You can change your condition to:
if(number <= 1){
return 1;
}
Besides of that: the factorial of -1 doesn't exist.
Related
I've been trying to write a recursive function that scans a series of numbers and returns the sum of the numbers in odd indexes minus the sum of numbers in even indexes.
biggest problems: the function is not supposed to receive any parameters when called upon; and I have to do it in one function.
Edit: so, I wrote this code and it seems to work for the most part, but the problem is I wasn't supposed to send any parameters with the function (f wasn't supposed to exist)
void Ex1() // this is sort of like the main
{
int f = 1, res;
res = sumofodd_even(f);
printf("sum is: %d\n", res-1);
}
int sumofodd_even(int flag)
{
int num = 0;
printf("enter a number. to stop enter -1 >> \n");
scanf_s("%d", &num);
if (num != -1)
{
if (flag == -1)
num *= -1;
return num + sumofodd_even((-1) * flag);
}
}
btw: can't use pointers or arrays...
will appreciate any help.
One approach might be to just use a boolean flag that gets flipped at every recursion:
#include <stdbool.h>
#include <stdio.h>
int sumofodd_even(const bool odd) {
printf("enter a number. to stop enter -1 >> ");
int num = 0;
scanf("%d", &num);
if (num == -1) {
return 0; // breaks the recursion
}
num *= odd ? 1 : -1;
return num + sumofodd_even(!odd);
}
int main(void) {
printf("sum is: %d\n", sumofodd_even(false)); // zero is even, thus we start with odd == false
return 0;
}
you can use odd to mark if the read value should be treated as an odd number or as an even number, and thus change its sign accordingly.
Alternative to counting iterations or flipping a flag is to simply use two functions. After all, your algorithm has two states: process an even-indexed number, or process an odd-indexed number. Rather than have one function with an if statement, just use a function for each state, and have those functions transition between states by calling on each other.
int sum_of_odd() {
// <Ask user for input>
if (num == -1) {
return 0;
}
return sum_of_even() + num;
}
int sum_of_even() {
// <Ask user for input>
if (num == -1) {
return 0;
}
return sum_of_odd() - num;
}
And of course you'd start the algorithm by calling sum_of_odd(), since the first number is odd-indexed (unless you want to "index by zero").
the question is "write a recursive function that ends when -1 is entered, than return how many times an even number was scanned.
naturals(int);
static void main() {
int num;
printf("enter numbers\n");
scanf("%d", &num);
naturals(num);
}
naturals(int num) {
int count = 0;
if (num % 2 == 0) {
count++;
}
if (num == -1) {
printf("%d", count);
return 0;
}
scanf("%d", &num);
return naturals(num);
}
i know that it resets "count" to 0 at the start of the function, how do i solve this?
This is a good place to make use of the ?: operator:
#include <stdio.h>
int naturals(int count)
{
int num;
scanf("%d", &num);
return num == -1 ? count : naturals(num % 2 == 0 ? count+1 : count);
}
int main(int argc, char **argv)
{
printf("enter numbers\n");
printf("even numbers entered = %d\n", naturals(0));
}
Here I'm passing 0 in as the initial count in the call to naturals in main, then for each number entered count is incremented if the number is even; otherwise we just pass the unincremented count to the next invocation of naturals. Prior to making the recursive call to naturals we check to see if the number entered is -1; if it is we return the current value of count, otherwise we proceed to make a recursive call to naturals.
If you prefer, the return line in naturals can be replaced with
if(num == -1)
return count;
else if(num % 2 == 0)
return naturals(count+1);
else
return naturals(count);
which is functionally the same. It has the disadvantage of having three separate return statements which IMO is more confusing, but YMMV.
You can't keep track of count inside your recursive function. As you have correctly observed, count is reset to 0 every time the function runs. Instead, you'll have to keep track of count outside of your function. Here are some ways of doing this:
Pass count as a parameter to your recursive function, update it, and have your recursive function return the new value;
Create a global variable count and update is as necessary every time the recursive function runs.
#include <stdio.h>
#include <math.h>l
naturals(int, int);
static void main() {
int num, count = 0;
printf("enter numbers\n");
scanf("%d", &num);
naturals(num, count);
}
naturals(int num, int count) {
if (num % 2 == 0) {
count += 1;
}
if (num == -1) {
printf("%d\n", count);
return 0;
}
scanf("%d", &num);
return naturals(num, count);
}
solved it thanks!
Now I am practicing using Vim on Linux.
I made a simple code like this
#include <stdio.h>
int factorial(int n){
if (n<0) { return 0; }
else if (n==0) { return 1; }
else { return n * factorial(n); }
}
int main(void){
int n = 0;
printf("Put n value : ");
scanf("%d", &n); /* non-OP inserted ";" to help people focus on the problem */
printf("%d! = %d\n", n, factorial(n));
return 0;
}
When I put -1 and 0, it works. They return 0 and 1.
However, when I put positive integer values on n, it didn't work.
I tried to find out the reason so I used gdb,
but it just said like this :
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400620 in factorial ()
What's wrong with my code? I even cannot understand the point.
When n > 0 your recursive program never terminates. The value of n is never decremented and so it continues running recursively until your run out of memory.
It should be return n * factorial(n-1);
You code is causing stack overflow. In the given function n is never decremented. Last statement should be
else { return n * factorial(n-1); }
Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.
EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.
EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
1. You never initialized i (it has indeterminate value - local variable).
2. You never call function is_prime.
And using a loop will be good idea .Comparing to what you have right now.
I just modified your function a little. Here is the code
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
Explanation-
In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don't want to check anymore. So, it will exit the loop.
In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).
If you have any doubts, let me hear them.
I suggest you start with trial division. What is the minimal set of numbers you need to divide by to decide whether a is prime? When can you prove that, if a has a factor q, it must have a smaller factor p? (Hint: it has a prime decomposition.)
Some errors your program had in your prime finding algorithm:
You start the loop with number 1 - this will make all numbers you test to be not prime, because when you test if the modulo of a division by 1 is zero, it's true (all numbers are divisible by 1).
You go through the loop until a, which modulo will also be zero (all number are divisible by themselves).
The condition for a number to be prime is that it must be divisible by 1 and itself. That's it. So you must not test that in that loop.
On main, the error you're getting (control reaches end of non-void function) is because you declare main to return an int.
int main(void)
And to solve that, you should put a return 0; statement on the end of your main function. Bellow, a working code.
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b;
for (b = 2; b < a; b++) {
if (a % b == 0)
return (0);
}
return 1;
}
int main(void)
{
int c, answer;
printf
("Please enter the number you would like to find is prime or not= ");
scanf("%d", &c);
answer = prime(c);
if (answer == 1) {
printf("%d is a prime number \n", c);
} else {
printf("%d is not a prime number\n", c);
}
return 0;
}
On a side note, don't use the CAPSLOCK to write full sentences. Seems like you're yelling.
Mathematically the maximum divisor of a number can be as a large as the square of it, so we just need to loop until sqrt(number).
A valid function would be:
//Function that returns 1 if number is prime and 0 if it's not
int prime(number) {
int i;
for (i = 2; i < sqrt(number); i++) {
if (a % i == 0)
return (0);
}
return 1;
}
#include<stdio.h>
int main()
{
int n , a, c = 0;
printf ("enter the value of number you want to check");
scanf ("%d", &n);
//Stopping user to enter 1 as an input.
if(n==1)
{
printf("%d cannot be entered as an input",n);
}
for(a = 2;a < n; a++)
{
if(n%a==0)
{
c=1;
break;
}
}
if(c==0 && n!=1)
{
printf("%d is a prime number \n",n);
}
else
{
if(c!=0 && n!=1)
{
printf("%d is not a prime number \n",n);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i;
printf("enter the number : ");
scanf("%d",&x);
for ( i=2; i<x;i++){
if ( x % i == 0){
printf("%d",x);
printf(" is not prime number ");
printf("it can be divided by : ");
printf("%d",i);
break;
}[this is best solution ][1]
}
if( i>=x) {
printf("%d",x);
printf(" is prime number");
}
}
it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr ยง6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}