How to make Fibonacci equation? (Error about uninitialized variable) - c

#include<stdio.h>
int main(void)
{
int a, b, c, n;
printf("What Fibonacci number would you like?:");
scanf("%d", &n);
if (n == 0 || n == 1)
return printf("%d", n);
else
for (c = 0; c < n; c++)
{
c = a + b;
a = b;
b = c;
}
printf("%d ", c);
return 0;
}
I have made this program for using Fibonacci equation. But I get following errors during compilation:
Error 1 error C4700: uninitialized local variable 'a' used d:\computer programming c++\20150923\20150923\20150923-1.c 15 1 20150923
Error 2 error C4700: uninitialized local variable 'b' used d:\computer programming c++\20150923\20150923\20150923-1.c 15 1 20150923
How can I fix it??

Change int a, b, c, n; as below in the code.
int a = 0, b = 1, c, n; /*Here you initialize the variables a to zero and b to one*/
You are trying to access the variables a and b without initializing it. As they are local variables, they contain garbage values.
When executing this line c = a + b;, the value of a and b are garbage values which may alter the way the code behaves which apparently leads to undefined behavior.

Well the compiler is right, you have to initialize variables before use, e.g.
int a = 0, b = 1, c = 0, n = 0; // etc.
Otherwise you will trigger undefined behaviour (which you should try to avoid when using languages such as C or C++) if you read values of uninitialized variables.
And indeed as noted in the comments it doesn't make sense to have c as loop index.

You have to initialize the variable declared. Since you didn't declare a and b, compiler is throwing the error.
Also you need to change c<n to c<=n to get the required fibonacci number
So your final code will look like this:
#include<stdio.h>
int main(void)
{
int a=0, b=1, c, n;
printf("What Fibonacci number would you like?:");
scanf("%d", &n);
if (n == 0 || n == 1)
return printf("%d", n);
else
for (c = 0; c < =n; c++)
{
c = a + b;
a = b;
b = c;
}
printf("%d ", c);
return 0;
}

In addition to initializing a and b, the code needs to use a separate variable for a loop counter (I used i). By using unsigned int, n can be up to 47, with result = 2971215073. I changed the summation to c = b + a since this corresponds to fib(i) = fib(i-1) + fib(i-2);
#include<stdio.h>
int main(void)
{
unsigned int a=0, b=1, c, i, n;
printf("What Fibonacci number would you like?:");
scanf("%d", &n);
if (n == 0 || n == 1){
printf("%u\n", n);
return 0;
}
for (i = 2; i <= n; i++)
{
c = b + a;
a = b;
b = c;
}
printf("%u\n", c);
return 0;
}

Related

How to put different digits in different sides

How to write a program in c that gets single integer and another integer that is more than 3 digits at least and after that the single integer goes to the left side of the three digits number and the right side as well.
Note: I need help for the left side right side number
For example:
I mean if I got 5 and 100
it should be 51005
something like this:
int a = 5, b = 100;
int length = 1;
int tmp = b;
while (tmp /= 10)
length++;
int left = 10;
for (int i = 0; i < length; i++)
left *= 10;
int result = (left * a) + (10 * b) + a;
std::cout << result;
Also, you can play here.
there are so many methods :
one is stated in the reply above by #MikeCAT .
int a = 5, b = 100; printf("%d%d%d\n", a, b, a);
you can also try to transfer them to strings , contact them and put it back as an int if you're asked to have a variable named as c using itoa and atoi with a very static manner
char string[100],string1[100],string2[210];
int a,b,c;
scanf("%d %d",&a,&b);
itoa(a,string,10);
itoa(b,string1,10);
string2 = string+string1+string;
c=atoi(string2);
printf("Your number %d",c);
you can also try to think about it mathematically
int a,b;
scanf("%d %d",&a,&b);
int x=b,i=0,c=a;
while (x!=0) { // to get the length of b
i++;
x= x/10; }
int j ;
for (j=1;j<i;j++)
c=c*10;
c=c+b+a;
printf("your number is %d",c);
etc etc

Rotate function,using recursion in C, that takes an array and integer as input

