Fibonacci Sequence with user inputting first 2 numbers - c

I am writing a C program to get Fibonacci number, the user needs to put the first 2 numbers and the sequence starts from there. Here is my code:
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int i, input[MAX_SIZE];
printf("please Enter first 2 digit of the Sequence\n");
scanf("%d, %d" , &input[0], &input[1]);
for (i = 2; i < MAX_SIZE; i++)
{
input[i] = input[i-2] + input[i-1];
printf("%d\n", input[i]);
}
return 0;
}
But when i run the code with a input 2 and 3, I get a output like this 1499141456, which is clearly not the sequence. please help.

When you exit from the loop i is equal to MAX_SIZE
printf("%d\n", input[i]);
you are printing a value outside of the bounds of the array (input[MAX_SIZE]).

It's because the result in your code is bigger that the maximum value an int can handle
Live example here!
From Wikipedia
The number 2,147,483,647 (or hexadecimal 7FFF,FFFF16) is the maximum
positive value for a 32-bit signed binary integer in computing. It is
therefore the maximum value for variables declared as integers (e.g.,
as int) in many programming languages, and the maximum possible score,
money, etc. for many video games.
Here's where it goes wrong
[...]
433494437 + 701408733 = 1134903170
701408733 + 1134903170 = 1836311903
1134903170 + 1836311903 = -1323752223

put print statement inside for loop braces.
or (i = 2; i < MAX_SIZE; i++)
{
input[i] = input[i-2] + input[i-1];
printf("%d\n", input[i]);
}

Related

converting array from binary to decimal

I'm converting a 4 bytes integer to binary, reversing the bits order, converting back to decimal and printing the integer. When I convert back to decimal somehow the number 49 get added to the correct number. Let my give you some examples:
decimal->binary -> reversed binary ->decimal(correct answer | my answer)
123->00000000000000000000000001111011->11011110000000000000000000000000->3724541952 | 3724542001
1->00000000000000000000000000000001->10000000000000000000000000000000->2147483648 | 2147483697
Everytime my answer - correct answer= 49 . Here is my code:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main() {
uint32_t f;
int a[32]={0};
int i;
int dec, j = 0;
printf("Enter a value :");
scanf ("%" SCNu32, &f);
for(i=0;f>0;i++)
{
a[i]=f%2;
f=f/2;
}
printf("\n Binary number(LSB) is=");
for(i=0;i<=31;i++)
printf("%d",a[i]);
printf("\n");
for(i=31;i>=0;i--)
{
dec = dec + (1u << i) * (a[j] - '0');
j++;
}
printf("The decimal representation:%u", dec);
return 0;
}
For converting back to decimal I used #Pras answer from here: Converting array of binary numbers to decimal
dec is not initialized.
- '0' is inappropriate because a[j] is a bit (0 or 1), not a character code ('0' or '1').
Either j is not needed (you can use 31-i) or it is not calculated correctly (should start at 31 and work down to 0 while i starts at 0 and works up to 31, or j can be calculated from i in each iteration).
With those errors corrected, the program produces the desired output. However, there are a number of other issues regarding the correct declaration of main and certain aspects of style, so here is a new version addressing some of them:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
// Declare main as "int main(void)" or "int main(int argc, char *argv[])".
int main(void)
{
uint32_t f;
int a[32] = { 0 };
/* Do not declare identifiers where you do not need them. This avoids
various errors that can occur where things are mistakenly used where
they were not intended.
i is used only in loops, so it is declared only inside those loops.
dec is only needed after some other work, so it is declared later.
j is not needed at all.
*/
printf("Enter a value:");
/* Do not put a space between a function and the parentheses for its
arguments.
*/
scanf("%" SCNu32, &f);
// Use more spaces; do not crowd symbols together.
for (int i=0; f>0; i++) // Or "for (int i = 0; i > 0; i++)".
/* Indent a loop body more than the code it is in; do not put { and }
further to the left and keep the loop body at the same indentation as
the code it is in.
*/
{
a[i] = f%2;
f = f/2;
}
printf("\nBinary number (LSB) is = ");
for (int i=0; i<=31; i++)
printf("%d", a[i]);
printf("\n");
/* Put blank lines in transitions between code that finishes one task,
like printing output, and code that starts another task, like
converting to binary.
*/
int dec = 0; // Declare dec here, just before it is needed.
for (int i=31; i>=0; i--)
{
/* Remove "- '0'" here. a[j] is a bit (0 or 1), not a character code
('0' or '1').
Do not use j. This loop has a counter, i. Using two counters for
different things may have confused you. While you want i to run
from 0 to 31, you want j to run from 31 to 0. You could use a
separate j for this, but it is easily replaced by 31-i.
*/
dec = dec + (1u << i) * a[31-i];
}
// Include spaces in output, like after the colon, to avoid crowding.
/* Print a "\n" at the end of each line of output. C is designed to use
"\n" to end lines, not to start them, because "\n" causes output to be
sent to interactive devices immediately instead of buffered.
*/
printf("The decimal representation: %u\n", dec);
return 0;
}

