Fibonacci Sequence C program error - c

I am trying to write a program which takes the first 2 numbers of the Fibonacci sequence as input and also the value of n. Then the program gives the output of the nth digit of the Fibonacci sequence.
#include <stdio.h>
#include <stdlib.h>
int main () {
int n, i;
int s[n - 1];
int a, b;
printf("Enter two first two numbers:");
scanf("%d %d", &a, &b);
printf("Enter the value of n(3-100):");
scanf("%d", &n);
for (i = 2; i <= n - 1; i++) {
s[i] = s[i - 1] + s[i - 2];
}
printf("The nth digit is %d", s[n - 1]);
return(0);
}
I am getting the answer number which is followed by some additional arbitrary numbers

Actually to implement your code there is no need of an array s[] .
This can be simply implemented as :-
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
int a, b;
printf("Enter two first two numbers:");
scanf("%d%d", &a, &b); // not scanf("%d %d", &a, &b);
printf("Enter the value of n(3-100):");
scanf("%d", &n);
for (i = 1; i < n; i++)
{
b += a;
a = b - a;
}
printf("The nth digit is %d\n", a);
return (0);
}
Output:
Enter two first two numbers:0 1
Enter the value of n(3-100):5
The nth digit is 3 // 0 1 1 2 3

Here you define an array of unknown size, being lucky that n does not happen to be 0 or 1 or negative.
int s[n-1];
Here you ignore the return value of scanf, which you really should check to verify success of scanning.
scanf("%d %d",&a,&b);
scanf("%d",&n);
Even assuming a meaningfully defined array, you set a loop up to produce indexes beyond the array here:
for (i=2 ; i<=n-1 ; i++)
And then you write beyond the array (during the last iteration in the loop) here:
s[i]=
With this code all bets are off, you have guaranteed undefined behaviour and therefor any explanation of what exactly goes wrong is futile.

A few things. As mentioned, you are trying to use n before it has been given a value. Also, you should use malloc() when using a variable to determine the array size.
Next, if you are computing the nth sum, then you need the array to have n elements, not n-1
Third, you read in the two starting values, a and b, but you never use them to initialize the first two elements of your array.
And finally, you need to fix your loop indexing. (actually, your indexing is ok once you change the array to have n elements instead of n-1 elements, however, it is certainly preferred to use i < n rather than i <= n-1)
int main() {
int n, i;
int a, b;
printf("Enter two first two numbers:");
scanf("%d %d", &a, &b);
printf("Enter the value of n(3-100):");
scanf("%d", &n);
int *s = malloc(n * sizeof(*s));
s[0] = a;
s[1] = b;
for (i = 2; i < n; i++) {
s[i] = s[i - 1] + s[i - 2];
}
printf("The nth digit is %d", s[n - 1]);
return(0);
}

Related

Floyd's Triangle right pattern

