How to convert hexadecimal to decimal in C? - c

So, with my beginner level of experience in C I've been trying to write a code that converts hexadecimal input to a decimal with an array. I believe you will get it more spesificly by looking at my code but it does not work properly. I keep getting an amount that is much larger than intended.
#include <stdio.h>
int main()
{
int i, k, j, N, power, result;
char array[50];
result = 0;
printf("how many charecters are there in your hexadecimal input?: \n");
scanf("%d", &N);
for(k=0; k<=N-1; k++)
{
printf("What is the %d . value of your hexadecimal input?: \n", k+1);
scanf("%s", &array[k]);
}
for(i=0; i<=N-1; i++)
{
power = 1;
for(j=0; j<=i; j++)
{
power = power *16;
}
if((array[i] >= 0) && (array[i] <= 9))
{
result = result + array[i] * power;
}
else
{
result = result + (array[i] - 'A' + 10) * power;
}
}
printf("your result is %d", result);
return 0;
}

Your code is overly complicated and wrong, but the idea is correct.
You want this:
#include <stdio.h>
#include <string.h>
int main()
{
char array[50];
scanf("%49s", array); // just use a single scanf with %s
// "49s" will avoid buffer overflow of array
int length = strlen(array); // get length of string (and use meaningful
// variable name length instead of N)
int result = 0;
for (int i = 0; i < length; i++)
{
int nibble; // nibble is the hexadécimal "digit" from 0 to 15
if ((array[i] >= '0') && (array[i] <= '9'))
{
nibble = array[i] - '0';
}
else
{
nibble = array[i] - 'A' + 10;
}
result *= 16; // no need to maintain power, just multiply by 16
// on each run
result += nibble; // ... and add the nibble
}
printf("your result is %d", result);
return 0;
}
There is still room for improvement:
you should accept lowercase
there is no test for invalid characters such as 'G', 'H' etc.
you should put the conversion code in a function such asint HexStringToDecimal(const char *hexstring)
and certainly a bunch of other things I forgot.
Exercise for you: convert that code so it converts a decimal string instead of a hexadecimal string. Hint: the code will be simpler.
Side note:
Avoid constructs like this:
for(k=0; k<=N-1; k++)
instead use this exact equivalent which is more readable:
for(k=0; k<N; k++)

just edited your code a little bit,
and also the input is supposed to be from left to right
instead of right to left according to which I think you have coded.
Hence, for C6, first C then 6.
#include <stdio.h>
int main()
{
int i, k, j, N, power, result;
char array[50];
result = 0;
printf("how many charecters are there in your hexadecimal input?: \n");
scanf("%d", &N);
for(k=0; k<=N-1; k++)
{
printf("What is the %d . value of your hexadecimal input?: \n", k+1);
scanf(" %c", &array[k]);
}
for(i=0; i<=N-1; i++)
{
power = 1;
for(j=0; j<=N-2-i; j++)
{
power = power*16;
}
if((array[i] >= '0') && (array[i] <= '9'))
{
result = result + (array[i] - '0') * power;
}
else
{
result = result + (array[i] - 'A' + 10) * power;
}
}
printf("your result is %d", result);
return 0;
}
the takeaways
your input taking is inefficeient. and in that too %c instead of %s in scanf.
if((array[i] >= 0) && (array[i] <= 9)), suppose i=1 and array[1] = 7. Now, you are comparing ascii value of 7 which is 55, instead of 7.
same thing in the statement of if, the ascii values of array[i] are being used so I have subtracted accordingly.

Related

Can we scanf an array?

