C function return error - c

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.

Related

How to create a function in C that prompts the user for positive integers only and call it in the main function?

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.

How to make an array accept only numbers in c programming?

So my task is to make an array that accepts 10 characters. If the characters entered by the user are greater than 10, then an error is dispayed. If the 10 characters entered contain a letter, it displays another error.
Therefore, the array can only have 10 numbers and nothing else, if the numbers entered are less or more than 10, error is displayed as well as if there are letters in the array.
My code accepts both numbers and letters, as i cannot figure out how to display error when letters are entered.
void getTenDigitPhone(char telNum[])
{
int i;
int z = 1;
do
{
scanf("%s", telNum);
if (strlen(telNum) != 10)
{
printf("Enter a 10-digit phone number: ");
z = 1;
}
else if (strlen(telNum) == 10)
{
return telNum;
}
} while (z == 1);
}
You just need to check that telNum contains only digits:
for (int i = 0; i < 10; i++)
if (!isdigit(telNum[i])) {
// handle error because a non-digit was found.
}
I'm not going to do your homework for you but this should give you the idea.
You can use the function isdigit(x).
This returns true (non-zero) if x is a digit and returns false (zero) if not.
You have to check digit by digit.
I'm going to give an answer because you have posted your current code as your effort. As other answers you should use isdigit(x) function.
...
else if (strlen(telNum) == 10)
{
int i;
char err = 0;
for (i = 0; i < 10; i++) {
if (!isdigit(telNum[i])) {
// Your error here
printf("Non-digit character found");
err = 1;
break;
}
}
if (err == 0) {
return telNum;
}
}
...

How to most effectively combine functions including checkprime

#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.

C making a Function Return 1 when user input is 0-9 ASCII

The problem I have been given to solve is as follows:
-Write a function named "is_digit" that accepts a char as input, and returns an integer value of 1 if the parameter input is an ASCII digit between 0 and 9 inclusive. Otherwise the function must return a value of 0.
-In the main function, call is_digit, and pass in an argument based upon user input. The main function must then output the result from calling is_digit.
This is what i have so far
#include <stdio.h>
char is_digit(int x)
{
if (x > '48' && x < '57') //The ascII range between 0-9 (i think...)
{
return 1;
}
else
//Whatever the user input is it always runs the else
{
return 0;
//Is this what the question means by "function must return a value of 0"
}
}
int main()
{
char x;
printf("input: ");
scanf("%c", &x);
is_digit(x);
}
Why is my program not returning 1 if my user input is 0-9??
Updated version with comments taken into consideration:
#include <stdio.h>
char is_digit(char x)
{
if (x >= 48 && x <= 57)
{
printf("1");
return 1;
}
else
{
printf("0");
return 0;
}
}
int main()
{
char x;
printf("input: ");
scanf("%c", &x);
is_digit(x);
}
Try this:
Also to note use 'unsigned char x' in your main this basically means positive values 0-255
#include <stdio.h>
int is_digit(int x)
{
if (x >= 48 && x <= 57)
{
return 1;
}
return 0;
}
It would be better to change your method to return an int and not char.
Remove the single quotes because you are comparing the number values of the ASCII characters (int)
Also use the '<=' and '>=' signs because the question said inclusive. '<' and '>' is exclusive.
You don't need a else block since the answer is immediately returned if it is a number.
"//Is this what the question means by "function must return a value of 0"?"
Yes, that's what it means.
You could do a direct comparison:
int is_digit(char x)
{
int result;
if (x >= '0' && x <= '9')
{
result = 1;
}
else
{
result = 0;
}
return result;
}
Your mistake is with
if (x > '48' && x < '57') //The ascII range between 0-9 (i think...)
It should be
if (x > 47 && x < 58) //The ascII range between 0-9 (i think...)
The corrected code is shown below
#include <stdio.h>
int is_digit(char x)
{
if (x > 47 && x < 58) //The ascII range between 0-9 (i think...)
{
return 1;
}
else
//Whatever the user input is it always runs the else
{
return 0;
//Is this what the question means by "function must return a value of 0"
}
}
int main()
{
char x;
printf("input: ");
scanf("%c", &x);
printf("result is: %d",is_digit(x));
return 0;
}
A return statement in programming is a proof of what the computer did. In c and c++, returning 0 in main means your program ended correctly, without crashing but not necessarily that you code is wrong or right.
Your return type is char,
try this:
int is_digit(int x)
In short: because you're not telling it to. The final line should be:
return is_digit(x);
Without the return, the result from is_digit() is simply being thrown away...

In C How to use leftmost digit from an integer

