Failed summing/adding every other component inside an integer array - c

I continue my quest to store an input credit card number and validate it.
1) User types hipothetic credit card number, like 1234567898769999 (stored as string).
2) Convert string to an array of integers int digits[].
3) Multiply digitis in positions 1, 3, 5 ... last odd position by 2,
for instance 2*2, 2*4, 2*6, 2*8, 2*8, 2*6, 2*9, 2*9.
4) Store them in the same array and position [4,8,12,16,16, 12, 18,18].
5) Sum digits in positions 0, 2, 4 ... last even position.
Trying to run the code below with abnormal values appearing:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main (void) {
string cc_string;
printf("Please enter a credit card number:\n");
//Capture credit card number
cc_string = GetString();
// Array of integers for credit card digits int cc_digits[15];
int sum_evens, sum_odds = 0;
for (int i = 0; i < 16; i++)
{
cc_digits[i] = cc_string[i] - '0';
//Sum digits in even positions (0 ... 14)
if (i % 2 == 0)
{
sum_evens = sum_evens + cc_digits[i];
//Checking values
printf("cc_digits[%d] = %d; Sum_evens = %d\n", i, cc_digits[i], sum_evens);
}
else if (i % 2 == 1)
{
//Multiplies values in each position by 2 and stores in the same position
cc_digits[i] = 2 * cc_digits[i];
sum_odds = sum_odds + cc_digits[i];
//Checking values
printf("cc_digits[%d] = %d; Sum_odds = %d\n", i, cc_digits[i], sum_odds);
}
}
}
Will anybody have a clue about what is going on here?
It has been three days since I have tried to solve this.
Thanks in advance for the help.

abnormal values appearing
int sum_evens, sum_odds = 0;
Here you have not initialized the value of sum_evens, but you are using it further in your program this way in the if block of for loop:
sum_evens = sum_evens + cc_digits[i];
So, this results in undefined behaviour and thus abnormal values appear. To avoid this, try initializing sum_evens.
int sum_evens = 0, sum_odds = 0;

Related

A function that takes an integer and inserts zeros between its digits

