Project Euler problem number 8, program only returning 0.
Thanks a lot. I'm sorry but how would the last part, "int intNum = element - '0';" work in my specific context? I'm sorry if this is a dumb question, I'm new at this.
It might help if you tried printing out stuff to see how it looks. So lets do an example with these two variables.
char two = '2';char zero = '0';
To print out the characters, you would do the following
printf("%c", two); // prints 2 printf("%c", zero); //prints 0
When working with ASCII characters, see the following table, each character has associated values. The "Dec" column is the value in our number system. So
A = 65, B = 66, C = 67, etc
0 = 48, 1 = 49, 2 = 50, etc
a = 97, b = 98, c = 99, etc
So getting back to the example, we can see these characters ASCII values by printing them like so
printf("%d", two); // prints 50printf("%d", zero); // prints 48
When we combine characters with operators like addition and subtraction, C will use their ASCII values to perform the computation. Since the characters 0-9 are in order, their ASCII values can be used to convert the character of a number into the actual value of that number by subtracting the character 0 from it.
'2' - '0' = 2// because50 - 48 = 2'9' - '0' = 9//because57 - 48 = 9
Knowing this, you should be able to change your program to be correct.

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now