Fibonacci number code with for-loop and if statement error - c

so i'm a beginner and trying to solve a small project about making fibonacci number.
The code essentially is about typing n (the sequence) and it will show you what value of fibonacci number in that n-sequence.
but of course the code went wrong, the code just stop until i type the n-sequence, and nothing being printed after that. Can anybody check my code pls?
#include <stdio.h>
int main(){
int n;
int seq[n];
int i;
printf("number of sequence for the fibonacci number that you want to find out (from 0)= ");
scanf("%d", &n);
for(i = 0; i <= n; i++){
if(i == 0){
seq[i] = 0;
}
else if(i == 1){
seq[i] = 1;
}
else if(i > 1){
seq[i] = seq[i-1] + seq[i-2];
}
}
if(i == n){
printf("the value in sequence %d is %d", n, seq[n]);
}
return 0;
}

You need to declare the variable length array seq after you entered its size
For example
int n;
int i;
printf("number of sequence for the fibonacci number that you want to find out (from 0)= ");
scanf("%d", &n);
int seq[n + 1];
The size of the array is specified as n + 1 because the user is asked to enter the fibonacci number starting from 0.
Also this for loop will be correct provided that the array has n + 1 elements.
for(i = 0; i <= n; i++){
It is better to write it like
for(i = 0; i < n + 1; i++){
And this if statement
if(i == n){
does not make a sense. Just output the value of the array element seq[n].

apparently, in the loop, you set the boarder as i<=n while the array seq[n] is with the size of n. So i must be less than n.

n is uninitialized. It contains a garbage value.
Don't use scanf() for reading user input. It is very error-prone. Just try typing some string and see what happens. Better use fgets() in combination with sscanf().
int n;
char input[255];
printf("Number of sequence: ");
fgets(input, sizeof input, stdin);
input[strcspn(input, "\n")] = '\0';
if (sscanf(input, "%d", &n) != 1) {
// Handle input error
}
int seq[n+1]; // Edited: n+1 because fib starts from 0
int i;
for (i = 0; i < n+1; i++) {
if (i == 0 || i == 1)
seq[i] = i;
else
seq[i] = seq[i-1] + seq[i-2];
}

Related

How do I make scanf function print whole array

I wrote a simple code that should read an array and print it, but it doesn't print anything.
What I noticed is that, when I make first for loop go to n-1 instead of n (but second loop still goes to n), it actually works. Example:
Input: 1 2 3 4 5 6
Output: 1 2 3 4 5 0
It also works when the second loop goes to n-1, so the mistake is in the first loop or scanf function.
What can I do to make it print whole array?
#include <stdio.h>
#define MAX_LENGTH 50
int main() {
int a[MAX_LENGTH];
int n, i;
printf("Insert the length of array: ");
scanf("%d", &n);
printf("Insert elements of array: ");
for (i = 0; i < n; i++)
scanf("%d ", &a[i]);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
The problem is you have a trailing space in the scanf() format: scanf keeps waiting for more input until you enter something that is not white space, newline being white space.
You should just use "%d" as a scanf() format.
Furthermore, you should check the return value of scanf() to avoid undefined behavior upon invalid input.
Here is a corrected version:
#include <stdio.h>
#define MAX_LENGTH 50
int main() {
int a[MAX_LENGTH];
int n, i;
printf("Insert the length of array: ");
if (scanf("%d", &n) != 1)
return 1;
if (n > MAX_LENGTH) {
printf("too many numbers, limiting to %d\n");
n = MAX_LENGTH;
}
printf("Insert elements of array: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1)
return 1;
}
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}

Unable to print numbers entered into an array in reverse order

I'm attempting to write a program with an array in which:
The user enters 10 integers, and the integers are then displayed in reverse order, or
The user enters up to 10 integers and exits the while-loop using a 0, and the integers entered are then displayed in reverse order.
The code below is my best effort (my 5th attempt at solving the problem), but it's collecting the integer zero and displaying it in the array index (I've attempted to attach the other five, but it keeps producing an error):
int main()
{
#define ARRAY_LENGTH 10
int numbers[ARRAY_LENGTH];
int numbersEntered = 0;
for (int i = 0; i < ARRAY_LENGTH; i++)
{
numbers[i] = 0;
}
int number = 0;
printf("Enter an integer; 0 to quit: ", ARRAY_LENGTH - 1);
scanf_s("%d", &number);
while (number != 0 && numbersEntered < ARRAY_LENGTH - 1)
{
numbersEntered++;
numbers[numbersEntered] = number;
printf("Enter another integer; 0 to quit: ", ARRAY_LENGTH - 1);
scanf_s("%d", &number);
}
for (int i = numbersEntered; i >= 0; i--)
{
printf("index %d -> %d\n", i, numbers[i]);
}
}
See the problem is first you're initializing the entire array with zero here
for (int i = 0; i < ARRAY_LENGTH; i++)
{
numbers[i] = 0;
}
Then you're doing this
while (number != 0 && numbersEntered < ARRAY_LENGTH - 1)
{
numbersEntered++;
numbers[numbersEntered] = number;
printf("Enter another integer; 0 to quit: ", ARRAY_LENGTH - 1);
scanf_s("%d", &number);
}
So what is happening is, since numbersEntered was already initialized with zero you're incrementing it by 1, so the first digit is entered in the array numbers is 0 as you initialized the entire array itself in the start.
So a quick fix would be just to move it a line down and change the while loop code to this
while (number != 0 && numbersEntered < ARRAY_LENGTH - 1)
{
numbers[numbersEntered] = number;
numbersEntered++;
printf("Enter another integer; 0 to quit: ", ARRAY_LENGTH - 1);
scanf_s("%d", &number);
}
Also as pointed out by Kiran in the comments, the printing for loop needs to be changed to this
for (int i = numbersEntered-1; i > 0; i--)
{
printf("index %d -> %d\n", i, numbers[i]);
}
The line
printf("Enter an integer; 0 to quit: ", ARRAY_LENGTH - 1); should be
printf("Enter an integer; 0 to quit: ");
You should use scanf not scanf_s
The following code could work:
#include <stdio.h>
#define ARRAY_LENGTH 10
int main()
{
int numbers[ARRAY_LENGTH];
int i;
int k;
for (k = 0; k != ARRAY_LENGTH; ++k)
{
printf("Enter an integer; 0 to quit: ");
if (scanf("%d", numbers + k) != 1 || numbers[k] == 0)
break;
}
for (i = k - 1; i >= 0; --i)
printf("index %d -> %d\n", i, numbers[i]);
return 0;
}
This here is a solution of mine which includes some good practices, that is a tweak of your code:
1) you would want your defines outside of a function (or main) so that you can use the same constant in the entire program;
2) any function that has a return type (e.g int main) must return something at the end, thus you must have a "return 0" at the end of your main function;
3) the do-while part will ensure that your piece of code will be executed once before the while condition is checked;
4) numbers[numbersEntered++] = number; will assign to "numbers[numbersEntered]" the value of "number" and then will increment "numbersEntered" by one; This is to reduce the amount of code that you have to write :);
Hope this helped, and if you have more questions, I hope I can answer them :).
#define ARRAY_LENGTH 10
int main()
{
int numbers[ARRAY_LENGTH];
int numbersEntered = 0;
for (int i = 0; i < ARRAY_LENGTH; i++)
numbers[i] = 0;
int number = 0;
do
{
printf("Enter an integer; 0 to quit: ");
scanf_s("%d", &number);
if (number == 0)
break;
numbers[numbersEntered++] = number;
} while (number != 0 && numbersEntered < ARRAY_LENGTH);
if (numbersEntered > 0)
{
for (int i = numbersEntered - 1; i >= 0; i--)
printf("index %d -> %d\n", i, numbers[i]);
}
return 0;
}
I think it's because you are not inserting any number to the first place in the array (place[0]), because you are prompting the value of numbersEntered too early. Try to write your loop this way:
while (number != 0 && numbersEntered < ARRAY_LENGTH - 1){
numbers[numbersEntered] = number;
printf("Enter another integer; 0 to quit: ", ARRAY_LENGTH - 1);
scanf_s("%d", &number);
numbersEntered++;
}