C random integer generator question (A book on C 4th Edition)

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, n;
printf("\n%s\n%s",
"Some randomly distributed integers will be printed.",
"How many do yo want to see? ";
scanf("%d", &n);
for (i = 0; i < n; ++i) {
if (i % 10 == 0)
putchar('\n');
printf("%7d", rand());
}
printf("\n\n");
return 0;
}
this is the code from the textbook "A book on C".
when you type 23 when prompted it is supposed to generate 23 random numbers in 3 rows, 8 columns (3*8-1).
i learned that printf("%7d", rand())is supposed to return a value printed in a format of a decimal integer and the width of the field where the integer gets printed is 7.
however, I am getting random numbers that are in a width of more than 7 and it doesn't look neat at all. (no columns nor rows, just a huge chunk of consecutive numbers like 1235289043528935294835698246182965982)
I thought it has something to do with the expression printf("%7d", rand()) function and the way how it is supposed to return values.
I'm starting to think that the textbook is wrong.
Your numbers are bigger than 7 digits. You can try:
A) Changing the width field higher:
printf("%14d", rand() );
or
B) Making the generated numbers smaller than 7 digits:
printf("%7d", rand() % 1000 );
More information on format specifiers can be found here
Hope that helps!
You are not printing any whitespace. Try inserting some:
printf("%7d\t", rand());
In addition to the comment above, if I understand correctly you want all 8 numbers then the line should be changed to be: if (i % 8 == 0);
Rather than guess the maximum width of a rand() number, calculate the width of maximum random number: RAND_MAX.
snprintf(NULL, 0, ... prints the number of characters that would have been written had the buffer been sufficiently large, not counting the terminating null character.
int width = snprintf(NULL, 0, "%d", RAND_MAX);
Later when printing, use the width.
printf(" %*d", width, rand());
as in
#define COLUMN_N 8
for (i = 0; i < n; ++i) {
printf(" %*d", width, rand());
if (i % COLUMN_N == COLUMN_N - 1 || i + 1 == n) {
putchar('\n');
}
}

Stack smashing error when trying to work with dynamic arrays

I'm trying to create 2 dynamic arrays from the user input but the compiler is throwing a stack smashing array. This is my code:
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#define NUMS 3
// Put your code below:
int main() {
int high, low;
int high_temp[3];
int low_temp[3];
int total_temp = 0;
double median = 0;
printf("---=== IPC Temperature Analyzer ===---\n");
for (int i = 1; i <= NUMS; i++) {
printf("Enter the high value for day %d: ", i);
scanf("%d/n", &high);
printf("Enter the low value for day %d: ", i);
scanf("%d/n", &low);
if(!((high > low && high < 41) && (low < high && low > -41))) {
printf("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low");
i = i - 1;
}else{
high_temp[i] = i;
low_temp[i] = i;
}
}
for (int i = 0; i < sizeof(high_temp); i++){
//total_temp = total_temp + high_temp[i] + low_temp[i];
printf("The high value: %d", high_temp[i]);
printf("The low value: %d", low_temp[i]);
printf("-----");
}
}
And this is the output. The error happens when I'm trying to print out the elements in each array. I'm doing this to see if any of the illegal values creeped into the array. I'm suppose to take their medians afterwards.
---=== IPC Temperature Analyzer ===---
Enter the high value for day 1: 8
Enter the low value for day 1: -2
Enter the high value for day 2: 41
Enter the low value for day 2: -4
Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low
Enter the high value for day 2: 9
Enter the low value for day 2: -4
Enter the high value for day 3: 5
Enter the low value for day 3: 11
Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low
Enter the high value for day 3: 11
Enter the low value for day 3: 5
*** stack smashing detected ***: terminated
There are two major problems in your code, one in each for loop.
In the first, you need to remember that, in C, array indexes run from zero through to n - 1 (where n is the size of the array). So, the code:
for (int i = 1; i <= NUMS; i++) {
//...
should be replaced with this:
for (int i = 0; i < NUMS; i++) { // Note that NUMS = 3 and high_temp[3] is out-of-bounds
//...
The second for loop has a different error. Here, you are correctly running from zero to the n - 1 value, but you are miscalculating the n. So, instead of sizeof(high_temp) (which will give you the total size of the integer array) you need to divide that value by the size of one element (conventionally, use the first). So, use this, instead:
for (size_t i = 0; i < sizeof(high_temp)/sizeof(high_temp[0]); i++){
//...
(I've changed the type from int to size_t as this is what the sizeof operator returns; it is generally an unsigned int or unsigned long, or some such.)
EDIT: In the first loop, with the modifications I have suggested, you can 'restore' the correct number in the printed questions by simply adding 1 to the value of i that is printed. So, like this:
printf("Enter the high value for day %d: ", i + 1);
EDIT2:
There is also an issue regarding the values you assign in the first loop. You are doing this:
}else{
high_temp[i] = i;
low_temp[i] = i;
}
but the values you actually want to assign have been read into the high and low variables a few lines earlier. So, use this, instead:
} else {
high_temp[i] = high;
low_temp[i] = low;
}
There are a few problems with the code.
Your first for loop is wrong. The index should start at 0 and end before NUMS like this:
for (int i = 0; i < NUMS; i++)
This way the loop will go from from 0 to 2, since array indices start at 0 and your high_temp and low_temp arrays can only store 3 values. The way you have it written it will try to write to high_temp[3] and low_temp[3] which are not valid.
The upper bound of your second loop is wrong. sizeof(high_temp) doesn't do what you think it does; it returns 12 not 3, so in your second loop you're trying to access elements outside the bounds of the array. In general you would use sizeof(high_temp) / sizeof(high_temp[0]) but in this case you have already have NUMS so use that.

In C, computing an equation using user input values is not giving the expected result?

I am doing an assignment for my class but I am stuck. The assignment is to:
Write a recursive program to precompute Fibonacci numbers and store them in an array. Fibonacci formula is Fib(0) = 1, Fib(1) = 1 and Fib(i) = Fib(i − 1) + Fib(i − 2). Store the ith Fibonacci number at index i. Have a loop to read i and print i and ith Fibonacci number. Use −1 to quit the loop. My output is wrong but I don't know how to fix it. I have been trying for a while now but I just couldn't pinpoint my mistake.
My code is
#include <stdio.h>
double Fib[50]; //globally declared
int fib(int i)
{
for(i=0; i<50; i++) //loop to scan
{
scanf("%lf", &Fib[i]); //scan and store numbers in an array
if (Fib[i]==-1) //i =-1 will end loop
break;
}
Fib[i]= Fib[i-1]+Fib[i-2];//formula
if(Fib[i]==0||Fib[i]==1) //i=0 and i=1 will print 1
Fib[i]=1;
else if(i>1) //performs the operation with the formula
printf("%d %lf\n", i, Fib[i]);
}
int main()
{
int i=0;
fib(i);
return 0;
}
Expected result:
user input: 4 10 20 15 5 -1
output:
4 5.000000
10 89.000000
20 10946.000000
15 987.000000
5 8.000000
My output:
5 20.000000
A couple points:
Your program isn't recursive
Compute all of Fib first with your recursive function then after
handle user input in a loop
The code below has the structure for dealing with user input, do the recursion:
#include <stdio.h>
// It would make sense for this to store unsigned long long instead of double
// because Fibonacci numbers are always positive integers
unsigned long long Fib[50];
// Your assignment specifically said use a recursive program to compute Fib.
// This is not a recursive function, but it is correct, I will leave the
// recursion for you to work out
void populateFib() {
Fib[0] = 1;
Fib[1] = 1;
unsigned i;
for (i = 2; i < 50; ++i)
Fib[i] = Fib[i - 1] + Fib[i - 2];
}
int main() {
// First compute Fib
populateFib();
// Deal with user input in an infinite loop
for (;;) {
int input;
scanf("%d", &input);
// Condition for breaking the infinite loop
if (input == -1)
break;
// Sanity check the user won't read out of bounds
if (input < 0 || input >= 50) {
printf("No!\n");
continue;
}
// Display what the user wants
printf("%d %llu\n", input, Fib[input]);
}
return 0;
}

Trailing Zeros in printf/sprintf

I would like to make the output of a number to always have 6 digits
e.g.:
if number is 1 the output should be 100000
if number is 23 the output should be 230000
if number is 236 the output should be 236000
How can I do this with printf/sprintf?
printf and its variants can pad zeroes to the left, not to the right. sprintf the number, then add the necessary zeros yourself, or make sure the number is 6 digits long:
while(num < 100000)
num *= 10;
(This code assumes the number isn't negative, or you're going to get in trouble)
printf will return the number of character printed out. This you can print out the remaining zeros:
int num = 3; // init
int len = printf("%d", num);
for (int i = 0; i < 6-len; ++i)
printf("0");
You should add some error checks (for example, if len is larger than 6).
With sprintf, you can use memset on the remaining buffer, which will be easier.
You can't do it directly with printf (at least in a standard-conforming way), you need to alter your numbers beforehand.
Use the return value of printf (as in the first line of the for loop below)
#include <stdio.h>
int main(void) {
int number, width = 6;
for (number = 1; number < 9999999; number *= 7) {
int digits = printf("%d", number);
if (digits < width) printf("%0*d", width-digits, 0);
puts("");
}
return 0;
}
See code running at http://ideone.com/TolIv
As Luchian said, this behavior is unsupported in printf, unlike the much more common reverse (left) padding.
You could, however, easily enough generate the requested result with something like this:
char *number_to_six_digit_string(char *resulting_array, int number)
{
int current_length = sprintf(resulting_array, "%d", number);
while (6 > current_length) {
resulting_array[current_length++] = '0';
}
resulting_array[current_length] = '\0';
return resulting_array;
}
and then you could print the result:
char my_number[7];
printf("my number is %s, other stuff\n", number_to_six_digit_string(my_number, 13));

Resources