C code showing ASCII instead of character - c

I've only used C++ in the past and I was trying to convert my decimal to hex code to C. When trying to do so, I'm noticing when I try to print out a character, it prints out the ASCII value instead. I'm unsure of why it is doing this. Example: 10 in hex = A, however it prints out 65 instead. Any help would be appreciated.
#include<stdio.h>
#include<stdlib.h>
int main ()
{
int num = 0;
printf("Please enter an integer ");
scanf("%d",&num);
//shown as 8 in the example
char hex[8];
char hex_values[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int count = 0;
while(num > 0)
{
int spot = num % 16;
hex[count] = hex_values[spot];
num = num / 16;
count++;
printf("%d ", hex[count-1]);
}
//places zeros in front of the array... in an easy way
int zeros = 8 - count;
for(int q = 0; q < zeros; q++)
{
printf("%c", '0');
}
}

You have to print with '%c' to get the ASCII representation of a number because in C char are just unsigned short int
printf("%c ", hex[count-1]);

Related

Digit Frequency calculating code in C not working

So, I was writing this code for counting the digit frequency i.e. the number of times the digits from 0-9 has appeared in a user inputted string(alphanumeric). So, I took the string, converted into integer and tried to store the frequency in "count" and print it but when I run the code, count is never getting incremented and the output comes all 0s. Would be grateful if anyone points out in which part my logic went wrong.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
// takes string input
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
//turns the string to int
int x = atoi(s);
int temp = x, len = 0;
//calculates string length
while (x != 0) {
x = x / 10;
len++;
}
x = temp;
//parses through the string and matches digits with each number
for (int j = 0; j < 10; j++){
int count = 0;
for(int i = 0; i < len; i++){
if(x % 10 == j){
count++;
}
x = x / 10;
}
x = temp;
printf("%d ", count);
}
return 0;
}
To write a correct and reasonable digit-counting program:
Do not allocate any buffer for this.
Create an array to count the number of times each digit occurs. The array should have ten elements, one for each digit.
Initialize the array to zero in each element.
In a loop, read one character at a time.
Leave the loop when the read routine (such as getchar) indicates end-of-file or a problem, or, if desired, returns a new-line or other character you wish to use as an end-of-input indication.
Inside the loop, check whether the character read is a digit. If the character read is a digit, increment the corresponding element of the array.
After the loop, execute a new loop to iterate through the digits.
Inside that loop, for each digit, print the count from the array element for that digit.
Your approach is way to complicated for a very easy task. This will do:
void numberOfDigits(const char *s, int hist[10]) {
while(*s) {
if(isdigit(*s))
hist[*s - '0']++;
s++;
}
}
It can be used like this:
int main(void) {
char buf[1024];
int hist[10];
fgets(buf, sizeof buf, stdin);
numberOfDigits(s, hist);
for(int i=0; i<10; i++)
printf("Digit %d occurs %d times\n", i, hist[i]);
}
This can also be quite easily achieved without a buffer if desired:
int ch;
int hist[10];
while((ch = getchar()) != EOF) {
if(isdigit(ch))
hist[ch - '0']++;
}
#include <stdio.h>
int main(void) {
int input = 1223330;
int freq[10] = {0};
input = abs(input);
while(input)
{
freq[input%10]++;
input /= 10;
}
for(int i=0; i<10; ++i)
{
printf("%d: %.*s\n", i, freq[i], "*************************************************");
}
return 0;
}
Output:
Success #stdin #stdout 0s 5668KB
0: *
1: *
2: **
3: ***
4:
5:
6:
7:
8:
9:
This app is currently limited by the size of an int (approximately 9 or 10 digits).
You can update it to use a long long easily, which will get you to about 19 digits.

(C Programming) How to find the most frequent occurring digit in long numbers without using array?

Input Format:
A single line that contains an integer.
Constraint:
(-) each element <= 9223372036854775807 and >= 0
Input Sample:
3214144
Output Format:
A single line that contains the most frequent occurring digit. It is guaranteed that there's only one such digit.
Output Sample:
4
Here's the code that I made:
int main(){
int input, i=0, num=0;
do{
scanf("%i", &input);
i=input%10;
break;
}while(input<= 9223372036854775807 && input>=0);
if (i+i==i*2){
num+=1;
}
else{
num=0;
}
if (num>0){
printf("%i", i);
}
return 0;
}
The chars in the [asciitable][1] can be treated as integers. The char '0' is the number 48. '9' is 48+9 (i.e.57).
'9' - '0' = 57 - 48 = 9.
Treat the characters that you read as integers. Make an array to hold the 10 values. Afterwards, the index of the number with the biggest number is your solution.
#include <stdio.h>
int main() {
char c;
int counts[10] = {0,0,0,0,0,0,0,0,0,0};
int max = 0;
while(c=getc(stdin)){
/* read until we get a newline */
if (c=='\n') break;
/* you can treat a char as an integer */
counts[c-'0']++;
}
for(int i=0; i<10; i++) {
if(counts[i] > counts[max]) max=i;
}
printf("%i is the max",max);
return 0;
}
Also consider that the maximum value for a 32 bit int is 2147483647 while a string can be unlimited.
[1]: https://www.asciitable.com

