Getting segmentation fault after while loop - c

Hi i have a project for tommorrow which i want to finish but im stuck. Im pretty new at this so don't be harsh.Basicly i want my program to ask how many numbers did the user play. How much money, after it asks for the lottery numbers and puts then in a border,then it asks for the users numbers,puts in on a second border and then i want to compare the 2 of them and if they have a same number it will add to 'sum'.
#include <stdlib.h>
int main()
{
int k[20],i;
int k2[12],f;
int numbers,sum,n,l,num;
float money,winnings;
l=0;
sum=0;
printf("How many numbers from 1 to 12?\n");
scanf("%d",&num);
printf("How much money?\n");
scanf("%f",&money);
for (i=0;i<19;i++)
{printf("Give lottery numbers\n");
scanf("%d",&k[i]);}
while (l<num){
printf("Give your numbers\n");
scanf("%d", k2 + f); !!fixed!!
l++;}
for (f=0;f<num;f++){
for (i=0;i>19;i++){ !!fixed!!
if ((k[i])==(k2[f])) !!! and here i think its a mistake.
{
sum=sum+1;
}
}
}
printf("You got %d numbers out of %d",sum,num);
if ((sum=1) && (num=1));
{winnings=(money*2,5);
printf("Won %f",winnings);}
if ((sum=1) && (num=2));
{winnings=(money*1);
printf("won %f",winnings);}
if ((sum=2) && (num=2));
{winnings=(money*5);
printf("Won %f",winnings);}
system("pause");}