I have to creat a program thats that asks from the user to enter a number of rows and then creats a floyd's triangle. The problem is i don't seem to manage to make this particular pattern:
1
2 3
4 5 6
7 8 9 10
I have only managed to creat the basic program
#include <stdio.h>
#include <stdlib.h>
int rows, r, c, a;
int number=1;
int main()
{
printf("Floyd Triangle\n");
printf("--------------");
printf("\nPlease enter an integer number of rows: ");
scanf("%d",&rows);
while(rows<=0)
{
printf("\nYou must enter an integer value: ");
scanf("%d",&rows);
}
for(r=1;r<=rows;r++)
{
for(c=1;c<=r;+c++)
{
printf("%d ", number++);
}
printf("\n");
}
there are no erros in my code so far
Just print some spaces before the first number in each row
// ...
for (r = 0; r < rows; r++) {
printsomespaces(r, rows); // prints some spaces depending on current row and total rows
for (c = 0; c < r; +c++) {
printf("%d ", number++);
}
printf("\n");
}
// ...
If you can't write your own function (no printsomespaces) use a loop instead:
//...
//printsomespaces(r, rows);
for (int space = 0; space < XXXXXXXX; space++) putchar(' ');
//...
where XXXXXXXX is some calculation using r and rows.
Try (untested) 2 * (rows - r) (2 is the width of each number: 1 for the number + 1 for the space).
i haven't learnt how to make my own functions yet. isnt there a way to accomplish this only by using loops?
There is. A main problem of this exercise is to compute the needed width of each column, which of course depends on the number in the bottom row. The count of digits of a number can be determined in various ways; perhaps the easiest is via the snprintf(char *s, size_t n, const char *format, ...) function, which
… returns the number of characters that would have been written
had n been sufficiently large…
If n is zero, nothing is written,
and s may be a null pointer.
// we need to compute the width the of widest number of each column
int width[rows];
const int max = rows*(rows+1)/2; // the greatest number
for (c=1; c<=rows; ++c) // see how many characters will be written
width[c-1] = snprintf(NULL, 0, "%d ", max-rows+c);
for (r=1; r<=rows; ++r, puts(""))
for (c=1; c<=rows; ++c)
if (c <= rows-r) // here comes an empty cell in this row
printf("%-*c", width[c-1], ' ');
else
printf("%-*d", width[c-1], number++);

Recursive function with array in C

The problem goes as follows:
Write a recursive function with three arguments: an array (a), the
number of elements of the array (n) and a number - k.
If k is positive and smaller than n it should print the first k positive
numbers of the array.
If k is negative and its absolute value is smaller than n the first k negative numbers should be printed.
If k is larger than n and positive all positive numbers should be printed.
If k is larger than n and negative all negative numbers should be
printed.
This is my attempt
#include <stdio.h>
#include <stdlib.h>
int function(int a[100], int n, int k)
{
int b[n], i;
if (k!=0 && n>1)
{
for (i=0; i<n; i++)
{
b[i]=a[i+1];
}
if (k<n || abs(k)<n)
{
if (k>0)
{
if (b[0]>0)
{
printf("%d", b[0]);
k=k-1;
}
}
if (k<0)
{
if (b[0]<0)
{
printf("%d", b[0]);
k=k+1;
}
}
return function(b, n-1, k);
}
}
else return 0;
}
int main()
{
int i, n, a[100], k;
printf("n = ");
scanf("%d", &n);
for (i=0; i<n; i++)
{
printf("a[%d] = ", i);
scanf("%d", &a[i]);
}
printf("k = ");
scanf("%d", &k);
printf("The new array is: \n");
function(a, n, k);
return 0;
}
But it only prints one number and I don't know how to fix it. Does anyone understand where I went wrong?
EDIT: If the array is {1, -1, 2, -2, 3, -3} and k=2, the expected result is {1, 2}. If k=-2 the expected result is {-1, -2}
EDIT 2: b is an array that contains all the elements of the a array other than a[0]
I found three issues with your code.
1) When I copied your code (converting to C# because that's what I work with), it threw an ArgumentOutOfRangeException for me here:
for (i=0; i<n; i++)
{
b[i]=a[i+1]; <------
}
When i is 99, it tries to copy a[100] into b[99], but there's no a[100]. You should change the for loop to this instead:
for (i=0; i<n-1; i++)
2) Your code is essentially treating a like a queue and popping the first number off (by copying all the others into a new array b), but instead of looking at that first number to determine whether or not to print it, you're skipping it and looking instead at the first item you just put into b:
if (k>0)
{
if (b[0]>0) <------
{
printf("%d", b[0]); <-----
k=k-1;
}
}
You should change your comparisons (and printf lines) to look at a[0] instead of b[0].
3) Whenever k is larger than n, then your entire logic block will get skipped (for example, I mistakenly set k to 34 instead of 3, and when I did, the if block reads if (34 < 6 || abs(34) < 6), which is always false.

Returning to the start of a for loop in C

Even though this question has been asked a million times I just haven't found an answer that actually helps my case, or I simply can't see the solution.
I've been given the task to make a program that takes in a whole number and counts how many times each digit appears in it and also not showing the same information twice. Since we're working with arrays currently I had to do it with arrays of course so since my code is messy due to my lack of knowledge in C I'll try to explain my thought process along with giving you the code.
After entering a number, I took each digit by dividing the number by 10 and putting those digits into an array, then (since the array is reversed) I reversed the reverse array to get it to look nicer (even though it isn't required). After that, I have a bunch of disgusting for loops in which I try to loop through the whole array while comparing the first element to all the elements again, so for each element of the array, I compare it to each element of the array again. I also add the checked element to a new array after each check so I can primarily check if the element has been compared before so I don't have to do the whole thing again but that's where my problem is. I've tried a ton of manipulations with continue or goto but I just can't find the solution. So I just used **EDIT: return 0 ** to see if my idea was good in the first place and to me it seems that it is , I just lack the knowledge to go back to the top of the for loop. Help me please?
// With return 0 the program stops completely after trying to check the digit 1 since it's been checked already. I want it to continue checking the other ones but with many versions of putting continue, it just didn't do the job. //
/// Tried to make the code look better. ///
#include <stdio.h>
#define MAX 100
int main()
{
int a[MAX];
int b[MAX];
int c[MAX];
int n;
int i;
int j;
int k;
int counter1;
int counter2;
printf("Enter a whole number: ");
scanf("%i",&n);
while (1)
{
for (i=0,counter1=0;n>10;i++)
{
a[i] = n%10;
n=n/10;
counter1+=1;
if (n<10)
a[counter1] = n;
}
break;
}
printf("\nNumber o elements in the array: %i", counter1);
printf("\nElements of the array a:");
for (i=0;i<=counter1;i++)
{
printf("%i ",a[i]);
}
printf("\nElements of the array b:");
for (i=counter1,j=0;i>=0;i--,j++)
{
b[j] = a[i];
}
for (i=0;i<=counter1;i++)
{
printf("%i ",b[i]);
}
for (i=0;i<=counter1;i++)
{
for(k=0;k<=counter1;k++)
{
if(b[i]==c[k])
{
return 0;
}
}
for(j=0,counter2=0; j<=counter1;j++)
{
if (b[j] == b[i])
{
counter2+=1;
}
}
printf("\nThe number %i appears %i time(s)", b[i], counter2);
c[i]=b[i];
}
}
The task at hand is very straightforward and certainly doesn't need convoluted constructions, let alone goto.
Your idea to place the digits in an array is good, but you increment counter too early. (Remember that arrays in C start with index 0.) So let's fix that:
int n = 1144526; // example number, assumed to be positive
int digits[12]; // array of digits
int ndigit = 0;
while (n) {
digits[ndigit++] = n % 10;
n /= 10;
}
(The ++ after ndigit will increment ndigit after using its value. Using it as array index inside square brackets is very common in C.)
We just want to count the digits, so reversing the array really isn't necessary. Now we want to count all digits. We could do that by counting all digits when we see then for the first time, e.g. in 337223, count all 3s first, then all 7s and then all 2s, but that will get complicated quickly. It's much easier to count all 10 digits:
int i, d;
for (d = 0; d < 10; d++) {
int count = 0;
for (i = 0; i < ndigit; i++) {
if (digit[i] == d) count++;
}
if (count) printf("%d occurs %d times.\n", d, count);
}
The outer loop goes over all ten digits. The inner loop counts all occurrences of d in the digit array. If the count is positive, write it out.
If you think about it, you can do better. The digits can only have values from 0 to 9. We can keep an array of counts for each digit and pass the digit array once, counting the digits as you go:
int count[10] = {0};
for (i = 0; i < ndigit; i++) {
count[digit[i]]++;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
(Remember that = {0} sets the first element of count explicitly to zero and the rest of the elements implicitly, so that you start off with an array of ten zeroes.)
If you think about it, you don't even need the array digit; you can count the digits right away:
int count[10] = {0};
while (n) {
count[n % 10]++;
n /= 10;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
Lastly, a word of advice: If you find yourself reaching for exceptional tools to rescue complicated code for a simple task, take a step back and try to simplify the problem. I have the impression that you have added more complicated you even you don't really understand instead.
For example, your method to count the digits is very confused. For example, what is the array c for? You read from it before writing sensible values to it. Try to implement a very simple solution, don't try to be clever at first and go for a simple solution. Even if that's not what you as a human would do, remeber that computers are good at carrying out stupid tasks fast.
I think what you need is a "continue" instead of a return 0.
for (i=0;i<=counter1;i++) {
for(k=0;k<=counter1;k++) {
if(b[i]==c[k]) {
continue; /* formerly return 0; */
}
for(j=0,counter2=0; j<=counter1;j++)
if (b[j] == b[i]){
counter2+=1;
}
}
Please try and see if this program can help you.
#include <stdio.h>
int main() {
unsigned n;
int arr[30];
printf("Enter a whole number: ");
scanf("%i", &n);
int f = 0;
while(n)
{
int b = n % 10;
arr[f] = b;
n /= 10;
++f;
}
for(int i=0;i<f;i++){
int count=1;
for(int j=i+1;j<=f-1;j++){
if(arr[i]==arr[j] && arr[i]!='\0'){
count++;
arr[j]='\0';
}
}
if(arr[i]!='\0'){
printf("%d is %d times.\n",arr[i],count);
}
}
}
Test
Enter a whole number: 12234445
5 is 1 times.
4 is 3 times.
3 is 1 times.
2 is 2 times.
1 is 1 times.
Here is another offering that uses only one loop to analyse the input. I made other changes which are commented.
#include <stdio.h>
int main(void)
{
int count[10] = { 0 };
int n;
int digit;
int elems = 0;
int diff = 0;
printf("Enter a whole number: ");
if(scanf("%d", &n) != 1 || n < 0) { // used %d, %i can accept octal input
puts("Please enter a positive number"); // always check result of scanf
return 1;
}
do {
elems++; // number of digits entered
digit = n % 10;
if(count[digit] == 0) { // number of different digits
diff++;
}
count[digit]++; // count occurrence of each
n /= 10;
} while(n); // do-while ensures a lone 0 works
printf("Number of digits entered: %d\n", elems);
printf("Number of different digits: %d\n", diff);
printf("Occurrence:\n");
for(n = 0; n < 10; n++) {
if(count[n]) {
printf(" %d of %d\n", count[n], n);
}
}
return 0;
}
Program session:
Enter a whole number: 82773712
Number of digits entered: 8
Number of different digits: 5
Occurrence:
1 of 1
2 of 2
1 of 3
3 of 7
1 of 8

Fibonacci Series in C Program where FIRST 2 numbers are given by user

When the first number is 1 and second number is 2, and the length is 5, it should be 1 2 3 5 8. But then my output is always 1 2 1 3 4. I can't seem to find the problem.
Another input is 2 and 5. Output is 2 5 1 6 7. The 3rd number which is 1 shouldn't be there. What should I change or add?
*This is already a submitted HW and yes its wrong I got the deductions already. Now I just want to fix this so I can study this.
int main()
{
int i, lenght = 0, fib, sum, sum1, sum2, a, b, c;
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
{
while ((a > b) || ((lenght < 2) || (lenght > 100)))
{
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
}
}
printf("%d\t%d\t", a, b);
printf("%d\t", fib);
for (i = 3; i < lenght; i++) {
if (i <= 1) fib = i;
else {
a = b;
b = fib;
fib = a + b;
}
printf("%d\t", fib);
}
}
The first time you print fib (before the for loop), you haven't assigned it anything yet.
Since this is for study, issues with your code: you don't need to duplicate the calls to scanf(), simply initialize one of the variables to fail (which you did: lenght = 0) and let the loop do its thing; pick one indentation style and stick with it; if you're new to C, always include the curly braces, even when the language says they're optional; you (correctly) allow for a length of 2, but then print three numbers; your if (i <= 1) clause is a no-op as the loop starts with for (i = 3; so i is never less than 3.
Putting it all together, we get something like:
#include <stdio.h>
int main() {
int length = 0, a, b;
while (length < 2 || length > 100 || a > b ) {
printf("\nFirst number: ");
(void) scanf("%d", &a);
printf("\nSecond number: ");
(void) scanf("%d", &b);
printf("\nHow long?: ");
(void) scanf("%d", &length);
}
printf("%d\t%d\t", a, b);
for (int i = 2; i < length; i++) {
int fib = a + b;
printf("%d\t", fib);
a = b;
b = fib;
}
printf("\n");
return 0;
}
Note that the input error checking isn't sufficient to prevent problems. E.g. b can be greater than a, but still mess up the sequence if you input random numbers. You're assuming the user knows to put in two adjacent items from fibonacci sequence which is tricky to test.
just add fib=a+b; before printing fib value.
Its a good coding habit to initialize all variable before using it(especially in C).
Your code seems strange to me. I tried to simplify your code a bit. See this once:
int main()
{
int a,b,next,last,i;
printf("Enter the first Value:");
scanf("%d",&a);
printf("Enter the second Value:");
scanf("%d",&b);
printf("Enter the length of Fab. series:");
scanf("%d",&last);
printf("%d,%d,",a,b);
for (i=3; i<= last; i++)
{
next = a + b;
if(i<last)
printf("%d,",next);
else
printf("%d",next);
a = b;
b = next;
}
return 0;
}
Hope it's Helpful!!

Computing the average of grades in C

I have write a program that allows me to firstly enter a character c followed by an integer n and n float values representing grades. Using array to store the grades I have entered and no more than 100 grades can be introduced. The program allowed me to calculate the sum of the elements in array when I enter 's', compute the production of the elements in array when i enter 'p' and compute the average of the element s when i enter other words. After i enter the grades and character. The program has no response when i hit return to continue. So where is the mistake in my code
#include<stdio.h>
#include<stdio.h>
int main()
{
char c;
int integer_grade [100];
float floting_grade [100];
printf("Enter a grade");
scanf("%i,%f",&integer_grade[100],&floting_grade[100]);
int *a;
a=&integer_grade[100];
int *b;
b=&floting_grade[100];
printf("Enter a character");
getchar();
scanf("%c",&c);
int n;
switch(c)
{
case 's':
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
printf("Sum is %d",*a+*b);
case 'p':
for (n=0;n=100;n++)
*a*=*a;
*b*=*b;
printf("Sum is %d",*a**b);
default:
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
printf("average is %d",(*a+*b)/100);
}
return 0;
}
The task is:
Write a program where you first enter a character c followed by an integer n and n float values representing grades. Use an array for storing the grades. You can assume that not more than 100 grades would be introduced. Yours program should compute and print the following: if c is 's' the sum of the grades, if c is 'p' the product of all grades and if another character was introduced then the arithmetic mean of all grades.
*use switch
*you can safely assume thee input will be valid.
Thoughts.
This is undefined behavior. You are assigning the read integer and float to offset 100 in those arrays, which doesn't exist.
int integer_grade[100];
float floting_grade[100];
scanf("%i,%f", &integer_grade[100], &floting_grade[100]);
These pointers point to memory that is outside the bounds of their respective arrays.
int *a = &integer_grade[100];
int *b = &floting_grade[100];
You ask for a character and then you ignore the value of that character:
getchar();
You then follow that up by getting the following character. Which is odd. But you do use the correct type and what not. So that's a win.
scanf("%c",&c);
Your indentation in these for loops implies that you think that both statements will be iterated on as part of the loop. That's incorrect. Use { ... } to accomplish that:
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
I have no idea what you think you're accomplishing by *a += *a. I do know that the value at *a is going to grow quite quickly (and will likely overflow).
Switch statements use fallthrough on the cases. That means that if your case is 's', it will run all of the code in the switch statement, including all three cases. If you don't want this behavior, you should place break statements at the end of each case.
Please go back to your book / faculty / internet resource and read how a for loop works. This doesn't do what you probably think it does. In fact, this is an infinite loop!
for (n=0; n=100; n++)
Whatever do you try to do here, it's not right at all.
First: You declare 2 arrays of 100 elements, THEN you assign values outside of that array bounds (100 element array start from 0, finishes at 99)
Second: You create 2 pointers that points to outside of those array bounds.
Third: Inside the switch , the for (n=0;n=100;n++) is wrong, it should be something like for(n = 0; n < 100; n++)
Fourth: This
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
it would increment (if that for would be correct) only the first statement.
Correct way would be
for (n = 0; n < 100; n++)
{
*a += *a;
*b += *b;
}
Proper code would be
#include <stdio.h>
int main()
{
char c;
int integer_grade[100];
float floting_grade[100];
int nr_of_grades;
int i = 0;
printf("Enter number of grades: ");
scanf("%d", &nr_of_grades);
for(i = 0; i < nr_of_grades; i++)
{
printf("Enter a int grade: ");
scanf("%d", &integer_grade[i]);
printf("Enter a float grade: ");
scanf("%f", &floting_grade[i]);
}
int operation_i = 0;
float operation_f = 0;
printf("Enter a character");
scanf(" %c", &c);
int n;
switch(c)
{
case 's':
for (n = 0; n < nr_of_grades; n++)
{
operation_i += integer_grade[n];
operation_f += floting_grade[n];
}
printf("Sums are Int: %d Float: %f", operation_i, operation_f);
case 'p':
operation_i = 1;
operation_f = 1;
for (n = 0; n < nr_of_grades; n++)
{
operation_i *= integer_grade[n];
operation_f *= floting_grade[n];
}
printf("Products are Int: %d Float: %f", operation_i, operation_f);
default:
for (n = 0; n < nr_of_grades; n++)
{
operation_i += integer_grade[n];
operation_f += floting_grade[n];
}
printf("Average is Int: %d Float: %f", operation_i / nr_of_grades, operation_f / nr_of_grades);
}
return 0;
}

Resources