Joseph Haugh
University of New Mexico
How can we transform an int into an array of digits?
void intToDigits(int x, int digits[], int n) {
int i = n - 1;
while (x > 0) {
...
}
}
void intToDigits(int x, int digits[], int n) {
int i = n - 1;
while (x > 0) {
digits[i] = x % 10; // 1s place
x = x / 10; // All but 1s place
i--;
}
}
Calling the function:
int main() {
int x = 123;
int numDigits = floor(log10(x)) + 1;
int digits[numDigits];
intToDigits(x, digits, numDigits);
for (int i = 0; i < numDigits; i++) {
printf("digits[%d]=%d\n", i, digits[i]);
}
return 0;
}
Note: We need to include the math.h
library to use log10
and floor
which means we need to compile with -lm
.
How can we transform an array of digits into an int?
int digitsToInt(int digits[], int n) {
int result = 0;
for (int i = 0; i < n; i++) {
result = result * 10 + digits[i];
}
return result;
}
How do you read in characters in C?
The getchar
function reads in a single character from standard in.
What happens if we read in a 1
character and print it as an int?
int main() {
int c = getchar(); // Read in '1'
printf("%d\n", c); // Prints 49
return 0;
}
Why does it print 49?
That is the ASCII value of the character 1
.
How could we then read in characters from standard in and convert it to an int?
First we need to transform the character ‘1’ to the int 1 not 49.
Let’s look at part of the ASCII table:
Character | ASCII |
---|---|
‘0’ | 48 |
‘1’ | 49 |
‘2’ | 50 |
‘3’ | 51 |
‘4’ | 52 |
We need to subtract the ‘0’ character from the character we read in.
Let’s then attempt to read in an int character by character.
int readNumber() {
int result = 0;
int c = getchar();
while (c != '\n') {
result = (result * 10) + (c - '0');
c = getchar();
}
return result;
}
In C it is common to use bits to represent error codes. For example:
#define ERROR_1 1
#define ERROR_2 2
#define ERROR_3 4
How do you then “raise” an error code?
You can use the |
operator to combine error codes.
#define NEGATIVE_ERROR 1
#define DIVIDE_BY_ZERO_ERROR 2
int error = 0;
int divide(int a, int b) {
if (a < 0 | b < 0) {
error |= NEGATIVE_ERROR;
return -1;
}
else if (b == 0) {
error |= DIVIDE_BY_ZERO_ERROR;
return -1;
}
return a / b;
}
How do you then “check” for an error code?
You can use the &
operator to check for an error code.
void checkError() {
if (error & NEGATIVE_ERROR) {
printf("Negative Error\n");
}
if (error & DIVIDE_BY_ZERO_ERROR) {
printf("Divide by Zero Error\n");
}
}
How can you feed the contents of a file through standard in to a C program?
You can use the <
operator to feed the contents of a file to a program.
./a.out < input.txt