I was wondering how to reverse my output to match entered number.
Example if user entered 543210, I want the output to be: Five Four Three Two One Zero. But instead it's reversed and I can't figure out how to reverse it.
I can't use loops or anything else.
Code:
int main(void){
int value;
int digit;
printf("enter:");
scanf("%i", &value);
while(value)
{
digit = value % 10;
value = value / 10;
if(digit != 0)
{
switch(digit)
{
case 0:
printf("zero ");
break;
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
}
}
}
return 0;
}
Exmaple: If user entered 1234
Output would be: four three two one.
How would I fix it to be: One Two Three Four.
Since you've said that you aren't allowed to use loops, then recursion really is the thing that you are probably being expected to use. I personally am not sure if it would be right to not consider a recursion as a loop, but whatever.
You are using a while there, which also is a loop. If you are allowed to use loops, then you could just do the following, easy-to-understand modification in your code, and get the output you desire:
...
int input; // <-- added this
int value;
int digit;
printf( "enter:" );
scanf( "%i", &input ); // <-- notice the change in variable usage
value = 0;
while ( input ) {
value = 10 * value + input % 10; // adds the last digit of input to value from right
input /= 10;
}
while ( value ) { ... }
...
If you aren't allowed to use loops, then you probably are expected to use a special function, a function which outputs a specific value for a single case, and returns back to itself in any other case. You need a recursive function. Examine this simple example:
// This is in maths, not C
f(x) = 2x + 1 for all integer x >= 0
Out of many ways, this one way to describe the function which maps 0 to 1, then 1 to 3, then n to 2n + 1. If we wanted to define the exact same function recursively:
// In maths
f(x = 0) = 1 for x = 0
f(x > 0) = f(x-1) + 2 for integer x > 0
You see what's going on in there? It's saying that each subsequent f(x) is 2 greater than the previous one f(x-1). But more importantly, the function is calling itself! If you look closer, the called function f(x-1) will also call itself:
f(x) = f(x-1) + 2
f(x) = f(x-2) + 2 + 2
f(x) = f(x-3) + 2 + 2 + 2
...
// all these are the same
All this calling deeper and deeper has to end somewhere, and that somewhere is when f(x-...) is f(0), which has been explicitly defined to be 1.
This is what recursion is all about. Let me write out the examples I gave above in C:
// non-recursive version
int fnonrec( int x ){
return 2 * x + 1;
}
// recursive version
int frec( int x ){
if ( x == 0 )
return 1; // explicit return value for f(0)
else // redundant else, hehe
return frec( x - 1 ) + 2;
}
Definitions of the functions really look similar to how they were defined in maths, don't they? Yeah, well, I don't think giving you the answer for your question would be nice of me. All I can say is that you can print things in reverse really nicely with recursive functions.
//store user input to int variable "value"
char str[15];
sprintf(str, "%d", value);
You can then use the strrev function to reverse the string array. Manipulate it from there.
#include <stdio.h>
void print(int v){
static char *numbers[] = {
"zero","one","two","three","four",
"five","six","seven","eight","nine"
};
int digit = v % 10;
int value = v / 10;
if(value){
print(value);
printf(" %s", numbers[digit]);
} else
printf("%s", numbers[digit]);
}
int main(void){
int value;
printf("enter:");
scanf("%i", &value);
print(value);
return 0;
}
Example using recursive function and numbers from the parameters :
#include <stdio.h>
void display(char c)
{
char *numbers[] = {
"zero","one","two","three","four",
"five","six","seven","eight","nine "
};
printf("%s ", numbers[c]);
}
int aff_num(char *c)
{
if (*c == '\0')
return (0);
display(*c-48);
aff_num(++c);
return (1);
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Need numbers\n");
return (-1);
}
aff_num(argv[1]);
return (0);
}
I'm a python hacker and I almost never program in C. that being said:
#include <stdlib.h>
#include <stdio.h>
int highest_power_of_ten(int value){
int exponent = 0;
int tens = 1;
while(value > tens){
tens *= 10;
exponent += 1;
}
return exponent-1;
}
int pow(int base, int exponent){
if (exponent == 0)
return 1;
int temp = base;
while(exponent > 1){
base *= temp;
exponent -= 1;
}
return base;
}
int main(int argc, char** argv){
char* digits[] =
{"zero","one","two","three","four","five","six","seven","eight","nine"};
int value, n, exp, x;
scanf("%i", &value);
while(highest_power_of_ten(value)>0){
exp = highest_power_of_ten(value);
x = pow(10, exp);
n = value/x;
printf("%s ",digits[n]);
value -= n*x;
}
printf("%s\n", digits[value]);
//system("PAUSE"); for windows i guess
return 0;
}
Another method to get the digits in the right order:
E.g. To get the digit at 1st position in 123 divide 123 by 100, to get 2nd - 123 / 10, to get 3rd 123 / 1. That equals: value / 10^(index of desired digit)
So what we have to do is
Get the length of the (remaining) number by calculating log10(value).
Then get the (remaining) first (most significant) digit by dividing value by 10^length (length of 1.)
calculate value := value - 10^length and start from 1, unless the result is 0 (mind handeling numbers that end on 0).
while (value)
{
len = log10(value);
digit = (int) value / pow(10, len);
value -= pow(10, len);
}
And your code does never enter case 0. To fix that just leave the if(digit != 0) - that's what I meant when I wrote "mind the 0").
if(digit != 0) // enters if digit is not 0
{
switch(digit)
{
case 0: // enters if digit is 0
...
}
}

Resources