I want to input an array of integers then print out the even numbers from the inputted numbers..
example is if I input 2466688992,
it will output 24666882;
I have a my code below:
#include<stdio.h>
int main()
{
int a[5],i;
printf("Enter array of numbers: ");
scanf("%d",&a);
for(i=0; i<sizeof(a); i++){
if(a[i]%2==0)
printf("%d",a[i]);
}
getch();
return 0;
}
It resulted into garbage : 2468000075416640419940000004225568000
This is the function that prints even numbers in an integer :
#include<stdio.h>
int main(){
int num,rem,even=0,digit;
printf(" Enter an integer number: ");
scanf("%d",&num);
printf("\n The even digits present in %d are \n",num);
while(num>0){
digit = num % 10;
num = num / 10;
rem = digit % 2;
if(rem == 0)
even++;
printf("\n %d.",digit);
}
return 0;
}
You should scan the array as a string (unless you want to impose the number of items in the array), and then parse the string to store the different numbers:
long a[50];
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
int j = 0;
for (int i = 0; i < len; ) {
long sign = 1;
long n = 0;
if (buf[i] == '+') {
++i;
}
else if (buf[i] == '-') {
sign = -1;
++i;
}
if (isdigit(buf[i])) {
while (isdigit(buf[i])) {
n = 10 * n + buf[i++] - '0';
}
a[j] = n * sign;
}
else
i++;
}
for (int i = 0; i < j; i++)
if (!(a[i] ℅ 2)) // true if even
printf("%ld ", a[i]);
This will store all your digits in your array a of size j.
Edit: if you are talking about digits then its easier:
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
for (int i = 0; i < len; i++)
if (isdigit(buf[i]) && !((buf[i] - '0') ℅ 2)) // true if even, note that '0' equals 0x30 so there is no need to sub it to check for odd/even in reality.
printf("%c ", buf[i]);

C program to insert elements into an array until user inputs a 0 or less number

I'm trying to make a C program to insert elements into an array until user inputs a 0 or less number, as the title says. But when I print the array out, it doesn't show the numbers I inputted. I have tried using a while as well as do-while loops but without success.
#include <stdio.h>
int main() {
int data[100];
int i;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
int n = sizeof(data[i]);
for (int i = 0; i < n; i++) {
printf("%d ", &data[i]);
}
}
Try this:
#include <stdio.h>
int main() {
int data[100];
int i;
int counter = 0;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
counter++;
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
for (int j = 0; j < counter - 1; j++) {
printf("%d ", data[j]);
}
}
The problem was that you had printf("%d ", &data[i]); instead of printf("%d ", data[i]);.
And also you've trying to get the sizeof() of an element data[i], not the size of the whole array. That's why there's counter in my code.
int n = sizeof(data[i]);
this is wrong, you want
int n = i;
sizeof(data[i]) gives you the size of an int (4 on my machine)
On the other hand, you need to check the result of scanf, if a bad input is entered do not increment the counter, something like:
int i = 0;
while (i < 100)
{
int res = scanf("%d", &data[i]);
if (res == EOF)
{
break;
}
if (res == 1)
{
if (data[i] <= 0)
{
break;
}
i++;
}
else
{
// Sanitize stdin
int c;
while ((c = getchar()) != '\n');
}
}
Finally, scanf wants a pointer to the object, but this is not the case of printf:
printf("%d ", &data[i])
should be
printf("%d ", data[i])

Program loops infinitely if a non-integer is entered, and does not accept plural digit inputs

