#include <stdio.h>
#include <string.h>
#include <math.h>
#define FALSE 0
#define TRUE 1
......................
int checkprime ( char number )
{
int i, valid;
valid = TRUE;
for ( i = 2; i <= number; i++ )
{
if ( number % i == 0 ) valid = FALSE;
}
return valid;
}
int main(void)
{
char inputarray[4];
int c, primeanswer;
........................
{
primeanswer = checkprime(c);
if ( primeanswer == 1)
{
printf("%d", "is a prime", inputarray);
}
else
{
printf("%d", "not prime", inputarray);
}
}
}
My issue here is trying to get the checkprime function working. I think I'm probably not initialising something as the numbers I'm getting seem to me like the program output isn't correct. Also when I do enter data for checkprime the numbers to me seem like uninitialised int values. And that the other functions don't seem to be called.
What is it that I am not initialising?
How can I combine the checkprime function more effectively with the others? Is it necessary to switch between char/int values as I've done in the functions?
EDIT:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
................
}
int checkprime ( int number )
{
int i, valid;
valid = TRUE;
for ( i = 2; i < number; i++ )
{
if ( number % i == 0 ) valid = FALSE;
}
return valid;
}
int main(void)
{
char inputarray[4];
int c, primeanswer;
.........................
else
{
c = atoi(inputarray);
primeanswer = checkprime(c);
if ( primeanswer == 1)
{
printf("%d", "is a prime", inputarray);
}
else
{
printf("%d", "not prime", inputarray);
}
}
}
You're passing c to checkprime, but you never set it to anything. As a result, the contents of c are undefined and trying to read it results in undefined behavior.
Pass your array to the atoi function to convert it to an integer and assign it to c. You should also change the type of the number parameter in checkprime to int to match what is being passed in.
It also looks like you're missing an else:
if ( !checknumeric(inputarray))
{
printf("Invalid input");
}
// else goes here
{
primeanswer = checkprime(c);
...
EDIT:
More issues with your code:
You're not printing the results correctly:
printf("%d", "is a prime", inputarray);
...
printf("%d", "not prime", inputarray);
There are two issues with these. First, the fixed portion of the string to print is the first parameter to printf. The rest get substituted in. So the first two parameters should be combined into a single string. Second, you use %d to print at int but inputarray is a char array. You should instead pass in c, which is the integer value you want to print.
printf("%d is a prime", c);
...
printf("%d not prime", c);
dbush's answer is correct, but you're still going to get the result that you're already seeing, because you have a bug in your checkprime method:
int checkprime ( char number )
{
int i, valid;
valid = TRUE;
for (i = 2; i <= number; i++) {
if (number % i == 0) valid = FALSE;
}
return valid;
}
Your problem is that number % number == 0 for all values of number, and you let i iterate up to number by using <= in your for-loop condition. Changing your for loop to:
for (i = 2; i < number; i++) {
if (number % i == 0) valid = FALSE;
}
Will fix the logic there.
Related
How to use isdigit function in C to check whether the given multiple digit string is numeric or not?
This is how I used isdigit function for a single digit character.
#include<stdio.h>
#include<cs50.h>
#include<ctype.h>
int main()
{
char c = get_char("Enter a single character:");
int a = isdigit(c);
if ( a != 0)
{
printf("%c is an integer \n", c);
}
else
{
printf("%c is not an integer \n",c);
}
}
Now, I want to check for the multiple digit character(eg. 92, 789). here is my code
#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<ctype.h>
int main()
{
string num = get_string(" Enter a number:");
int final = 1;
for(int i =0; i< strlen(num); i++)
{
// final = final * isdigit(num(i));
final*= isdigit(num[i]);
}
if(final!=0)
{
printf("%s is an integer.\n", num);
}
else
{
printf("%s is not an integer.\n", num);
}
}
However, the above code only works for two digit integer , but not for 3 digit integer. See this:
Compiled Code SS
The isdigit function isn't required to return a boolean 0 or 1 value. It's specified to return zero if the character isn't a digit, and any non-zero value if it is a digit.
Take for example the implementation used by here. We can see that isdigit returns 2048.
Because it returns that value, the multiplication will lead to a signed integer arithmetic overflow, which in turn leads to undefined behavior.
Instead I suggest you use isdigit directly in a condition, and if it returns 0 then print the message and terminate the program:
size_t length = strlen(num);
if (length == 0)
{
printf("String is empty\n");
return EXIT_FAILURE;
}
for (size_t i = 0; i < length; ++i)
{
if (isdigit(num[i]) == 0)
{
printf("Input was not a number\n");
return EXIT_FAILURE;
}
}
// Here we know that all characters in the input are digits
You could simply replace the multiply operation with &... Once a non-digit appears and isdigit() returns 0 (meaning false), the flag variable will remain false.
You may want to consider combining operations into compact code such as the following.
#include <stdio.h>
#include <ctype.h>
#include <cs50.h> // less "generic" that the others
int main( void ) {
string num = get_string(" Enter a number:");
int i = 0;
while( isdigit( num[i] ) ) i++; // loop fails on '\0', too
if( i == 0 || num[i] ) // empty string or did not reach its end
printf( "%s is NOT an integer.\n", num );
else
printf( "%s is an integer.\n", num );
return 0;
}
This is my code. I failed to use the break keyword after the printf function in order to break out of the loop. When I enter a negative number or zero, it doesn't prompt me again to re-enter.
#include <stdio.h>
#include <cs50.h>
int get_positive_int(void);
int main (void)
{
get_positive_int();
}
int get_positive_int(void)
{
int i;
i = get_int("Integer: ");
while (true)
{
if (i<1)
{
return i;
}
else
{
printf("%i", i);
}
}
}
The algorithm in the function get_positive_int() is wrong:
You need to place i = get_int("Integer: "); inside of the while loop.
Your if condition:
if (i < 1)
is wrong as that would return i if i is a negative integer or 0. If you want to return i when i is a positive integer or 0 you should use if(i >= 0).
Note that you can also place:
if (i == INT_MAX)
{
// optional error handling.
return INT_MAX;
}
after the call to maintain the occurrence of a read error. But if you want to only return INT_MAX then, you do not need to do so and can omit it since this would fit to the conditional statement ``if(i >= 0)` and its body.
The code is then:
int get_positive_int(void)
{
int i;
while (true)
{
i = get_int("Integer: ");
if (i == INT_MAX)
{
// optional error handling.
return INT_MAX;
}
else if (i >= 0)
{
return i;
}
printf("%i", i);
}
}
Side note: If you donĀ“t want to count 0 as positive integer, you need to have i >= 1 as the condition of the if statement.
As you said in the comments you only want to continue if i is a positive integer and exit if i is a negative characters or 0:
void get_positive_int(void)
{
int i;
while (true)
{
i = get_int("Integer: ");
if (i < 1)
{
return;
}
printf("%i\n", i);
}
}
Note that in this case, the return type of get_positive_int shall be void instead of int and it should omit to return i as it is not necessary to return any value from the function.
I'm writing a function that takes a user input up to a 1000 and then adds each number of the input. So if a user inputs 12 the function outputs 3.
When a user inputs 1000 or over the function will print "That number is to high". I can get the function to print the statement, but it also outputs 14...I do not understand why?
I understand there are probably other bugs in my code but right now this is the one that is killing me. Anything that can help would be great.
Here is my code.
#include <stdio.h>
int SummItAll(int value);
int main ()
{
int userNumber=0, result;
printf("Enter a positive number \n ");
scanf("%d", &userNumber);
result = SummItAll(userNumber);
printf("%d\n", result);
return 0;
}
int SummItAll(int value)
{
int a=value, b, c, d, f, g;
if(a < 100)
{
b = a/10;
c = a%10;
return b+c;
}
else if(a >= 100 && a < 1000)
{
b = a/100;
c = a%100;
d = c/10;
f = c%10;
return b+d+f;
}
else
return printf("That number is to high!\n");
}
printf returns the number of characters printed, so it's telling you that your message was 14 characters long.
Rather than returning the result of printf, you should probably return an invalid value (e.g., -1) to indicate an error:
Since the sum of 3 positive digits can never be a negative number, you can check the result of SumItAll, and then take different action in the case of an error:
#include <stdio.h>
int SummItAll(int value);
int main ()
{
int userNumber=0, result;
printf("Enter a positive number \n ");
scanf("%d", &userNumber);
result = SummItAll(userNumber);
if (result == -1)
{
printf("Please enter a POSITIVE number!\n");
}
else if (result == -2)
{
printf("That number is to high!\n");
}
else
{
printf("%d\n", result);
}
return 0;
}
int SummItAll(int value)
{
int a=value, b, c, d, f, g;
if (a < 0)
{
return -1; // too low!
}
else if(a < 100)
{
b = a/10;
c = a%10;
return b+c;
}
else if(a >= 100 && a < 1000)
{
b = a/100;
c = a%100;
d = c/10;
f = c%10;
return b+d+f;
}
else
{
return -2; // too high!
}
}
Note that -1 and -2 would be considered "magic numbers" in the code above, since they have a special meaning that isn't immediately obvious. It would probably be better to define some symbols to use in the code in place of the integer literals -1 and -2 in order to make the meaning more clear. For example:
#define ERR_NUM_IS_NEGATIVE -1
#define ERR_NUM_IS_TOO_LARGE -2
And then you can use those symbolic names in the code instead of the literals, which should make it more clear.
For your use case, it is better that SummItAll accepts a pointer parameter where both the input and output are passed and return a boolean value to indicate the returned result is valid or not.
bool SummItAll(int *value)
{
if(...) {
*value = ...
return true;
} else if(...) {
..
} else {
return false;
}
}
The printf() function returns an integer which indicates how many characters it has written out.
I am trying to count the number of ones in an array of characters that represent a binary number with a recursive type program. However, it seems as if my program is just counting the number of characters in the array. I do not know if I am just comparing wrong or not but I can't seem to find the problem
#include <stdio.h>
# include <stdlib.h>
#include <string.h>
#define SIZE 20
int determine (char array[SIZE], int count, int track );
int main()
{
int answer = 0;
char input[SIZE]={"1001001"};
int count = 0;
int track = 0;
answer = determine(input, count, track);
printf("The number of 1's is %d ", answer);
system("PAUSE");
return 0;
}
int determine(char array[], int count, int track)
{
if (array[track] != '\0')
{
if ( array[track] == '1');
{
count++;
}
return determine(array, count, track = track+1);
}
else
{
return count;
}
}
In method determine():
if ( array[track] == '1');
remove the semicolon ;. The semicolon makes the if condition to execute an empty block. So the count++ will always execute whether the if condition succeeded(true) or not(false).
I run your code with ; and get the output:
The number of 1's is 7
And without ; :
The number of 1's is 3
if ( array[track] == '1');
should be
if ( array[track] == '1')
remove the ;
If you have the ; then irrespective of the condition evaluation result (TRUE or FALSE) count++ will get executed
Have you tried a simple countif function?
=sum if (range="1")
The Following two Codes Yield the same output but has some diffrence which i couldn't figure out
1.
#include<stdio.h>
int main(void)
{
int a=1;
while(a>0)
{
scanf("%d",&a);
if(a != 42)
printf("%d\n",a);
else
break;
}
}
2
#include <stdio.h>
int main(void) {
int x;
for(; scanf("%d",&x) > 0 && x != 42; printf("%d\n", x));
return 0;
}
The working is different because the semantics are different because the code is different.
If you would want to rewrite the 2nd part to the 1st, you would get
#include <stdio.h>
int main(void) {
int x;
while (scanf("%d",&x) > 0 && x != 42) {
printf("%d\n", x);
}
return 0;
}
or
int main(void) {
int a;
while (scanf("%d",&a) > 0) {
if (x != 42) {
printf("%d\n", x);
} else {
break;
}
}
return 0;
}
Do you see the difference? On the one, you base your decision on the variable being scanned (x or a) and on the other on the return value of scanf(), which is simply the number of values read:
while(a>0)
vs.
while (scanf("%d",&a) > 0)
In the first case it's simple looping structure.
In the second case. The For Loop arguements like initialization of looping variable, condition and incrementation/decremenation are always options.
here For loop initialization is omitted, the condition scanf("%d",&x) will return no of values properly read from console, in case if you give any random character as input scanf return 0 and the condition x!= 42 is obvious. printf in the incremation/decrematation place just prints.
Only when the condition fails the loop terminates.