The function should take the address of the integer and modify it by inserting zeros between its digits. For example:
insert_zeros(3) //3
insert_zeros(39) //309
insert_zeros(397) //30907
insert_zeros(3976) //3090706
insert_zeros(39765) //309070605
My code:
#include <stdio.h>
#include <math.h>
void insert_zeros(int* num);
int main() {
int num;
printf("Enter a number:");
scanf("%d", num);
insert_zeros(&num);
printf("Number after inserting zeros: %d", num);
return 0;
}
void insert_zeros(int* num){
int count = 0;
int tmp = *num;
//Count the number of digits in the number
while(tmp != 0){
tmp /= 10;
count++;
}
//calculating the coefficient by which I will divide the number to get its digits one by one
int divider = (int)pow(10, count-1);
int multiplier;
tmp = *num;
*num = 0;
/*
The point at which I'm stuck
Here I tried to calculate the degree for the number 10
(my thought process and calculations are provided below)
*/
(count >= 3)? count += (count/2): count;
//the main loop of assembling the required number
while (count >= 0){
multiplier = (int)pow(10, count); //calculating a multiplier
*num += (tmp / divider) * multiplier; //assembling the required number
tmp %= divider; //removing the first digit of the number
divider /= 10; //decreasing divider
count -= 2; //decreasing the counter,
//which is also a power of the multiplier (witch is 10)
}
}
My idea consists of the following formula:
For number "3" I shold get "30" and it will be:
30 = (3 * 10^1) - the power is a counter for number "3" that equals 1.
For number "39" it will be "309":
309 = (3 * 10^2) + (9 * 10^1)
For number "397" it will be "30907":
30907 = (3 * 10^4) + (9 * 10^2) + (7 * 10^0)
For number "3976" it will be "3090706":
3090706 = (3 * 10^6) + (9 * 10^4) + (7 * 10^2) + (6 * 10^0) - with each iteration power is decreasing by 2
For number "39765" it will be "309070605":
309070605 = (3 * 10^8) + (9 * 10^6) + (7 * 10^4) + (6 * 10^2) + (5 * 10^0)
And so on...
For a 3-digit number, the start power should be 4, for a 4-digit number power should be 6, for a 5-digit it should be 8, for 6-digit it should be 10, etc.
That algorithm works until it takes a 5-digit number. It outputs a number like "30907060" with an extra "0" at the end.
And the main problem is in that piece of code (count >= 3)? count += (count/2): count;, where I tried to calculate the right power for the first iterating through the loop. It should give the right number to which will be added all the following numbers. But it only works until it gets a 5-digit number.
To be honest, so far I don't really understand how it can be realized. I would be very grateful if someone could explain how this can be done.
As noted in comments, your use of scanf is incorrect. You need to pass a pointer as the second argument.
#include <stdio.h>
#include <math.h>
int main(void) {
int num;
scanf("%d", &num);
int num2 = 0;
int power = 0;
while (num > 0) {
num2 += (num % 10) * (int)pow(10, power);
num /= 10;
power += 2;
}
printf("%d\n", num2);
return 0;
}
There's an easy recursive formula for inserting zeros: IZ(n) = 100*IZ(n/10) + n%10.
That gives a very concise solution -- here the test cases are more code than the actual function itself.
#include <stdio.h>
#include <stdint.h>
uint64_t insert_zeros(uint64_t n) {
return n ? (100 * insert_zeros(n / 10) + n % 10) : 0;
}
int main(int argc, char **argv) {
int tc[] = {1, 12, 123, 9854, 12345, 123450};
for (int i = 0; i < sizeof(tc)/sizeof(*tc); i++) {
printf("%d -> %lu\n", tc[i], insert_zeros(tc[i]));
}
}
Output:
1 -> 1
12 -> 102
123 -> 10203
9854 -> 9080504
12345 -> 102030405
123450 -> 10203040500
Adapting some code just posted for another of these silly exercises:
int main() {
int v1 = 12345; // I don't like rekeying data. Here's the 'seed' value.
printf( "Using %d as input\n", v1 );
int stack[8] = { 0 }, spCnt = -1;
// Peel off each 'digit' right-to-left, pushing onto a stack
while( v1 )
stack[ ++spCnt ] = v1%10, v1 /= 10;
if( spCnt == 0 ) // Special case for single digit seed.
v1 = stack[ spCnt ] * 10;
else
// multiply value sofar by 100, and add next digit popped from stack.
while( spCnt >= 0 )
v1 = v1 * 100 + stack[ spCnt-- ];
printf( "%d\n", v1 );
return 0;
}
There's a ceiling to how big a decimal value can be stored in an int. If you want to start to play with strings of digits, that is another matter entirely.
EDIT: If this were in Java, this would be a solution, but the problem is in C, which I'm not sure if this can convert to C.
This may be a lot easier if you first convert the integer to a string, then use a for loop to add the zeros, then afterward reconvert to an integer. Example:
int insert_zeros(int num) {
String numString = Integer.toString(num);
String newString = "";
int numStringLength = numString.length();
for (int i = 0; i < numStringLength; i++) {
newString += numString[i];
// Only add a 0 if it's not the last digit (with exception of 1st digit)
if (i < numStringLength - 1 || i == 0) newString += '0';
}
return Integer.parseInt(newString);
}
I think this should give you your desired effect. It's been a little bit since I've worked with Java (I'm currently doing JavaScript), so I hope there's no syntax errors, but the logic should all be correct.

CS50 Luhn's Algorithm in C. Help much appreciated :)

I need to solve the problem on the link below, using Luhn's algorithm and what we have learned so far in CS50 (no arrays).
My program compiles but it doesn't identify the card type. What am I doing wrong?
Many thanks in advance!
Problem: https://cs50.harvard.edu/x/2020/psets/1/credit/#:~:text=check50%20cs50/problems/2020/x/credit
/* This program checks if a bank card number is syntactically valid, using Luhn's algorithm */
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
long long n, temp;
int digit, last, first, product;
int lenght = 0;
int sumOdd, sumEven;
// Prompt user for input as long as the inputted number is equal or smaller than zero
do
{
n = get_long_long("Enter your credit card number without special characters:\n");
} while (n < 0);
// Count the number of digits
while (n > 0)
{
n = n/10;
lenght++;
}
// Check if the number's length is valid
if (lenght != 13 && lenght != 15 && lenght != 16)
{
printf("INVALID");
}
// Find the last digit and add it to the even sum
while (n > 0)
{
last = n % 10;
temp = n - last;
sumEven = sumEven + last;
}
/* Starting with second-to-last digit, multiply every other digit by 2. Add those
products together and then add the sum to the sum of the digits that weren't multiplied by 2 */
while (n > 0)
{
digit = n % 10;
temp = n/10;
if (lenght % 2 == 0)
{
product = digit * 2;
sumOdd = sumOdd + product;
} else
{
sumEven = sumEven + digit;
}
// If the last digit of the sum of sums is zero print the number. Else print INVALID.
if (sumOdd + sumEven % 10 != 0)
{
printf("INVALID\n");
}
else
{
printf("%lld\n", n);
}
// Identify the user's card type as per CS50 Credit instructions. Cards commencing with 3 are AMEX, with 5 MasterCard and with 4, VISA.
while (first >= 10)
{
first = n;
first = first / 10;
if (first == 3)
{
printf("AMEX\n");
}
if (first == 5)
{
printf("MASTERCARD\n");
}
if (first == 1)
{
printf ("VISA\n");
}
}
}
}
You have several consecutive while blocks
while (n>0){
// some code
}
while (n>0){
// some code
}
Your program will only exit the first loop when n is no longer larger than 0. When it reaches the next while loop n will still not be larger than 0 so the body of the next while loop will never be entered. Large chunks of your code are not getting executed.

