C outputting variable positions (pointers) instead of actual values [duplicate] - c

This question already has answers here:
How to convert a string to integer in C?
(13 answers)
Closed 6 years ago.
I was working on a class project and I wanted to do a little bit extra and make validation on my data. The problem seems to happen at num1 = num1Input (and num2 = num2Input) where it is getting the location (I assume) instead of the actual input value
int main(void) {
//variables
char num1input[10];
char num2input[10];
int length, i;
int num1 = 0;
int num2 = 0;
int countErrors1 = 0;
int countErrors2 = 0;
bool correct1 = false;
bool correct2 = false;
//--end of variable declarations--//
do {
printf("Please enter a number: ");
scanf("%s", num1input);
length = strlen(num1input);
for (i = 0; i < length; i++) {
if (!isdigit(num1input[i])) {
countErrors1++;
}
}
if (countErrors1 > 0) {
printf("Input is not a number \n");
} else {
correct1 = true;
}
} while (correct1 == false);
num1 = num1input;
do {
printf("Please enter second number: ");
scanf("%s", num2input);
length = strlen(num2input);
for (i = 0; i < length; i++) {
if (!isdigit(num2input[i])) {
countErrors2++;
}
}
if (countErrors2 > 0) {
printf("Input is not a number \n");
} else {
correct2 = true;
}
} while (correct2 == false);
num2 = (int)num2input;
printf("%d %d \n", num1, num2);
int addition = num1 + num2;
int substraction = num1 - num2;
int multiplication = num1 * num2;
float division = num1 / num2;
printf("Addition: %d Subtraction: %d Multiplication: %d Division: %.1e", addition, substraction, multiplication, division);
getch();
}

You cannot convert a string to a number with a cast such as num1 = num1input;. You need to call a library function from <stdlib.h>:
#include <stdlib.h>
...
num1 = atoi(num1input);
But atoi ignores parsing errors. To ensure that overflows are detected, you can use strtol() as follows:
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
...
errno = 0;
char *endp;
long lval = strtol(num1input, &endp, 10);
if (endp == num1input || errno != 0 || lval < INT_MIN || lval > INT_MAX) {
/* parse error detected:
* you could print an error message.
*/
if (lval < INT_MIN) lval = INT_MIN; /* clamp lval as an int value. */
if (lval > INT_MAX) lval = INT_MAX;
}
num1 = lval;
Or if you want to recognize hexadecimal syntax such as 0x10:
num1 = strtol(num1input, NULL, 0);
The same is applicable for num2input.
Note that isdigit(num1input[i]) is potentially incorrect if char is signed and num1input[i] has a negative value. You should write:
isdigit((unsigned char)num1input[i])
Also note that float division = num1 / num2; will compute the integer division and convert the result to a float. If you want the floating point division, you should write:
float division = (float)num1 / num2;
Note finally that it is recommended to use double instead of float for better accuracy.
Here is a corrected and simplified version:
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
/* simple implementation of strtoi(), inspired by elegant code from chux */
int strtoi(const char *s, char **endptr, int base) {
long y = strtol(s, endptr, base);
#if INT_MAX != LONG_MAX
if (y > INT_MAX) {
errno = ERANGE;
return INT_MAX;
}
#endif
#if INT_MIN != LONG_MIN
if (y < INT_MIN) {
errno = ERANGE;
return INT_MIN;
}
#endif
return (int)y;
}
int main(void) {
char num1input[20];
char num2input[20];
char *endp;
int num1, num2;
for (;;) {
printf("Please enter a number: ");
if (scanf("%19s", num1input) != 1)
return 1;
errno = 0;
num1 = strtoi(num1input, &endp, 10);
if (errno == 0 && *endp == '\0')
break;
printf("Input is not a number\n");
}
for (;;) {
printf("Please enter a second number: ");
if (scanf("%19s", num2input) != 1)
return 1;
errno = 0;
num2 = strtoi(num2input, &endp, 10);
if (errno == 0 && *endp == '\0')
break;
printf("Input is not a number\n");
}
printf("%d %d\n", num1, num2);
int addition = num1 + num2;
int subtraction = num1 - num2;
int multiplication = num1 * num2;
double division = (double)num1 / num2;
printf("Addition: %d Subtraction: %d Multiplication: %d Division: %g\n",
addition, subtraction, multiplication, division);
getch();
}

