I want to find the sum of all the digits entered by a user after the decimal point in c.
Eg. 12.36 must return 9
15.06 must return 6
9.0 must return 0
My approach
#include <stdio.h>
int main()
{
double num,numfloat;
int digitf,numint,sumf=0;
scanf("%lf",&num);
numint=num;
numfloat=num-numint;
while(numfloat!=0)
{
digitf=(numfloat*10);
numfloat=numfloat*10-digitf;
sumf=sumf+digitf;
}
printf("Sum float %d",sumf);
return 0;
}
The sum comes out a lot more than the expected.
Try, (The reason why in this example, I haven't joined the loops is that: I want this to be usable on other situations where they use an alternate method of validating input, see the SECOND EXAMPLE for both loops joined):
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
// read from stdin
char num[512] = { };
fgets(num, sizeof(num), stdin);
num[strcspn(num, "\n")] = '\0';
// verify if number is valid
int decimal_point_found = 0;
for (int i = 0; i < strlen(num); i++) {
// check if digit
if (!isdigit(num[i])) {
// be safe from multiple decimal points
if (num[i] == '.' && decimal_point_found == 0) {
decimal_point_found = 1;
continue;
}
printf("ERROR: enter a valid number\n");
return 1;
}
}
int total = 0;
// add all the decimal points
for (int i = 0, decimal_point_found = 0; i < strlen(num); i++) {
if (decimal_point_found == 1) {
total += num[i] - '0'; // - '0' converts char to int
}
if (num[i] == '.') {
decimal_point_found = 1;
}
}
// show total
printf("%d\n", total);
}
In the above, I have read char instead of reading float. I have read using fgets() which is safer than scanf().
Handling char makes it so much easier to calculate such things. As we know the number of digits, etc.
With both loops joined:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char num[512] = { };
fgets(num, 512, stdin);
num[strcspn(num, "\n")] = '\0';
// verify if number is valid
int decimal_point_found = 0;
int total = 0;
for (int i = 0; i < strlen(num); i++) {
if (!isdigit(num[i])) {
if (num[i] == '.' && decimal_point_found == 0) {
decimal_point_found = 1;
continue;
}
printf("ERROR: enter a valid number\n");
break;
}
if (decimal_point_found == 1) {
total += num[i] - '0';
}
}
printf("%d\n", total);
}
Original code fails as unless the fraction if exactly an integer/power-of-2, the input number, as decimal text, does not convert exactly to the same double. Instead num is the closet double possible. Yet that closest double may have many more digits when manipulated.
Further OP's numfloat=numfloat*10-digitf; injects repeated rounding errors.
Instead code needs to compensate for that rounding in some fashion.
the input has to be a number
Hmm, better to read in as a string, yet we can code a tolerable solution if we know the length of input by using "%n" to record the length of user input.
width below is the number of non-white-space characters in input. If we assume things like 1) sign only when negative, 2) no exponential 3) not infinity nor NAN, 4) no more than 15 significant digits 5) no more than 15 fraction digits --> then width will almost always*1 gives us what is needed to process num.
#include<stdio.h>
#include<math.h>
int sumFraction(void) {
int sum = 0;
double num;
int start, end;
if (scanf(" %n%lf%n", &start, &num, &end) != 1) {
return -1;
}
if (num == 0) {
return 0;
}
int width = end - start;
if (num < 0) {
num = -num;
width--;
}
int p10 = (int) log10(num);
width--; // Decrement for the '.'
if (width > 15) {
printf("Too many leading digits\n");
return -1;
}
width -= (p10 + 1);
// Only care about fractional part
double ipart;
num = modf(num, &ipart);
if (num == 0) {
return 0;
}
// assert(width >= 0);
num *= pow(10, width);
long long ival = llround(num); // Form an integer
while (width > 0) {
width--;
sum += ival % 10;
ival /= 10;
}
return sum;
}
int main() {
printf(" %d\n", sumFraction());
printf(" %d\n", sumFraction());
printf(" %d\n", sumFraction());
}
*1 IMO, code is not robust as the given limitation of not reading in as a string is not real for the real world. So here is a non-real solution.
You mentioned in a comment that the input has to be a number.
This first point to mention is that when coding, we are not manipulating such abstract things as numbers,
but imperfection representations of numbers. Think to the famous painting "This is not a pipe".
Same here, "This is not a number".
float, double and char* are all or can be all representations of numbers.
Depending on the context, one representation can be more suitable than others. Here, using a char* is the best solution, has no internal conversion error occurs.
Now, let us assume that the input format double is imposed by your professor.
Why is your code not working? Mainly because internally, the representation of the numbers is generally imperfect.
A small error can lead to a large error when converting a float to an integer.
For example, int i = 0.999999 will give i = 0.
The solution is to account for the internal error representation, by introducing a margin, e.g. eps = 1.0e-14,
when performing the float-to-integer conversion, or when testing if a number is equal to 0.
A difficulty is that the internal error is multiplied by 10 when the number is multiplied by 10. So the value of epshas to be updated accordingly.
Moreover, we have to take into accout that the mantissa provides a relative accurracy only, not an absolute one.
Therefore, the eps value must be increased when the number is large.
0.123456789 --> 45
19.1 -> 1
12.45e-36 -> 12
12345.973 -> 19
0.83 -> 11
#include <stdio.h>
int main() {
double num, numfloat;
int digitf, numint, sumf = 0;
double eps = 1.0e-14; // to deal with representation inaccuracy of numbers
if (scanf("%lf", &num) != 1) return 1;
printf("number in memory: %.20g\n", num);
if (num < 0.0) num = -num;
numint = (int) (num + eps);
numfloat = num - numint;
int deal_with_low_number = numint == 0;
while (numint) { // the mantissa only proposes a relative accurracy ...
eps *= 10;
numint /= 10;
}
while (numfloat > eps || deal_with_low_number) {
numfloat *= 10;
digitf = (int) (numfloat + eps);
numfloat -= digitf;
sumf = sumf + digitf;
if (digitf != 0) deal_with_low_number = 0;
if (!deal_with_low_number) eps *= 10;
}
printf("Sum float %d\n", sumf);
return 0;
}
Related
#include <stdio.h>
#include <stdlib.h>
#define TEN 10
int main ()
{
int number = 0;
int digit = 0;
int last_digit = 0;
int digit_sum = 0;
int i = 0;
while (i == 0)
{
printf("Please Enter A Positive Number! \n"); //explaining
scanf("%d",&number);
if (number > 0)
{
i++;
}
}
while (number > 0)
{
digit = number % TEN; //breaking number into digits
number /= TEN;
if (last_digit != digit) //comparing digits
{
last_digit = digit;
digit_sum += digit;
}
}
printf("The Sum Of The Digits Is : %d",digit_sum);
return 0;
}
the code will divide the number into digits and check if there are duped digits, in case there are, only one of them will be calculated for exmple: 3211
3+2+1, but my problem is thats the code wont work with numbers like 31211 Im thankful for any kind of help.
The code doesn't work because there is no guarantee that duplicate's will appear consecutive manner. your code handles that not the other ways. That's why it fails.
A simple solution would be to consider a 10 element array where you will keep count of which element appeared and which didn't.
The idea is to map the digits to the array indices of the 10 element array. Intialized with 0.
...
int digitAppeared[10]={0};
while (number)
{
digit = number % TEN; //breaking number into digits
number /= TEN;
digit_sum += (1 - digitAppeared[digit]) * digit;
digitAppeared[digit] = 1;
}
...
To give you a clear idea this line basically checks whether the element appeared or not and as per the result it will add the digit.
If digit D appeared then digitAppeared[D]=1
and if it didn't then digitAppeared[D]=0.
We will add it to digitsum if it appears first time. That's why the (1-digitAppeared[D]) will tell us whether to add it or not.
digit_sum += (1 - digitAppeared[digit]) * digit;
Convert the number to string use itoa() . sort it and then walk through it , looking for unique number and do your calculation
You can mark which digits were already added by using setting logical flags as represented by done in program below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TEN 10
int main ()
{
int number = 0;
int digit = 0;
int last_digit = 0;
int digit_sum = 0;
int i = 0;
int done[10];
while (i == 0)
{
printf("Please Enter A Positive Number! \n"); //explaining
scanf("%d",&number);
if (number > 0)
{
i++;
}
}
memset(done,0,sizeof(done));
while (number > 0)
{
digit = number % TEN; //breaking number into digits
number /= TEN;
if(done[digit] == 0)
{
digit_sum += digit;
done[digit] = 1;
}
}
printf("The Sum Of The Digits Is : %d",digit_sum);
return 0;
}
I have to write a program that finds every number (except 0) which can be factored by numbers from 2-9.
For example first such a number would be number 2520 as it can be divided by every single number from 2 to 9.
It also has to be a number that contains only 1 type of digit of its own (no multiple digits in a number). So for example 2520 will not meet this requirement since there are two same digits (2). The example of a number that meets both requirements is number 7560. That is the point I don't how to do it. I was thinking about converting value in an array to string, and then putting this string in another array so every digit would be represented by one array entry.
#include <stdio.h>
#include <math.h>
int main() {
int i, n, x, flag, y = 0;
scanf("%d", &n);
double z = pow(10, n) - 1;
int array[(int)z];
for (i = 0; i <= z; i++) {
flag = 0;
array[i] = i;
if (i > 0) {
for (x = 2; x <= 9; x++) {
if (array[i] % x != 0) {
flag = 1;
}
}
if (flag == 0) {
y = 1;
printf("%d\n", array[i]);
}
}
}
if (y == 0) {
printf("not exist");
}
return 0;
}
This should give you a base:
#include <stdio.h>
#include <string.h>
int main()
{
char snumber[20];
int number = 11235;
printf("Number = %d\n\n", number);
sprintf(snumber, "%d", number);
int histogram[10] = { 0 };
int len = strlen(snumber);
for (int i = 0; i < len; i++)
{
histogram[snumber[i] - '0']++;
}
for (int i = 0; i < 10; i++)
{
if (histogram[i] != 0)
printf("%d occurs %d times\n", i, histogram[i]);
}
}
Output:
Number = 11235
1 occurs 2 times
2 occurs 1 times
3 occurs 1 times
5 occurs 1 times
That code is a mess. Let's bin it.
Theorem: Any number that divides all numbers in the range 2 to 9 is a
multiple of 2520.
Therefore your algorithm takes the form
for (long i = 2520; i <= 9876543210 /*Beyond this there must be a duplicate*/; i += 2520){
// ToDo - reject if `i` contains one or more of the same digit.
}
For the ToDo part, see How to write a code to detect duplicate digits of any given number in C++?. Granted, it's C++, but the accepted answer ports verbatim.
If i understand correctly, your problem is that you need to identify whether a number is consisted of multiple digits.
Following your proposed approach, to convert the number into a string and use an array to represent digits, i can suggest the following solution for a function that implements it. The main function is used to test the has_repeated_digits function. It just shows a way to do it.
You can alter it and use it in your code.
#include <stdio.h>
#define MAX_DIGITS_IN_NUM 20
//returns 1 when there are repeated digits, 0 otherwise
int has_repeated_digits(int num){
// in array, array[0] represents how many times the '0' is found
// array[1], how many times '1' is found etc...
int array[10] = {0,0,0,0,0,0,0,0,0,0};
char num_string[MAX_DIGITS_IN_NUM];
//converts the number to string and stores it in num_string
sprintf(num_string, "%d", num);
int i = 0;
while (num_string[i] != '\0'){
//if a digit is found more than one time, return 1.
if (++array[num_string[i] - '0'] >= 2){
return 1; //found repeated digit
}
i++;
}
return 0; //no repeated digits found
}
// test tha function
int main()
{
int x=0;
while (scanf("%d", &x) != EOF){
if (has_repeated_digits(x))
printf("repeated digits found!\n");
else
printf("no repeated digits\n");
}
return 0;
}
You can simplify your problem from these remarks:
the least common multiple of 2, 3, 4, 5, 6, 7, 8 and 9 is 2520.
numbers larger than 9876543210 must have at least twice the same digit in their base 10 representation.
checking for duplicate digits can be done by counting the remainders of successive divisions by 10.
A simple approach is therefore to enumerate multiples of 2520 up to 9876543210 and select the numbers that have no duplicate digits.
Type unsigned long long is guaranteed to be large enough to represent all values to enumerate, but neither int nor long are.
Here is the code:
#include <stdio.h>
int main(void) {
unsigned long long i, n;
for (n = 2520; n <= 9876543210; n += 2520) {
int digits[10] = { 0 };
for (i = n; i != 0; i /= 10) {
if (digits[i % 10]++)
break;
}
if (i == 0)
printf("%llu\n", n);
}
return 0;
}
This program produces 13818 numbers in 0.076 seconds. The first one is 7560 and the last one is 9876351240.
The number 0 technically does match your constraints: it is evenly divisible by all non zero integers and it has no duplicate digits. But you excluded it explicitly.
I need to write a C program which will read a number (in base 10) from user input and output it in any base which is a power of 2. The calculations have to be performed in one function, to_base_n, which takes the parameters num and base and prints the number in the respective base. As a validation check, the program also checks if the base is a power of two with the isPowerofTwo function.
The way the conversion is carried out is by means of long division which carries out the logic in the pseudocode below:
void to_base_n(int x, int n){
int r, i = 0
int digits[16]
while (x ≠ 0){
r = x mod n
x = x / n
digits[i] = r
i++
}
for (i = 0, i < 15, i++)
print digits[i]
}
Which I believe is arithmetically sound. But when I try to, for example, convert 82000 to base 4, I get the following output:
The large digits appearing are even bigger than num itself, so I figured the modulus cannot be entering the array properly (because ∀{x,n}; x mod n < x). I can't seem to find what's wrong with it. The full code is listed below.
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
bool isPowerofTwo(int);
void to_base_n(int, int);
int main(){
//Variables
int num, base;
//Prompt
printf("Please enter a number in base 10: ");
scanf("%d", &num);
printf("Please enter a base (2^n) to convert it to: ");
scanf("%d", &base);
//Precaution
while(!isPowerofTwo(base)){
printf("That number is not a power of 2. Please try again: ");;
scanf("%d", &base);
}
if(isPowerofTwo(base)){
//Output
printf("The number %d (base 10) is equivalent to ", num);
to_base_n(num, base);
printf(" (base %d).", base);
}
//Return Statement
return 0;
}
//Checks if Base is a Power of Two
bool isPowerofTwo(int base){
while((base % 2 == 0) && base > 1){
base = base / 2;
if(base == 1){
return true;
break;
}
}
return false;
}
//to_base_n
void to_base_n(int x, int n){
int r, i = 0;
int digits[16];
while(x != 0){
r = x % n;
x = x / n;
digits[i] = r;
i++;
}
for(i = 0; i < 15; i++)
printf("%d|",digits[i]);
}
Can anyone help explain what's wrong with it?
The number 82000 in base 4 would be:
110001100
Which is exacly what you get. Your mistake is that:
They are printed backwards.
You are printing more digits than you should, so you print garbage.
You ignore the number of digits extracted with your pseudo code, so you print uninitialised elements of the array.
for (i = 0, i < 15, i++)
print digits[i]
And they are printed in reverse order. I suggest changing it to this
for (i = i - 1, i >= 0, i--)
print digits[i]
and as C code in your function
for(i = i - 1; i >= 0; i--)
printf("%d|",digits[i]);
I have a problem, then given some input number n, we have to check whether the no is factorial of some other no or not.
INPUT 24, OUTPUT true
INPUT 25, OUTPUT false
I have written the following program for it:-
int factorial(int num1)
{
if(num1 > 1)
{
return num1* factorial(num1-1) ;
}
else
{
return 1 ;
}
}
int is_factorial(int num2)
{
int fact = 0 ;
int i = 0 ;
while(fact < num2)
{
fact = factorial(i) ;
i++ ;
}
if(fact == num2)
{
return 0 ;
}
else
{
return -1;
}
}
Both these functions, seem to work correctly.
When we supply them for large inputs repeatedly, then the is_factorial will be repeatedly calling factorial which will be really a waste of time.
I have also tried maintaining a table for factorials
So, my question, is there some more efficient way to check whether a number is factorial or not?
It is wasteful calculating factorials continuously like that since you're duplicating the work done in x! when you do (x+1)!, (x+2)! and so on.
One approach is to maintain a list of factorials within a given range (such as all 64-bit unsigned factorials) and just compare it with that. Given how fast factorials increase in value, that list won't be very big. In fact, here's a C meta-program that actually generates the function for you:
#include <stdio.h>
int main (void) {
unsigned long long last = 1ULL, current = 2ULL, mult = 2ULL;
size_t szOut;
puts ("int isFactorial (unsigned long long num) {");
puts (" static const unsigned long long arr[] = {");
szOut = printf (" %lluULL,", last);
while (current / mult == last) {
if (szOut > 50)
szOut = printf ("\n ") - 1;
szOut += printf (" %lluULL,", current);
last = current;
current *= ++mult;
}
puts ("\n };");
puts (" static const size_t len = sizeof (arr) / sizeof (*arr);");
puts (" for (size_t idx = 0; idx < len; idx++)");
puts (" if (arr[idx] == num)");
puts (" return 1;");
puts (" return 0;");
puts ("}");
return 0;
}
When you run that, you get the function:
int isFactorial (unsigned long long num) {
static const unsigned long long arr[] = {
1ULL, 2ULL, 6ULL, 24ULL, 120ULL, 720ULL, 5040ULL,
40320ULL, 362880ULL, 3628800ULL, 39916800ULL,
479001600ULL, 6227020800ULL, 87178291200ULL,
1307674368000ULL, 20922789888000ULL, 355687428096000ULL,
6402373705728000ULL, 121645100408832000ULL,
2432902008176640000ULL,
};
static const size_t len = sizeof (arr) / sizeof (*arr);
for (size_t idx = 0; idx < len; idx++)
if (arr[idx] == num)
return 1;
return 0;
}
which is quite short and efficient, even for the 64-bit factorials.
If you're after a purely programmatic method (with no lookup tables), you can use the property that a factorial number is:
1 x 2 x 3 x 4 x ... x (n-1) x n
for some value of n.
Hence you can simply start dividing your test number by 2, then 3 then 4 and so on. One of two things will happen.
First, you may get a non-integral result in which case it wasn't a factorial.
Second, you may end up with 1 from the division, in which case it was a factorial.
Assuming your divisions are integral, the following code would be a good starting point:
int isFactorial (unsigned long long num) {
unsigned long long currDiv = 2ULL;
while (num != 1ULL) {
if ((num % currDiv) != 0)
return 0;
num /= currDiv;
currDiv++;
}
return 1;
}
However, for efficiency, the best option is probably the first one. Move the cost of calculation to the build phase rather than at runtime. This is a standard trick in cases where the cost of calculation is significant compared to a table lookup.
You could even make it even mode efficient by using a binary search of the lookup table but that's possibly not necessary given there are only twenty elements in it.
If the number is a factorial, then its factors are 1..n for some n.
Assuming n is an integer variable, we can do the following :
int findFactNum(int test){
for(int i=1, int sum=1; sum <= test; i++){
sum *= i; //Increment factorial number
if(sum == test)
return i; //Factorial of i
}
return 0; // factorial not found
}
now pass the number 24 to this function block and it should work. This function returns the number whose factorial you just passed.
You can speed up at least half of the cases by making a simple check if the number is odd or even (use %2). No odd number (barring 1) can be the factorial of any other number
#include<stdio.h>
main()
{
float i,a;
scanf("%f",&a);
for(i=2;a>1;i++)
a/=i;
if(a==1)
printf("it is a factorial");
else
printf("not a factorial");
}
You can create an array which contains factorial list:
like in the code below I created an array containing factorials up to 20.
now you just have to input the number and check whether it is there in the array or not..
#include <stdio.h>
int main()
{
int b[19];
int i, j = 0;
int k, l;
/*writing factorials*/
for (i = 0; i <= 19; i++) {
k = i + 1;
b[i] = factorial(k);
}
printf("enter a number\n");
scanf("%d", &l);
for (j = 0; j <= 19; j++) {
if (l == b[j]) {
printf("given number is a factorial of %d\n", j + 1);
}
if (j == 19 && l != b[j]) {
printf("given number is not a factorial number\n");
}
}
}
int factorial(int a)
{
int i;
int facto = 1;
for (i = 1; i <= a; i++) {
facto = facto * i;
}
return facto;
}
public long generateFactorial(int num){
if(num==0 || num==1){
return 1;
} else{
return num*generateFactorial(num-1);
}
}
public int getOriginalNum(long num){
List<Integer> factors=new LinkedList<>(); //This is list of all factors of num
List<Integer> factors2=new LinkedList<>(); //List of all Factorial factors for eg: (1,2,3,4,5) for 120 (=5!)
int origin=1; //number representing the root of Factorial value ( for eg origin=5 if num=120)
for(int i=1;i<=num;i++){
if(num%i==0){
factors.add(i); //it will add all factors of num including 1 and num
}
}
/*
* amoong "factors" we need to find "Factorial factors for eg: (1,2,3,4,5) for 120"
* for that create new list factors2
* */
for (int i=1;i<factors.size();i++) {
if((factors.get(i))-(factors.get(i-1))==1){
/*
* 120 = 5! =5*4*3*2*1*1 (1!=1 and 0!=1 ..hence 2 times 1)
* 720 = 6! =6*5*4*3*2*1*1
* 5040 = 7! = 7*6*5*4*3*2*1*1
* 3628800 = 10! =10*9*8*7*6*5*4*3*2*1*1
* ... and so on
*
* in all cases any 2 succeding factors inf list having diff=1
* for eg: for 5 : (5-4=1)(4-3=1)(3-2=1)(2-1=1)(1-0=1) Hence difference=1 in each case
* */
factors2.add(i); //in such case add factors from 1st list " factors " to " factors2"
} else break;
//else if(this diff>1) it is not factorial number hence break
//Now last element in the list is largest num and ROOT of Factorial
}
for(Integer integer:factors2){
System.out.print(" "+integer);
}
System.out.println();
if(generateFactorial(factors2.get(factors2.size()-1))==num){ //last element is at "factors2.size()-1"
origin=factors2.get(factors2.size()-1);
}
return origin;
/*
* Above logic works only for 5! but not other numbers ??
* */
}
I'm trying to write the first 10 terms of the Fibonacci sequence. I feel like I'm on the right line, but I can't seem to quite grasp the actual code (in C).
float fib = 0;
const float minn = 1;
const float maxn = 20;
float n = minn;
while (n <= maxn);{
n = n + 1;
printf (" %4,2f", fib);
fib = (n - 1) + (n - 2);
}
With the fibonacci sequence the value f(n) = f(n - 1) + f(n = 2). the first three values are defined as 0, 1, 1.
The fibonacci sequence is a sequence of integer values (math integers, not necessarily C language values). consider using int or long for the fibonacci value. float is worthless, it only adds unneeded overhead.
when calculating the fibonacci sequence you must store the previous 2 values to get the next value.
you want 10 fibonacci values. you know the first three already so print those and then calculate the next seven values.
7 values implies a loop that iterates 7 times. it has no bearing on the maximum value of the fibonacci value returned, just how many values you want to print.
do something like this:
printf("0, 1, 1");
int currentValue;
int valueN1 = 1;
int valueN2 = 1;
for (int counter = 1; counter <= 7; ++counter)
{
currentValue = valueN1 + valueN2;
printf(", %d", currentValue);
valueN2 = valueN1;
valueN1 = currentValue;
}
You need run loop 10 times only,to find first 10 terms of the Fibonacci sequence.
in your code,while loop would not let you go further because of semicolon at the end of loop
//declare fib value as long int or unsigned int
// because the value of any fib term is not at all
long int fib;
int n=1;
while (n <= 10)
{
printf (" %d", fib);
fib = fib_term(n);
n = n + 1;
}
implement fib_term(int n); by seeing this snippet
First off, I would suggest changing your datatype from a float to an integer or other datatype. floats are not exact numbers and if you had used while (n = maxn) instead of while (n <= maxn) you could have ended up with an infinite loap since the two floats would never have matched.
Second, you don't seem to really understand what the fibonacci sequence is. Take a look at the wikipedie article http://en.wikipedia.org/wiki/Fibonacci_number.
The fibinocci number is NOT (n - 1) + (n - 2) like you have. It is the sum of the previous two numbers in the sequence. You need to restructure your loop to hold the last two values and calculate the next one based on these values.
There are (at least) 2 ways to implement the Fibonacci Algorithm in C:
The Iterative:
int fib(int n){
if (n == 0)
return 0;
int a = 1
int b = 1;
for (int i = 3; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
The Recursive:
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);
}
void main(){
unsigned int i = fibonacci_recursive(10);
}
Suggestions
Consider integer types before FP types when doing integer problems.
Omit a ; in your while (n <= maxn);{
Use a . in floating point formats %4.2f instead of %4,2f.
Fibonacci is the sum of the previous 2 terms, not simply fib = (n - 1) + (n - 2).
Consider an unsigned solution:
C code:
void Fibonacci_Sequence(unsigned n) {
const unsigned minn = 1;
const unsigned maxn = 20;
unsigned F[3];
F[0] = 0;
F[1] = 1;
unsigned i = 0;
for (i = 0; i <= maxn; i++) {
if (i >= minn) printf(" %u,", F[0]);
F[2] = F[1] + F[0];
F[0] = F[1];
F[1] = F[2];
}
}
This uses n/2 iterations
#include<stdio.h>
main()
{
int i,n,a=0,b=1,odd;
scanf("%d",&n);
odd=n%2;
for(i=1;i<=n/2;i++)
{
printf("%d %d ",a,b);
a=a+b;
b=a+b;
}
if(odd)
printf("%d",a);
}