Adding values based on the user's input in array basis

I'm stuck with this code:
int main()
{
int a[ ] = {0};
int n,sum = 0;
printf("Enter your element: ");
scanf("%d", &a[n]);
while(n != -1)
{
sum = sum + a[n];
printf("Enter your element: ");
scanf("%d", &n);
}
printf("The sum is %d", sum);
}
My aim is to make a prompt to user to enter his value that will be stored in the elements of the array, then give him the sum of the values that he entered.
However the code does not show any error, but it ends up giving garbage value.
You probably want this:
#include <stdio.h>
int main()
{
int a[100] = { 0 }; // array of 100 numbers all initialized to 0
int sum = 0;
int n = 0;
do
{
printf("Enter your element: ");
int number;
scanf("%d", &number);
if (number == -1)
break;
a[n] = number;
sum += a[n];
n++;
}
while (1);
printf("The sum is %d", sum);
}
Disclaimer: There is no error checking, and there is no check if you entewr more than 100 numbers which results in an index out of range problem.
scanf("%d", &a[n]); accessing array index out of bound if n!=0 this is Undefined Behavior.
And n is uninitialized. So using that as an index is using as index in the array some indeterminate value.
while(n!=1) is not an exhaustive check. better would be n==0 as the array has only 1 element.
Maybe you wanted this
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
printf("Enter no of element: ");
if( scanf("%d", &n) != 1){
fprintf(stderr,"%s","Error in input");
exit(1);
}
if( n <= 0){
fprintf(stderr,"Enter positive number of elements");
exit(1);
}
int a[n];
int sum = 0;
for(size_t i = 0; i < n; i++){
if( scanf("%d",&a[i]) != 1){
fprintf(stderr,"%s","Error in input: give integers");
exit(1);
}
sum+=a[i];
}
printf("The sum is %d", sum);
}
Notice that this program has the following flaws which is difficult to overcome with scanf() - you can try to modify over this using strtol and overflow-checking
If user inputs something other than this range [INT_MIN,INT_MAX], thre will be overflow. (Soln: Use strtol)
Sum can overflow given any large inputs whose sum is not in this range.
(Overflow check:
if ((a[i] > 0 && sum > INT_MAX - a[i]) || (a[i] < 0 && sum < INT_MIN - a[i]))
{
fprintf(stderr,"%s","Sum has overflown");
exit(1);
}

C program for assigning elements of a matrix without letters

I'm having trouble outputting an invalid statement if the user inputs a letter instead of a number into a 2D array.
I tried using the isalpha function to check if the input is a number or a letter, but it gives me a segmentation fault. Not sure what's wrong any tips?
the following code is just the part that assigns the elements of the matrix.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main() {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
scanf("%d", &n);
if (n <= 1 || n >= 11) { // can't be bigger than a 10x10 matrix
printf("Invalid input.");
return 0;
}
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (!isalpha(matrix[i][j])) { // portion I'm having trouble with
continue;
} else {
printf("Invalid input.");
return 0;
}
}
}
...
As the value of n will be number, we can solve it using string instead of int.
char num[10];
int n;
scanf("%s", num);
if(num[0] < '0' || num[0] > '9' || strlen(num) > 2){
printf("invalid\n");
}
if(strlen(num) == 1) n = num[0] - '0';
if(strlen(num) == 2 && num[0] != 1 && num[1] != 0) printf("invalid\n");
else n = 10;
Also we can use strtol() function to convert the input string to number and then check for validity.You can check the following code for it. I have skipped the string input part. Also you have to add #include<stdlib.h> at the start for the strtol() function to work.
char *check;
long val = strtol (num, &check, 10);
if ((next == num) || (*check != '\0')) {
printf ("invalid\n");
}
if(val > 10 || val < 0) printf("invalid\n");
n = (int)val; //typecasting as strtol return long
You must check the return value of scanf(): It will tell you if the input was correctly converted according to the format string. scanf() returns the number of successful conversions, which should be 1 in your case. If the user types a letter, scanf() will return 0 and the target value will be left uninitialized. Detecting this situation and either aborting or restarting input is the callers responsibility.
Here is a modified version of your code that illustrates both possibilities:
#include <stdio.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main(void) {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
if (scanf("%d", &n) != 1 || n < 2 || n > 10) {
// can't be bigger than a 10x10 matrix nor smaller than 2x2
// aborting on invalid input
printf("Invalid input.");
return 1;
}
for (int i = 0; i < n; i++) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; j++) {
if (scanf("%d", &matrix[i][j]) != 1) {
// restarting on invalid input
int c;
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("unexpected end of file\n");
return 1;
}
}
printf("invalid input, try again.\n");
j--;
}
}
}
...
The isdigit() library function of stdlib in c can be used to check if the condition can be checked.
Try this:
if (isalpha (matrix[i][j])) {
printf ("Invalid input.");
return 0;
}
So if anyone in the future wants to know what I did. here is the code I used to fix the if statement. I am not expecting to put any elements greater than 10000 so if a letter or punctuation is inputted the number generated will be larger than this number. Hence the if (matrix[i][j] > 10000). May not be the fanciest way to do this, but it works and it's simple.
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (matrix[i][j] > 10000) { // portion "fixed"
printf("Invlaid input");
return 0;
}
}
}
I used a print statement to check the outputs of several letter and character inputs. The lowest out put is around and above 30000. So 10000 I think is a safe condition.