Related

Determining the largest non-whole number in C language

I'm trying to make a program that accepts 4 numbers, regardless if it is a whole or non-whole number. It will determine the largest non-whole number found in the inputs. If there are no non-whole numbers present, then it will print a message that there are none.
Here is my code:
#include <stdio.h>
int main()
{
float num1, num2, num3, num4;
//Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", &num1, &num2, &num3, &num4);
//Numbers are Integer
if ((num1 - (int) num1) == 0
&& (num2 - (int) num2) == 0
&& (num3 - (int) num3) == 0
&& (num4 - (int) num4) == 0) {
printf("Output : No Non-Whole Numbers found\n");
} else {
//Numbers are Float
if (num1 > num2 && num1 > num3 && num1 > num4) {
printf("Output : %.1f\n", num1);
} else if (num2 > num1 && num2 > num3 && num2 > num4) {
printf("Output : %.1f\n", num2);
} else if (num3 > num1 && num3 > num2 && num3 > num4) {
printf("Output : %.1f\n", num3);
} else {
printf("Output : %.1f\n", num4);
}
}
}
But I have some problems with it, for example when a user inputs:
Enter 4 Numbers : 12.5 15 2 1
Output: 15
Instead it should be 12.5
Enter 4 Numbers : 10.5 10.5 7 8
Output: 8.0
Instead it should be 10.5
As Nils Martel pointed out this should be coded as a loop over an array.
The only difference from his implementation is that I think mine is easier to understand, because it's closer to the original code
#include <stdio.h>
#include <stdlib.h>
#define FALSE (0 != 0)
#define TRUE (!FALSE)
#define ABS(x) ((x >= 0) ? (x) : (-x))
#define NUMS 4
int is_whole(float num)
{
return (ABS(num) - (int)ABS(num)) == 0;
}
int main()
{
float nums[NUMS];
int contains_float = FALSE;
int largest = 0; // Initialized with the first element
//Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", &nums[0], &nums[1], &nums[2], &nums[3]);
//Numbers are Integer
for (int i = 0; i < NUMS; ++i) {
if (is_whole(nums[i]) == FALSE) {
contains_float = TRUE;
// The additional condition here accounts for the case when
// nums[0] is the largest element in the array
if (nums[i] > nums[largest] || is_whole(nums[largest]))
largest = i;
}
}
if (contains_float)
printf("Output : %.1f\n", nums[largest]);
else
printf("Output : No Non-Whole Numbers found\n");
}
You can run it here https://onlinegdb.com/rkVwPZaZu
I think the best check for determining, if a number is non while would be
floor(n) != n
Now, In your code you repeat yourself quite often and your logic gets quite complex and hard to understand by just looking at it.
You might find this exercise a great moment, to learn more about arrays and loops!
I've tried to rewrite your code using the floor(n) != n check, and by using arrays and loops. Mind, my C is a little rusty, but I hope you can reason with my code:
#include <stdio.h>
#include <math.h>
void print_largest_non_while(float *numbers, int length) {
int is_set = 0;
float greatest;
for (int i = 0; i < length; i++) {
float n = numbers[i];
if (floor(n) != n) {
// n is a non while number
if (!is_set) {
is_set = 1;
greatest = n;
continue;
}
if (greatest < n) greatest = n;
}
}
if (is_set) printf("%f\n", greatest);
}
int main() {
float num[4];
// Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", num, num + 1, num + 2, num + 3);
print_largest_non_while(num, 4);
}
Your test consider that all your numbers are not integers, or that they are all integers. Also consider that the test num1 - (int)num1) == 0 could give false results. Better: compare the abs of the difference to a threshold.
#define N 4
#include <stdio.h>
#include <math.h>
int main(){
float num[N];
//Enter Numbers
printf("Enter %d Numbers : ", N);
for (int i = 0; i < N; ++i) {
int t = scanf ("%f", &num[i]);
if (t != 1) return 1;
}
float eps = 1.0e-5;
int found = 0;
float vmax;
for (int i = 0; i < N; ++i) {
int check = fabs(num[i] - rint(num[i])) > eps;
found += check;
if (check) {
if (found == 1) {
vmax = num[i];
} else {
if (num[i] > vmax) {
vmax = num[i];
}
}
}
}
//Numbers are all Integer if found == 0
if(found == 0) {
printf("Output : No Non-Whole Numbers found\n");
} else {
printf("Output : %.1f\n", vmax);
}
return 0;
}

