Sie sind auf Seite 1von 11

Assignment Set 1

1. Define the Function prototype? Write a C program to solve the Tower of Hanoi Problem.
Ans. In modern C programming, it is considered good practice to use prototype declarations for all functions that you call. As we mentioned, these prototype help to ensure that the compiler can generate correct code for calling the functions, as well as allowing the compiler to catch the certain mistakes you might make. In general terms, a function prototype can be written as Data-type name(type1, type2,.....type n) Examples: int sample(int, int) or int sample (int a, int b); floal fun (int,float) or float fun(int a, float b); void demo(void) ; Here void indicates function neither return any value to the caller nor it has any arguments. If you write the function definition after the definition of its caller function, then the prototype is required in the caller, but the prototype is optional if you write the definition of the function before the definition of the caller function. But it is good programming practice to include the function prototype wherever it is defined. #include <stdio.h> We have been including at the top of all our programs. Stdio.h is conceptually a file full of external declarations and other information pertaining to the Standard I/O library functions, including printf . The #include directive arranges all of the declaration within stdio.h that are considered by the compiler , rather as if we had typed them all in ourselves. Somewhere within these declarations is an external function prototype declaration for printf, which satisfies the rule that these should be a prototype for each function we call. (for other standard library functions we call, there will be other header files to include.)Finally one more thing about external function prototype declarations: we have said the distinction between external declarations and defining instances of normal variables hinges on the presence or absence of the keyword extern . The situation is a little bit different for functions. The defining instance of a function is the function, including its body (that is, the brace-enclosed list of a function, even

without the keyword extern, looks nothing like a function declaration. Therefore , the keyword extern is optional in function prototype declarations. If we wish, we can write Int multbyfour(int); And this is just like an external function prototype declaration as Extern int multbyfour(int); Recursive Program to solve Tower of Hanoi Problem #include<stdio.h> Main() { Void Recursive Hanoi (int, char, char, char); Int n; Printf(Towers of Hanoi\n\n); Printf(how many disks?); Scanf(%d, &n); Printf (\n); Recursive Hanoi(n, L, R, C); } Void Recursive Hanoi(int n, char from, char to, char temp) { /*Transfer n disks from one pole to another */ Recursive Hanoi (n-1, from, temp, to); /*move nth disk from origin to destination */ Printf(Move disk %d from %c to %c\n, n, from, to); /* move n-1 disks from temporary to destination */ Recursive Hanoi(n-1, temp, to, from); } Return; }

2. With the help of suitable examples, explain type conversions using various DATA types Ans: In computer science, type conversion or typecasting refers to changing an entity of one DATA type into another. This is done to take advantage of certain features of type hierarchies. For instance, values from a more limitedset, suchas integers, can be stored in a more compact format and later converted to a different format enabling operations not previouslypossible, such as division with several decimal places' worthof accuracy. In object-oriented programminglanguages, type conversion allows programs to treat objects of one type as one of their ancestor types to simplify interacting with them. There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. The most common form of explicit type conversion is known as casting. Explicit type conversion can also be achieved with separately definedconversion routines such as an overloaded object constructor. Each programminglanguage has its own rules on how types can be converted. In general, both objects and fundamental DATA types can be converted.

IMPLICIT TYPE CONVERSION

Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler. Some languages allow, or even require, compilers to provide coercion. In a mixed-type expression, DATA of one or more subtypes can be converted to a supertype as needed at runtime so that the program will run correctly. For example, the following is legal Clanguage code:

double d; long l; int i; if (d > i) d= i;

if (i > l) l= i; if (d ==l) d*= 2;

Although d,landibelong to different DATA types, they will be automatically converted to equal DATA types each time a comparison or assignment is executed. This behavior should be used withcaution, as unintendedconsequences can arise. DATA can be lost when floating-point representations are converted to integral representations as the fractional components of the floating-point values will be truncated (rounded towards zero). Conversely, converting from an integral representation to a floating-point one can also lose precision, since the floating-point type may be unable to represent the integer exactly(for example, float might be an IEEE 754 single precision type, which cannot represent the integer 16777217 exactly, while a 32-bit integer type can). This can lead to situations such as storing the same integer value into two avalchandas of type integer and type float which return false if compared for equality.

