Counting recursive function calls which are a multiple of k in C - c

The assignment was to create a program that computes the Ackermann equation using recursion, which I successfully did. Part of the assignment says:
"The function should print the number of recursive function calls which are multiple of k. Set k = 100 for
values of n; m <= 3, and k = 1; 000; 000 for all other values. Your program should also print the total number
of function calls made."
The ackermann function is supposed to print out the number of function calls and recursive functions calls, but I can't figure out how to do it. Any help would be great. Thanks!
This is what I have so far:
#include <stdio.h>
//function to compute the end result ackermann equation
int ackermann (int n, int m)
{
int result = 0;
if (n == 0)
{
result = m + 1;
} else if (m == 0)
{
result = ackermann(n - 1, 1);
} else
{
result = ackermann(n - 1, ackermann(n, m - 1));
}
return result;
}
//main function
int main(int argc, const char * argv[])
{
char ans = 'y';
int m, n, result;
printf("\n\n------Ackermann Function------");
while (ans == 'Y' || ans == 'y') {
printf("\nPlease enter n: ");
scanf("%d", &n);
printf("\nPlease enter m: ");
scanf("%d", &m);
result = ackermann(n, m);
printf("\nResult: %d", result);
printf("\n\nDo you want to go again? ");
scanf(" %c", &ans);
}
return 0;
}

static int count = 0;
int func()
{
count ++
// do your work
// recursive call
}
Make static variable which will keep the total number of calls made to functions.
And in this case you don't have to make count as global making it local static into function is enough because static variable retains it's value as static has file scope.