Assigned task is to ask for # of values, and then at the end output the minimum, maximum, and average values and at this point I've run out of bug fixes
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
int ErrorDetection = 1;
char valCounter;
int valnumber;
int Incrementer;
int StoredValue;
int MinimumValue = 100;
int MaximumValue = 0;
float Average;
int AddToStored;
int Sum = 0;
printf("MIN, MAX, and MEAN CALCULATOR\n\n");
while (ErrorDetection != 0)
{
printf("How many values are to be entered?\n");
scanf("%s", &valCounter);
if (valCounter > '0' && valCounter < '9') {
ErrorDetection = 0;
}
else {
ErrorDetection = 1;
printf("INPUT ERROR!\n");
}
valCounter = valCounter - 47;
}
for (Incrementer = 1; Incrementer < valCounter; Incrementer++)
{
ErrorDetection = 1;
while (ErrorDetection != 0) {
printf("Value %d: ", Incrementer);
scanf(" %d", &StoredValue);
if (StoredValue > 0 && StoredValue < 9) {
ErrorDetection = 0;
}
else {
ErrorDetection = 1;
printf("INPUT ERROR!\n");
continue;
}
}
if (StoredValue > MaximumValue) {
MaximumValue = StoredValue;
}
if (StoredValue <= MinimumValue) {
MinimumValue = StoredValue;
}
Sum = Sum + StoredValue;
}
valCounter = valCounter - 1;
Average = (float)Sum / (float)valCounter;
printf(
"Minimum value is %d, maximum value is %d, and average value is %g.\n",
MinimumValue, MaximumValue, Average
);
}
If you input a 2 digit number things begin to breakdown, but at the same time I don't know how to go through with errorchecking if I allow multiple digit answers, as I make use of ASCII conversions to check if an input is a number or not.
You have undefined behavior here.
char valCounter;
scanf("%s", &valCounter);
You have declared valCounter as char type but trying to read string type.
Hence change the scanf to.
scanf("%c", &valCounter);
I would suggest you declare valCounter as int
int valCounter;
scanf("%d", &valCounter);
in that case your if will become.
if ((valCounter > 0) && (valCounter < 9))
and you don't need
valCounter = valCounter - 47; //remove
Also your for loop should start from 0 instead of 1
for(Incrementer = 1 ; Incrementer < valCounter; Incrementer++)
should be
for(Incrementer = 0 ; Incrementer < valCounter; Incrementer++)
Your problem is here.
char valCounter;
scanf("%s", &valCounter);
You're telling scanf to read a string, but you're passing it the address of a character. You should be asking for an integer, and giving it the address of an integer.
int valCounter;
scanf("%d", &valCounter)
There's more information here, including reasons why scanf might not be the best idea:
How to scanf only integer?

C program for assigning elements of a matrix without letters

I'm having trouble outputting an invalid statement if the user inputs a letter instead of a number into a 2D array.
I tried using the isalpha function to check if the input is a number or a letter, but it gives me a segmentation fault. Not sure what's wrong any tips?
the following code is just the part that assigns the elements of the matrix.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main() {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
scanf("%d", &n);
if (n <= 1 || n >= 11) { // can't be bigger than a 10x10 matrix
printf("Invalid input.");
return 0;
}
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (!isalpha(matrix[i][j])) { // portion I'm having trouble with
continue;
} else {
printf("Invalid input.");
return 0;
}
}
}
...
As the value of n will be number, we can solve it using string instead of int.
char num[10];
int n;
scanf("%s", num);
if(num[0] < '0' || num[0] > '9' || strlen(num) > 2){
printf("invalid\n");
}
if(strlen(num) == 1) n = num[0] - '0';
if(strlen(num) == 2 && num[0] != 1 && num[1] != 0) printf("invalid\n");
else n = 10;
Also we can use strtol() function to convert the input string to number and then check for validity.You can check the following code for it. I have skipped the string input part. Also you have to add #include<stdlib.h> at the start for the strtol() function to work.
char *check;
long val = strtol (num, &check, 10);
if ((next == num) || (*check != '\0')) {
printf ("invalid\n");
}
if(val > 10 || val < 0) printf("invalid\n");
n = (int)val; //typecasting as strtol return long
You must check the return value of scanf(): It will tell you if the input was correctly converted according to the format string. scanf() returns the number of successful conversions, which should be 1 in your case. If the user types a letter, scanf() will return 0 and the target value will be left uninitialized. Detecting this situation and either aborting or restarting input is the callers responsibility.
Here is a modified version of your code that illustrates both possibilities:
#include <stdio.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main(void) {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
if (scanf("%d", &n) != 1 || n < 2 || n > 10) {
// can't be bigger than a 10x10 matrix nor smaller than 2x2
// aborting on invalid input
printf("Invalid input.");
return 1;
}
for (int i = 0; i < n; i++) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; j++) {
if (scanf("%d", &matrix[i][j]) != 1) {
// restarting on invalid input
int c;
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("unexpected end of file\n");
return 1;
}
}
printf("invalid input, try again.\n");
j--;
}
}
}
...
The isdigit() library function of stdlib in c can be used to check if the condition can be checked.
Try this:
if (isalpha (matrix[i][j])) {
printf ("Invalid input.");
return 0;
}
So if anyone in the future wants to know what I did. here is the code I used to fix the if statement. I am not expecting to put any elements greater than 10000 so if a letter or punctuation is inputted the number generated will be larger than this number. Hence the if (matrix[i][j] > 10000). May not be the fanciest way to do this, but it works and it's simple.
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (matrix[i][j] > 10000) { // portion "fixed"
printf("Invlaid input");
return 0;
}
}
}
I used a print statement to check the outputs of several letter and character inputs. The lowest out put is around and above 30000. So 10000 I think is a safe condition.

