help with my recursive program..

Write a program containing the recursive function that will find the following series of numbers 2, 1, 4, 3, 6?
*c program


#include<stdio.h>

main( )
{
int a, b;
printf("Enter a value:");
scanf("%d", &a);
b = solve(a);
printf("The new value is %d", b);
getch( );
}

solve(int a)
{
int b;
if (a == 1)
{
b = 1;
printf("%d", b);
return b;
}
else
{
b = solve2 (a-1) + 2;
printf("%d", b);
return b;
}
}

solve2(int a)
{
int b;
if (a == 1)
{
b = 1;
printf("%d", b);
return b;
}
else
{
b = solve (a-1) + 2;
printf("%d", b);
return b;
}
}


i have this program but it only shows odd numbers like 1,3,5,7...
how do i make it 2,1,4,3,6,7...?

i know the general term of the sequence is a-(-1)^a
but whenever i use that to solve the program exits.

need help >.<
The power function is named pow and it lives in math.h

Alternatively, since you're using integers and it's quite simple, write your own power function.

"^" does not mean "to the power of" in C. It means "bitwise XOR"
Last edited on
thanks for the informative answer but when i change b = solve (a-1) + 2; into
b = solve (a - pow(-1,a));
it wont work..

>.< sorry im just a beginner..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<stdio.h>
#include<math.h>

main( )
{	
	int a, b;
	printf("Enter a value:");
	scanf("%d", &a);
	b = solve(a);
	getch( ); 
}

solve(int a)
{
	int b;
	if (a == 1) 
	{
		b = 2;
		printf("%d", b);
		return b;
	}
	else
	{
		b = solve2 (a - pow(-1,a));
		printf("%d",b);
		return b;
	}
}

solve2(int a)
{
	int b;
	if (a == 1) 
	{
		b = 2;
		printf("%d", b);
		return b;
	}
	else
	{
		b = solve (a - pow(-1,a));
		printf("%d",b);
		return b;
	}
}


the program doesn't exit now but instead of having the output 2,1,4,3,6,5,8,7...
it shows 2 if i input a=1
1 if i input a=2
4 if i input a=3
and so on

but i need the whole series in the output.. >.< how do i do it?
Topic archived. No new replies allowed.