I am trying to do some multiplication. I am asking users to enter 9 digits number and multiply each digit with. Lets say if user enters 123456789 then we will do this:
123456789
246824682
We will multiply user input with this code:
#include <stdio.h>
int main(void) {
char num[10];
int num1,num2,num3;
printf("Enter your num: ");
fgets(num,10,stdin);
num1 = num[1] * 2;
num2 = num[2] * 4;
num3 = num[3] * 6;
printf("%d %d %d", num1,num2,num3);
return 0;
}
When I run this this is what I get:
admin#matrix:~/cwork> ./lab2
Enter your num: 123
100 204 60admin#matrix:~/cwork>
Why am I getting 100 204 and 60
I though I would get : 2 8 18 OR 2818!
First, in the C programming language, arrays are indexed starting at 0. So you need to change the indexes from [1], [2], [3] to [0], [1], [2].
Second, each digit in the input is an ASCII character. So the character 2 is actually stored in your array as the number 50. That's why num[1] * 2 is 100.
The easiest way to convert the digits to the numbers you expect is to subtract '0' from each digit. Putting it all together, your code should look like this
num1 = (num[0] - '0') * 2;
num2 = (num[1] - '0') * 4;
num3 = (num[2] - '0') * 6;
When you read from stdin you get a char array.
So in your example with "123"
your array looks like this:
num[1] == '2' == 50 // 50 is the ascii code for '2'
num[2] == '3' == 51 // 51 is the ascii code for '3'
So of course you are getting 100, 204 for these numbers.
Also note that arrays start with 0, not with 1!
Related
I've already written a program, but it's a bit incorrect.
I will be very grateful if you show me how to fix it.
So, here is the trouble:
You have to convert the number from hexadecimal to decimal form.
The main problem is that program must CALCULATE MANUALLY the number , instead of using a format specification ( as i did )
I apologize for possible inaccuracies and mistakes in English, I am just starting to familiarize myself with programming))
There is my variant:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define SIZE 20
int main(void) {
system("chcp 1251");
char str[SIZE][SIZE], (*pstr)[SIZE];
pstr = str;
char* pcode;
int kst;
printf("Specify the number of lines you want to enter: ");
scanf_s("%d", &kst);
getchar();
while (kst > SIZE)
{
printf("You have exceeded the allowed value (the number of lines must be less than 20): ");
scanf_s("%d", &kst);
getchar();
}
while (kst < 1)
{
printf("You entered a number that is too small, try entering a number between 1 and 20:");
scanf_s("%d", &kst);
getchar();
}
int isXDigit;
printf("\nEnter the lines:\n\n");
while (pstr < str + kst)
{
isXDigit = 1;
gets_s(*pstr);
for (pcode = *pstr; *pcode != '\0'; pcode++){
if (isxdigit(*pcode) == 0){
**pstr = 0;
break;
}
}
pstr++;
}
printf("\nThe result\n");
unsigned long long sixteen;
for (pstr = str; pstr < str + kst; pstr++)
{
if (**pstr == 0)
printf("16: The error!\n");
else {
sixteen = strtoull (*pstr, NULL, 16);
printf("16: %#020llx | 10: %llu\n", sixteen, sixteen);
}
}
return 0;
}
unsigned long long hexToNum(const char *hexSTR)
{
const char *digits = "0123456789ABCDEF";
const char *found = NULL;
unsigned long long result = 0;
while(*hexSTR)
{
result *= 0x10;
if(found = strchr(digits, toupper((unsigned char)*hexSTR)))
result += found - digits;
else { result = 0; break;}
hexSTR++;
}
return result;
}
Textual representation of a number
“Hexadecimal” and “decimal” (and “octal” and “binary” et cetera) are all textual representations of a number.
That is, we write numbers with a radix, but a number exists independently of any particular representation.
That is why 0xA equals 10 equals 012 equals 0b1010 (hexadecimal, decimal, octal, and binary representations).
Remember in grade school when you were taught digit places? That is because a number is a polynomial representation of a value.
→ 123 equals 100 + 20 + 3
Or, written as a polynomial:
→ 1×102 + 2×101 + 3×100
That 10 is the radix. If we change the radix, the number gets written differently. The following, even though it has the same digits, is a totally different number:
→ 1×162 + 2×161 + 3×160
We can see this by doing the math.
3×160 is 3
2×161 is 32
1×162 is 256
256 + 32 + 3 is 291
Dissecting a number to a polynomial representation with radix
To get the least-significant digit of a number, you simply take the remainder of dividing it by the radix:
→ 123 ÷ 10 is 12 with a remainder of 3
You can repeat this process to get every digit in the given radix:
→ 12 ÷ 10 is 1 with a remainder of 2
→ 1 ÷ 10 is 0 with a remainder of 1
So the digits, radix 10, of 123 are, least-significant to most-significant, 3, 2, and 1. We write this as 123.
Suppose we take a radix of 16?
→ 123 ÷ 16 is 7 with a remainder of 11 (which we write as B)
→ 7 ÷ 16 is 0 with a remainder of 7
So the hexadecimal (radix == 16) value of 123 is 7B.
Suppose we take a radix of 8?
→ 123 ÷ 8 is 15 with remainder 3
→ 15 ÷ 8 is 1 with remainder 7
→ 1 ÷ 8 is 0 with remainder 1
So the octal (radix == 8) value of 123 is 173.
In C the operators for getting the quotient and remainder are / and %:
42 / 10 is 4 (quotient)
42 % 10 is 2 (remainder)
Building a number from a polynomial representation with radix
If you are given a textual number representation and wish to build that into an actual numeric value, you only need to know the radix and have access to multiplication and addition.
For example, given 2 7 B:
0 * 16 + 2 → 0 + 2 → 2
2 * 16 + 7 → 32 + 7 → 39
39 * 16 + 11 → 624 + 11 → 635
Indeed this is correct: The hexadecimal representation of 635 is 27B. Said another way, the decimal representation of 0x27B is 635.
Functions!
We can make ourselves functions both to build and dissect polynomial text representations.
int hex_to_int( const char * text );
void int_to_hex( int number, char result[] );
Digit symbols
One thing to be aware of is the number of digit symbols available to a given radix.
For decimal we use the digit symbols 0 through 9.
For octal we only use the digit symbols 0 through 7.
For binary we only need 0 and 1.
But we don’t have enough Arabic digit symbols for hexadecimal, which needs 16 digit symbols. So we just start using the alphabet:
→ 0 1 2 3 4 5 6 7 8 9 A B C D E F
Converting to hex is easy. Just use an array:
char digits[] = "0123456789ABCDEF";
To output the digit symbol for digit 13, just use the array:
printf( "%c", digits[13] ); // prints "D"
Going the other way is a little trickier. I recommend you make yourself a little function:
int hex_digit_to_value( int digit )
{
if ((digit >= '0') and (digit <= '9')) return (digit - '0');
if ((digit >= 'A') and (digit <= 'F')) return (digit - 'A') + 10;
if ((digit >= 'a') and (digit <= 'f')) return (digit - 'a') + 10;
return 0; // can't happen? maybe return -1?
}
So I was assigned to store two 50 digit integers in c language and do math equations using them. the problem for me was to store the input digit by digit in an array. I figured that I can store the input in a char string like this:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char string_test [50];
scanf("%s", string_test);
return 0;
}
But I couldn't use it as a number because it was stored as char and I couldn't copy them digit by digit into another array which was defined as int
after a whole day of searching, I found out that I need to copy my string one by one like this:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char string_test [50];
scanf("%s", string_test);
int arr[50];
for (int i = 0; i < 50; i++)
{
arr[i] = string_test[i] - '0';
}
return 0;
}
Now my question is why do I need to subtract '0' to get a suitable result?
The ASCII values for digits 0 - 9 are:
Digit 0 1 2 3 4 5 6 7 8 9
ASCII value 48 49 50 51 52 53 54 55 56 57
So if you have a string representation of an integer, say
char int_str[] = "123456";
and need to convert each char to its numeric value, subtracting the value for '0' (48) from each will will result in the values
int_str[0] == '1' ==> '1' - '0' ==> 42 - 41 == 1
int_str[1] == '2' ==> '2' - '0' ==> 43 - 41 == 2
int_str[2] == '3' ==> '3' - '0' ==> 44 - 41 == 3
int_str[3] == '4' ==> '4' - '0' ==> 45 - 41 == 4
int_str[4] == '5' ==> '5' - '0' ==> 46 - 41 == 5
int_str[5] == '6' ==> '6' - '0' ==> 47 - 41 == 6
To get digits 1 2 3 4 5 6 into the integer 123456 requires additional steps:
This example uses the same conversions encapsulated into a function to convert discrete char digit to int digit values, then assimilate each discrete int digit value into the composite integer value:
int main(void)
{
char str[] = "123456";
int int_num = str2int(str);
return 0;
}
int str2int(char *str)
{
int sum=0;
while(*str != '\0')
{ //qualify string
if(*str < '0' || *str > '9')
{
printf("Unable to convert it into integer.\n");
return 0;
}
else
{ //assimilate digits into integer
sum = sum*10 + (*str - '0');
str++;
}
}
return sum;
}
A char like '0' is just an ASCII representation of a 1 byte number. The numeric representations of these characters can be found in the manual (man ascii). Here you will see that '0' actually represents number 48 or 0x30 and that ASCII '0' to '9' are consecutive.
To convert a numeric char value to its integer counterpart, it is necessary to subtract this value of 48 or '0'.
I hope this clears things up. For further info, look into char arithmetic in C.
This is actually related to the ASCII code representation of numbers; when you input a character, '0', it is stored in memory as value 48 (in decimal) and also any other number or character.
You will find that the ASCII code value for '1' is 49 so, if we applied the operation, int x = '1' - '0';, we are storing the decimal value 1 in x and dealing with it as a number, not a character any more.
You can search more about ASCII codes; it's a very useful topic for any programmer.
I have a task (currently studying the loop statement so I'm in the beginner phase)that asks to make a program to reverse an integer number so it must have the do statement .
The output should be (example):
Enter a number: 4568
The reversal is: 8654
Please put in mind that since I'm following my book so far I've studied and know the very basics + selection and loop statements. I have very limited choices so no arrays.
The book suggests to make a do loop to divide repeatedly the number by 10 until it reaches 0 this is what I did so far (code not completed) :
int main(void)
{
int n,x;
printf("Enter a number: ");
scanf("%d", &n);
printf("The reversal is: ");
x = n % 10;
printf("%d",x); /*outputs the last number digit in the first place*/
do{
....
n /= 10; /* for example if I divide the number 56222 by ten the output would come out as
5622 562 56 5*/
....
}while (n!=0);
return 0;
}
I found a way to put the last digit in the first place as you can see but
I'm struggling to figure out how to reverse the rest of the numbers after dividing the number by 10 repeadetly with this very limited choices.
What should I put in the do statement?
Many thanks in advance .
int main(void)
{
int n,x;
printf("Enter a number: ");
scanf("%d", &n);
printf("The reversal is: ");
int rev = 0;
do{
x = n % 10;
rev = rev * 10 + x;
n /= 10;
}while (n!=0);
printf ("%d", rev);
return 0;
}
here you need a new integer rev whose value is 0 initially. Lets take
example of 432
n = 432
when you do x = n % 10 x = 2
so when you do rev = rev * 10 + x rev is 0 and value of rev will be 2
n /= 10 make n = 43
-->so in the next iteration
n = 43
x = n % 10 results in x = 3
rev value now is 2
so rev = rev * 10 + x results in 2 * 10 + 3
so rev = 23
n /= 10 results in n = 4
-->in the last iteration n = 4
x = n % 10 results in x = 4 rev value now is 23
so rev = rev * 10 + x results in 23 * 10 + 4 so rev = 234
n /= 10 results in n = 0
so when you print rev you get the answer 234 reverse of 432
I quite don't know what this loop does.
int atoi(char s[])
{
int i, n;
n = 0;
for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
n = 10 * n + (s[i] - '0');
return n;
}
This part I don't get:
for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
n = 10 * n + (s[i] - '0');
I get the whole for loop inside parentheses, and what s[i] - '0' does.
But I don't get what kind of operation is going on here --> n = 10 * n.
I don't know what n is representing and why is multiplying 10.
I know it's converting string of digits to numeric equivalent, but I just don't get the whole operation there.
But I don't get what kind of operation is going on here --> n = 10 * n
That's just how you build a number digit by digit. It's basically the same as it would work if you were writing a calculator. If I wrote a simple calculator, here's how it would handle the input 547:
Start with 0
5 ==> 0*10 + 5 = 5
4 ==> 5*10 + 4 = 54
7 ==> 54*10 + 7 = 547
Basically, atoi does, the exact same thing, but instead of reading each digit from button presses, it's reading them from a string. Each time you read a new digit, you do n *= 10 to make room for that next digit, which just gets directly added on the end.
n is the digits that has already been processed. For instance, for the string "123", first, the program gets digit 1, convert it to integer and store it in n, and then get the next digit 2, this is where n = 10 * n is useful, the previous 1 is multiplied by 10, and added to the next digit 2, the result is 12, and this is stored as the current n.
The same goes on, when processing 3, the previous stored 12 is multiplied by 10, results in 120 and added to 3, ended as 123 as result.
How to check if a int var contains a specific number
I cant find a solution for this. For example: i need to check if the int 457 contains the number 5 somewhere.
Thanks for your help ;)
457 % 10 = 7 *
457 / 10 = 45
45 % 10 = 5 *
45 / 10 = 4
4 % 10 = 4 *
4 / 10 = 0 done
Get it?
Here's a C implementation of the algorithm that my answer implies. It will find any digit in any integer. It is essentially the exact same as Shakti Singh's answer except that it works for negative integers and stops as soon as the digit is found...
const int NUMBER = 457; // This can be any integer
const int DIGIT_TO_FIND = 5; // This can be any digit
int thisNumber = NUMBER >= 0 ? NUMBER : -NUMBER; // ?: => Conditional Operator
int thisDigit;
while (thisNumber != 0)
{
thisDigit = thisNumber % 10; // Always equal to the last digit of thisNumber
thisNumber = thisNumber / 10; // Always equal to thisNumber with the last digit
// chopped off, or 0 if thisNumber is less than 10
if (thisDigit == DIGIT_TO_FIND)
{
printf("%d contains digit %d", NUMBER, DIGIT_TO_FIND);
break;
}
}
Convert it to a string and check if the string contains the character '5'.
int i=457, n=0;
while (i>0)
{
n=i%10;
i=i/10;
if (n == 5)
{
printf("5 is there in the number %d",i);
}
}