Use a global variable, incrementing its value on each call:
int calls_count = 0;
...
int ackermann (int n, int m)
{
++calls_count;
...

Related

Why this function gives me first sums correct and then prints bad sums

Write a program that prints the sum of digits for the entered interval limits. To calculate the sum of
digits form the corresponding function.
#include <stdio.h>
void suma(int a ,int b ){
int s= 0,i;
for(i=a;i<=b;i++){
while(i != 0 ){
int br = i % 10;
s+=br ;
i = i/10;
}
printf("%d\n",s);
}
}
int main(void){
int a,b;
printf("enter the lower limit of the interval: "); scanf("%d",&a);
printf("enter the upper limit of the interval: "); scanf("%d",&b);
suma(a,b);
return 0;
}
when i set a to be 11 and b to be 13 program does first 3 sums but after that it doesent stop.why doesn't it stop. But if i set a to 3 digit number program gives me first sum but then gives me random sums
The reason why your code is not working is because in your while-loop, you are changing the value of i, but i is also used in the for-loop. This results in undefined behaviour. In order to fix this, I would suggest breaking the problem up in two functions. One for calculating the sum of a the digits of a number, and one function that adds these sums in a particular range.
int sumNumber(int number) {
int sum = 0;
while(number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
int suma(int a ,int b){
int totalSum = 0;
for(int i=a;i<=b;i++){
int sum = sumNumber(i);
totalSum += sum;
}
return totalSum;
}
This way, you are not modifying i in the while-loop.
You are mixing up the two loop variables. As arguments are passed by value just a instead of introducing an unnecessary variable. Minimize scope of variables. Check the return value from scanf() otherwise you may be operating on uninitialized variables.
#include <stdio.h>
void suma(int a, int b) {
for(; a <= b; a++) {
int s = 0;
for(int i = a; i; i /= 10) {
s += i % 10;
}
printf("%d\n", s);
}
}
int main(void){
printf("enter the lower limit of the interval: ");
int a;
if(scanf("%d",&a) != 1) {
printf("scanf failed\n");
return 1;
}
printf("enter the upper limit of the interval: ");
int b;
if(scanf("%d",&b) != 1) {
printf("scanf failed\n");
return 1;
}
suma(a,b);
}
and example run:
enter the lower limit of the interval: 10
enter the upper limit of the interval: 13
1
2
3
4
I was unreasonably annoyed by how the code was formatted. Extra white space for no reason including at end of line, missing white space between some operations, variables lumped together on one line.
It's a really good idea to separate i/o from logic as in #mennoschipper's answer. My answer is as close to original code as possible.
i did function like this and it works now
void suma(int a ,int b ){
int s= 0,i;
int x ;
for(i=a;i<=b;i++){
x = i;
while(x != 0 ){
int br = x % 10;
s+=br ;
x = x/10;
}
printf("%d\n",s);
s = 0;
} }

Reverse of a number using recursion

The reverse of the number is getting printed many times. How do I print it just once?
For example, if I give input as 1234 then the output is coming out as 4321 4321 4321 4321.
#include <stdio.h>
#include <stdlib.h>
//function declaration
void printReverse(int);
int main()
{
int n;
printf("\n\t\t\t\t\t\tThis program prints reverse of a given number");
printf("\nEnter a number: ");
scanf("%d",&n);
//if someone enters 0
if(n==0)
{
printf("%d",n);
exit(0);
}
//function call
printReverse(n);
return 0;
}
void printReverse(int n)
{
static int rev=0;
//base case
if(n)
{
int rem = n % 10;
rev = rev*10 + rem;
printReverse(n/10);
}
printf("%d ",rev);
}
The way your printReverse function is currently written, the last line (printf("%d ",rev);) will always be executed whenever the function is called, because there is no code path through the function that skips that line. So, when the recursion has reached the point where the given argument is zero, you will get that line being called each time on the 'rewind' of the stacked, recursive calls (once for each digit in the initial n).
To fix this, you can either enclose that printf line in an else block:
void printReverse(int n)
{
static int rev = 0;
if (n) {
int rem = n % 10;
rev = rev * 10 + rem;
printReverse(n / 10);
}
else { // Only print the result when we're finished (n = 0):
printf("%d\n", rev);
}
}
Or, accomplishing much the same thing, add a return statement after you make the recursive call:
void printReverse(int n)
{
static int rev = 0;
if (n) {
int rem = n % 10;
rev = rev * 10 + rem;
printReverse(n / 10);
return; // Don't print on the rewind from recursion
}
printf("%d\n", rev);
}
C Program to reverse a given number using Recursive function
based on https://beginnersbook.com/2014/06/c-program-to-reverse-a-given-number-using-recursive-function/
#include <stdio.h>
int sum=0, rem;
int reverse_function(int num) {
if(num) {
rem=num%10;
sum=sum*10+rem;
reverse_function(num/10);
}
else
return sum;
return sum;
}
int main() {
int num,reverse_number;
//Take the number as an input from user
printf("Enter any number:");
scanf("%d",&num);
//Calling user defined function to perform reverse
reverse_number=reverse_function(num);
printf("The reverse of entered number is :%d",reverse_number);
return 0;
}
Output:

scanning several numbers using Recursion and counting how many even numbers were scanned (in c)

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!

Can I 'return' a result from the main variable?

So I have this exercise where I need to show the N first prime numbers, but I need to specifically create a function to know if the number is a prime number
#include <stdio.h>
#include <stdlib.h>
int prime(int num){
int cont,i,j=0,b;
b=num;
do{
j++;
i=0;
for(cont=1;cont<j;cont++){
if(j%cont == 0)
i++;
}
if(i == 1){
return(j);
c=j;
b--;
}
} while (b > 0);
}
int main(){
int *v,n,cont;
do{
printf("Input an integer: ");
scanf("%d",&n);
} while (n <= 0);
v = (int *)malloc(n * sizeof(int));
for(cont=0;cont<n;cont++){
v[cont] = prime(n);
}
for(cont=0;cont<n;cont++){
printf("%d ",v[cont]);
}
}
The problem with the way i've done this is that the variable J is aways being set to 0 when i call the function again, i've tried to set something like c=j so when the program return to the prime function it would have the 'previous' j value but it gets a weird random number. So I wanted to know if is there a way to 'return' the result in the main function to the prime function, i couldn't find anything that helped me, not that i could understand at least
Your function prime() is not working as intended and there are many other errors -
1) Since smallest prime is 2, variable cont should start from 2.
2) scanf need not be in a loop in this case
3) Enter values in v only when cont is confirmed a prime.
See this function prime2( not optimize though for clarity):
bool prime2(int n)
{
for(int i = 2 ; i<n-1;i++)
if( n% i == 0) return false;
return true;
}
int main(){
int *v,n,cont,cc=0;
printf("Input range: ");
scanf("%d",&n);
v = malloc(n * sizeof(int));
for(cont=2;cc<n;cont++){
if( prime2(cont) == true )
{
v[cc] = cont;
cc++;
}
}
for(cont=0;cont<n;cont++){
printf("%d ",v[cont]);
}
delete v;
}
Output:

srand() in dice game [duplicate]

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 8 years ago.
I've been searching the site for possible answers to this problem, and although they're all similar they don't seem to be the exact same problem that I have, which is why I've been forced to open this question. SO I need to make a dice game that is supposed to roll 2 dice ranged from 1-6 and the user is supposed to guess what the number will be. The program then outputs the values of the die and reroll's if the guessed value isn't the real value of the 2 die. If it is then the program stops rolling the die and tells you how many rolls it took for the die to reach your guessed value.
For some reason my program keeps rolling the die over and over without stopping and I'm not exactly sure why. I tried testing it in a seperate program and have gotten even more confused as to why I still can't get different values even with srand() being called only once at the beginning of main.(I realized that, among a few other problems were what was wrong with the functions throwCalc1 and the unnecessary throwCalc2) If I try to place rand() outside a variable, I get different values, but if I put it within a variable the values stay the same. I've tried making the variable a function and it still doesn't work as the compiler gives me an error saying "initialization makes pointer from integer without a cast"
test function:
int main(void)
{
srand(time(NULL));
int i;
int *throwCalc = rand() % 6 + 1;
for(i = 0; i < 6; i++) {
printf("value is: %d\n", *throwCalc);
}
return 0;
}
original program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
#define MIN 2
#define MAX 12
int getInt(int min, int max) {
int retry = 1;
int value;
char after;
int cc;
do {
printf("Enter total sought \n"
"Range must be within [%d - %d]", min, max);
cc = scanf("%d%c", &value, &after);
if(cc == 0) {
printf("bad char or 0 input, please re-enter input");
clear();
} else if (after != '\n') {
printf("Error:Trailing characters, please re-ente input");
clear();
} else if (value < min || value > max) {
printf("Error: value outside of range, please re-enter input");
clear();
} else {
retry = 0;
}
} while(retry == 1);
return value;
}
void clear() {
while (getchar() != '\n') {
; //intentional empty statement
}
}
int throwCalc1() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwCalc2() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwResult(int input, int getcalc1, int getcalc2) {
int i = 0;
do {
throwCalc1();
throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
printf("You got your total in %d throws!\n", i);
return 0;
}
int main(void)
{
int input = getInt(MIN, MAX);
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
printf("Game of Dice\n");
printf("============\n");
printf("hi number is: %d", input);
throwResult(input, getCalc1, getCalc2);
return 0;
}
You do this once at the top of main:
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
And then expect the values to update just by calling throwCalc1() & 2 again.
Besides fixing srand(), have throwCalc1 & 2 return values into local variables instead of passing something in.
Right now you are calling throwCalc1() and throwCalc2() within your loop, but throwing away the results. You need to save those results in a pair of variables:
do {
getcalc1 = throwCalc1();
getcalc2 = throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
After you've done this, you might notice that getcalc and getcalc2 don't need to be parameters to that function - they can just be local variables within throwResult().
In addition, your throwCalc1() and throwCalc2() functions are identical, so you can remove one them and just call the remaining one twice.
Your test function should look like:
int main(void)
{
srand(time(NULL));
int i;
int throwCalc;
for(i = 0; i < 6; i++) {
throwCalc = rand() % 6 + 1;
printf("value is: %d\n", throwCalc);
}
return 0;
}

Resources