It doesn't appear that f has ever been initialized to anything. Therefore,
scanf("%d",k2[f]);
Will result in undefined behavior, and is the likely cause of the crash.
Additionally, you need to fix your indentation. Furthermore, your loop is off by one. You initialize l to 1, then execute the following loop, whose apparent purpose is reading num numbers:
while (l<num){
So, if, for example, "1" was entered, in order to read only one number, the body of the loop will never execute, since the comparison "1<1" will be false.
It's likely there are other problems with this code, hard to analyze it due to bad indentation.

This loop
for (i=0;i=19;i++){
will never end since i=19 will evaluate to always true.
I think that the intention was:
for (i=0;i<19;i++){

Instead of l, what you probably intended, you are using f, which, as Sam Varshavchik spotted already, is not initialized.
Additionally, you are not passing a pointer to scanf: scanf("%d", k2[f]);. You need scanf("%d", k2 + l); instead, or scanf("%d", &k2[l]), if you prefer.

Related

How to add the first number and last number of a series of number in C?

I am a beginner to C language and also computer programming. I have been trying to solve small problems to build up my skills. Recently, I am trying to solve a problem that says to take input that will decide the number of series it will have, and add the first and last number of a series. My code is not working and I have tried for hours. Can anyone help me solve it?
Here is what I have tried so far.
#include<stdio.h>
int main()
{
int a[4];
int x, y, z, num;
scanf("%d", &num);
for (x = 1; x <= num; x++) {
scanf("%d", &a[x]);
int add = a[0] + a[4];
printf("%d\n", a[x]);
}
return 0;
}
From from your description it seems clear that you should not care for the numbers in between the first and the last.
Since you want to only add the first and the last you should start by saving the first once you get it from input and then wait for the last number. This means that you don't need an array to save the rest of the numbers since you are not going to use them anyway.
We can make this work even without knowing the length of the series but since it is provided we are going to use it.
#include<stdio.h>
int main()
{
int first, last, num, x = 0;
scanf("%d", &num);
scanf("%d", &first);
last = first; //for the case of num=1
for (x = 1; x < num; x++) {
scanf("%d", &last);
}
int add = first + last;
printf("%d\n", add);
return 0;
}
What happens here is that after we read the value from num we immediately scan for the first number. Afterwards, we scan from the remaining num-1 numbers (notice how the for loop runs from 1 to num-1).
In each iteration we overwrite the "last" number we read and when the for loop finishes that last one in the series will actually be the last we read.
So with this input:
4 1 5 5 1
we get output:
2
Some notes: Notice how I have added a last = first after reading the first number. This is because in the case that num is 1 the for loop will never iterate (and even if it did there wouldn't be anything to read). For this reason, in the case that num is 1 it is reasonably assumed that the first number is also the last.
Also, I noticed some misconceptions on your code:
Remember that arrays in C start at 0 and not 1. So an array declared a[4] has positions a[0], a[1], a[2] and a[3]. Accessing a[4], if it works, will result in undefined behavior (eg. adding a number not in the input).
Worth noting (as pointed in a comment), is the fact that you declare your array for size 4 from the start, so you'll end up pretending the input is 4 numbers regardless of what it actually is. This would make sense only if you already knew the input size would be 4. Since you don't, you should declare it after you read the size.
Moreover, some you tried to add the result inside the for loop. That means you tried to add a[0]+a[3] to your result 4 times, 3 before you read a[3] and one after you read it. The correct way here is of course to try the addition after completing the input for loop (as has been pointed out in the comments).
I kinda get what you mean, and here is my atttempt at doing the task, according to the requirement. Hope this helps:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first, last, num, x=0;
int add=0;
printf("What is the num value?\n");//num value asked (basically the
index value)
scanf("%d", &num);//value for num is stored
printf("What is the first number?\n");
scanf("%d", &first);
if (num==1)
{
last=first;
}
else
{
for (x=1;x<num;x++)
{
printf("Enter number %d in the sequence:\n", x);
scanf("%d", &last);
}
add=(first+last);
printf("Sum of numbers equals:%d\n", add);
}
return 0;
}

SIGSEGV Error in short C code

So, as someone who is fairly new to C, I came across my first SIGSEGV Error.
It appeared in a short C program that is meant to be a "guess the number" game. It consists of a self-defined function that compares two numbers and a do-while loop with an input inside it.
The start and the do-while loop:
#include<stdio.h>
int checkNum(int num1, int num2); //See below for explanation
int main(void) {
int input=0, rand=3; //"Random" number has fixed value for testing
do {
printf("Enter number from 0-10: "); //There is not actual range yet
scanf("%d",input); //Get input
} while(checkNum(input, rand)); //Checks if difference != 0
}
The function for comparing:
//Function for comparing input with "random" number
int checkNum(int num1,int num2) { //The two numbers that get compared; First one: input, Second one: "random" rumber
if(num1==num2) {
printf("Correct. The random number was %d",num2);
} else if(num1<num2) {
printf("Wrong. The random number is bigger.");
} else if(num1>num2) {
printf("Wrong. The random number is smaller.");
}
return num2-num1; //Return the difference, leads to 0 if equal
}
I suspect the error to be in the function, caused by a missing use of a pointer, but as far as I understand pointers, they don't seem necessary here: I don't change a single variable in the function, and the return only subtracts two values (which are given I assume).
I hope my error isn't too stupid, and I'd like to thank everyone who can help or tries to.
(I can post my processor values, altough I am not sure if that will help; If any more information is needed for debugging, please tell me)
This:
scanf("%d",input); //Get input
should be:
scanf("%d",&input); //Get input
^^^
Pro tip: always compile with warnings enabled (e.g. gcc -Wall ...) and the compiler will happily point out simple mistakes such as this, saving you a lot of time and grief.

Why does the program crash when the function is called in c?

I recently had to create a program where the user enters a certain integer N. After that, my int main() had to call a seperate function, int getNextFibonacciNumber(void), which calculates the Nth term in the fibonacci sequence and then prints it. When I compile the code, Vode::Blocks says that there aren't any errors or warnings. This said, when I try to run the program, it automatically crashes. I have read it and re-read it but I am not able to see where it all went wrong. Would anyone be able to shed some light on this mysery? Thank you very much! When the program crashes, it says: filename.exe has stopped working. A problem caused the program to stop working correctly. Windows will close the program and notify you if a solutions is available. However, when the code is compiled in Code::Blocks, everything is fine.
#include <stdio.h>
#include <stdlib.h>
int getNextFibonacciNumber(void);
int main()
{
int N, fibonacci[N];
printf("Enter a positive integer:");
scanf("%d", &N);
printf("The %d th term in the Fibonacci sequence is: %d", N, getNextFibonacciNumber());
}
int getNextFibonacciNumber()
{
int N, i, fibonacci[N];
fibonacci[0] = 0;
fibonacci[1] = 1;
for(i = 2; i < N+1; i++)
{
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
}
return(fibonacci[N-1]);
}
The problem is, that this
int main()
{
int N, fibonacci[N];
invokes undefined behavior. N is not initialized, but used as a C99 variable length array size specifier. Reading a value from a uninitialized variable invokes UB.
To fix this issue you have to write
int main()
{
int N;
printf("Enter a positive integer:");
scanf("%d", &N);
int fibonacci[N];
However there's another problem, namely that you have the same UB causing construct in getNextFibonacciNumber. You have to fix that to. Also the number entered into N is not "communicated" to getNextFibonacciNumber, so I highly doubt that this program worked at all, even if it didn't crash.
Code::Blocks (or rather the compiler Code::Blocks calls) only checks if you have written "legal" c code. It does not (and can not) check if your program does what you want, if your program will exit at any point (or simply run forever), if your program causes errors and crashs and stuff like this.
When you say
int N, fibonacci[N];
I guess you want to create an integer N and an array of the same size. However right now you create an integer N (that has some "random" value, presumably 0) and an array of the FIXED size N.
If you change N late on in your program this does not affect the size of your array "fibonacci" in any way. So if your N was by chance 0 at the beginning of your program than you have created an array of size 0. Even if you read a value (say 5) from the console input. Trying to read and write to this array causes problems.
Moving the part
int fibonacci[N];
below your "scanf" line will fix this problem. At this point N is initialized (and not some random number).
Also be aware that the variable N in the main function
int main()
has no connection at all to the N variable in your function
int getNextFibonacciNumber()
The second N is a newly created variable (again set to some "random" value). If you want to pass data from one function to another you should do it by passing it as an argument in brackets:
int getNextFibonacciNumber( int N)

program going into infinite loop after 15 seconds

I am making a program to find prime factorials of a given number.
Although the program works fine, I have two problems.
1. when i enter an odd number, it prints 2 in the result although 2 should not be in it.
2. After 15 seconds , it turns into an infinite loop , Which is really creepy.
#include<stdio.h>
#include<conio.h>
int num(int); // Making a function for finding prime factors
int main()
{
int i,j;
printf("Enter any number");
scanf("%d",&i);
num(i);
getch();
}
int num(int i)
{
int a=2;
while(a<=i)
{
if(i%a==0) //if the number is divisible then divide it
i=i/a;
printf(" %d",a);
if(i%a!=0)
{
i%a;
while(i%a!=0)// If it is not divisible by 2 then increment it until it is
a++;
}
}
}
It always prints 2 because the print statement is not part of the if which tests for mod 0. It goes into an infinite loop because once a passes i, the second while loop will never exit.
The infinite loop is your second while loop, while(i%a!=0). For a prime number, this will continue endlessly. There are smart ways to fix that, but at the very least, change it to
while(i%a!=0 && a<=i)
I'm not sure why 2 is coming up on odd numbers, still thinking that part through.
EDIT As Fred mentioned, the printout is not part of the if statement, causing 2 to always show up. Personally, I recommend getting into the habit of always putting { } after an if statement. Even if you've been coding for decades, this will make sure you get the right statements in your condition.

Get exception error in C when trying to loop array

//Program Written By: Andre Chitsaz-zadeh
//Program Written On: 10/7/12
//Program calculates book cost for multiple book orders. Program written using multiple functions.`
#include <stdio.h>
#define SIZE 5
void inputData();
int main ()
{
inputData();
}
void inputData()
{
int i = 0;
int costs[5];
printf( "\nPlease enter five products costs.\n" );
while(i < 5)
{
scanf("%d", costs[i]);
i = i + 1;
}
}
Why do I get in exception error? The program looks simple enough! It compiles without problems but as soon as I input a number it says that "this program has stopped working". Thanks!!
scanf("%d", costs[i]);
Should be:
scanf("%d", &costs[i]);// &cost[i] gets the address of the memory location you want to fill.
It should be
while(i < 5) {
scanf("%d", &costs[i]);
i = i + 1;
}
a little typo I assume, anyway you need to provide the address of the element of the array you want to scan the integer into.
I would guess it's this line:
scanf("%d", costs[i]);
It should be:
scanf("%d", &costs[i]);
scanf needs a pointer to the variable in which it should put the read result.
This looks like a homework question, judging by the comment about the program have multiple functions. If functions are new, then pointers have probably not been covered yet. In that case, read my explanation as:
scanf needs a & before the variable in which it should put the read result. You'll learn why in a few weeks.
I think you'll need to change you scanf line to
scanf("%d", &costs[i]);
You need to pass the address of the int to have user input written to it. Your current code passes the value of costs[i]. This is undefined so will point to an unpredictable, and probably not writeable, location in memory.

Resources