Undefined reference error to function that is actually defined in C - c

I wrote this program to build a number diamond. The issue is that when I compile the program, it throws the error
build2.c:(.text+0x5): undefined reference to `get_input'
collect2: error: ld returned 1 exit status
I've tried for hours to figure out what exactly the problem is (e.g. if there is a spelling mistake or something similar), but the function call looks identical. I have attempted to rename it, write it as both a prototype and as an implementation, and nothing seems to work. Is there an issue that I'm not seeing?
//Define prior to main
int is_valid(int);
int get_input(void);
void print_pattern(int);
//Main
int main(void){
int diamond_size;
//diamond_size = get_input();
//value from get imput method used for diamond size
print_pattern(get_input());
return 0;
}
void print_pattern(int size){
int length, num, i, j;
//beginning of new diamond
printf("\n");
//Define each integer to work in layout of diamond
//First for loop fans out
for(i=1; i <= size; i += 2){
length = size-i+1;
num = 1;
printf("%*s", length," ");
for(j = 0; j < i; j++){
printf("%d ", num);
num++;
}
printf("\n");
}
//second for loop fans in
for(i=size-2; i >= 1; i -= 2){
length = size-i+1;
num = 1;
printf("%*s", length," ");
for(j = 0; j < i; j++){
printf("%d ", num);
num++;
}
printf("\n");
}
int is_valid(int value){
int rem;
//uses remainder to determine if it is odd or even; an even number will not have a reaminder in this case
rem = value % 2;
if (rem == 0){
printf("You've entered a even number. Please try again.\n");
return (0);
}
//greater than 9 cnd
if (value > 9){
printf("You have entered a number greater than 9. Please try again.\n");
return (0);
}
//less than 1 cnd
if (value < 1){
printf("You have entered a number less than 1. Please try again.\n");
return (0);
}
return (1);
}
int get_input()
{
int cont, number, valid;
cont = 1;
while (cont = 1)
{
printf("Enter an odd number less than 9 and greater than 0 < ");
scanf("%d", &number);
valid = is_valid(number);
if (valid == 1)
{
cont = 0;
}
}
return number;
}
}

You seem to have nested functions; this is (a) a non-standard GCC extension, and (b) I presume the scope of the nested get_input() function is the enclosing function, not the file scope. The solution is to move get_input() to file scope. At the end of print_pattern() add an extra }, and delete the final } at the end of the file.
Also, please format your code - most IDEs these days have options to tidy it up, and with correct indentation you may have seen your problem earlier.
Oh, and as a bonus bug fix, you also have in get_input():
while (cont = 1)
This will always be true - use this instead:
while (cont == 1)

The function print_pattern is not terminated at proper place but instead at the very end of the file:
void print_pattern(int size){
...
... end of the loop
}
... more functions
...
... end of print_pattern
}
This results into defining nested functions instead of global level.
It's generally good habit to indent the blocks, in which case you would realized the mistake very quickly.

Related

Can I 'return' a result from the main variable?

So I have this exercise where I need to show the N first prime numbers, but I need to specifically create a function to know if the number is a prime number
#include <stdio.h>
#include <stdlib.h>
int prime(int num){
int cont,i,j=0,b;
b=num;
do{
j++;
i=0;
for(cont=1;cont<j;cont++){
if(j%cont == 0)
i++;
}
if(i == 1){
return(j);
c=j;
b--;
}
} while (b > 0);
}
int main(){
int *v,n,cont;
do{
printf("Input an integer: ");
scanf("%d",&n);
} while (n <= 0);
v = (int *)malloc(n * sizeof(int));
for(cont=0;cont<n;cont++){
v[cont] = prime(n);
}
for(cont=0;cont<n;cont++){
printf("%d ",v[cont]);
}
}
The problem with the way i've done this is that the variable J is aways being set to 0 when i call the function again, i've tried to set something like c=j so when the program return to the prime function it would have the 'previous' j value but it gets a weird random number. So I wanted to know if is there a way to 'return' the result in the main function to the prime function, i couldn't find anything that helped me, not that i could understand at least
Your function prime() is not working as intended and there are many other errors -
1) Since smallest prime is 2, variable cont should start from 2.
2) scanf need not be in a loop in this case
3) Enter values in v only when cont is confirmed a prime.
See this function prime2( not optimize though for clarity):
bool prime2(int n)
{
for(int i = 2 ; i<n-1;i++)
if( n% i == 0) return false;
return true;
}
int main(){
int *v,n,cont,cc=0;
printf("Input range: ");
scanf("%d",&n);
v = malloc(n * sizeof(int));
for(cont=2;cc<n;cont++){
if( prime2(cont) == true )
{
v[cc] = cont;
cc++;
}
}
for(cont=0;cont<n;cont++){
printf("%d ",v[cont]);
}
delete v;
}
Output:

function_tester.exe has stopped working

In this file I am trying to make something that adds all numbers up to a number entered by a user. Such as, 4: 1 + 2 + 3 + 4 = 10. So if they enter 4 it returns 10.
When I run the code I get an error message saying my file has stopped working. Do i have an endless loop?
#include "biglib.h"
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
// Asking them for their number
int num;
scanf("%i", num);
// then I run a loop, if num == 0 then the program should break from the loop and return 0 in the main function if not run the code inside the program.
int i;
while(num != 0)
{
// I define "i" to be one less than that of num then as long as "i" is greater than 0 keep running the loop and subtract one at the end of it.
for(i = num - 1; i > 0; i--)
{
// in here I do the addition.
num = num + i;
}
// finally I print out the answer.
printf("%i\n",num);
continue;
}
return 0;
}
Yes, you have an infinite loop. Also the input is not stored in the num variable.
#include "stdio.h"
int main(void) {
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
scanf("%i", &num);
int sum = 0;
while(num>0){
sum += num;
num -= 1;
}
printf("%i\n",sum);
return 0;
}
Some lines of your code seem odd to me.
Why do you use a while loop to test the value of num ?
Why do you put a continue statement as last while loop instruction ?
Remarks:
Your code does not work for negative number, is it the expected behaviour?
You are not testing the scanf return value, which could cause trouble.
I am pretty sure that you should check the scanf prototype.
Hope these questions will lead you to improve your code.
Thank you yadras fro informing me that I had the scanf outside of the while loop that was the problem and now it works when I do this.
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
int i;
while(num != 0){
scanf("%i", &num);
for(i = num - 1; i > 0; i--)
{
num = num + i;
}
printf("%i\n",num);
}
return 0;
}

How to successfully output a function call?

My assignment is to check if a number is prime, but I have to use three sections to do it. The first is the main body of code and that is followed by two functions. The first checks if the number is even, and the second checks if it is prime. I know this is a rather tedious way to check if a number is prime but it is meant to get us introduced to functions and function calls!
UPDATE
I have gotten it all to work besides printing the smallest divisor of a non prime number. I thought using i from the second function would work but it will not output. I have copied by code below -- please help if you have any suggestions!
#include <stdio.h>
#include <math.h>
int even (int);
int find_div (int);
int main() {
int num, resultEven, resultPrime, i;
printf("Enter a number that you think is a prime number (between 2 and 1000)> \n");
scanf("%d", &num);
while (num < 2 || num > 1000) {
if (num < 2) {
printf("Error: number too small. The smallest prime is 2.\n");
printf("Please reenter the number > \n");
scanf("%d", &num);
}
else if (num > 1000) {
printf("Error: largest number accepted is 1000.\n");
printf("Please reenter the number > \n");
scanf("%d", &num);
}
else {
}
}
resultEven = even(num);
resultPrime = find_div(num);
if (resultEven == 1) {
printf("2 is the smallest divisor of %d. Number not prime\n", num);
}
else if (resultPrime == 1) {
printf("%d is the smallest divisor of %d. Number not prime\n", i, num);
}
else {
printf("%d is a prime number.\n", num);
}
return 0;
}
int even(int num) {
if (num % 2 == 0) {
return 1;
}
else {
return 0;
}
}
int find_div(int num) {
int i;
for (i = 2; i <= (num/2); i++) {
if (num % i == 0) {
return 1;
}
if (num == i) {
return 0;
}
}
return i;
}
I would create a function for Wilsons theorem (p-1)! = 1 (mod p) iff p is prime, first off, to make the functions nice and easy you will only need the one. for numbers less than 1000 it should work fine.
something like,
//it will return 1 iff p is prime
int wilson(int p)
{
int i, result = 1;
for (i = 0; i < p; i++)
{
result *= i;
result = result % p;
}
return result;
}
however if your not printing check that you have included, at the top of your file
#include <stdio.h>
your
resultEven = even(num)
needs a ; at the end but that was mentioned in the comments, besides that your methodology though odd is correct, also you do not need the empy else, that can simply be removed and your good
UPDATE:
//if return value == 1 its prime, else not prime, and
//return value = smallest divisor
int findDiv(int p)
{
int i= 0;
for (; i <= n/2; i++)
{
//you number is a multiple of i
if (num % i == 0)
{
//this is your divisor
return num;
}
}
//1 is the largest divisor besides p itself/smallest/only other
return 1;
}
your function call is correct but you need a semi colon (;) at the end of:
resultEven = even(num)
otherwise this program effectively checks for evenness. To check for prime one way is to ensure the number has no factors other than one and itself. This is done by finding the div of every whole number from 2 to half of the number being tested using a for loop. If a number produces a div of 0 then it is not prime because t has a factor other than 1 and itself.

Printf: pops out after the break statement

Being at the very beginning of learning programming,
C in particular, I am struggling with how to restrict
printf only to the valid outputs, i.e. to make sure
that printf does not appear after the "break" statement.
I understand that my test for scanf is within the for
loop, and when i reaches 3 the for loop stops and printf
appears. I hope to find the correct way to both test
scanf, and make sure printf doesn't appear after
the break statement (in case user types in integers).
// a program that calculates the average of an array
of 3 floating-point values and check if correct inputs
are types in scans (only floating values)
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
float values[3];
float element, average;
float sum = 0;
int i, n;
bool is_float;
printf ("Please, enter 3 floating values: \n");
for ( i = 0; i < 3; i++)
{
scanf ("%f", &element);
is_float = 1;
n = (int) element;
if (n - element == 0 || element == 0 )
{
is_float = 0;
printf ("Sorry, invalid input\n");
break;
}
else
{
values[i] = element;
sum += values[i];
}
}
printf ("The average of 3 values is %.2f\n", sum / 3);
return 0;
}
Thank you!
If you want the program to exit directly after this line:
printf ("Sorry, invalid input\n");
then you must replace the break statement directly below that printf line with something like this:
return 1;
On another note, when you want to print error messages, you should use fprintf() instead of printf(). The entire for loop would look like this:
for (i = 0; i < 3; i++)
{
scanf ("%f", &element);
is_float = 1;
n = (int) element;
if (n - element == 0 || element == 0 )
{
is_float = 0;
fprintf (stderr, "Sorry, invalid input\n");
return 1;
} else {
values[i] = element;
sum += values[i];
}
}

srand() in dice game [duplicate]

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 8 years ago.
I've been searching the site for possible answers to this problem, and although they're all similar they don't seem to be the exact same problem that I have, which is why I've been forced to open this question. SO I need to make a dice game that is supposed to roll 2 dice ranged from 1-6 and the user is supposed to guess what the number will be. The program then outputs the values of the die and reroll's if the guessed value isn't the real value of the 2 die. If it is then the program stops rolling the die and tells you how many rolls it took for the die to reach your guessed value.
For some reason my program keeps rolling the die over and over without stopping and I'm not exactly sure why. I tried testing it in a seperate program and have gotten even more confused as to why I still can't get different values even with srand() being called only once at the beginning of main.(I realized that, among a few other problems were what was wrong with the functions throwCalc1 and the unnecessary throwCalc2) If I try to place rand() outside a variable, I get different values, but if I put it within a variable the values stay the same. I've tried making the variable a function and it still doesn't work as the compiler gives me an error saying "initialization makes pointer from integer without a cast"
test function:
int main(void)
{
srand(time(NULL));
int i;
int *throwCalc = rand() % 6 + 1;
for(i = 0; i < 6; i++) {
printf("value is: %d\n", *throwCalc);
}
return 0;
}
original program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
#define MIN 2
#define MAX 12
int getInt(int min, int max) {
int retry = 1;
int value;
char after;
int cc;
do {
printf("Enter total sought \n"
"Range must be within [%d - %d]", min, max);
cc = scanf("%d%c", &value, &after);
if(cc == 0) {
printf("bad char or 0 input, please re-enter input");
clear();
} else if (after != '\n') {
printf("Error:Trailing characters, please re-ente input");
clear();
} else if (value < min || value > max) {
printf("Error: value outside of range, please re-enter input");
clear();
} else {
retry = 0;
}
} while(retry == 1);
return value;
}
void clear() {
while (getchar() != '\n') {
; //intentional empty statement
}
}
int throwCalc1() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwCalc2() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwResult(int input, int getcalc1, int getcalc2) {
int i = 0;
do {
throwCalc1();
throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
printf("You got your total in %d throws!\n", i);
return 0;
}
int main(void)
{
int input = getInt(MIN, MAX);
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
printf("Game of Dice\n");
printf("============\n");
printf("hi number is: %d", input);
throwResult(input, getCalc1, getCalc2);
return 0;
}
You do this once at the top of main:
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
And then expect the values to update just by calling throwCalc1() & 2 again.
Besides fixing srand(), have throwCalc1 & 2 return values into local variables instead of passing something in.
Right now you are calling throwCalc1() and throwCalc2() within your loop, but throwing away the results. You need to save those results in a pair of variables:
do {
getcalc1 = throwCalc1();
getcalc2 = throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
After you've done this, you might notice that getcalc and getcalc2 don't need to be parameters to that function - they can just be local variables within throwResult().
In addition, your throwCalc1() and throwCalc2() functions are identical, so you can remove one them and just call the remaining one twice.
Your test function should look like:
int main(void)
{
srand(time(NULL));
int i;
int throwCalc;
for(i = 0; i < 6; i++) {
throwCalc = rand() % 6 + 1;
printf("value is: %d\n", throwCalc);
}
return 0;
}

Resources