EXPLICIT TYPE CONVERSION

Explicit type conversion is a type conversion which is explicitly definedwithin a program (instead of being done by a compiler for implicit type conversion). USIN G CASTING double da = 5.5; double db = 5.5; int result = static_cast<int>(da) + static_cast<int>(db); //Result would be equalto 10 instead of 11. There are several kinds of explicit conversion. CHECKE D Before the conversion is performed, a runtime checkis done to see if the destination type can hold the source value. If not, an error condition is raised.

UNC HECKED No check is performed. If the destination type cannot hold the source value, the result is undefined.

BIT PATTER N The raw bit representation of the source is copiedverbatim, andit is re-interpreted accordingto the destination type. This can also be achieved via aliasing. In object-oriented programminglanguages, objects can also be downcasted : a reference of a base class is castedto one of its derived classes.

USIN G OVERLOADED OBJECT CONSTR UCTOR

class Myclass { public: double myD; Myclass(double d) : myD(d) {}; }; int main(int argc, char *argv[]) { Myclass obj = 5.2; // here is the type conversion return 0; } 3. Using input and output functions in C, write a program to accept a string of characters Ans: There is an example which will help to understand about Initializing Strings, Reading Strings from the terminal, writing strings to screen, Arithmetic operations on characters. A string is a sequence of characters. Any sequence or set of characters defined within double quotation symbols is a constant string. In c it is required to do some meaningful operations on strings they are: Reading string displaying strings Combining or concatenating strings Copying one string to another. Comparing string &checking whether they are equal Extraction of a portion of a string

Strings are stored in memory as ASCII codes of characters that make up the stringappended with \0 (ASCII value of null). Normally each character is storedin one byte, successive characters are stored in successive bytes. Character m y a g e i s ASCII Code 77 121 32 97 103 10 32 105 115 Character 2 ( T W O ) \0 ASCII Code 32 50 32 40 116 119 41 0 0 The last character is the null character having ASCII value zero /* Example program to use string functions*/ #include <stdio.h> #include <string.h> void main() { char s1[20],s2[20],s3[20]; int x,l1,l2,l3; printf(Enter the strings); scanf(%s%s,s1,s2); x=strcmp(s1,s2); if(x!=0) {printf(\nStrings are not equal\n); strcat(s1,s2); } else printf(\nStrings are equal); strcpy(s3,s1); 11=strlen(s1); 12=strlen(s2); 13=strlen(s3); printf(\ns1=%s\t length=%d characters\n,s1,11); printf(\ns2=%s\t length=%d characters\n,s2,12); printf(\ns3=%s\t length=%d characters\n,s3,13); }

4. Explain the following operators with an example for each:

a. Conditional Operators b. Bitwise Operators c. gets() and puts() function with a programming example for each. Ans: a. Conditional Operators The Conditional operator is also called as Ternary Operator . The conditional operator consists of 2 symbols the question mark (?) and the colon (:) The syntax for a ternary operator is as follows exp1 ? exp2 : exp3 The ternary operator works as follows exp1 is evaluated first. If the expression is true then exp2 is evaluated &its value becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the expression. Note that only one of the expression is evaluated. For example a = 10; b = 15; x = (a > b) ?a : b Here x will be assigned to the value of b. The condition follows that the expression is false therefore b is assigned to x. b. Bitwise Operators C has a distinction of supporting special operators known as bitwise operators for manipulation DATA at bit level. A bitwise operator operates on each bit of DATA. Those operators are used for testing, complementing or shifting bits to the right on left. Bitwise operators may not be applied to a float or double. Operator Meaning

&

Bitwise AND

Bitwise OR

Bitwise Exclusive

<<

Shift left

>>

Shift right

For example, The & operator performs a bitwise AND on two integers. Each bit in the result is 1 only if both corresponding bits in the two input operands are 1. x= y & z; assigns x the result of "y AND z". This is different from logical "and" operator, "&&", which takes two logical operands as input and produces a result of "true" or "false". If, y = 0x56 z = 0x32 Then, x will be 0x12, because (in binary) 01010110 &00110010 -------------------00010010 c. gets() and puts() function gets()

reads a complete line of text into a string until a end-of-file (EOF) is encountered. It is theresponsibility of the programmer to ensure that the string which receives the input text read by getsis large enough.

puts()

displays a string onto the standard output or terminal and follows it with a newlinecharacter. #include <stdio.h> main ()

{ char answer[256]; puts("Enter your name"); while((gets(answer))!= NULL) printf("Hello " %s, answer); }

6. Write a program in C to explain pointer arithmetic.


Ans: In c a pointer is aavalchanda that points to or references a memory location in which DATA is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer avalchanda points to a memory location we can access and change the contents of this memory location via the pointer A pointer is aavalchanda that contains the memory location of another avalchanda. The syntax is as shown below. You start by specifying the type of DATA stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer avalchanda. Finally you give the name of the avalchanda. type * avalchanda name Example: int *ptr; float *string; Address operator: Once we declare a pointer avalchanda we must point it to something we can do this by assigning to the pointer the address of the avalchanda you want to point as in the following example: ptr=&num; This places the address where num is stores into the avalchandaptr. If num is stored in memory 21260 address then the avalchandaptr has the value 21260.

/* Aprogram to illustrate pointer declaration*/ main() { int *ptr; int sum; sum=45; ptr=. printf (\n Sum is %d\n, sum); printf (\n The sum pointer is %d, ptr);

} 7. Write a program demonstrating the usage of pointers with one dimensional and two dimensional arrays. Ans: Arrays and pointers are very intimately connected. Most important point to remember is that array name without the brackets is the base address of that array or address of its first (0th) element. This address can be stored in the pointer. More fading this subtle difference is that pointer can also be used with brackets to index array as if it was an array name. In general access provided by the pointer is faster if pointer arithmetic(which by the way is almost completely different from normal arithmetic)is used for acess. Formula for accessing Ithelement in a 1-D array is *(pointer name + I) Formula for accessing Ith row, Jth Column element in a 2-D array is *(pointer name + I * Number_Of_Elements_Per_Row + J) And so on, formula become more complicated with increase in dimension of the array. Code below shows how to access a 1-D array using pointers. #include <stdio.h> int main () { int value [1000],i; // Declaring an Array int *pointer; pointer = value; for (i = 0; i<1000; i++) { *(pointer +i) = i; // Loading the Array } for (i = 0; i<1000; i++) { printf ("\n%d",*(pointer + i); // Displaying the Array } return 0; }

An array is actually very much like pointer. We can declare the arrays first element as a[0] or asint *a because a[0] is an address and *a is also an address the form of declaration is equivalent. The difference is pointer is aavalchanda and can appear on the left of the assignment operator that islvalue. The array name is constant and cannot appear as the left side of assignment operator.

An example program which shows how to access 2-D array using pointer :

#include <stdio.h> #include <stdlib.h> main() { l o n g m a t [ 5 ] [ 5 ] , * * p t r ; mat[0][0] = 3;ptr = (long **)mat; printf(" mat %p \n", mat); printf(" ptr %p \n", ptr); printf(" mat[0][0] %d \n", mat[0][0]); printf(" &mat[0][0] %p \n", &mat[0][0]); printf(" &ptr[0][0] %p \n", &ptr[0][0]); return; }

The output is:mat 7FDF6310ptr 7FDF6310mat[0][0] 3&mat[0][0] 7FDF6310&ptr[0][0] 3

Das könnte Ihnen auch gefallen