First time posting, I apologize if my question isn't following guidelines but any feedback on my question and posting questions is welcome :)!
I'm working on a problem that requires writing a recursive void function with two parameters, an array and an integer count n, that rotates the first n integers in the array to the left.
So the Input would look something like this:
5 10 20 30 40 50
Output:
50 40 30 20 10
I've written the rotate function using recursion and it seems to work as expected.
#include <stdio.h>
void rotateLeft(int y[], int n){
int temp;
if (n > 1){
temp = y[0];
y[0] = y[1];
y[1] = temp;
rotateLeft(y + 1, n - 1);
}
}
int main(void){
int y[5];
int n;
int i = 0;
//input number from user
printf("Enter 'Count' number and 'elements' into array: ");
scanf("%d", &n);
for (i = 0; i < 5; i++){
scanf("%d", &y[i]);
}
rotateLeft(y, n);
for ( size_t i = 0; i < sizeof( y ) / sizeof( *y ); i++ ) printf( "%d ", y[i] );
puts( "" );
return 0;
}
I'm using Visual Code Studio and I encounter two issues when trying to run this code. The first being the it never asks for my input and it will just output random numbers at the specified array locations such as:
3345345 345456 564565 56 4564
The other times the code just runs and never stops and I have to force it to stop.
I've hit a wall at this point and am positive the issue lies within my main function, but I've hit a wall in my head as where to go. I'm out of coding for the last 5 years so I'm very out of practice.
The code in the answer works fine when compiled with gcc (and entering n less or equal 5, otherwise the rotateLeft method will go beyond the array limit).
Since standard input with scanf doesn't seem to be working, it could be a problem related to how the program is built (it should probably be a win32 or win64 subsystem:console application, link: description of /SUBSYSTEM at Microsoft).
#include <stdio.h>
#include <stdlib.h>
//recursion
//a b c d e
//round-1
//e b c d a
//round-2
//e d c b a
void Rec_ReverseAr(int y[], int n,int max_n){
int temp;
if (max_n > n*2){
temp = y[max_n-n-1];
y[max_n-n-1] = y[n];
y[n] = temp;
Rec_ReverseAr(y, n+1,max_n);
}
}
//inplace
void Better_ReverseAr(int y[],int max_n){
int Upper=max_n/2,i,temp;
for (i = 0; i < Upper; i++){
temp = y[max_n-i-1];
y[max_n-i-1] = y[i];
y[i] = temp;
}
}
int main(){
int *y;
int n;
int i = 0;
//input number from user
printf("Enter 'Count' number and 'elements' into array: ");
scanf("%d", &n);
if(n<1){//prevent nagtive int
printf("Hey You Enter Wrong Number!\n");
return 0;
}
y=(int*)malloc(sizeof(int)*n);//alloc amount n of int for y
for (i = 0; i < n; i++){
scanf("%d", &y[i]);
}
Rec_ReverseAr(y,0,n);
//Better_ReverseAr(y,n);
for (i = 0; i < n; i++ ){
printf( "%d ", y[i] );
}
free(y);//release memory of y
return 0;
}
Here you are
your function
void rotateLeft(int y[], int n){
int temp;
if (n > 1){
temp = y[0];
y[0] = y[1];
y[1] = temp;
rotateLeft(y + 1, n - 1);
}
}
0.a b c d e f
1.*b a* c d e f
2.b *c a* d e f
3.b c *d a* e f
...
is wrong

How to multiply 2 numbers using recursion