I'd like to know how to convert variable value to number in ASCII array?

I'd like to know how to convert variable value to number in ASCII array?
For example:
int a=8;
I can check that '8' is 56 but how to write in a code?
int a=8;
b=(char)('(char)(a)');
printf(" %d",b);
I came up with that but I don't know if it's right.
Assign the character constant '8' to a and print that.
int a = '8';
printf("%d\n", a);
If you're working with the value 8, you can use the fact that the character constants '0' to '9' are guaranteed to be sequential and add the value of the character constant '0' to the value you have:
int a = 8;
printf("%d\n", a + '0');
You don't need to convert anything. If you have an array holding the values, print the array
using %c to print the character representation (digit)
using %d to print the decimal value in ASCII.
Sample code:
#include <stdio.h>
int main(void)
{
int arr [10] = {0};
// initialize array
for (int i = 0; i< 10; i++) {arr[i] = '0' + i;}
//print values
for (int i = 0; i< 10; i++) {
printf ("Element %d: Character value = %c, Decimal value =%d\n", (i+1), arr[i], arr[i]);
}
return 0;
}

scanf makes first element null in C

I am trying to get 2, length of 8, inputs. With the code I have, my problem is that bit1[0] is null. Where is my problem ?
This is kind of debug I have, to see it null-ifies the first element
PS: Dont mind about the calculations I have at the bottom of the code. I am trying to create a calculator that does binary summation. I still couldn't try my code, it can be meaningless to do it in the way I do. But its not the question I am asking so please avoid giving advice on that one. Thank you.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char bit1[8];
char bit2[8];
int result[8];
int sum;
int dig1;
int dig2;
printf("Enter first binary number without any whitespaces!\t");
scanf("%s", bit1);
printf("Enter second binary number without any whitespaces!\t");
scanf(" %s", bit2);
int handle = 0;
puts(bit1);
puts(bit2);
for(int i = 7; i >= 0; i--){
//printf("%d", bit1[i] - '0');
dig1 = bit1[i] - '0';
dig2 = bit2[i] - '0';
if(dig1 + dig2 + handle < 2){
result[i] = dig1 + dig2 + handle;
handle = 0;
} else {
result[i] = (dig1 + dig2 + handle)%2;
handle = 1;
}
printf("dig1: %d\tdig2: %d\thandle: %d\n", dig1, dig2, handle);
printf("%d is added!\n", result[i]);
}
for(int i = 0; i < 8; i++){
printf("%c", result[i]);
}
printf(" And carry is: %d", handle);
return 0;
}
UPDATED
Working code is:
char bit1[9];
char bit2[9];
int result[8];
int sum;
int dig1;
int dig2;
printf("Enter first binary number without any whitespaces!\t");
scanf("%8s", bit1);
printf("Enter second binary number without any whitespaces!\t");
scanf("%8s", bit2);
Rest are the same
When you want to get a string (that is exactly 8 characters) from user input you should write:
char string[9];
scanf("%8s", string);
The reason you need char string[9] and not char string[8] is because a C-string always ends in the null-character (0 or '\0'). Thus, you need one extra space to store that null-character.
Don't forget to always use %8s. If the user input then exceeds the 8 characters you want, C will automatically cut off the exceeding characters.

Retrieving an int's binary value, outputting the ASCII the binary corresponds to

Not really sure how to word this.
I have the int 'value' = 121, which is 1111001 in binary.
1111001 from binary to ASCII = "y"
I was wondering how I can convert the int value 121 to be printed as an ASCII character. Is there a built in function in C to do this?
Code I wrote earlier for someone else's question and adapted to your question:
#include <stdio.h>
int main(void)
{
int nr_to_binary = 0;
printf("Number: ");
scanf("%d", &nr_to_binary);
int i = (sizeof(nr_to_binary) * 8);
for(; i > 0 ; i--)
{
printf("%d", (nr_to_binary >> (i - 1)) & 1);
}
printf("\n\nASCII value of %d is %c", nr_to_binary, nr_to_binary);
return 0;
}
Result
Number: 121
00000000000000000000000001111001
ASCII value of 121 is y

Resources