how to extract the even number from user input, and combine them as a new number in C program

test case:
input: 1234
output: 24
input: 2468
output: 2468
input: 6
output: 6
I have this code:
#include <stdio.h>
#include <math.h>
int main() {
int num;
printf("Enter a number: \n");
scanf("%d", &num);
int numberLength = floor(log10(abs(num))) + 1;
int inputNumberArray[numberLength];
int evenNumberCount = 0;
int even[10];//new even no. array
int i = 0;
do {
inputNumberArray[i] = num % 10;
num = num / 10;
i++;
} while (num != 0);
i = 0;
while (i < numberLength) {
if (inputNumberArray[i] % 2 == 0) {
evenNumberCount ++;
even[i] = inputNumberArray[i];
}
i++;
}
printf("array count %d\n", evenNumberCount);
i = 0;
for (i = 0; i < 8; i++) {
printf(" %d", even[i]);//print even array
}
i = 0;
int result = 0;
for (i = 0; i < 10; i++) {
if (evenNumberCount == 1) {
if (even[i] != 0) {
result = even[i];
} else {
break;
}
} else {
if (even[i] != 0) {
result = result + even[i] * pow(10, i);
} else
break;
}
}
printf("\nresult is %d", result);
/*
int a = 0;
a = pow(10, 2);
printf("\na is %d", a);
*/
}
when I enter number 1234, the result/outcome is 4, instead of 24.
but when I test the rest of test case, it is fine.
the wrong code I think is this: result = result + even[i] * pow(10, i);
Can you help on this?
Thanks in advance.
why do you have to read as number?
Simplest algorithm would be
Read as text
Validate
loop through and confirm if divisible by 2 and print live
next thing, have you try to debug?
debug would let you know what are doing wrong. Finally the issue is with indexing.
evenNumberCount ++; /// this is technically in the wrong place.
even[i]=inputNumberArray[i]; /// This is incorrect.
As the user Popeye suggested, an easier approach to accomplish this would be to just read in the entire input from the user as a string. With this approach, you can iterate through each letter in the char array and use the isdigit() method to see if the character is a digit or not. You can then easily check if that number is even or not.
Here is a quick source code I wrote up to show this approach in action:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char input[100] = { '\0' };
char outputNum[100] = { '\0' };
// Get input from user
printf("Enter a number: ");
scanf_s("%s", input, sizeof(input));
// Find the prime numbers
int outputNumIndex = 0;
for (int i = 0; i < strlen(input); i++)
{
if (isdigit(input[i]))
{
if (input[i] % 2 == 0)
{
outputNum[outputNumIndex++] = input[i];
}
}
}
if (outputNum[0] == '\0')
{
outputNum[0] = '0';
}
// Print the result
printf("Result is %s", outputNum);
return 0;
}
I figured out the solution, which is easier to understand.
#include <stdio.h>
#include <math.h>
#define INIT_VALUE 999
int extEvenDigits1(int num);
void extEvenDigits2(int num, int *result);
int main()
{
int number, result = INIT_VALUE;
printf("Enter a number: \n");
scanf("%d", &number);
printf("extEvenDigits1(): %d\n", extEvenDigits1(number));
extEvenDigits2(number, &result);
printf("extEvenDigits2(): %d\n", result);
return 0;
}
int extEvenDigits1(int num)
{
int result = -1;
int count = 0;
while (num > 1) {
int digit = num % 10;
if (digit % 2 == 0) {
result = result == -1 ? digit : result + digit * pow(10, count);
count++;
}
num = num / 10;
}
return result;
}
}
You are overcomplicating things, I'm afraid.
You could read the number as a string and easily process every character producing another string to be printed.
If you are required to deal with a numeric type, there is a simpler solution:
#include <stdio.h>
int main(void)
{
// Keep asking for numbers until scanf fails.
for (;;)
{
printf("Enter a number:\n");
// Using a bigger type, we can store numbers with more digits.
long long int number;
// Always check the value returned by scanf.
int ret = scanf("%lld", &number);
if (ret != 1)
break;
long long int result = 0;
// Use a multiple of ten as the "position" of the resulting digit.
long long int power = 1;
// The number is "consumed" while the result is formed.
while (number)
{
// Check the last digit of what remains of the original number
if (number % 2 == 0)
{
// Put that digit in the correct position of the result
result += (number % 10) * power;
// No need to call pow()
power *= 10;
}
// Remove the last digit.
number /= 10;
}
printf("result is %lld\n\n", result);
}
}

