#include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> struct object_code { int locctr; char add[10]; }obcode[300]; void main() { char input[100][16],output[100][16],binary[20],address[20],stloc[10]; int len,bitmask,loc,tlen=0,tloc,textloc,i=0,location,j,k,count=0,start,n,num=0,inc=0; FILE *fp1,*fp2; clrscr(); fp1=fopen("linput.dat","r"); fp2=fopen("reloadout.dat","w"); printf("Enter the location where the program has to be loaded:"); scanf("%s",stloc); start=atoi(stloc); location=start; tloc=start; fscanf(fp1,"%s",input[i]); while(strcmp(input[i],"T")!=0) { strcpy(output[i],input[i]); i++; fscanf(fp1,"%s",input[i]); strcpy(output[i],input[i]); } itoa(start,output[2],10); while(strcmp(input[i],"E")!=0) { strcpy(output[i],input[i]); if(strcmp(input[i],"T")==0) { for(j=0;j<3;j++) { i++; fscanf(fp1,"%s",input[i]); strcpy(output[i],input[i]); } bitmask=atoi(output[i]); itoa(bitmask,binary,2); strcpy(output[i],NULL); textloc=atoi(output[i-2]); textloc=textloc+start; itoa(textloc,output[i-2],10); for(n=0;n<(textloc-(tloc+tlen));n++) { strcpy(obcode[inc].add,"xx"); obcode[inc++].locctr=location++; } tlen=atoi(output[i-1]); tloc=textloc; k=0; } else { if(binary[k]==1) { num=0; len=strlen(output[i]); strcpy(address,NULL); for(j=2;j<len;j++) { address[num]=output[i][j]; output[i][j]='\0'; num++; } loc=atoi(address); loc=loc+start; itoa(loc,address,10); strcat(output[i],address); } k++; len=strlen(output[i]); num=0; for(n=0;n<len;n++) { obcode[inc].add[num++]=output[i][n]; if(num>1) { obcode[inc++].locctr=location++; num=0; } } } i++; fscanf(fp1,"%s",input[i]); } strcpy(output[i],input[i]); i++; fscanf(fp1,"%s",input[i]); loc=atoi(input[i]); loc=loc+start; strcpy(output[i],itoa(loc,address,10)); count=0; i=0; n=0; fprintf(fp2,"%d\t",obcode[n].locctr); for(n=0;n<inc;n++) { fprintf(fp2,"%s",obcode[n].add); i++; if(i>3) { fprintf(fp2,"\t"); i=0; count++; } if(count>3) { fprintf(fp2,"\n%d\t",obcode[n+1].locctr); count=0; } } getch(); }
A conversion function is a function that converts data from one type to another. A conversion function has one argument of the type being converted from while the return type is the type being converted to. If required, additional arguments may be used to refine the conversion. Conversion functions are required to provide conversions between types that cannot be handled by a built-in cast.char* itoa(int value, char* str, int base);This non-standard function is an example of a conversion function, converting a built-in integer type to a null-terminated ASCII string representing the integer's value in a given base. The return value is simply the string pointed to by the strargument.
A conversion function is a function that converts data from one type to another. A conversion function has one argument of the type being converted from while the return type is the type being converted to. If required, additional arguments may be used to refine the conversion. Conversion functions are required to provide conversions between types that cannot be handled by a built-in cast.char* itoa(int value, char* str, int base);This non-standard function is an example of a conversion function, converting a built-in integer type to a null-terminated ASCII string representing the integer's value in a given base. The return value is simply the string pointed to by the strargument.
Decimal to Binary Using a StackThere is no need to program a computer to convert from decimal to binary because all programming languages do this by default; they are binary computers after all. That is, if we want to store the decimal value 42 in computer memory, we simply assign the literal constant 42 to some variable or constant. But the value that is actually assigned is really the binary value 00101010. Moreover, even if we were to assign the hexadecimal value 0x2A or even the octal value 052, the value will still be automatically converted to the binary value 00101010. These are all different representations of the decimal value forty-two, but 00101010 is the only way that value can be physically stored in computer memory. Of course we may choose to store the value as a string, "42", however it is no longer a numeric value at that point, it is a character array. However, most languages will provide some library function that can convert the string representation of a numeric value into their actual numeric representation. In C, for instance, we would simply use the atoi() function. Nevertheless, it is not something we need to specifically cater for; the function does all the hard work for us, converting the string, "42", into the equivalent binary value 00101010. However, although decimal integer values are always stored in native binary code, presenting that binary value to the user isn't as straightforward. All languages will automatically convert the binary value back to decimal for display purposes, but what it's actually doing behind the scenes is converting the binary value 00101010 into the string "42" and then printing the string. In other words, it is the reverse of the atoi() function, essentially the equivalent of the itoa() function. Given that we don't need to program either of these conversions, it's easy to forget that these conversions are taking place. Given that humans work predominantly in decimal it is only natural that these conversions be done automatically for us, but it is a high-level concept; it is an abstraction. While there's nothing wrong in thinking at a high-level, it's important to be aware of the low-level operations that are actually taking place, because the more we know about what's really going on behind the scenes, the more easily we can exploit them. The high-level concept of converting from decimal to binary is only one such example where we can exploit the fact that the conversion to binary is already done for us behind the scenes. All we really need to do is present the result to the user. To achieve this we need to convert the binary value to a string, in much the same way as the itoa() function converts a binary value into a decimal string, except we convert to a binary string. A stack makes this incredibly simple. We simply examine the low-order bit and push a '1' character onto the stack if the bit is set, otherwise we push a '0'. We then shift all the bits one bit to the right and repeat the process. We continue in this manner until the binary value is zero. If the number of elements on the stack is not an exact multiple of 8, we can (optionally) push additional '0' characters onto the stack for padding. Finally, we print the top-most element on the stack and then pop it off the stack, repeating until the stack is empty. Thus if we use the value 00101010 once more, we examine the low-order bit. It is not set so we push a '0' onto the (empty) stack. We then shift the bits one place to the right, giving us 00010101. The low-order bit is now set so we push a '1'. We repeat the process, pushing a '0', then a '1', another '0' and another '1'. At this stage, the binary value is 00000000 so we are done. The stack has only six elements so we (optionally) push another two '0' characters onto the stack for padding. Now we begin popping the stack, printing the top-most element before each pop. When we are done, we will have output the character sequence "00101010". The following code in C++ shows how this might be implemented as a function. The return value is a string containing the binary representation of the function argument, dec. std::string dec2bin(int dec) { std::stack s {}; initialise an empty stack of characters while (dec) { if (dec & 0x1) // if the low-order bit is set... s.push ('1'); else s.push ('0'); dec >>= 0x1; // shift-right } while (s.size() % 8) s.push('0'); // pad the stack to the nearest 8-bit boundary std::string bin {}; // initialise return value (empty string)while (!s.empty()) {bin.append (s.top());s.pop();}return bin;} Example usage:int main() {std::cout > i;std::cout
/*Program to find Armstrong number between 1 to N*/ int main() { int n = 0, remainder, sum = 0, i = 0, noDigits = 0, isArm = 0; char ch[60] = {0}; printf("Find the Arm Strong Numbers between 1 to N"); scanf("%d", &n); for(i = 1; i<n; i++) { isArm = i; itoa(isArm, ch, 10); noDigits = strlen(ch); while(isArm) { remainder = isArm%10; isArm=isArm/10; sum= sum+pow(remainder, noDigits); } if(sum == i) printf("\nArm Strong Nos are %d\n", i); sum = noDigits = 0; } }
In C, an integer and a character are the same thing, just represented differently. For example: int x = 65; printf("x = (int) %d, (char) %c\n", x, x) should print "x = (int) 65, (char) A" You can also use the atoi (ascii to integer) and itoa (integer to ascii) functions.
#include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> struct object_code { int locctr; char add[10]; }obcode[300]; void main() { char input[100][16],output[100][16],binary[20],address[20],stloc[10]; int len,bitmask,loc,tlen=0,tloc,textloc,i=0,location,j,k,count=0,start,n,num=0,inc=0; FILE *fp1,*fp2; clrscr(); fp1=fopen("linput.dat","r"); fp2=fopen("reloadout.dat","w"); printf("Enter the location where the program has to be loaded:"); scanf("%s",stloc); start=atoi(stloc); location=start; tloc=start; fscanf(fp1,"%s",input[i]); while(strcmp(input[i],"T")!=0) { strcpy(output[i],input[i]); i++; fscanf(fp1,"%s",input[i]); strcpy(output[i],input[i]); } itoa(start,output[2],10); while(strcmp(input[i],"E")!=0) { strcpy(output[i],input[i]); if(strcmp(input[i],"T")==0) { for(j=0;j<3;j++) { i++; fscanf(fp1,"%s",input[i]); strcpy(output[i],input[i]); } bitmask=atoi(output[i]); itoa(bitmask,binary,2); strcpy(output[i],NULL); textloc=atoi(output[i-2]); textloc=textloc+start; itoa(textloc,output[i-2],10); for(n=0;n<(textloc-(tloc+tlen));n++) { strcpy(obcode[inc].add,"xx"); obcode[inc++].locctr=location++; } tlen=atoi(output[i-1]); tloc=textloc; k=0; } else { if(binary[k]==1) { num=0; len=strlen(output[i]); strcpy(address,NULL); for(j=2;j<len;j++) { address[num]=output[i][j]; output[i][j]='\0'; num++; } loc=atoi(address); loc=loc+start; itoa(loc,address,10); strcat(output[i],address); } k++; len=strlen(output[i]); num=0; for(n=0;n<len;n++) { obcode[inc].add[num++]=output[i][n]; if(num>1) { obcode[inc++].locctr=location++; num=0; } } } i++; fscanf(fp1,"%s",input[i]); } strcpy(output[i],input[i]); i++; fscanf(fp1,"%s",input[i]); loc=atoi(input[i]); loc=loc+start; strcpy(output[i],itoa(loc,address,10)); count=0; i=0; n=0; fprintf(fp2,"%d\t",obcode[n].locctr); for(n=0;n<inc;n++) { fprintf(fp2,"%s",obcode[n].add); i++; if(i>3) { fprintf(fp2,"\t"); i=0; count++; } if(count>3) { fprintf(fp2,"\n%d\t",obcode[n+1].locctr); count=0; } } getch(); }
A conversion function is a function that converts data from one type to another. A conversion function has one argument of the type being converted from while the return type is the type being converted to. If required, additional arguments may be used to refine the conversion. Conversion functions are required to provide conversions between types that cannot be handled by a built-in cast.char* itoa(int value, char* str, int base);This non-standard function is an example of a conversion function, converting a built-in integer type to a null-terminated ASCII string representing the integer's value in a given base. The return value is simply the string pointed to by the strargument.
A conversion function is a function that converts data from one type to another. A conversion function has one argument of the type being converted from while the return type is the type being converted to. If required, additional arguments may be used to refine the conversion. Conversion functions are required to provide conversions between types that cannot be handled by a built-in cast.char* itoa(int value, char* str, int base);This non-standard function is an example of a conversion function, converting a built-in integer type to a null-terminated ASCII string representing the integer's value in a given base. The return value is simply the string pointed to by the strargument.
When a significant number of values must be tested to perform an operation, an array is more efficient then "if else" or "switch case" statements. Juge by the following example in C: const char* ConverteIntegerToCStr( unsigned int number, char cstr[] ) { // predefined array with the first 10000 number string representation // Note: the ellipsis is not part of the code static const Array[10000] = { "0", "1", "2", ..., "9998", "9999" }; if (number < 10000) memcpy( cstr, Array[number], strlen( Array[number] ) ); // very fast else itoa( number, cstr ); // standard C function that is much slower return cstr; }
1. Define a structure? A. A structure is a set of variables positioned under one name, offering a suitable means of relevant information together. Declaration of structure creates a template which can be used to produce structure objects that are called as its instances. The variables which form the structure are called as members, also referred as fields or elements. 2. Define a pointer? A. A pointer is nothing but a reference to some memory location. As a computer has billions or may be even trillions of cells, every cell can be filled with some data. With the help of pointers, one can know and access the value of its memory cell and its location. 3. What are the advantages of a pointer? A. Dynamic Memory Allocation, Passing structures and array to functions, creating data structures like linked lists, trees and so on, and passing addresses to functions. 4. Define static variable? A. A special variable which is stored in the data segment not like the default auto variable that is stored in stack, is called static variable. It can be initialized through using keyword static before variable name. 5. How are structure passing and returning implemented? A. When you pass structures as arguments to functions, the whole structure is usually pushed on the stack, through as several words as are needed. To avoid this overhead, programmers usually opt to use pointers to structures instead. Some compilers simply pass a pointer to the structure, even though they have to produce a local copy to save pass-by-value semantics. Structures are usually returned from functions in a position pointed to by an additional, compiler-supplied hidden argument to the function. Few older compilers used to use unique, static locations for structure returns, though this made structure-valued functions non-reentrant that ANSI C disapproves. 6. Why can't we compare structures? A. We do not have one or fine way for a compiler to apply structure evaluation that is constant with lower level flavor of C. A plain byte-by-bye comparison could be found on random bits available in unused 'holes' in the structure; such filling is used to maintain the arrangement of following fields accurate. A field-by-field assessment may require improper amounts of recurring code for larger structures. 7. Why doesn't struct x { … };x thestruct; work? A. C is not similar to C++. Typedef names are not automatically produced for structure tags 8. Why doesn't this code: a[i] = i++; work? A. The subexpression i++ creates a side effect. It changes i's value which directs to undefined behavior as i as well is referenced somewhere else in the same expression 9. Can we initialize unions? A. ANSI C permits an initializer for the foremost member of a union. We do not have any standard method of initializing other members (there is no way even under a pre-ANSI compiler to initialize a unionl) 10. Can main () be called recursively? A. Yes, any function that has main() could be called recurrently. 11. Are the variables argc and argv are always local to main? A. Yes, argc and argv are local to main 12. What would be the similar pointer expression for referring the equivalent element as a[p][q][r][s]? A. *( * ( * ( * (a+p) + q ) + r ) + s) 13. Are the expressions *ptr ++ and ++ *ptr same? A. No. *ptr++ increments pointer, not the value pointed by it. Where as ++*ptr increments the value being pointed to by ptr. 14. What are the benefits of using array of pointers to string instead of an array of strings? A. (i) Effective usage of memory (ii) Simpler to swap the strings through moving their pointers when sorting 15. Discuss on pointer arithmetic? A. (i) Assigning pointers to the similar kind of pointers (ii) Subtracting or adding a pointer and an integer (iii) comparing and subtracting two pointers (iv) Decrementing or incrementing the pointer that are pointing to the elements of an array while a pointer to an integer is added by one, the address is added by two. The Compiler does this automatically. Assiging value 0 to the pointer variable and comparing it with the pointer. Pointer consisting 0 points to nothing at all 16. What is the invalid pointer arithmetic? A. (i) Adding, dividing and multiplying two pointers (ii) Adding double or float to pointer (iii) Masking or shifting pointer (iv) Assigning a pointer of one type to another type of pointer. 17. Is the allocated space within a function automatically deallocated when the function returns? A. None of the pointers are similar to that of what they actually point to. Local variables like local pointer variables in a function are automatically deallocated if function returns. However, coming to a local pointer variable, deallocation is nothing but the pointer being deallocated and not blocking of memory allocated to it. Memory that is allocated dynamically always continues till the program terminates or allocation is freed. 18. What are the pointer declarations used in C? A. (i) Pointers to an array (ii) Array of pointers (iii) Pointer to a data type (iv) Pointer to a pointer (v) Function returning a pointer 19. Can we use any name in place of argv and argc as command line arguments? A. Yes. We can certainly use any user defined name instead of argc and argv. 20. Difference between an array of pointers and a pointer to an array? A. Array of pointers (i) Declaration - data type *array_name[size] (ii) Size indicates size of the row (iii) The space for columns may be dynamically allocated Pointer of Arrays (i) Declaration - data_type (*array_name)[size] (ii) Size indicates size of the column 21. Difference between an array name and a pointer variable? A. A pointer variable is a variable while an array name is not a variable but is a fixed address. Unlike a pointer variable, array name cannot be initialized. An array name being a constant value, - and ++ operators can not be applied to it. 22. What is the purpose of rewind()? A. The rewind() function is used to get the file pointer to the starting of the file. Rewind (fp); Fp is a file pointer. And we can get similar effect through feek(fp,0,0); 23. What is the purpose of ftell? A. The ftell() function is used to get the current file referred by the file pointer. ftell(fp); returns a long integer value referring the current location of the file pointed by the file pointer fp. If any error occurs, it will return -1. 24. What is a random access file? A. A file can be accessed at random through function fseek(), fseek(fp,position,origin); file pointer number file pointer fp positions number of bytes offset origin from 0, 1 or 2 denoting the starting, current or end position of the file respectively. 25. How is fopen()used? A. The fopen() function return a file pointer. So a file pointer is declared and is assigned as FILE *fp; fp=fopen(filename,mode); 26. How is a file closed? A. A file is closed using fclose() function 27. What is a file pointer? A. The pointer to a FILE data type is known as a file pointer or a stream pointer. This pointer points to the block of information of the stream/file that had just been accessed. 28. What is a stream? A. A stream is nothing but source of destination of data or simply data that is associated with a hard disk or other input/output device. The source stream that offers data to a program is known as input stream and the source stream that receives the result from the program is known as output stream. 29. What is meant by file opening? A. The process of connecting a program to a file is known as file opening. It needs I/O stream creation in advance to writing or reading the data. 30. What exactly is a file? A. A file is an area of storage in auxiliary storage devices or in hard disks. It includes information in bytes. 31. What are the types of files? A. Files are of two types 1-high level files (stream oriented files) - These are accessed through library functions 2-low level files (system oriented files) - These are accessed through system calls 32. What is the difference between the functions memmove() and memcpy()? A. The arguments of memmove() can overlie in memory, while the arguments of memcpy() cannot 33. What do the functions atoi(), itoa() and gcvt() do? A. atoi() is a macro that converts integer to character. itoa() It converts an integer to string gcvt() It converts a floating point number to string 34. How would you use the functions randomize() and random()? A. Randomize() initiates random number generation with a random value. Random() generates random number between 0 and n-1 35. What are the two forms of #include directive? A. 1. #include"filename" 2. #include 36. What are the facilities provided by preprocessor? A. File inclusion, substitution facility and conditional compilation 37. What is a preprocessor? What are the advantages of preprocessor? A. Preprocessor practices the source code program before it is sent through the compiler. (i) It includes the readability of a program (ii) It helps in easier modification (iii) It facilitates writing convenient programs (iv) It helps in easier debugging (v) It helps in testing a portion of program (vi) It enables implementing comprehensive program 38. Define bit fields? Point out their uses in Structure declaration? A. A bit field is a group of adjoining bits in a one execution based on storage unit which we call as a "word". Usually, the field definition's syntax and access is based on a structure. Struct { unsigned int k :1; unsigned int l :1; unsigned int m :1; }flags; The number that is preceeding the colon indicates the field width. And flag is a variable that includes 3 bit fields. 39. What is the maximum combined length of command line arguments including the space between adjacent arguments? A. It depends on the operating system 40. Compose a program to swap two variables without the help of third variable. A. a^=b; b^=a; a^=b; In the above program, the numbers are converted into binary numbers and then xor operator is executed. 41. What is pre-increment and post-increment? A. ++num (pre-increment) increases value of num before it is used in the expression, where num++ (post-increment) increases the num after its value is used. 42. Difference between logical vs syntax errors? A. Logical error: It occurs by a wrong algorithm or a mistyped statement in such a way that it does not violate the syntax, and these are difficult to find. Syntax error: It involves syntax validation, and compiler prints diagnostic message. Ex: a=b 43. What are C identifiers? A. C identifiers are the names given to different programming elements like arrays, functions and variables. It is usually a combination of a letter, a digit and an underscore. It should start with a letter, and backspace is not allowed. 44. What are C tokens? A. There are 6 classes of C tokens - keywords, constants, identifier, operators, string literals and other separators. 45. What do the 'c' and 'v' in argc and argv stand for? A. The c in argument count, argc stands for the number of the command line argument that the program is invoked with. And v in argument vector, argv is a pointer to an array of the character string that contains the argument. 46. Difference between array and pointer? A. Array: (i) Arrays allocate space, automatically (ii) They can not be reassigned (iii) They can not be resized (iv) sizeof (arrayname) returns the number of bytes occupied by the array. Pointer: (i) Assigned explicitly to point an allocated space. (ii) It can be reassigned (iii) It can be resized using realloc() function (iv) sizeof (p) gives the number of bytes used to store the pointer variable p. 47. Compose a program using Command Line Arguments? A. #include void main(int argc,char *argv[]) { int i; clrscr(); for(i=0;i printf("\n%d",argv[i]); } 48. Write a program which employs Recursion? A. int fact(int n) { return n > 1 ? n * fact(n - 1) : 1; } 49. How can we read/write Structures from/to data files? A. To compose a structure fwrite() can be used as Fwrite(&e, sizeof(e),1,fp); Here, e is a structure variable. A consequent fread() invocation will be able to read the structure back from file. Calling function fwrite() will write out sizeof(e) byte from the address & e. Data files that are written as memory images with function fwrite(), but will not be portable, especially if they include floating point fields or pointers. It is because structures' memory layout is compiler and machine dependent. Hence, structures written as memory are not need to be read back by programs running on other machine, also this is an important factor if the data files that you are writing will ever be exchanged between machines. 50. Can a Structure contain a Pointer to itself? A. Yes such structures are called self-referential structures. Other Questions What is the similarity between a Structure, Union and enumeration? How are Structure passing and returning implemented by the complier? What is the difference between an enumeration and a set of pre-processor # defines? Is it possible to have more than one main() function in a C program? Difference between formal argument and actual argument? What are built in functions? What is an argument? What is a function? What modular programming? Why is it necessary to give the size of an array in an array declaration? Is it possible to have negative index in an array? Difference between linker and linkage? What is an array of pointers? What is pointer to a pointer? What is the purpose of realloc? What is dynamic memory allocation? What is static memory allocation? How pointer variables are initialized? Are the expressions arr and &arr same for an array of integers? What is generic pointer in C? What does the error 'Null Pointer Assignment' means and what causes this error? Are pointers integer? What is a NULL Pointer? Whether it is same as an uninitialized pointer? In C, why is the void pointer useful? When would you use it? What is near pointer? What is a normalized pointer, how do we normalize a pointer? What is a huge pointer? What is a far pointer? Where do we use it? What is the difference between Strings and Arrays? What the advantages of using Unions? What is storage class? What are the different storage classes in C? Differentiate between a for loop and a while loop? What are it uses? What is recursion? Difference between strdup and strcpy? Out of fgets() and gets() which function is safe to use and why? Can we specify variable field width in a scanf() What is the use of typedef? What are register variables? What are the advantages Describe about storage allocation and scope of
#include<stdlib.h> #include<stdio.h> #include<string.h> /* returns true of the given string represents a palindrome, otherwise returns false */ bool is_palindrome (const char* str) { size_t len; char *left, *right; if (!str) return false; /* null-strings are not palindromes */ len = strlen (str); if (!len) return false; /* empty strings are not palindromes */ left = (char*) str; right = (char*) str + len - 1; while (left<right && *left==*right) { ++left; --right; } return (*left==*right); } int main (void) { int x, y, z, product, largest[4]; largest[0] = 0; char str[7]; for (x=10; x<100; ++x) { for (y=10; y<100; ++y) { for (z=10; z<100; ++z) { product=x*y*z; if (product>largest[0]) { itoa(product, str, 10); if (is_palindrome(str)) { largest[0]=product; largest[1] = x; largest[2] = y; largest[3] = z; } } } } } if (largest[0]==0) printf ("There is no palindromic integer that is the product of 3 two-digit integers\n"); else { printf ("The largest palindromic integer that is the product of 3 two-digit integers is: %d\n", largest[0]); printf ("The two-digit integers are: %d, %d and %d\n", largest[1], largest[2], largest[3]); } }
Decimal to Binary Using a StackThere is no need to program a computer to convert from decimal to binary because all programming languages do this by default; they are binary computers after all. That is, if we want to store the decimal value 42 in computer memory, we simply assign the literal constant 42 to some variable or constant. But the value that is actually assigned is really the binary value 00101010. Moreover, even if we were to assign the hexadecimal value 0x2A or even the octal value 052, the value will still be automatically converted to the binary value 00101010. These are all different representations of the decimal value forty-two, but 00101010 is the only way that value can be physically stored in computer memory. Of course we may choose to store the value as a string, "42", however it is no longer a numeric value at that point, it is a character array. However, most languages will provide some library function that can convert the string representation of a numeric value into their actual numeric representation. In C, for instance, we would simply use the atoi() function. Nevertheless, it is not something we need to specifically cater for; the function does all the hard work for us, converting the string, "42", into the equivalent binary value 00101010. However, although decimal integer values are always stored in native binary code, presenting that binary value to the user isn't as straightforward. All languages will automatically convert the binary value back to decimal for display purposes, but what it's actually doing behind the scenes is converting the binary value 00101010 into the string "42" and then printing the string. In other words, it is the reverse of the atoi() function, essentially the equivalent of the itoa() function. Given that we don't need to program either of these conversions, it's easy to forget that these conversions are taking place. Given that humans work predominantly in decimal it is only natural that these conversions be done automatically for us, but it is a high-level concept; it is an abstraction. While there's nothing wrong in thinking at a high-level, it's important to be aware of the low-level operations that are actually taking place, because the more we know about what's really going on behind the scenes, the more easily we can exploit them. The high-level concept of converting from decimal to binary is only one such example where we can exploit the fact that the conversion to binary is already done for us behind the scenes. All we really need to do is present the result to the user. To achieve this we need to convert the binary value to a string, in much the same way as the itoa() function converts a binary value into a decimal string, except we convert to a binary string. A stack makes this incredibly simple. We simply examine the low-order bit and push a '1' character onto the stack if the bit is set, otherwise we push a '0'. We then shift all the bits one bit to the right and repeat the process. We continue in this manner until the binary value is zero. If the number of elements on the stack is not an exact multiple of 8, we can (optionally) push additional '0' characters onto the stack for padding. Finally, we print the top-most element on the stack and then pop it off the stack, repeating until the stack is empty. Thus if we use the value 00101010 once more, we examine the low-order bit. It is not set so we push a '0' onto the (empty) stack. We then shift the bits one place to the right, giving us 00010101. The low-order bit is now set so we push a '1'. We repeat the process, pushing a '0', then a '1', another '0' and another '1'. At this stage, the binary value is 00000000 so we are done. The stack has only six elements so we (optionally) push another two '0' characters onto the stack for padding. Now we begin popping the stack, printing the top-most element before each pop. When we are done, we will have output the character sequence "00101010". The following code in C++ shows how this might be implemented as a function. The return value is a string containing the binary representation of the function argument, dec. std::string dec2bin(int dec) { std::stack s {}; initialise an empty stack of characters while (dec) { if (dec & 0x1) // if the low-order bit is set... s.push ('1'); else s.push ('0'); dec >>= 0x1; // shift-right } while (s.size() % 8) s.push('0'); // pad the stack to the nearest 8-bit boundary std::string bin {}; // initialise return value (empty string)while (!s.empty()) {bin.append (s.top());s.pop();}return bin;} Example usage:int main() {std::cout > i;std::cout
/*Program to find Armstrong number between 1 to N*/ int main() { int n = 0, remainder, sum = 0, i = 0, noDigits = 0, isArm = 0; char ch[60] = {0}; printf("Find the Arm Strong Numbers between 1 to N"); scanf("%d", &n); for(i = 1; i<n; i++) { isArm = i; itoa(isArm, ch, 10); noDigits = strlen(ch); while(isArm) { remainder = isArm%10; isArm=isArm/10; sum= sum+pow(remainder, noDigits); } if(sum == i) printf("\nArm Strong Nos are %d\n", i); sum = noDigits = 0; } }
#includeint main(){int a, b, choice;printf("This program implements a calculator\n");do{printf("Enter your choice:\n1-Addition\n2-Subtraction\n3-Multiplication\n4-Division\n5-Modulus\n6-Quit\t:");scanf("%d", &choice);switch(choice){case 1: printf("Enter two numbers :");scanf("%d%d", &a, &b);printf("Sum = %d\n", a+b);break;case 2: printf("Enter two numbers :");scanf("%d%d", &a, &b);printf("Subtraction = %d\n", a-b);break;case 3: printf("Enter two numbers :");scanf("%d%d", &a, &b);printf("Product = %d\n", a*b);break;case 4: printf("Enter two numbers :");scanf("%d%d", &a, &b);printf("Quotient = %d\n", a/b);break;case 5: printf("Enter two numbers :");scanf("%d%d", &a, &b);printf("Remainder = %d\n", a%b);break;case 6: break;default: printf("Invalid choice\n");}}while(choice != 6);return 0;}