I would like to return the minimum of three given numbers like this.
I don't know why it doesn't return anything
#include <stdio.h>
int minimum3(int un, int deux , int trois)
{
int minimum;
if (un<deux && un <trois)
minimum= un;
else if (deux<trois && deux<un)
minimum= deux;
else if (trois<deux && trois<un )
minimum= trois;
return minimum;
}
int main(void) {
minimum3(4,88,8999);
return 0;
}
As others mentioned in the comments, you ignore the returned value, a quick fix for that would be :
int main(void) {
int min = minimum3(4,88,8999);
printf("min: %d\n",min);
return 0;
}
Despite that, your algorithm isn't that effective, as Jonathan mentioned, if 2 of the numbers you process are equal, there is no way to calculate the minimum. The better would,imo, would be to have another function that calculates the minimum of 2 numbers and then use that to compare to the third number. Much cleaner this way.
#include <stdio.h>
int min2(int a,int b)
{
return ((a <= b) ? a : b);
}
int min3(int a,int b,int c)
{
int mintmp = 0;
mintmp = min2(a,b);
return ((mintmp <= min2(mintmp,c)) ? mintmp : min2(mintmp,c));
}
int main(void)
{
printf("%d\n",min2(5,10));
printf("%d\n",min3(5,-1,1));
return 0;
}
You can of course replace the conditional expressions with simpler if else .
I am writing the code to solve the Rod Cut problem but I have been getting Segmentation Fault prompts at run-time. I tried to debug this using gdb and it showed the issue with the recRodCut function. Can anyone please help me find the issue?
#include <stdio.h>
int recRodCut(int* arr, int n)
{
int res;
int i;
if(n==0)
{
return 0;
}
for( i = 0; i< n ; i++)
{
res = max(recRodCut(arr,n) , arr[i]+recRodCut(arr,n-i));
}
return res;
}
int max(int a, int b)
{
return (a<b)?a:b;
}
int main()
{
int value[] = {0,1,5,8,9,10,17,17,20,24,30};
int result = recRodCut(value, 4);
printf("The value is %d \n", result);
}
I'm not seeing a segfault here, but I am seeing an unterminated recursion, which ends up in a stack overflow.
Consider how you are calling your recRodCut():
recRodCut(value, 4);
// i = 0, first iteration:
res = max(recRodCut(value, 4), value[0]+recRodCut(value, 4-0));
As you can see, you are always calling recRodCut with the same arguments. Which means it will never hit if(n==0) and bail early.
By the way, your max() function is actually a min() function :)
I'm having trouble creating a recursive program that multiplies a large number with a single digit number. I understand they're are simpler methods to doing this, but I would like to do it recursively. I provided a SSCCE in the code. The problem is that the multiplication is not occurring correctly. For numbers with more than 1 digit, the program will only multiply the last digit, instead of multiplying the entire number.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *getmem(int len) {
char *ret;
ret = malloc(len);
if (NULL == ret) {
printf("memory allocation failed!\n");
exit (0);
}
else
return ret;
}
void printdigs(char *digs) {
if('0' == digs[0]) {
if (0 == digs[1]){
printf("%s", digs);
return;
}
else printdigs(&digs[1]);
}
else printf("%s",digs);
}
void multi_helper(char *a, char *r, char b, int len, int carry) {
int sum;
if (-1 == len) {
r[0] = (char) (carry + 48);
return;
}
sum = (a[len]-48) * (b-48) +carry;
r[len+1] = (char) ((sum % 10) + 48);
if (sum > 9)
carry = 1;
else carry = 0;
multi_helper(a,r,'0', len-1,carry);
}
char *multi(char *a, char b) {
char *res;
int l = strlen(a);
res = getmem(l + 2);
res[l+1] = 0;
multi_helper(a, res, b, l-1,0);
return res;
}
int main(int argc, char *argv[]) {
char *n1 = "1000";
printf("%s multiplied by 5 is ", n1);
printdigs(multi(n1,"5"));
printf("\n");
return 0;
}
Thanks for any help.
printdigs(multi(n1,"5"));
to
printdigs(multi(n1,'5'));
also need free return value of function multi
multi_helper(a,r,'0', len-1,carry);
to
multi_helper(a,r,b, len-1,carry);
I don't really know what you're looking for (this doesn't use strings to store numbers), but this uses recursion to add a number to itself a certain number of times (multiplication) using recursion for counting how many iterations are left.
int recursive_multiply(a, b) {
if (b==0) {
return 0;
}
char sign = 1;
if (b < 0) {
sign = -1;
b = -b;
}
return (a + recursive_multiply(a, b-1)) * sign;
}
edit: with the updates to the question, it's clear this solution doesn't directly answer the question Ace has, but it may answer questions other people may have when they search for something similar to the question, so I'm going to leave it. If anyone thinks this is wrong, comment and I'll consider removing it if warranted.
While simulating the Colatz Conjecture problem i have made recursion when i want to print the count number in the recursion i get the result i need but when the function return the result it gives me weird numbers, why is that?
#include <stdio.h>
#include <stdlib.h>
int divide(int n,int count){
if(n<=1){printf("%d ",count);return count;}
if(n%2==1){divide(n=3*n+1, ++count);}
else{divide(n/=2, ++count);}
}
int main(void) {
printf("%d ",divide(10,1));
return 0;
}
You don't have any default return. So the return value is undefined.
You need to return the results of the recursive calls:
if (n % 2) { return divide(3 * n + 1, count + 1); }
// %%%%%%
else { return divide(n / 2, count + 1); }
Note that there's no point in assigning to the local variables, so I've changed that to simple computations.
A. you need to return the returned value from the recursion calls.
B. why do you assign a value to n in the calls to divide?
#include <stdio.h>
#include <stdlib.h>
int divide(int n,int count){
if(n<=1){printf("%d ",count);return count;}
if(n%2==1)
{
return divide(3*n+1, ++count);
}
else
{
return divide(n/2, ++count);
}
}
int main(void) {
printf("%d ",divide(10,1));
return 0;
}
I want to write a C function that will print 1 to N one per each line on the stdout where N is a int parameter to the function. The function should not use while, for, do-while loops, goto statement, recursion, and switch statement. Is it possible?
#include <stdlib.h>
int callback(const void *a, const void *b) {
static int n = 1;
if (n <= N)
printf("%d\n", n++);
return 0;
}
int main(int argc, char *argv) {
char *buf;
/* get N value here */
buf = malloc(N); // could be less than N, but N is definitely sufficient
qsort(buf, N, 1, callback);
}
I think it doesn't count as recursion.
With blocking read, signals and alarm. I thought I'd have to use sigaction and SA_RESTART, but it seemed to work well enough without.
Note that setitimer/alarm probably are unix/-like specific.
#include <signal.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
volatile sig_atomic_t counter;
volatile sig_atomic_t stop;
void alarm_handler(int signal)
{
printf("%d\n", counter++);
if ( counter > stop )
{
exit(0);
}
}
int main(int argc, char **argv)
{
struct itimerval v;
v.it_value.tv_sec = 0;
v.it_value.tv_usec = 5000;
v.it_interval.tv_sec = 0;
v.it_interval.tv_usec = 5000;
int pipefds[2];
char b;
stop = 10;
counter = 1;
pipe(pipefds);
signal(SIGALRM, alarm_handler);
setitimer(ITIMER_REAL, &v, NULL);
read(pipefds[0], &b, 1);
}
N is not fixed, so you can't unrole the loop. And C has no iterators as far as I know.
You should find something that mimics the loop.
Or thinking outside the box:
(for example N is limited to 1000, but it is easy to adapt)
int f(int N) {
if (N >= 900) f100(100);
if (N >= 800) f100(100);
if (N >= 700) f100(100);
...
f100(n % 100);
}
int f100(int N) {
if (N >= 90) f10(10);
if (N >= 80) f10(10);
if (N >= 70) f10(10);
...
f(n % 10);
}
int f10(int N) {
if (N >= 9) func();
if (N >= 8) func();
if (N >= 7) func();
...
}
I'd go for using longjmp()
#include <stdio.h>
#include <setjmp.h>
void do_loop(int n) {
int val;
jmp_buf env;
val = 0;
setjmp(env);
printf("%d\n", ++val);
if (val != n)
longjmp(env, 0);
}
int main() {
do_loop(7);
return 0;
}
You can do this by nesting macros.
int i = 1;
#define PRINT_1(N) if( i < N ) printf("%d\n", i++ );
#define PRINT_2(N) PRINT_1(N) PRINT_1(N)
#define PRINT_3(N) PRINT_2(N) PRINT_2(N)
#define PRINT_4(N) PRINT_3(N) PRINT_3(N)
:
:
#define PRINT_32(N) PRINT_31(N) PRINT_31(N)
There will be 32 macros in total. Assuming size of int as 4 bytes. Now call PRINT_32(N) from any function.
Edit:
Adding example for clarity.
void Foo( int n )
{
i = 1;
PRINT_32( n );
}
void main()
{
Foo( 5 );
Foo( 55 );
Foo( 555 );
Foo( 5555 );
}
You can use setjmp and logjmp functions to do this as shown in this C FAQ
For those who are curious to why someone have a question like this, this is one of the frequently asked questions in India for recruiting fresh grads.
write all possible output to a string first, and null terminate it where the output should stop.
this is a rather dirty solution, but given the limitations, all I can think of,
except for using assembler, off course.
char a[]="1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n"/*...*/;
main(n,v)char**v;{n=atoi(v[1]);
#define c(x)(n>x?n-x:0)
a[n+c(1)+c(9)+c(99)+c(999)+c(9999)+c(99999)+c(999999)+c(9999999)/*+...*/]=0;
puts(a);}
Given that MAX_INT==2147483647 on popular architectures, we only need to go up to +c(999999999). Typing out that initial string might take a while, though...
You did not forbid fork().
If you know the upper limit of N you can try something like this ;)
void func(int N)
{
char *data = " 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n10\n11\n12\n";
if (N > 0 && N < 12)
printf("%.*s", N*3, data);
else
printf("Not enough data. Need to reticulate some more splines\n");
}
Joke aside, I don't really see how you can do it without recursion or all the instructions you mentioned there. Which makes me more curious about the solution.
Edit: Just noticed I proposed the same solution as grombeestje :)
This does it:
int main ()
{
printf ("1 to N one per each line\n");
return 0;
}
Here is another one:
#include <stdlib.h>
#include <stdio.h>
int main (int c, char ** v) {
char b[100];
sprintf (b, "perl -e 'map {print \"$_\\n\"} (1..%s)'", v[1]);
system (b);
return 0;
}
Another thingy (on linux) would be to do as below where 7 is N
int main() {
return system("seq 7");
}
This takes the integer N from the command line and prints out from 1 to N
#include <stdio.h>
#include <stdlib.h>
int total;
int N;
int print16(int n)
{
printf("%d\n",n+0x01); total++; if (total >= N) exit(0);
printf("%d\n",n+0x02); total++; if (total >= N) exit(0);
printf("%d\n",n+0x03); total++; if (total >= N) exit(0);
printf("%d\n",n+0x04); total++; if (total >= N) exit(0);
printf("%d\n",n+0x05); total++; if (total >= N) exit(0);
printf("%d\n",n+0x06); total++; if (total >= N) exit(0);
printf("%d\n",n+0x07); total++; if (total >= N) exit(0);
printf("%d\n",n+0x08); total++; if (total >= N) exit(0);
printf("%d\n",n+0x09); total++; if (total >= N) exit(0);
printf("%d\n",n+0x0A); total++; if (total >= N) exit(0);
printf("%d\n",n+0x0B); total++; if (total >= N) exit(0);
printf("%d\n",n+0x0C); total++; if (total >= N) exit(0);
printf("%d\n",n+0x0D); total++; if (total >= N) exit(0);
printf("%d\n",n+0x0E); total++; if (total >= N) exit(0);
printf("%d\n",n+0x0F); total++; if (total >= N) exit(0);
printf("%d\n",n+0x10); total++; if (total >= N) exit(0);
}
int print256(int n)
{
print16(n);
print16(n+0x10);
print16(n+0x20);
print16(n+0x30);
print16(n+0x40);
print16(n+0x50);
print16(n+0x60);
print16(n+0x70);
print16(n+0x80);
print16(n+0x90);
print16(n+0xA0);
print16(n+0xB0);
print16(n+0xC0);
print16(n+0xD0);
print16(n+0xE0);
print16(n+0xF0);
}
int print4096(int n)
{
print256(n);
print256(n+0x100);
print256(n+0x200);
print256(n+0x300);
print256(n+0x400);
print256(n+0x500);
print256(n+0x600);
print256(n+0x700);
print256(n+0x800);
print256(n+0x900);
print256(n+0xA00);
print256(n+0xB00);
print256(n+0xC00);
print256(n+0xD00);
print256(n+0xE00);
print256(n+0xF00);
}
int print65536(int n)
{
print4096(n);
print4096(n+0x1000);
print4096(n+0x2000);
print4096(n+0x3000);
print4096(n+0x4000);
print4096(n+0x5000);
print4096(n+0x6000);
print4096(n+0x7000);
print4096(n+0x8000);
print4096(n+0x9000);
print4096(n+0xA000);
print4096(n+0xB000);
print4096(n+0xC000);
print4096(n+0xD000);
print4096(n+0xE000);
print4096(n+0xF000);
}
int print1048576(int n)
{
print65536(n);
print65536(n+0x10000);
print65536(n+0x20000);
print65536(n+0x30000);
print65536(n+0x40000);
print65536(n+0x50000);
print65536(n+0x60000);
print65536(n+0x70000);
print65536(n+0x80000);
print65536(n+0x90000);
print65536(n+0xA0000);
print65536(n+0xB0000);
print65536(n+0xC0000);
print65536(n+0xD0000);
print65536(n+0xE0000);
print65536(n+0xF0000);
}
int print16777216(int n)
{
print1048576(n);
print1048576(n+0x100000);
print1048576(n+0x200000);
print1048576(n+0x300000);
print1048576(n+0x400000);
print1048576(n+0x500000);
print1048576(n+0x600000);
print1048576(n+0x700000);
print1048576(n+0x800000);
print1048576(n+0x900000);
print1048576(n+0xA00000);
print1048576(n+0xB00000);
print1048576(n+0xC00000);
print1048576(n+0xD00000);
print1048576(n+0xE00000);
print1048576(n+0xF00000);
}
int print268435456(int n)
{
print16777216(n);
print16777216(n+0x1000000);
print16777216(n+0x2000000);
print16777216(n+0x3000000);
print16777216(n+0x4000000);
print16777216(n+0x5000000);
print16777216(n+0x6000000);
print16777216(n+0x7000000);
print16777216(n+0x8000000);
print16777216(n+0x9000000);
print16777216(n+0xA000000);
print16777216(n+0xB000000);
print16777216(n+0xC000000);
print16777216(n+0xD000000);
print16777216(n+0xE000000);
print16777216(n+0xF000000);
}
int print2147483648(int n)
{
/*
* Only goes up to n+0x70000000 since we
* deal only with postive 32 bit integers
*/
print268435456(n);
print268435456(n+0x10000000);
print268435456(n+0x20000000);
print268435456(n+0x30000000);
print268435456(n+0x40000000);
print268435456(n+0x50000000);
print268435456(n+0x60000000);
print268435456(n+0x70000000);
}
int main(int argc, char *argv[])
{
int i;
if (argc > 1) {
N = strtol(argv[1], NULL, 0);
}
if (N >=1) {
printf("listing 1 to %d\n",N);
print2147483648(0);
}
else {
printf("Must enter a postive integer N\n");
}
}
int x=1;
void PRINT_2(int);
void PRINT_1(int n)
{ if(x>n)
return;
printf("%d\n",x++);
PRINT_2(n);
}
void PRINT_2(int n)
{ if(x>n)
return;
printf("%d\n",x++);
PRINT_1(n);
}
int main()
{ int n;
scanf("%d",&n);
if(n>0)
PRINT_1(n);
system("pause");
}
#include "stdio.h"
#include "stdlib.h"
#include "signal.h"
int g_num;
int iterator;
void signal_print()
{
if(iterator>g_num-1)
exit(0);
printf("%d\n",++iterator);
}
void myprintf(int n)
{
g_num=n;
int *p=NULL;
int x= *(p); // the instruction is reexecuted after handling the signal
}
int main()
{
signal(SIGSEGV,signal_print);
int n;
scanf("%d",&n);
myprintf(n);
return 0;
}
I'm very disappointed that this doesn't work. To me, the phrase "a function is called after any previously registered functions that had already been called at the time it was registered" suggests that it is possible to register atexit handlers after they have started to be called. That is, a handler can register another handler. Otherwise, how is it even possible for there to exist a function which has been called at the time another function is registered? But for me the call to atexit is returning 0 success, but not actually resulting in another call. Anyone know why, have I made some silly error?
#include "stdio.h"
#include "stdlib.h"
int count = 0;
int limit = 10;
void handler() {
printf("%d of %d\n", ++count, limit);
if (count < limit) atexit(handler);
}
int main(int argc, char **argv) {
if (argc > 1) limit = atoi(argv[1]);
atexit(handler);
}
By the way, not recursion because atexit doesn't call its parameter, it queues it to be called later. Obviously the C runtime contains a loop to call atexit handlers, but that loop exists whether you actually register any atexit handlers or not. So if this program contains a loop, so does every C program ;-)
/// <summary>
/// Print one to Hundred without using any loop/condition.
/// </summary>
int count = 100;
public void PrintOneToHundred()
{
try
{
int[] hey = new int[count];
Console.WriteLine(hey.Length);
count--;
PrintOneToHundred();
}
catch
{
Console.WriteLine("Done Printing");
}
}