C - scan user inputs into an array to be sorted

Forgive me, I'm a C programming rookie. What I need to do is take values from standard input and store them in an array which is to be sorted later on down the line.
The method of entry for the user is one number on one line at a time (i.e. enter a number, press enter, enter number, press enter, etc..). When the user is done entering numbers, they press ENTER without providing a number.
My code for accepting the values and storing them is as follows. You'll probably see the issue immediately, but I'm not seeing it.
#include <stdio.h>
#define MAX 100
int main()
{
int n, i, array[MAX];
printf("Enter a list of integers\n");
for(i = 0; i <= MAX; ++i){
printf("> ");
if (scanf("%d", &n) == -1)
break;
else
scanf("%d", &n);
array[i] = n;
}
printf("The array is %d", *array);
return 0;
}
The picture below is how the program should run. I have the sort code already, and it seems to work quite well. Your help is greatly appreciated.
You have it doing what you want, you just need a few tweaks. First, enter doesn't return -1, to keep it simple you need to enter ctrl+d to stop input. After your final input, just hit ctrl+d. Take a look:
#include <stdio.h>
#define MAX 100
int main()
{
int n, i, array[MAX];
printf("Enter a list of integers [ctrl+d] to end\n");
for(i = 0; i <= MAX; ++i){
printf("> ");
if (scanf("%d", &n) == -1)
break;
array[i] = n;
}
puts ("");
int z;
for (z = 0; z < i; z++)
printf("The array is %d\n", array[z]);
return 0;
}
output:
Enter a list of integers [ctrl+d] to end
> 1
> 2
> 3
> 4
> 5
>
The array is 1
The array is 2
The array is 3
The array is 4
The array is 5
Here is the updated previous answer to exit on enter.
#include <stdio.h>
#define MAX 100
int main()
{
int n, i, array[MAX];
char num[MAX];
int res;
printf("Enter a list of integers [ctrl+d] to end\n");
for(i = 0; i <= MAX; ++i){
printf("> ");
fgets(num, sizeof(num), stdin);
res = sscanf(num, "%d", &n);
if(res != 1)
break;
n = atoi(num);
array[i] = n;
}
puts ("");
int z;
for (z = 0; z < i; z++)
printf("The array is %d\n", array[z]);
return 0;
}

Resources