When trying to debug a isPrime program, i started running into an warning that would not allowing me to run the program. The warning states Relocation truncated to fit: R_X86_64PC32 against undefined symbol "isPrime(int)". I had ran into this problem a while ago but have since forgotten exactly how to deal with it. Is it a problem with the program that usually causes this, or is it a problem with netbeans and the compiler it uses for C.
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int userInput);
int main(int argc, char** argv)
{
int userInput;
bool prime = false;
int again = 0;
printf("This program will check if a number is Prime\n");
while(again == 0)
{
printf(" Enter number: \n ");
scanf("%d",&userInput);
prime = isPrime(userInput);
if( prime )
printf("%d is prime.",userInput);
else
printf("%d is not prime",userInput);
printf("again? \n 0 for yes \n 1 for no");
scanf("%d", &again);
}
return 0;
}
bool isPrime(int userInput)
{
int tmp = 0;
bool result = true;
while(tmp != 1 && result == true)
{
if( userInput % tmp == 0)
result = false;
tmp--;
}
return true;
}
\
Code has been edited
Related
I want my code to print "YES" if there is digit 7 in the entered number, and otherwise print "NO".
When I use while(T != 0) for test cases, my code prints "YES" for all the numbers - even for number 45. Without while(T != 0) my code runs perfectly.
Where is my mistake?
#include <stdio.h>
int main() {
int T;
scanf("%d", &T);
while (T != 0) {
int X;
scanf("%d", &X);
int flag, result;
while (X != 0) {
result = X % 10;
if (result == 7) {
flag = 1;
}
X = X / 10;
}
if (flag == 1) {
puts("YES");
} else {
puts("NO");
}
T--;
}
return 0;
}
After trying out your code, the main issue was not with the "while" test. Rather, in the code your test flag was not being reset so once the a value was found to have the digit "7" in it, all subsequent tests were noted as being "YES". With that, following is a refactored version of your code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int T;
printf("How many numbers to test: "); /* Clarifies what the user is being asked for */
scanf("%d", &T);
while (T != 0)
{
int X;
printf("Enter a number to be tested: "); /* Again, lets the user know what to enter */
scanf("%d", &X);
int flag = 0, result;
while (X != 0)
{
result = X % 10;
if (result == 7)
{
flag = 1;
}
X = X / 10;
}
if (flag == 1)
{
puts("YES");
}
else
{
puts("NO");
}
flag = 0; /* Needs to be reset after being set and before next check */
T--;
}
return 0;
}
Some things to note.
Although not really needed, verbiage was added as prompts to clarify to the user what needed to be entered for values.
Most importantly, the flag variable gets initialized to zero and then subsequently gets reset to zero after each test has been completed.
With those bits addressed, following is some sample terminal output.
#Vera:~/C_Programs/Console/Seven/bin/Release$ ./Seven
How many numbers to test: 4
Enter a number to be tested: 3987
YES
Enter a number to be tested: 893445
NO
Enter a number to be tested: 8445
NO
Enter a number to be tested: 58047
YES
Give that a try and see if it meets the spirit of your project.
I recently wrote a program in C for a calculator. To produce a function that checks if the user input is a prime number or not (amongst other functions).
I essentially used this code (excluding all other functions):
#include <stdio.h>
#include <math.h>
int testForPrime(int);
int main(void) {
int ioperand1 = 0;
printf("\nEnter the value to check if prime (positive integer): ");
scanf("%d", &ioperand1);
if (testForPrime(ioperand1) != 0)
printf("\nThis number is prime.\n");
else
printf("\nThis number is not prime.\n");
return 0;
}
int testForPrime(int operand1) {
int i = 0;
for (i = 2; i <= sqrt(operand1); i++) {
if (operand1 == 0 || operand1 == 1)
return 0;
else if (operand1 % i == 0)
return 0;
else
return 1;
}
}
^
This code above produces the errors
I am not sure why the code produces an error for the value 9 (I fixed that above by adding the condition: if (operand1 == 9), but I don't understand why 9 is seemingly the only value that results in an incorrect solution (It would say 9 was prime, but not any other number give an incorrect result).
One other bug that I remidied with an extra condition statement was the value of 2.
Before adding the extra conditional statement in the main function: if (ioperand1 == 2), the value 2 would always come up as a non prime number.
I originally found this solution to check for prime numbers online, and I still don't understand why the for loop starts from 2.
#include <stdio.h>
#include <math.h>
int testForPrime(int);
int main(void) {
int ioperand1 = 0;
printf("\nEnter the value to check if prime (positive integer): ");
scanf("%d", &ioperand1);
if (testForPrime(ioperand1) != 0 || ioperand1 == 2)
printf("\nThis number is prime.\n");
else
printf("\nThis number is not prime.\n");
return 0;
}
int testForPrime(int operand1) {
int i = 0;
for (i = 2; i <= sqrt(operand1); i++) {
if (operand1 == 0 || operand1 == 1 || operand1 == 9)
return 0;
else if (operand1 % i == 0)
return 0;
else
return 1;
}
}
^This code above fixed the problem, though I don't undesttand why the problem existed in the first place.
TL;DR:
I don't know why this code doesn't work without the extra conditional statements:
if (operand1 == 9) in function definition,
and
if (ioperand1 == 2) in main function.
If anyone could help clear this up, I'd appreciate it.
It is because your prime checking loop does not iterate. It always returns on the first iteration. It must run to completion, and then the number will be prime. So
int testForPrime(int operand1) {
if(operand1 < 2) {
return 0;
}
int sr = (int)round(sqrt(operand1));
for(int i = 2; i <= sr; i++) {
if (operand1 % i == 0) {
return 0;
}
}
return 1;
}
This is the problem I'm trying to solve:
Input:
First line contains N, the size of the string.
Second line contains the letters (only lowercase).
Output:
Print YES if all vowels are found in the string, NO otherwise.
Constraints:
The size of the string will not be greater than 10,000. 1 ≤ N ≤ 10000
The following code I wrote is always showing NO.
#include <stdio.h>
#include<conio.h>
int main()
{
int a,b,c=0,d=0,e=0,f=0,g=0,i;
char string[10000];
scanf("%d",&a);
scanf("%s",string);
for(i=0;i<a;a++)
{
if(string[i]==('a'))
c=1;
if(string[i]==('e'))
d=1;
if(string[i]==('i'))
e=1;
if(string[i]==('o'))
f=1;
if(string[i]==('u'))
g=1;
}
if((c==1)&&(d==1)&&(e==1)&&(f==1)&&(g==1))
printf("YES");
else
printf("NO");
return 0;
getch ();
}
Here is an infinite loop that causes a problem:
for(i=0;i<a;a++)
You should increment i, instead of a (length of a string). If you fix this one char in loop statement, the program will run well at all. Anyway, I changed your code a bit to be more readable. Take a look if you want, just for your information, sir:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int len, a=0, e=0, i=0, o=0, u=0, it;
char string[10000];
scanf("%d", &len);
scanf("%s", string);
for(it=0;it<len;it++)
{
if(string[it]=='a') a = 1;
else if(string[it]=='e') e = 1;
else if(string[it]=='i') i = 1;
else if(string[it]=='o') o = 1;
else if(string[it]=='u') u = 1;
}
if(a && e && i && o && u) printf("YES\n");
else printf("NO\n");
system("PAUSE");
return 0;
}
I assume you are running your program under Windows, so instead of conio's getch() try to use system("PAUSE") or just even better way to do this (for both Windows for UNIX): getchar()
I've renamed all of your variables, but otherwise left the code the same.
#include <stdio.h>
#include<conio.h>
int main()
{
int foundA = 0, foundE = 0, foundI = 0, foundO = 0, foundU = 0;
int i, length;
char string[10000];
scanf("%d", &length);
scanf("%s", string);
for(i=0; i<length; length++)
{
if(string[i]==('a'))
foundA=1;
else if(string[i]==('e'))
foundE=1;
else if(string[i]==('i'))
foundI=1;
else if(string[i]==('o'))
foundO=1;
else if(string[i]==('u'))
foundU=1;
}
if((foundA==1)&&(foundE==1)&&(foundI==1)&&(foundO==1)&&(foundU==1))
printf("YES");
else
printf("NO");
return 0;
getch ();
}
Looking the the for-loop condition for(i=0; i<length; length++), I think it's pretty clear what's wrong. Instead of incrementing the counter, you're incrementing the length of the string. Eventually, the counter overflows to a negative number, and the loop terminates without ever looking at a character besides the first one. The lesson here is to name your variables properly.
If you want to be picky, then signed integer overflow is undefined behavior, but for most systems, INT_MAX + 1 will be INT_MIN.
This program can be done in more simpler way other as below.
#include <stdio.h>
#include<conio.h>
int main()
{
int i, flag = 0;
char string[10000], *ptr;
char cmp[] = "aeiou";
printf("Please enter string = " );
scanf("%s", string);
i = 0;
while(cmp[i])
{
ptr = string;
while(*ptr)
{
if(cmp[i] == *ptr)
break;
ptr++;
}
if(*ptr != cmp[i++])
{
flag = 1;
break;
}
}
if(flag == 1)
printf("NO");
else
printf("YES");
}
In this program I have used just one flag instead of 5 flags. Always try to write simple code rather then using unnecessary variable and flags.
The code compiles however where my while loop should run until an odd number is inputted it only runs through once no matter whatever is added in there. From what I understand I should be able to use it like this however I cannot seem to figure it out what-so-ever
#include <stdio.h>
#include <stdbool.h>
//variables
bool flag = false;
int input = 0;
//function protoypes
void get_input(void);
bool is_valid(int);
int main(){
get_input();
return 0;
}
void get_input(){
while(flag == false){
printf("please enter an odd number betwen 1 and 9\n");
scanf("%d", &input);
if(is_valid){
flag = true;
}else{
flag = false;
}
}
}
bool is_valid(int number){
if(number == 1 || number == 3 || number == 5 || number == 7 || number == 9){
return true;
}else{
return false;
}
}
You calling is_valid function in wrong way.
Try :
if(is_valid(input)) {
//code
} ....
It's because you are not calling your function. (line is_valid should be is_valid(number)
#include <stdio.h>
#include <stdbool.h>
//variables
bool flag = false;
int input = 0;
//function protoypes
void get_input(void);
bool is_valid(int);
int main(){
get_input();
return 0;
}
void get_input(){
while(flag == false){
printf("please enter an odd number betwen 1 and 9\n");
scanf("%d", &input);
if(is_valid(input)){
flag = true;
}else{
flag = false;
}
}
}
bool is_valid(int number){
if(number == 1 || number == 3 || number == 5 || number == 7 || number == 9){
return true;
}else{
return false;
}
}
also, you can remove the function entirely by doing a modulo operation, so your is_valid will be:
if(input <= 9 && input >= 1 && input % 2 != 0){
flag = true;
}else{
flag = false;
}
It can even be further simplified to:
flag = (input <= 9 && input >= 1 && input % 2 != 0);
So your whole code can be:
#include <stdio.h>
#include <stdbool.h>
//variables
bool flag = false;
int input = 0;
//function protoypes
void get_input(void);
int main(){
get_input();
return 0;
}
void get_input(){
while(flag == false){
printf("please enter an odd number betwen 1 and 9\n");
scanf("%d", &input);
flag = (input <= 9 && input >= 1 && input % 2 != 0);
}
}
The problem is here
if(is_valid)
it should be
if(is_valid(input))
You did not pass input to the function is_valid(). That is what had been causing the problem.
Hope this solves your problem :)
This line is the problem:
if(is_valid){
Since is_valid is a function, the expression is_valid, without parentheses, evaluates as the address of the function rather than the result of calling said function.
Since the address of the function will never be NULL or 0, it will always be treated as a truth value, hence flag will be set to true always.
The correct way to do this is:
if (is_valid()) {
And, as an aside, it's not considered good form to compare boolean values such as with:
while (flag == false)
It's better to use something like:
while (! flag)
especially if you choose your variable names carefully:
int input_is_okay = 1;
void get_input (void) {
while (input_is_okay) {
printf ("please enter an odd number between 1 and 9\n");
input_is_okay = (scanf ("%d", &input) == 1);
input_is_okay = input_is_okay && is_valid (input);
}
}
You'll notice I'm setting input_is_okay to false if the scanf() fails as well since that means you didn't enter a valid integer.
I would appreciate some help with this. I'm trying to create this simple program that repeatedly loops asking for the user to enter in an int. If he enters an int, it exits but if he enters something else or bigger than int (ex.4gs4r33) it will loop again asking to enter an int. This is what I have tried, and it's not working. It says it's an int even if it's not.
#include<stdio.h>
unsigned int findInt();
int main() {
printf("Please input an int.\n");
findInt();
}
unsigned int findInt() {
char input;
long num = 0;
int b = 0;
do {
scanf("%c", &input);
if (isdigit(input)){
num = num*10+input+'0';
b = 1;
}
else if (input == '\n')
b = 1;
else
b = 0;
} while(input != '\n');
if (b == 1)
printf("Great!\n");
else{
printf("Not an int \n");
findInt();
}
return 0;
}
Two possible approaches. One would be to modify your code:
b = 1; // start off with good intentions…
do {
scanf("%c", &input);
if (isdigit(input)){
num = num*10+input -'0'; // *** SUBTRACT '0', don't add it!
}
else if (input != '\n') {
b = 0;
break; // *** break when you find non-digit
}
} while (input != '\n');
Two changes: getting the math right as you compute the integer, and fixing the logic (so you break out of your loop when you find a non digit character)
Second approach:
char buf[100];
char intAsString[100];
fgets(buf, 100, stdin);
sscanf(buf, "%d", num);
sprintf(intAsString, "%d\n", num);;
if(strcmp(buf, intAsString) == 0 ) {
printf("yay - you entered an integer!\n");
}
I'm sure you can figure out how that works.
update a complete code snippet that solves the issue of "loop logic" as well: you call the findInt function once from the top level, and it keeps going until you get the int. Note - in order for this to work properly, I read the entire input at once (rather than one at a time), then pick off the characters one by one using sscanf (and updating the pointer manually). It has a number of advantages - not least of which is that you start with a fresh input every time you call findInt, instead of having the rest of the input buffer that still needs reading (and which was giving rise to "no,no,no,great!" - as you would keep reading the bad input until you got to the newline, and accept that...)
#include<stdio.h>
#include <ctype.h>
unsigned int findInt();
int main() {
findInt();
}
unsigned int findInt() {
char input;
char buf[100];
char *temp;
long num = 0;
int b = 0;
printf("please enter an int:\n");
fgets(buf, 100, stdin);
temp = buf;
do {
sscanf(temp++, "%c", &input);
if (isdigit(input)){
num = num*10+input-'0';
b = 1;
}
else if (input == '\n')
{
b = 1;
break;
}
else {
b = 0;
break;
}
} while(input != '\n');
if (b == 1)
printf("Great! %d is an integer!\n", num);
else{
printf("Not an int \n");
findInt();
}
return 0;
}
In the else branch - i.e. not a digit or a newline - you set b to 0. Now if a digit DOES follow you reset that to 1.
You'll probably want to break or somehow record the permanent failure instead of just continuing.
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
void findInt(){
int x;
bool ok;
do{
char buff[32], *endp;
long long num;
ok = true;//start true(OK)
printf("Enter a number: ");
fgets(buff, sizeof(buff), stdin);
//strtoll : C99
x=(int)(num=strtoll(buff, &endp, 0));//0: number literal of C. 10 : decimal number.
if(*endp != '\n'){
if(*endp == '\0'){
printf("Too large!\n");//buffer over
while('\n'!=getchar());
} else {
printf("Character that can't be interpreted as a number has been entered.\n");
printf("%s", buff);
printf("%*s^\n", (int)(endp - buff), "");
}
ok = false;
} else if(num > INT_MAX){
printf("Too large!\n");
ok = false;
} else if(num < INT_MIN){
printf("Too small!\n");
ok = false;
}
}while(!ok);
}
,