I'm trying to multiply (3, 6) and (9, 9) using recursion. However, the result printed is 18 and 45. I need to find out which part is wrong.
Here's my code:
#include <stdio.h>
int multiply (int, int);
int main()
{
int a, b, c;
a = 6; b = 3; c = multiply(a, b);
printf("%d\n", c);
a = 9; b = 9; c = multiply(a, b);
printf("%d\n", c);
return 0;
}
int multiply(int a, int b)
{
static int c = 0, i = 0;
if (i < a) {
c = c + b;
i++;
multiply(a, b);
}
return c;
}
The issue is that multiply's static variables persist from call to call, which throws the second calculation off. It is possible to bandage this wound, but it's better to address the underlying design problem that is compelling use of static variables in the first place. There is no need to artificially maintain state in the function using i (the number of additions to perform) and c (a product accumulator).
Given that multiplication is repeated addition of a b times, you can establish a base case of b == 0 and recursively add a, incrementing or decrementing b (depending on b's sign) until it reaches 0. The product accumulator c is replaced by the function return value and the number of multiplications i is represented by b.
Using this approach, each stack frame's state is naturally self-reliant.
#include <stdio.h>
int multiply(int a, int b) {
if (b > 0) {
return a + multiply(a, b - 1);
}
else if (b < 0) {
return -a + multiply(a, b + 1);
}
return 0;
}
int main() {
printf("%d\n", multiply(3, 6));
printf("%d\n", multiply(9, 9));
printf("%d\n", multiply(-6, 2));
printf("%d\n", multiply(6, -2));
printf("%d\n", multiply(-7, -3));
printf("%d\n", multiply(0, 7));
printf("%d\n", multiply(7, 0));
printf("%d\n", multiply(0, 0));
return 0;
}
Output:
18
81
-12
-12
21
0
0
0
As a final note, I recommend following proper code style. Minifying your code and using single-character variable names only makes debugging more difficult (someone has since de-minified the original code in an edit).
Both c and i need to be reset to zero on each [outer] call to multiply [as others have mentioned] because a function scope static variable is only initialized once.
There is no way to do this because the static variables are at multiply function scope (i.e. how does main access/reset them?). They would need to be moved to global/file scope.
Adding a helper function and moving the variables to global scope will do it:
#include <stdio.h>
int multiply(int, int);
int
main()
{
int a,
b,
c;
a = 6;
b = 3;
c = multiply(a, b);
printf("%d\n", c);
a = 9;
b = 9;
c = multiply(a, b);
printf("%d\n", c);
return 0;
}
static int c, i;
int
mul(int a, int b)
{
if (i < a) {
c = c + b;
i++;
mul(a, b);
}
return c;
}
int
multiply(int a, int b)
{
i = 0;
c = 0;
return mul(a,b);
}
Try resetting your static variables before second call to multiply or do without them
int multiply(int a, int b) {
If (a==0)
return 1;
else if (a>0)
return b+multiply(a-1, b);
else
return - 1*multiply(-1*a, b); }

qsort(): Sorting only even numbers of an array

I'm trying to use the qsort() function in order to sort only the even numbers of an array (the odds remains in their positions).
For instance if I have the array:
5 122 3 26 48
After sorting one would get:
5 26 3 48 122
My intuition was only to make a sort when both numbers pointed by a and b are even.
This is my attempt:
#include <stdio.h>
#include <stdlib.h>
int comp_even(const void *a, const void *b) {
int l = *(int *)a;
int r = *(int *)b;
if ( !(l&1) && !(r&1) ) //if both are even, then sort them in ascending order
return (l-r);
return 0;
}
int main() {
int i, n;
int a[1001];
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
qsort(a, n, sizeof(int), comp_even);
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
return 0;
}
Unfortunately, qsort doesn't support anything like that; for any two elements, the comparison function must return one of three results:
a negative integer, meaning that its first argument should end up before its second;
a positive integer, meaning that its first argument should end up after its second;
zero, meaning that either ordering is fine (in which case qsort makes no guarantees about which element ends up before the other).
And, crucially, the function must do this using only the values of its two arguments; it doesn't know the array-indices that they came from.
Instead, you can take one of two approaches:
copy all of the even elements into an array, sort that array using a straightforward comparison function, and then copy the elements of that array back over the even elements in the original array.
create an int[][2] that stores not just the values in the array, but also their original indices. You can then sort the elements such that if either value is odd, then the element with the lesser original index comes first.
It seems impossible to design a comparison function for your purpose, but you can make a copy of the even numbers, sort that with qsort and dispatch the sorted subset over the even numbers of the original array:
#include <stdio.h>
#include <stdlib.h>
int comp_int(const void *a, const void *b) {
const int *ap = a;
const int *bp = b;
return (*ap > *bp) - (*ap < *bp);
}
int main(void) {
int i, j, n, n_even;
int a[1001];
int even[1001];
if (scanf("%d", &n) != 1 || n <= 0 || n > 1001)
return 1;
n_even = 0;
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
if ((a[i] & 1) == 0) {
even[n_even++] = a[i];
}
}
qsort(even, n_even, sizeof(int), comp_int);
for (i = j = 0; i < n; i++) {
if ((a[i] & 1) == 0) {
a[i] = even[j++];
}
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
Note also that your original comparison function uses a trick to compare integers that fails for large values. The difference of 2 integers may be outside the range of int. So returning l - r may be incorrect for many values of l and r.
For example l=INT_MIN and r=1 will return INT_MIN-1, the subtraction causes an arithmetic overflow, which invokes undefined behavior and in current 2s complement architectures evaluates to INT_MAX, a positive value although INT_MIN < 1.

Given two int numbers A and B. How to find next multiple of B that is not less than A?

Suppose you input A = 15, B = 6, The answer is 18. What algorithm do I need?
This is what I try, but it doesn't work:
#include <stdio.h>
int main() {
int a, b;
scanf("%d %d", &a, &b);
for ( ; a % b != 0; a++ ) {
if ( a % b == 0 ) {
printf("%d\n", a);
return a;
}
}
return 0;
}
I get infinite loop.
The question (now) asks for:
The next multiple of b that is not less than a?
Using your notation of a and b, you can write it directly like this:
int NextMultipleUp(int a, int b)
{
int r = a % b;
if (r == 0)
return a;
else
return a + b - r;
}
The question originally asked for
The next multiple of a that is not greater than b
And for that the answer is
int NextMultipleDown(int a, int b)
{
return b - b % a;
}
This was the answer for which the original comments applied to.
return (((a-1) / b )+1) * b;
Always returns a multiple of b. Increment the integer dividend to get a multiple that is larger than the original a - subtract one from the original, because we want 'not less than' rather than 'greater than' a
I think that you want a do - while iterative loop, so I will give an alternative answer.
How to find next multiple of B that is not less than A?
Obviously this code is slower than David's.
int main ( void ){
int a, b, c;
long int result;
scanf("%d %d", &a, &b);
c = 0;
do {
result = b * c;
c++;
} while ( result < a );
printf( " The number is: %d \n", result );
}
int nextMultiple(int a,int b)
{
if(a%b == 0) return a;
return a+(b-(a%b));
}
so if a=15 b=6
the ans is
=15+(6-(15%6))
=15+(6-(3))
=15+3
=18

Resources