C: Looping without using looping statements or recursion - c

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");
}
}

Related

Print a number converted in base 2 recursively

So I've been trying to do this but I just can't think of a solution for this. I've got this bit of code but it outputs it backwards(if the answer is 11110 I get 01111):
#include <stdio.h>
int base(int n)
{
if(n==0)
return 0;
else
{
printf("%d",n%2);
}
return base(n/2);
}
int main() {
int n;
scanf("%d",&n);
base(n);
return 0;
}
Is there any trick for this problem or do I need to analyze this deeper?
As #rici stated, a very simple fix is to print after the recursive call:
#include <stdio.h>
void base(int n){
if(n==0)
return;
base(n/2);
printf("%d",n%2);
}
int main() {
int n;
scanf("%d",&n);
base(n);
return 0;
}
I would use a mask:
#include <stdio.h>
int base(int n, int mask){
if(!mask) {
printf("\n"); // we reach the end, print a line return
return 0;
}
printf("%d", !!(n & mask)); // if mask and n match, print '1', else print '0'. !! convert any value into 1, and 0 remains 0.
return base(n, mask >> 1); // divide mask by 2, check the next bit on the right
}
int main() {
int n;
scanf("%d",&n);
base(n, 1 << (31 - __builtin_clz(n))); // call the function with a mask initialized at the same level than the most important bit of n.
return 0;
}

Can someone help me with a C programming task?

I need to write a program which would take a number of any length, would put its digits in opposite order (for example from 12365 would make 56321) and check if those two numbers can be divided from all its digits. If both numbers can be divided from every digit then program should output both numbers: the given one and the opposite one. For now My program can only reverse that number.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i, m, n, atb = 0, nr = 1, skait = 0, j;
printf("Iveskite intervalo pradzia ir pabaiga:\n");
scanf("%d", &m);
scanf("%d", &n);
//---
for(i = m; i <= n; i++)
{
int temp = i;
int dalys[skait];
do
{
atb = atb*10 + temp%10;
dalys[skait] = temp;
temp = temp / 10;
skait++;
}
while (temp != 0);
//-------------------------------------------
for(j = 1; j <= skait; j++){
int dal = pow(10,(skait-1));
}
//-------------------------------------------
printf("\n%d skaicius: %d", nr, atb);
printf("\nSkaicius susideda is %d skaitmenu.", skait);
atb=0;
skait=0;
nr++;
}
return 0;
}
I already started to try to solve the division part... but I cant find how to make the program take every digit and make it check that division part...
I've written also this version! I think is better of the previous! This solution uses a vector smaller than the version in the other reply and it doesn't make useless divisions! :) Furthermore the function compute() returns 1 if the condition requested are verified (0 elsewhere), then you may easily move the final printf out of the function in the main!
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define SEESTEPS
#ifdef SEESTEPS
#define Dprintf(a...) printf(a);
#else
#define Dprintf(a...) ;
#endif
int compute(uint64_t x,int zeroGo)
{
uint64_t y,z,t;
int div[10];
int cntdiv,i;
for(i=0;i<10;i++)
div[i]=0;
z=x;y=0;cntdiv=0;
while(z) {
t=(z%10);
if (!div[t]) {
cntdiv++;
div[t]=1;
}
y*=10;y+=t;
z/=10;
}
Dprintf("%lu => Inverted %lu\n",x,y);
if (zeroGo || !div[0]) {
t=div[0];
for(i=1;i<10;i++) {
if (!div[i])
continue;
Dprintf("%lu mod %d = %lu\n",x,i,x%i );
if ( (x%i) )
break;
Dprintf("%lu mod %d = %lu\n",y,i,y%i );
if ( (y%i) )
break;
t++;
}
} else {
t=cntdiv-1;
}
//Dprintf("%d %d -",cntdiv,t);
if ((int)t==cntdiv) {
printf("%lu %lu\n",x,y);
return 1;
}
return 0;
}
int main(void) {
uint64_t f,t;
int cnt=0;
printf("From...: ");
scanf("%lu",&f);
printf("To.....: ");
scanf("%lu",&t);
for(;f<=t;f++)
cnt+=compute(f,1);
printf("%d\n",cnt);
return 0;
}
Try this! It should be run as you require! If you comment the code #define SEESTEPS the code prints only the required result! This code computes only one number at time, you may transform it in a function!!!
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define SEESTEPS
#ifdef SEESTEPS
#define Dprintf(a...) printf(a);
#else
#define Dprintf(a...) ;
#endif
int main(void) {
uint64_t x,y,z;
uint64_t div[20];
int cntdiv,i;
scanf("%lu",&x);
/* This inverts the number and computes the digit */
z=x;y=0;cntdiv=0;
while(z) {
div[cntdiv]=(z%10);
y*=10;y+=div[cntdiv];
z/=10;cntdiv++;
}
Dprintf("Inverted %lu\n",y);
/* This verifies the divisibility! */
for(i=0;i<cntdiv;i++) {
if (!div[i])
continue; /* Or break; if you prefer */
Dprintf("%lu mod %lu = %lu\n",x,div[i],x%div[i] );
if ( (x%div[i]))
break;
Dprintf("%lu mod %lu = %lu\n",y,div[i],y%div[i] );
if ( (y%div[i]))
break;
}
if (i==cntdiv)
printf("%lu %lu",x,y);
return 0;
}