C program which returns the sum of the digits of an integer

#include <stdio.h>
int main()
{
int sum=0, prod=1, a, b;
printf("Enter a number: \n");
scanf("%d",&a);
while (a!=0)
sum = sum + a%10;
a = a/10;
while (b!=0)
prod = prod + b%10;
b = b/10;
printf("Sum=%d\nProd=%d\n", sum, prod);
return 0;
}
This C program returns the sum and product of the digits of a given integer, but i want someone to break it down for me, and also when i ran it, it doesn't work, so can someone correct me, please.
% is the modulus operation, i.e. it gives you the reminder of the division by the divisor. In your case the operation % 10 effectively returns the last digit of the number. You sum this digit to the prod variable which represents the total sum of digits. Once you have summed the current digit you perform the next main operation / 10 which is integer divison and just removes the last digit of the number.
Your code is very badly indented and necessary block delimiters {} are missing. Also b is not initialized and you compute the sum, not the product of the digits.
Here is a corrected version:
#include <stdio.h>
int main() {
int n, sum, prod, a, b;
printf("Enter a number: \n");
if (scanf("%d", &n) != 1)
return 1;
a = n;
sum = 0;
while (a != 0) {
sum = sum + a % 10;
a = a / 10;
}
b = n;
prod = 1;
while (b != 0) {
prod = prod * (b % 10);
b = b / 10;
}
printf("Sum=%d\nProd=%d\n", sum, prod);
return 0;
}
As you're reading the number from the user, read a string.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[999];
while (fgets(buf, sizeof buf, stdin)) { // read a string rather than scanf an integer
buf[strcspn(buf, "\n")] = 0; // remove trailing newline
char *p = buf;
int invalidflag = (*p == 0);
unsigned sum = 0;
unsigned product = 1;
while (*p) {
if (isdigit((unsigned char)*p)) {
sum += *p - '0';
product *= *p - '0';
} else {
invalidflag = 1;
break;
}
p++;
}
if (invalidflag) {
printf("input = \"%s\" ==> INVALID INPUT\n", buf);
} else {
printf("input = \"%s\"; sum = %d; product = %d\n", buf, sum, product);
}
}
return 0;
}
See ideone.com/ZLkOfJ

C program with a function which checks if integer A contains integer B

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int funkcija(int num, int num2)
{
int doesContain;
if (doesContain == 1)
return 1;
else
return 0;
}
int main(void)
{
int num, num2;
scanf("%d", num);
scanf("%d", num2);
printf("%d", funkcija(num, num2));
return 0;
}
So basically, I need to make a function which takes number 1 and number 2, checks if number2 is in number1, then returns 0 or 1.
So for example, if number 1 is let's say '2452325678', and number 2 is '7', number 1 DOES contain number 2 and the statement is true. But if num1 is '2134' and num2 is '5', the statement is false.
It needs to be done PRIMITIVELY, without arrays and whatnot.
I need any help I can get with the algorithm.
int numsub(int haystack, int needle)
{
for (; haystack; haystack /= 10)
if (haystack % 10 == needle)
return 1;
return 0;
}
fairly simple, works by keeping dividing the number by 10 and each time
checking if currentNumber % 10 == the digit checked.
that's all.
example:
int i;
int num;
int flag;
int digit;
flag = 1;
num = 1234;
digit = 2;
while(num != 0 && flag)
{
if(num % 10 == digit)
{
flag = 0;
}
else
{
num = num / 10;
}
}
if(flag == 1)
{
//flag stays set,which means that digit is not inside num
}
else
{
//flag is not set, which means that digit is indeed a part of num.
}

Converting binary to number string to decimal number in C