sprintf "access violation reading location" exception

I'm taking a programming class in C, and I've run into a bug I can't solve no matter how hard I try.
The program instructs me to:
"Ask the user for the first 12 digits of an EAN number, then calculate the 13th "security" digit by performing the following operations:
Add the second, fourth, sixth, eighth, tenth, and twelfth digits
Add the first, third, fifth, seventh, ninth, and eleventh digits
Multiply the first sum by 3 and add it to the second sum
Subtract 1 from the total
Compute the remainder when the adjusted total is divided by 10
Subtract the remainder from 9
I'm coming from Python, so the easiest way to split the number into it's individual digits is to convert it to a string and then revert each element in the character array to an int stored in an integer array.
Here's my code so far:
#include <stdio.h>
int main(void)
{
long ean; //creates variable to store a 12 digit integer
int digits[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //initializes a 1x12 integer array
printf("Please enter the first 12 digits in your EAN: ");
scanf_s("%ld", &ean); //collects the appropriate user input and stores it in ean
char seperated[12]; //creates character array
**sprintf_s(seperated, "%ld", ean); //converts the long integer ean to a string called separated
for (int i = 0; i < 12; i++)
{
sscanf_s(seperated[i], "%d", &digits[i]); //iterates through the characters and converts each one to an integer
//stored in the array created earlier
printf("%d\n", digits[i]);
}
int sumEvens = digits[1] + digits[3] + digits[5] + digits[7] + digits[9] + digits[11]; //sums the even digits
int sumOdds = digits[0] + digits[2] + digits[4] + digits[6] + digits[8] + digits[10]; //sums the odd digits
int total = (3 * sumEvens + sumOdds)-1; //multiplies the first sum by 3 and adds it to the second sum,
//then subtracts one from the total
int securityDigit = 9 - (total % 10); //Computes the remainder when the total is divided by 10 and subtracts that from 9
return 0;
}
The problem is, my sprintf statement (marked with **) is throwing an exception saying
Exception thrown at 0x0FB7373A (ucrtbased.dll) in ECE1400_2.exe: 0xC0000005: Access violation reading location 0xBE991A6D.
Does anyone know what I'm doing wrong and how I can fix it? I hope it's just something little, but I've been staring at this and researching for well over 2 hours.
there's a lot of unnecessary part.
int main()
{
char s[12] = {0};
int n = 0;
int digits[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //initializes a 1x12 integer array
printf("Please enter the first 12 digits in your EAN: ");
for (int i = 0; i < 12; i++)
{
scanf("%d", &digits[i]);
}
int sumEvens = digits[1] + digits[3] + digits[5] + digits[7] + digits[9] + digits[11]; //sums the even digits
int sumOdds = digits[0] + digits[2] + digits[4] + digits[6] + digits[8] + digits[10]; //sums the odd digits
int total = (3 * sumEvens + sumOdds)-1; //multiplies the first sum by 3 and adds it to the second sum,
//then subtracts one from the total
int securityDigit = 9 - (total % 10); //Computes the remainder when the total is divided by 10 and subtracts that from 9
for (int i = 0; i <= 11; i++) {
n += sprintf (&s[n], "%d", digits[i]);
}
}
You probably want to do something like this
int main(void)
{
int a[5]={1,2,3,1,3};
char s[9] = {0};
int n = 0;
for (int i = 0; i < 5; i++) {
n += sprintf (&s[n], "%d", a[i]);
}
printf ("\n char* s = %s\n\n", s);
return 0;
}
instead of making it long.
and there's no need for you to use sscanf_s as mentioned in the comments.
This would be a start:
int main(void)
{
__int64 ean; // using 64 bit integer
int digits[12] = { 0 }; // one zero is enough
printf("Please enter the first 12 digits in your EAN: ");
scanf_s("%lld", &ean); // using %lld here because ean is a 64 bit type
char seperated[12];
sprintf_s(seperated, 12, "%lld", ean); // also using %lld
for (int i = 0; i < 12; i++)
{
digits[i] = seperated[i] - '0'; // I let you find out yourself about this "magic"
printf("%d\n", digits[i]);
}
...

Trying to implement Luhn's Algorithm in C

Iam trying to implement Luhn's algorithm in the C language to check credit card validity, for those who don't know... this is it:
Multiply every other digit by 2, starting with the number’s
second-to-last digit, and then add those products’ digits together.
Add the sum to the sum of the digits that weren’t multiplied by 2.
If the total’s last digit is 0 (or, put more formally, if the total
modulo 10 is congruent to 0), the number is valid!
and to implement that, I looped through the whole number and if the number place I was in had a modulo 2 equal to 0 then I would multiply by two and add to a variable called totalEven.
if that wasn't the case I would add the number I was in to totalOdd without multiplication.
I would then increment the place by one and check the other numbers until I reach 16 (the max digits for a card).
I would later add both variables and check if the total modulo ten was equal to 0. If it means the credit card number is correct, else it is false.
here is the code:
#include <stdio.h>
#include <cs50.h>
//list of variables
//is the card valid
bool isValid = true;
// the creditcard number
long input;
//mod stands for modules, and is used to single out each number as seen later
int mod = 10;
//the location at which number I am checking
int place = 1;
//num is the number I am checking that has been singled out
int num = 0;
//total of numbers * 2 located at locations numbered with even numbers
int totalEven = 0;
//total of numbers located at locations numbered with odd numbers
int totalOdd = 0;
//gets input and stores it in well.. input
input = get_long("Number: ");
// a formula to single out a number, starting with the ones and then as you can see, mod is muliplied by 10 to go over the second number.
num = ((input % mod) - (input % (mod /10))) / (mod/10);
//loops 16 times
for(int i = 0; i < 16; i++)
{
// if the place is even execute below
if(place % 2 == 0)
{
totalEven = totalEven + num * 2;
}
//else do this
else if (place % 2 != 0)
{
totalOdd = totalOdd + num;
}
//moves to the next number
mod = mod * 10;
place++;
}
//fufils the last step of the algorithm
if((totalEven + totalOdd) % 10 == 0 )
{
isValid = true;
}
else
{
isValid = false;
}
problem is that this block of code gives me invalid or !isValid even though the credit card number is supposed to be correct and I checked my "formula" and it works just fine...
I have absolutely no idea what to do... I am a humble hobbyist so plz don't roast me for the monstrosity above.
here is a complete version of the code
#include <stdio.h>
#include <cs50.h>
long power();
int main(void)
{
//AMERX 15 STRT 34 OR 37
//MC 16 STRT 51, 52, 53, 54, 55
//VZA 13 OR 16 STRT 4
long input;
bool isValid = true;
string type;
int mod = 10;
int place = 1;
int num = 0;
int totalEven = 0;
int totalOdd = 0;
do
{
input = get_long("Number: ");
}
while(input < 0);
for(int i = 0; i < 16; i++)
{
num = ((input % mod) - (input % (mod /10))) / (mod/10);
if(place % 2 == 0)
{
totalEven = totalEven + num * 2;
}
else
{
totalOdd = totalOdd + num;
}
mod = mod * 10;
place++;
}
if((totalEven + totalOdd) % 10 == 0 )
{
isValid = true;
}
else
{
isValid = false;
printf("%i , %i", totalEven, totalOdd);
}
if (isValid == true){
if((input < (38 * power(10, 13)) && input >=(37 * power(10, 13))) || (input < (35 * power(10,13)) && input >= (34 * power(10, 13))))
{
type = "AMEX\n";
}
else if(input >= (51 * power(10, 14)) && input < (56 * power(10, 14)))
{
type = "MASTERCARD\n";
}
else if((input < (5 * power(10, 12)) && input >= (4 * power(10, 12))) || (input < (5 * power(10, 15)) && input >= (4 * power(10, 15))))
{
type = "VISA\n";
}
else{
type = "error\n";
}
}
else
{
type = "INVALID\n";
}
if((totalEven + totalOdd) % 10 == 0 )
{
isValid = true;
}
else
{
isValid = false;
}
printf("%s", type);
}
long power(int n, int p)
{
long result = 1;
for(int i = 0; i<p; i++)
{
result = result * n;
}
return result;
I'm not an expert in Luhn algorithm but when I read https://en.wikipedia.org/wiki/Luhn_algorithm it seems to me that you are doing it wrong.
Quote from https://en.wikipedia.org/wiki/Luhn_algorithm :
From the rightmost digit (excluding the check digit) and moving left, double the value of every second digit. The check digit is neither doubled nor included in this calculation; the first digit doubled is the digit located immediately left of the check digit. If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then add the digits of the result (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or, alternatively, the same final result can be found by subtracting 9 from that result (e.g., 16: 16 − 9 = 7, 18: 18 − 9 = 9).
I don't see anywhere in your code where you handle that bolded part.
Instead of
totalEven = totalEven + num * 2;
I think you need
int tmp = num * 2;
if (tmp > 9) tmp = tmp - 9;
totalEven = totalEven + tmp;
That said - I think you are making the implementation much more complex than needed by storing the input as a number. Instead of a number you could use an array of digits.
That is - instead of
long input = 1122334455667788
use
int digits[] = {8, 8, 7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1};
// Notice that index zero is the rightmost digit
In this way the algorithm is much more simple:
// Double every second element and check for overflow
for (idx = 1; idx < 16; idx += 2)
{
digits[idx] = 2 * digits[idx];
if (digits[idx] > 9) digits[idx] = digits[idx] - 9;
}
// Calculate the sum
sum = 0;
for (idx = 0; idx < 16; ++idx)
{
sum = sum + digits[idx];
}
If you must receive the input as a number, start by calling a function that converts the number to an array of digits. You can find many, many examples of how that conversion is done here on SO. Here Converting integer into array of digits is just one of many examples.
As I was looking at your code, there some mistakes I want to point out.
You forgot: #include <string.h> as you did declare string type in the code.
input = get_long("Number: "); should have its own do-while loop in case user inputs letters or incorrect numbers.
if(place % 2 == 0){
totalEven = totalEven + num * 2;
}
else if (place % 2 != 0){
totalEven = totalEven + num;
} should totalOdd = totalOdd + num for the second part
totalEven = totalEven + num * 2 is right and wrong at the same time. It only works if the number multiplied by 2 is less than 10. If the num * 2 >= 10, lets say num = 6, then 6 * 2 is 12 which would then be 1 + 2 + totalEven.
num = ((input % mod) - (input % (mod /10))) / (mod/10); This should be in the first for loop.
In #include <math.h>, there is a power function called pow which does exactly as your power() function.
Caution: I have made use of CS50X Library as the question seems to be the one from the same.
#include <stdio.h>
#include <cs50.h>
// Luhn's Algorithm
int main(void)
{
long cardNumber = get_long("Please, enter your card number: ");
int sum1 = 0, num = 0, remainder = 0, sum2 = 0;
long temp = cardNumber;
while (temp > 0)
{
num = ((temp / 10) % 10) * 2; // Multiplying every other digit by 2, starting with the number’s second-to-last digit
while (num > 0)
{
remainder = num % 10;
sum1 += remainder; // Adding those products’ digits together
num /= 10;
}
temp /= 100;
}
// So as to restore the initial values of remainder and temp for the use in next loop
remainder = 0;
temp = cardNumber;
while (temp > 0)
{
remainder = temp % 10;
sum2 += remainder; // Sum of the digits that weren’t multiplied by 2
temp /= 100;
}
((sum1 + sum2) % 10) == 0 ? printf("Valid\n") : printf("Invalid\n");
return 0;
}

C programming segmentation error

This is the code for finding the last digit of nth Fibonacci number
#include <stdio.h>
int main() {
long i, j, fib[1000];
fib[0] = 0;
fib[1] = 1;
scanf("%li", &j);
for(i = 2; i != 1000; i++)
{
fib[i] = (fib[i - 2] + fib[i - 1]) % 10;
}
printf("%li", fib[j]);
return 0;
}
It shows segmentation fault. How can I fix it?
The only reason I can see for this not working is that you're inputting a number that is outside of the range 0 <= j <= 999. This is due to the limit on your array variable: long fib[1000].
This can be fixed in one of two ways, depending on what you want:
You can add a check to make sure that the input value j is in range, and ask for another number if it isn't.
You can stop using an array variable, and only use three variables: one to store the current value, and two more to store the two previous values. These are updated as you calculate. A loop is still used with this approach.
#1 is the simplest to implement, as shown here:
while (1)
{
printf("j > ");
scanf(" %li", &j);
if (0 <= j <= 999)
{
break;
}
}
#2 is a bit more complex, but it effectively removes the arbitrary limit that j must be less than 1000 (and changes the limit so that j must be less than LONG_MAX):
// num_cache[0] is the number before the previous number
// num_cache[1] is the previous number to the current number
long num_cache[2] = { 0, 0 };
long current_fib = 1;
for (i = 2; i < j; i++)
{
// Push back the numbers
num_cache[0] = num_cache[1];
num_cache[1] = current_fib;
// Calculate the new number
current_fib = (num_cache[0] + num_cache[1]) % 10;
}
One of those solutions should fix your issue.
It appears that the segmentation fault is occurring due to inadequate checking of input values.
If the input to the program is not a valid number, then the value of j will be unchanged after the call to scanf(). Since this variable is uninitialized, this will result in undefined behaviour when you attempt to access the jth element of the fib[] array.
If the value of j is less than zero or greater than 999, you will be accessing a non-existent member of fib[] when you exit the for() loop. Your code should check that j is valid before continuing.
Here's your code with a few modifications to implement these safeguards and move the "magic number" 1000 to a #defined value.
#include <stdio.h>
#define FIBONACCI_LIMIT 1000L
int main(){
long i, j, fib[FIBONACCI_LIMIT];
fib[0] = 0;
fib[1] = 1;
if (scanf("%li", &j) != 1)
{
fprintf(stderr, "Invalid input\n");
return 1;
}
if (j<0 || j>=FIBONACCI_LIMIT)
{
fprintf(stderr, "Number must be in range 0 <= n < %li\n", FIBONACCI_LIMIT);
return 2;
}
for(i=2; i!=1000; i++)
{
fib[i] = (fib[i-2] + fib[i-1])%10;
}
printf("%li\n", fib[j]);
return 0;
}
The code can be improved by getting rid of the fib[] array altogether, since there is no need to store 1000 values when you only need to calculate one value. Furthermore, the final digits of numbers in the Fibonacci sequence form a repeating pattern of 60 values, so your first step should be to replace j with j % 60. Here is an improved version of the code that will work with any non-negative input capable of fitting into a long integer:
#include <stdio.h>
int main() {
long i, j, t, f0=0, f1=1;
if (scanf("%li", &j) != 1)
{
fprintf(stderr, "Invalid input\n");
return 1;
}
if (j < 0)
{
fprintf(stderr, "Number must be non-negative\n");
return 2;
}
j %= 60;
for (i=0; i<j; i++)
{
t = f0;
f0 = f1;
f1 = (f1 + t) % 10;
}
printf("%li\n", f0);
return 0;
}
You did not show what value of the variable j was entered.
Take into account that the next Fibonacci number is calculated incorrectly in the loop.
If to use the integer type unsigned long long then an object of this type can accommodate only 93 Fibonacci numbers.
The program can look like
#include <stdio.h>
#define N 100
int main(void)
{
while ( 1 )
{
unsigned long long fib[N] = { 0, 1 };
unsigned int n;
printf( "Enter a sequantial number of a fibonacci number (0 - exit): " );
if ( scanf("%u", &n) != 1 || n == 0 ) break;
unsigned int i = 2;
for (; i < N && i <= n && fib[i-1] <= fib[i-2] + fib[i-1]; i++)
{
fib[i] = fib[i - 2] + fib[i - 1];
}
if (n < i)
{
printf("#%u: %llu %llu\n", n, fib[n], fib[n] % 10);
}
else
{
puts("Too big fibonacci number");
}
}
return 0;
}
Its output might look like
Enter a sequantial number of a fibonacci number (0 - exit): 1
#1: 1 1
Enter a sequantial number of a fibonacci number (0 - exit): 2
#2: 1 1
Enter a sequantial number of a fibonacci number (0 - exit): 3
#3: 2 2
Enter a sequantial number of a fibonacci number (0 - exit): 93
#93: 12200160415121876738 8
Enter a sequantial number of a fibonacci number (0 - exit): 94
Too big fibonacci number
Enter a sequantial number of a fibonacci number (0 - exit): 0

Resources