Multiplying a large number in C with a single digit number recursively?

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.

Program to print the binary equivalent of a number without using format specifiers

Jus check out this program.Logically it seems fine but its giving 000000000000000000000 for everything
#include<stdio.h>
void main()
{
int n=25,k=32;
printf("binary equivalent\n");
while(k!=0)
{
if((n>>1&0x01)!=0)
printf("1");
else
printf("0");
k--;
}
}
You don't ever change n.
Don't try and cram everything into one line, be a little more verbose so that things are clearer.
while(k!=0)
{
if((n & 0x01) != 0)
printf("1");
else
printf("0");
k--;
n >>= 1;
}
That is because you don't change n.
For n=25 we have (n>>1)=12 hence it prints zero. And since you don't change n it prints zero for all k.
You can change it in the following way:
#include
void main()
{
int n=25,k=32;
printf("binary equivalent\n");
while(k!=0)
{
if((n & 0x01)!=0)
printf("1");
else
printf("0");
k--;
n = n >> 1;
}
}
However it will print binary presentation in reversed form.
Your n is never getting changed:
if((n>>1&0x01)!=0)
should be
if(n & 0x01)
and add
n>>=1; after k--;
Also this will produce the binary representation in reverse order.
You are not modifying n - every time you compare 0x01 with second bit on n.
You don't change the value of n within the loop. And probably you want to test the least significant bit before shifting.
/*
* Author: Andrey Vlassov
* Date: Thu Apr 19 03:10:49 UTC 2012
*
* Description:
* An expample program demonstrating how
* to convert decimal integer number to
* binary representation
*
* NOTE:
* For simplicity additional check left out
*
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char help[] = ">>> Please provide an integer number as argument!!!";
char id[] = "d2b (c) Andrey Vlassov Apr 18, 2012 8:15PM PST";
if( argc < 2 ) {
printf("%s\n", help);
exit(0);
}
printf("\n%s\n\n", id);
int n = atoi(argv[1]);
int i, bites, bits, mask;
printf("Number is %d\n", n);
printf("size: %d bites\n", bites=sizeof(n));
printf("dec: %d\n", n);
printf("hex: %#x\n", n);
printf("oct: %#o\n", n);
printf("bin: b");
bits = bites*8-1;
mask = 0x01 << (bits-1);
for( i=0; i<bits; i++) {
printf("%d", ( n & mask ? 1 : 0 ) );
mask >>= 1;
}
printf("\n\n");
exit(0);
}
i think it will help the result is the same as other poster posted
#include<stdio.h>
int main()
{
int n=25;
int k=32;
printf("binary equivalent\n");
for (int i=0;i<32;i++){
if((n&1)!=0)
printf("1");
else
printf("0");
n>>=1;
}
}
as #falagar said result will be printed in reverse order
// how to print binary number representation of an integer
// using bitwise operators
//
// oon
// 18.04.2013
// Refs
// http://www.cs.northwestern.edu/~wms128/bits.c
// http://www.cs.cmu.edu/~guna/15-123S11/
#include <stdio.h>
#define no_of_bits_in_a_byte 8
#define get_bit(w,i) ((w>>i)&1)
void print_binary(signed int x);
int main()
{
print_binary(2); // 00000000000000000000000000000010
print_binary(-2); // 11111111111111111111111111111110
return 0;
}
void print_binary(signed int x)
{
int i;
int no_of_bytes = sizeof(x);
for (i=no_of_bytes*no_of_bits_in_a_byte-1; i>=0; i--) {
printf("%d",get_bit(x,i));
}
printf("\n");
}
/*
* print_binary2.c
*
* oon
*
* 19.04.2013
*/
// http://www.cs.northwestern.edu/~wms128/bits.c
// http://www.cs.cmu.edu/~guna/15-123S11/
#include <stdio.h>
#define no_of_bits_in_a_byte 8
#define get_bit(w,i) ((w>>i)&1)
void print_binary2(signed int x, unsigned int n);
int check_bits_fit_in_2s_complement(signed int x, unsigned int n);
void main()
{
print_binary2(2,2); // output: The signed integer 2 cannot be represented by 2 bit(s) in two complements form.
print_binary2(2,3); // output: 010
print_binary2(-2,2); // output: 10
print_binary2(-2,3); // output: 110
}
int check_bits_fit_in_2s_complement(signed int x, unsigned int n) {
int mask = x >> 31;
return !(((~x & mask) + (x & ~mask))>> (n + ~0));
}
void print_binary2(signed int x, unsigned int n)
{
// check if x can be represented by n bits in two's complement form.
if (check_bits_fit_in_2s_complement(x,n)) {
int i;
for (i=n-1; i>=0; i--) {
printf("%d",get_bit(x,i));
}
printf("\n");
} else {
printf("The signed integer %d cannot be represented by %u bit(s) in two complements form.\n",x,n);
}
}
The above code shows how to print binary number in two's complement form where n denotes the number of bits.
int binary(int n)
{
if(n/2)
binary(n/2);
printf("%d",n%2);
}
void main()
{
int n;
printf("enter any number");
scanf("%d",&n);
binary(n):
getch();
}
Try this!
#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<int> st;
int n=25, k=32;
while(k!=0){
if((n&0x01)!=0)
st.push(1);
else
st.push(0);
k--;
n=n>>1;
}
while(!st.empty()){
cout<<st.top();
st.pop();
}
}