Sum 2 Big Integers store in array by using getchar not scanf - C programing

I need a help with this program, below is the object and the program I wrote so far:
Objective: Write a C program that allow user 100 digit positive integers and then print out the sum of the two numbers.
Program I wrote so far by using scanf:
#include <stdio.h>
int main(void) {
int sum=0,i,j,array[100];
for(i=1;i<3;i++)
{
printf("operand #%d :",i);
scanf("%d",&array[i]);
printf("value entered: %d\n", array[i]);
}
for(j=1;j<i;j++)
{
sum=sum+array[j];
}
printf("The sum of array is %d ", sum);
return 0;
}
The following is the code I used getchar():
#include <stdio.h>
int main(void) {
int c,i,j,sum=0;
char a[100];
for(i=1;i<3;i++)
{
printf("operand #%d :",i);
do{
if(i < 100){
a[i] = (char)c;
i++;
}
else{
printf("Error: Number must be greater than 0,try again");
}
} while((c = getchar()) != '\n');
printf("value entered: %d\n", a[i]);
}
for(j=1;j<i;j++)
{
sum=sum+a[j];
}
printf("The sum of array is %d ", sum);
return 0;
}
Any help is appropriate!
One of your problems is that you're using i for two different jobs at the same time. It isn't going to work.
for(i=1;i<3;i++) // Use #1
{
printf("operand #%d :",i);
do{
if(i < 100){
a[i] = (char)c; // Use #2
i++;
}
else{
printf("Error: Number must be greater than 0,try again");
}
} while((c = getchar()) != '\n');
printf("value entered: %d\n", a[i]);
}
The outer loop will probably execute just once — it would execute twice if the first number was a single-digit number.
This code also assigns c before you've called getchar(), which is not going to improve things, either. You probably also need to convert the ASCII digits into single-digit numbers (subtract '0' from the digits but you should check that it is a digit first, and should break the inner loop on a non-digit).
If you're going to store 3 numbers of up to 100 digits each, you're going to need to have storage for up to 300 digits. char a[100] isn't big enough.
You might use something like:
char a[3][100];
int n[3];
for (int i = 0; i < 3; i++)
{
int c;
int j;
printf("Operand #%d: ", i);
for (j = 0; j < 100 && (c = getchar()) != EOF && isdigit(c); j++)
a[i][j] = c - '0';
n[i] = j;
while (c != EOF && c != '\n')
c = getchar();
}
If you enter numbers with 80, 60 and 20 digits, then this stores the 80 digits in a[0][0..79] and puts 80 into n[0] (so you know how long the number is); it stores the 60 digits in a[1][0..59] and puts 60 into n[1]; and it stores the 20 digits in a[2][0..19] and puts 20 into n[2].
When it comes to doing the addition, you need to be careful to align the numbers correctly, and ensure that you don't overflow the answer buffer if your addition has 101 digits. With three positive decimal numbers of up to 100 digits each, the answer can't be more than 101 digits long.
However, your code doesn't work.
True: the previous version use for (int j = 0; …) and then tried to access j outside the loop. The fix is obviously to declare j before the loop.
However, otherwise, the code does work. I've adjusted the occurrences of 3 to 2 since you say you only need two numbers. I decline to mess with indexing from 1; this is C and arrays are indexed from 0 in C. If you want a 1-based language, go and use Pascal or something.
Sample code to demonstrate:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
char a[2][100];
int n[2];
for (int i = 0; i < 2; i++)
{
int c;
int j;
printf("Operand #%d: ", i);
for (j = 0; j < 100 && (c = getchar()) != EOF && isdigit(c); j++)
a[i][j] = c - '0';
n[i] = j;
while (c != EOF && c != '\n')
c = getchar();
}
for (int i = 0; i < 2; i++)
{
printf("%d: %2d digits: ", i, n[i]);
for (int j = 0; j < n[i]; j++)
putchar(a[i][j] + '0');
putchar('\n');
}
return 0;
}
Sample data:
124232345289086098234232398098403242380980256454798796324635
98068704234280980243242349080928402342398408920482080980482034278795847396
Sample output:
Operand #0: 124232345289086098234232398098403242380980256454798796324635
Operand #1: 98068704234280980243242349080928402342398408920482080980482034278795847396
0: 60 digits: 124232345289086098234232398098403242380980256454798796324635
1: 74 digits: 98068704234280980243242349080928402342398408920482080980482034278795847396
That's the way it is supposed to work. You may want to do it differently; that's your prerogative. Have at it! I'm not going to solve the addition part of the problem for you — I've pointed out the most obvious gotchas (primarily, adding a[0][1] to a[1][1] will produce nonsense for the given inputs).
This only uses tiny functions. There's some tricky code in it; be wary of handing it in because you might be asked to explain what it does in detail, and you'll need to understand it all to be safe.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
static inline int max(int x, int y) { return (x > y) ? x : y; }
/* Return dth digit from RH end of string of n digits in x */
static inline int digit(char *x, int n, int d)
{
return (d < n) ? x[n - 1 - d] : 0;
}
int main(void)
{
char a[2][100];
int n[2];
/* Input - can probably be tightened up */
for (int i = 0; i < 2; i++)
{
int c;
int j;
printf("Operand #%d: ", i);
for (j = 0; j < 100 && (c = getchar()) != EOF && isdigit(c); j++)
a[i][j] = c - '0';
n[i] = j;
if (j == 0)
{
printf("No number - exiting\n");
exit(0);
}
if (c != EOF && c != '\n')
{
if (j < 100 && !isdigit(c) && !isblank(c))
{
printf("Bogus data in input (%c)\n", c);
exit(1);
}
while ((c = getchar()) != EOF && c != '\n')
{
if (!isblank(c))
{
printf("Bogus data in input (%c)\n", c);
exit(1);
}
}
}
}
/* Print for validation */
int n_max = max(n[0], n[1]);
for (int i = 0; i < 2; i++)
{
printf("V-%d: %2d digits: ", i, n[i]);
int n_blanks = n_max - n[i] + 1;
for (int j = 0; j < n_blanks; j++)
putchar(' ');
for (int j = 0; j < n[i]; j++)
putchar(a[i][j] + '0');
putchar('\n');
}
/* Addition */
char sum[101];
int carry = 0;
int max_digits = max(n[0], n[1]);
for (int i = 0; i < max_digits; i++)
{
int d0 = digit(a[0], n[0], i);
int d1 = digit(a[1], n[1], i);
int r = d0 + d1 + carry;
if (r > 9)
{
carry = 1;
r -= 10;
}
else
carry = 0;
sum[max_digits - i] = r;
}
if (carry)
sum[0] = 1;
else
sum[0] = 0;
/* Print result */
printf("Sum: %2d digits: ", (sum[0] == 0) ? max_digits : max_digits + 1);
if (sum[0] == 0)
putchar(' ');
for (int j = ((sum[0] == 0) ? 1 : 0); j <= max_digits; j++)
putchar(sum[j] + '0');
putchar('\n');
return 0;
}
Sample runs:
Operand #0: 888
Operand #1: 888
V-0: 3 digits: 888
V-1: 3 digits: 888
Sum: 4 digits: 1776
Operand #0: 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
Operand #1: 9876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210
V-0: 100 digits: 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
V-1: 100 digits: 9876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210
Sum: 101 digits: 11111111101111111110111111111011111111101111111110111111111011111111101111111110111111111011111111100
Operand #0: 9876543210a
Bogus data in input (a)
Operand #0: 9876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210a
Bogus data in input (a)
Operand #0: 98765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109
Bogus data in input (9)
Operand #0:
No number - exiting
It isn't perfect:
Operand #0: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Operand #1: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
V-0: 100 digits: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
V-1: 100 digits: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Sum: 100 digits: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Stripping leading zeroes from input (and output) is left as an exercise for you.

Resources