I've written a program that asks the user to input a number using strings, the program then will convert that number to decimal, however Im having a problem with it, when I compile (using -lm) and run the a.out, I get a Segmentation fault (core dumped), not really sure where to look or how to fix it, also one more question what do i need so that it prints the result of the conversion (printf("something..")) ?
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char string[100];
int s;
char a;
char j;
int sum;
printf("B = B to D\n");
printf("D = D to B\n");
printf("choose which one to convert to:");
scanf("%c%c", &a, &j);
if (a == 'B')
{
printf("enter binary number to convert to decimal: ");
scanf("%s", string);
for(s = strlen-1; s >= 0; s--)
{
if(string[s] == '1')
{
sum = sum + pow(2,s);
}
}
}
return 0;
You probably meant to have strlen(string) - 1, not strlen - 1. My best guess is that your program is interpreting strlen as a function pointer, and it's pretty much a given that crazy things happen after that.
As it is, you might be interested in the strtol function, which appears to do exactly what you're looking for.
You use strlen as an integer. I think you mean strlen(string)
for(sum=0, j=0, s=strlen(string)-1; s >= 0; s--, ++j){
if(string[s] == '1'){
sum = sum + pow(2,j);
}
}
printf("%d\n",sum);
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
void reverse_string(char *string)
{
int string_length = strlen(string);
char temp;
int i;
for (i = 0; i < string_length/2; i++)
{
temp = string[i];
string[i] = string[string_length - (i + 1)];
string[string_length - (i + 1)] = temp;
}
}
int main()
{
char string[100];
int s;
char a;
char j;
int sum = 0;
int string_length = 0;
int number, original_number;
int remainder;
char binary_string[200];
int i = 0;
printf("B = B to D\n");
printf("D = D to B\n");
printf("choose which one to convert to:");
scanf("%c%c", &a, &j);
a = toupper(a);
if (a == 'B')
{
printf("enter binary number to convert to decimal: ");
scanf("%s", string);
string_length = strlen(string);
for(s = strlen(string)-1; s >= 0; s--)
{
if(string[s] == '1')
{
sum = sum + pow(2,string_length - (s + 1));
}
}
printf("%s in binary is %d\n",string,sum);
}
else if (a == 'D')
{
printf("enter positive decimal number to convert to binary: ");
scanf("%s",string);
number = atoi(string);
original_number = number;
if ( number < 0 )
{
printf("ERROR: only positive numbers please\n");
return 1;
}
do
{
remainder = number % 2;
if ( remainder == 0 )
binary_string[i] = '0';
else
binary_string[i] = '1';
number = number / 2;
i += 1;
}
while (number > 0);
binary_string[i] = '\0';
reverse_string(binary_string);
printf("decimal %d is %s in binary\n",original_number,binary_string);
}
return 0;
}
strlen isn't used properly. I think you want to do something like strlen(string)-1. BTW your logic wont work to convert the fractional part. Check this code:
#include <stdio.h>
#define MAX 1000
int main()
{
double fraDecimal=0.0,dFractional=0.0 ,fraFactor=0.5;
long dIntegral = 0,bIntegral=0,bFractional[MAX];
long intFactor=1,remainder,i=0,k=0,flag=0;
char fraBinary[MAX];
printf("Enter any fractional binary number: ");
scanf("%s",&fraBinary);
while(fraBinary[i]) //Separating the integral and fractional parts
{
if(fraBinary[i] == '.')
flag = 1; //If dot is found start taking the fractional part.
else if(flag==0)
bIntegral = bIntegral * 10 + (fraBinary[i] -48);
/* char - 48 to get the numerical value.*/
else
bFractional[k++] = fraBinary[i] -48;
i++;
}
while(bIntegral!=0){
remainder=bIntegral%10;
dIntegral= dIntegral+remainder*intFactor;
intFactor=intFactor*2;
bIntegral=bIntegral/10;
}
for(i=0;i<k;i++){
dFractional = dFractional + bFractional[i] * fraFactor;
fraFactor = fraFactor / 2;
}
fraDecimal = dIntegral + dFractional ;
printf("Equivalent decimal value: %Lf",fraDecimal);
return 0;
}
Source:
C Program to Convert Binary into Decimal Number

Resources