Calculating Fibonacci Numbers Recursively in C

I'm trying to learn C by writing a simple program to output Fibonacci numbers. It isn't working.
fibonacci.h
unsigned int fibonacci_recursive(unsigned int n);
fibonacci.c
#include <stdio.h>
#include "fibonacci.h"
main() {
unsigned int i;
for (i = 0; i < 10; i++) {
printf("%d\t%n", fibonacci_recursive(i));
}
getchar();
}
fibonacci_recursive.c
unsigned int fib_rec(unsigned int n);
main(unsigned int n) {
return fib_rec(n);
}
unsigned int fib_rec(unsigned int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fib_rec(n - 1) + fib_rec(n - 2);
}
This is the error message VS 2010 gives me when I try to build the project:
1>ClCompile:
1> fibonacci_recursive.c
1>fibonacci_recursive.obj : error LNK2005: _main already defined in fibonacci.obj
1>fibonacci.obj : error LNK2019: unresolved external symbol _fibonacci_recursive referenced in function _main
1>c:\users\odp\documents\visual studio 2010\Projects\Fibonacci\Debug\Fibonacci.exe : fatal error LNK1120: 1 unresolved externals
1>
1>Build FAILED.
1>
What am I doing wrong here? Thanks for helping someone new to C.
Your approach seems strange, you should have:
a main file (example main.c) with the main method and that includes fibonacci.h
a fibonacci.h with the prototype unsigned int fibonacci_recursive(unsigned int n);
a fibonacci.c with the implementation of the method, and it should include fibonacci.h too
Actually you define main function twice too..
main.c
#include <stdio.h>
#include "fibonacci.h"
main()
{
unsigned int i;
for (i = 0; i < 10; i++)
{
printf("%d\t%n", fibonacci_recursive(i));
}
getchar();
}
fibonacci.h
unsigned int fibonacci_recursive(unsigned int n);
fibonacci.c
#include "fibonacci.h"
unsigned int fibonacci_recursive(unsigned int n)
{
if (n == 0)
{
return 0;
}
if (n == 1) {
return 1;
}
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}
You have the main() function defined twice in your project. This is the entry point of your program, and you only need one.
You need \n not %n for your printf. Also, you can simplify as:
#include "fibonacci.h"
unsigned int fibonacci_recursive(unsigned int n) {
if (n < 2)
return n;
else
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}
You haven't created a fibonacci_recursive function that you declared in fibonacci.h.
You declared two main() functions, and the new line character is '\n'.
Well, I preface that recursive function is not an efficient method to calculate Fibonacci and it may be used for dev training/demonstrations purposes only, because every recursion is stored in stack, and it may also overflow for large fibonacci numbers.
It is rather worth the effort to write down a more efficient Fibonacci function that uses a loop, like following code:
#include <stdio.h>
#define MAX_ITERS 20
int fibonacci(int);
int main(int argc, char *argv[])
{
unsigned int iters;
if(argc>1) {
iters=atoi(argv[1]);
} else
iters=MAX_ITERS;
fibonacci(iters);
return 0;
}
int fibonacci(int iterations)
{
unsigned register int i;
double first=0.0, second = 1.0, lastsum;
printf("First %d iterations of Fibonacci series are :\n",iterations);
for ( i = 0 ; i < iterations ; i++ )
{
if ( i <= 1 )
lastsum = (double)i;
else
{
lastsum = first + second;
first = second;
second = lastsum;
}
printf("%.0f\n",lastsum);
}
}
Try to compare by your own, running ./fibonacci 50 with this method, for instance on a low cost processor (eg. on a Raspberry PI), and the one with the recursive functions and 50 first numbers as well, and see the difference! ,-)

Resources