Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The following code prints out 5. Can someone explain it to me? I think I am mostly confused about the math; for example, using '0' instead of 0 and how I can do that math on paper...
#include <stdio.h>
int main (int argc , char * argv [])
{
char * c_pt ;
int n = 0;
if( argc == 2)
{
c_pt = argv [1];
while (* c_pt )
{
if (* c_pt < '0' || * c_pt > '1') break ;
n = n*2 + * c_pt - '0';
c_pt ++;
}
printf ("%d\n", n);
}
}
When you access the characters in a string containing digits you might get the character '0' or '1' for example. But the integer value of '0' is 48 and the integer value of '1' is 49 so if you want to turn them into the integers 0 and 1 for arithmetic you need to substract something. You could subtract 48 but then the next person that reads your code has no idea why you did that. So nornally you subtract the character represented by the value: '0' - '0' = 0 and '1' - '0' = 1
This particular program reads a string containing a binary number from the command line (so the string contains the characters '0' and '1') and converts that binary number to a decimal number by first converting the '0' and '1' at *c_pt to 0 and 1 and then adding it to the decimal number being built in n. It does that by starting with 0 and then on each iteration multiplying the number by two (which just shifts everything left one bit) and then adding the next digit. So if the string contained 10101 it would follow these steps:
number = 0
input = 10101
pointer = ^
number = number*2 + *pointer = 0*2 + ('1'-'0') = 0*2 + 1 = 1 (in binary: 1)
input = 10101
pointer = ^
number = number*2 + *pointer = 1*2 + ('0'-'0') = 1*2 + 0 = 2 (in binary: 10)
input = 10101
pointer = ^
number = number*2 + *pointer = 2*2 + ('1'-'0') = 2*2 + 1 = 5 (in binary: 101)
input = 10101
pointer = ^
number = number*2 + *pointer = 5*2 + ('0'-'0') = 5*2 + 0 = 10 (in binary: 1010)
input = 10101
pointer = ^
number = number*2 + *pointer = 10*2 + ('1'-'0') = 10*2 + 1 = 21 (in binary: 10101)
void main ( void )
{
int a[] = {22, 33,44};
'a' is a static array (or string) of 3 int, 22, 33, and 44.
int *x = a;
'x' is an int pointer, initialized to point to the same static array as 'a'.
printf (" sizeof ( int )=% lu ", sizeof (int ));
Prints the number of bytes [4] required to represent an int type on this system.
printf ("x=%p, x [0]=% d\n", x, x [0]);
Prints the memory address where the int pointer 'x' is currently pointing[0x7fff29af6530],
then also prints the integer value [22] stored in the [4] bytes starting at that address.
(Note: 'x[0]' is the same as '*x').
x = x + 2;
x [0x7fff29af6530]
+2 + 8 (or (2 * 4) or (2 * sizeof(int)))
---- ----------------
new x [0x7fff29af6538]
Advance the pointer 'x' 8 bytes.
The effect on 'x' is that it will now be pointing at its original memory address plus '(2 * sizeof(int))' bytes. 'a[2]' resolves to the same location.
printf ("x=%p, x [0]=% d\n", x, x[0]);
Prints the memory address where the int pointer 'x' is currently pointing [0x7fff29af6538]
then also prints the integer value [44] stored in the [4] bytes starting at that address.
Hence; 'x' now resolves to the same address as '&a[2]'; and '*x' resolves to the same number as 'a[2]'.
}
Related
I have an assignment that requires me to make a quiz which generates random math questions. I'm fine with everything but i'm struggling to find a way to randomly choose between the mathematical operators "+" and "-".
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
int choice = 0;
int lives = 0;
int question = 1;
int a;
int b;
int answer = 0;
int ans = 0;
int correct = 0;
printf("\n Welcome to Maths Tester Pro.");
printf("\n Please Select a difficulty:");
printf("\n 1) Easy");
printf("\n 2) Medium");
printf("\n 3) Hard \n");
scanf("%d%*c",&choice);
switch(choice)
{
case 1:
printf("You have selected Easy mode!");
lives = lives+3;
while ((lives !=0)&&(question !=6)){
if(question !=5){
//Ask Question
printf("\nQuestion %d of 5. You have %d lives remaining", question, lives);
srand(time(NULL));
a = (rand() % (10 - 1 + 1)) + 1; //make the sign random
b = (rand() % (10 - 1 + 1)) + 1;
printf("\n%d + %d = ",a ,b);
scanf("%d", &answer);
ans = a+b;
//If answer is correct
if((a+b) == answer){
printf("Correct!\n");
correct = correct + 1;
}
//If answer is incorrect
else{
printf("Incorrect! The correct answer was %d\n",ans);
lives=lives-1;
}
question = question + 1;
}
In my code I have it written as ans=a+b but I want it to be able to randomly pick either "+" or "-".
The easiest way to go would be to change the sign of b. To do so, simply multiply it by either 1 (keeps positive sign) or -1 (makes it a negative):
b = b * ((rand() - (RAND_MAX / 2)) > 0 ? 1 : -1);
Upon execution, you will randomly get a + b or a + (-b).
Example print of the resulting operator:
printf("%d%s%d = %d\n", a, (b > 0 ? "+" : ""), b, a + b);
Note: as pointed in earlier comments, you may also want to randomize the seed in order to prevent you application to keep providing the "same" random numbers with:
/* Randomize seed (needed once). */
srand(time(NULL));
/* Then make your calls to `rand()`. */
...
I offer this as an example of how to cleanly generate and print the sort of problems that you seem to want.
This produces 20 'sum' and/or 'difference' equations. You can simply suppress printing the total in order to pose the question to the user.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand( time( NULL ) );
for( int i = 0; i < 20; i++ ) {
int a = (rand() % 10) + 1; // 1 <= a <= 10
int b = (rand() % 20) - 9; // -9 <= b <= 10
printf( "%d %c %d = %d\n", a, "+-"[b<0], abs( b ), a+b );
}
return 0;
}
1 + 3 = 4
1 - 6 = -5
4 + 10 = 14
8 + 2 = 10
10 + 0 = 10
4 + 4 = 8
8 + 10 = 18
8 + 9 = 17
8 - 2 = 6
8 - 4 = 4
2 + 1 = 3
8 - 5 = 3
2 - 6 = -4
4 + 9 = 13
6 + 6 = 12
5 + 0 = 5
3 + 4 = 7
1 + 0 = 1
9 - 5 = 4
8 + 8 = 16
The keen eyed reader will notice that even "10 + 0" is a reasonable problem. Zero is the identity operator(?) for addition (like 1 being the identity operator(?) for multiplication.)
You're free to adjust the ranges of the terms to suit your questions.
You can use rand() function, which is defined in stdlib. And if you want your program to give you different random numbers every time you run it, you need to put srand(time(NULL)) at the beginning, but for the time function, you need to include time.h library
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;
}
In this code what is s[i]-'0' doing? Can anyone please explain the detailed working of this function?
Have a look at the table in the link below-
http://www.asciitable.com/
The table is called ASCII Table and it is one of the character-encoding schemes used to represent characters in the binary world.
You can see the decimal numbers 0-9 are represented by numbers 48-57 in the ASCII table. All digits(0-9) are stored as characters.
If your computer stores 48 for decimal number 0, 49 for decimal number 1, 50 for decimal number 2 and so-on.
Then, to convert a ASCII number into decimal number, you just need to subtract 48 from ASCII number.
For example,
48 - 48 => 0
49 - 48 => 1
50 - 48 => 2
.. and so-on
'0' also represents 48. It is a character form of number 48. That's why, the equation n = 10 * n + (s[i] - '0'); has '0'.
In this code what is s[i]-'0' doing?
In C, each character like '0', 'A', '+', ' ' is assigned a numeric value or code. C requires that the codes for '0', '1', '2' ... '9' are sequential but does not specify their values.
When code performs the below test, it knows that s[i] has a value within codes '0' and '9'. Since these codes are sequential, the only values s[i] could have are '0', '1', '2' ... '9'.
(s[i]>='0') && (s[i]<='9')
By subtracting '0' from s[i], code obtains the difference:
`0`-'0' --> 0
`1`-'0' --> 1
`2`-'0' --> 2
...
`9`-'0' --> 9
Code has successfully translated the character code for an numeric character into a corresponding integer value.
In your function, s is a sequence of ASCII encoded characters: a string. Actually, the encoding does not matter as long as it has the characters 0 through 9 as a sequence. Let's say it has the value "123ABC", for this explanation.
n is the output number. At the start of the function it is initialized to zero.
In the first iteration of the loop we have
i=0
s[i] = '1' (which is encoded as 49, in ASCII)
n = 0
so the math is like this:
n = n * 10 + (s[i] - '0')
n = 0 * 10 + ('1' - '0')
n = '1' - '0'
And converting the character syntax to the ASCII encoding gives this:
n = 49 - 48
n = 1
In the next iteration we have:
i = 1
s[i] = '2' (ASCII 50)
n = 1
n = n * 10 + (s[i] - '0')
n = 1 * 10 + ('2' - '0')
n = 10 + ('2' - '0')
n = 10 + (50 - 48)
n = 10 + 2
n = 12
And, in the third iteration:
i = 2
s[i] = '3' (ASCII 51)
n = 12
n = n * 10 + (s[i] - '0')
n = 12 * 10 + ('3' - '0')
n = 120 + ('3' - '0')
n = 120 + (51 - 48)
n = 120 + 3
n = 123
And, in the final iteration s[i] = 'A' which is not in the range specified by the if statement, so the loop exits.
As you can see it has correctly converted the string "123" to the number 123.
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!
I have one character array of 8 bytes containing integer values. I need to copy the 1 byte to one integer variable, next 4 bytes to different integer variable, next 3 bytes to another integer variable.
I have used "memcpy" but the results are not proper.
My try:
unsigned char bytes[8];
int Data1 = 32769;
int Data2 = 65535;
int logic1 = 0;
int logic2 = 0;
int logic3 = 0;
memcpy(&bytes[0], &Data1, sizeof(Data1));
memcpy(&bytes[4], &Data2, sizeof(Data2));
//Value of bytes[] array after this operation is
//bytes[0] = 1
//bytes[1] = 128
//bytes[2] = 0
//bytes[3] = 0
//bytes[4] = 255
//bytes[5] = 255
//bytes[6] = 0
//bytes[7] = 0
memcpy(&logic1,&bytes,1);
memcpy(&logic2,&bytes + 1,4);
memcpy(&logic3,&bytes + 5,1);
My output should be :
logic1 = bytes[0]
logic2 = bytes[1] to bytes[4]
logic3 = bytes[5] to bytes[7]
I think you meant
memcpy( &logic1, &bytes[0], 1 );
memcpy( &logic2, &bytes[1], 4 );
memcpy( &logic3, &bytes[5], 3 );
Note that &bytes is a pointer to the whole array, so &bytes + 1 points beyond the end of the array, and &bytes + 5 is way beyond the end of the array. Hence you get undefined behavior, and unexplainable results.
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.