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>=@?0+A8B90?DCFEG,/.020HJI#6,8>149LKM;NEPORQKDSTE':"U@.6,V8>=W,.0LXY64ZBI#01+6[8\9]Q;^6DON6[;`_a("bc(&d (e &f(Bgah9=(%c
#J*VM "'yW m{ h
v'W4 [
> !#"$&%'()"*,+ -./01 24356*7-8:9; 0 $":$ 1 <+$$:+$ &=-9> ?<-+@A-.B9>+@=C+ -./ DE:9>F-8"HG'(3JI4"K$L2!&M=-N- F-. B DE#"$O+$PQ9>"R-8"S-8-8+$F-T:+@/ DE:9>U
5V3XW YZ63[Y'\ 3[Y ]^V3[%'5_$ 3 \
9LVLW { | }zVv[|zxLyw ~ { |wn}_ vpz
p v: ; { | [t S v{6vu,vzVv
| { [
:! {
_ vpzv 6 :>P> > O Q >P v 6 Pd>j> & SS F @: O >L i! Q>& _
=4
_@! &
>.
:dpd d
XE
:;H :>
uklu] Ki u {Q * Y k5i Kihki * ? i ? kYk o dQ5 { { ~Q x i ukl% {] Qkk | YkQS W k ] * b ukl A { E k
b iUQh ]* k
{k] E kf dQ5 k W]kk iY| S i uk p kf q ] ] Wz6 W] gW ~ e
Wl k k | W
k] k uk u W 0iQ Y ] bA {h W giQk kb QoY l i k Wz uk O . o9(uklEEEE ] Q UWkk lQYW]
ko*O h ~ W k] ]5 WUYkW]ukl E iY{k l]b k Wk 9 keh
YEQk
A W k k| W] 0Q{W fk] Y= ~Q E k
ukl kk AE iY{k We %]b A Wk W AgY{ {UW gQkSb Y fk] uk gk7
AA xf Y 0W0QkU =Y 0W
g Wff =k W k] 0l 0Wx0Quk p% {# Q0QfQp A W]#lWxp k Q % pYk Q0Q{ UQYW]Yk#UW 0lk kW g{gk gQ
Y k gQ uk W Kh
WSW {S KfQ50i Yeh k |gkgk eA {gY{ YY {xgk hWSU{k uk ! l WEk W
kl Q"
b]g]g hl kp k]# b Qg{YQ bY$ k x e U Q uk % &(k WW"' kkS) AYiQ! * {hE W #YAW b i{+ 0f kk]bk AYiQp o gkQ Yk|W]0QQQ
5gk ,- / .~ ! - 0.12A- .~! *- .1uk - 0. %k WW{3 YWQ AYW lQYi4 kg YWQl bYW i4 h6 5AWp odQ5gfWgQxWheY k xh WQ7 uk E8 Ww kb0/ 9S
]; : %'2< =k ! (k & (?oWk 0 A {> ? Sx] Q" k? Q | W]A
" k # 0W 0:@ % <
E ] 0gkA 5pk0 g b kkbW 5A/ .B& / =0=0.C W7W .g W W .E W Wuk - .8
C QuestionsNote :of the "constant integer".2. main(){char s[ ]="man";int i;for(i=0;s[ i ];i++)printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);}Answer:mmmmaaaannnnExplanation:s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the sameidea. Generally array name is the base address for that array. Here s is the baseaddress. i is the index number/displacement from the base address. So, indirecting itwith * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].3. main(){float me = 1.1;double you = 1.1;if(me==you)printf("I love U");9
9LVLW}
Answer:I hate UExplanation:For floating point numbers (float, double, long double) the valuescannot be predicted exactly. Depending on the number of bytes, the precession withof the value represented varies. Float takes 4 bytes and long double takes 10 bytes.So float stores 0.9 with less precision than long double.Rule of Thumb:Never compare or at-least be cautious when using floating pointnumbers with relational operators (== , >, <, <=, >=,!= ) .4. main(){static int var = 5;printf("%d ",var--);if(var)main();}Answer:54321Explanation:When static storage class is given, it is initialized once. The change inthe value of a static variable is retained even between the function calls. Main is alsotreated:2222223465Explanation:Initially pointer c is assigned to both p and q. In the first loop, sinceonly q is incremented and not c , the value 2 will be printed 5 times. In second loop pitself is incremented. So the values 2 3 4 6 5 will be printed.
10
9LVLW. main(){extern int i;i=20;printf("%d",i);}Answer:Linker Error : Undefined symbol '_i'Explanation:extern storage class in the following declaration,extern int i;specifies to the compiler that the memory for i is allocated in some other program andthat address will be given to the current program at the time of linking. But linkerfinds that no other variable of name i is available in any other program with memoryspace allocated for it. Hence a linker error has occurred .7. main(){int i=-1,j=-1,k=0,l=2,m;m=i++&&j++&&k++||l++;printf("%d %d %d %d %d",i,j,k,l,m);}Answer:00131Explanation :Logical operations always give a result of 1 or 0 . And also the logicalAND (&&) operator has higher priority over the logical OR (||) operator. So theexpression i++ && j++ && k++ is executed first. The result of this expression is 0(-1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because ORoperator always gives 1 except for 0 || 0 combination- for which it gives 0). So thevalue of m is 1. The values of other variables are also incremented by 1.8. main(){char *p;printf("%d %d ",sizeof(*p),sizeof(p));}Answer:12Explanation:The sizeof() operator gives the number of bytes taken by its operand. Pis a character pointer, which needs one byte for storing its value (a character). Hencesizeof(*p) gives a value of 1. Since it needs two bytes to store the address of thecharacter pointer sizeof(p) gives 2.
11
9. main(){int i=3;switch(i){default:printf("zero");case 1: printf("one");break;case 2:printf("two");break;case 3: printf("three");break;}}Answer :threeExplanation :The default case can be placed anywhere inside the loop. It is executedonly when all other cases doesn't match.10. main(){printf("%x",-1<<4);}Answer:fff0Explanation :-1 is internally represented as all 1's. When left shifted four times theleast significant 4 bits are filled with 0's.The %x format specifier specifies that theinteger value be printed as a hexadecimal value.11. main(){char string[]="Hello World";display(string);}void display(char *string){printf("%s",string);}Answer:Compiler Error : Type mismatch in redeclaration of function displayExplanation :In third line, when the function display is encountered, the compilerdoesn't know anything about the function display. It assumes the arguments and
12
9LVLW types to be integers, (which is the default type). When it sees the actualfunction display, the arguments and type contradicts with what it has assumedpreviously. Hence a compile time error occurs.12. main(){int c=- -2;printf("c=%d",c);}Answer:c=2;Explanation:Here unary minus (or negation) operator is used twice. Same mathsrules applies, ie. minus * minus= plus.Note:However you cannot give like --2. Because -- operator can only beapplied to variables as a decrement operator (eg., i--). 2 is a constant and not avariable.13. #define int charmain(){int i=65;printf("sizeof(i)=%d",sizeof(i));}Answer:sizeof(i)=1Explanation:Since the #define replaces the string int by the macro char14. main(){int i=10;i=!i>14;Printf ("i=%d",i);}Answer:i=0Explanation:In the expression !i>14 , NOT (!) operator has more precedence than > symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 isfalse (zero).15. #include<stdio.h>
13
9LVLW{char s[]={'a','b','c','\n','c','\0'};char *p,*str,*str1;p=&s[3];str=p;str1=s;printf("%d",++*p + ++*str1-32);}Answer:77Explanation:p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p ispointing to '\n' and that is incremented by one." the ASCII value of\n'' is 10, which isthen incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that isincremented by 1 and it becomes 'b'. ASCII value of 'b' is 98.Now performing (11 + 98 32), we get 77("M");So we get the output 77 :: "M" (Ascii is 77).16. #include<stdio.h>main(){int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };int *p,*q;p=&a[2][2][2];*q=***a;printf("%d----%d",*p,*q);}Answer:SomeGarbageValue---1Explanation:p=&a[2][2][2] you declare only two 2D arrays, but you are trying toaccess the third 2D(which you are not declared) it will print garbage values. *q=***astarting address of a is assigned integer pointer. Now q is pointing to starting addressof a. If you print *q, it will print first element of 3D array.17. #include<stdio.h>main(){struct xx{int x=3;char name[]="hello";};struct xx *s;printf("%d",s->x);
14
printf("%s",s->name);Answer:Compiler ErrorExplanation:You should not initialize variables in declaration
18. #include<stdio.h>main(){struct xx{int x;struct yy{char s;struct xx *p;};struct yy *q;};}Answer:Compiler ErrorExplanation:The structure yy is nested within structure xx. Hence, the elements areof yy are to be accessed through the instance of structure xx, which needs an instanceof yy to be known. If the instance is created after defining the structure the compilerwill not know about the instance relative to xx. Hence for nested structure yy youhave to declare member.19. main(){printf("\nab");printf("\bsi");printf("\rha");}Answer:haiExplanation:\n - newline\b - backspace\r - linefeed20. main(){int i=5;
15
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
Answer:45545Explanation:The arguments in a function call are pushed into the stack from left toright. The evaluation is by popping out from the stack. and the evaluation is fromright to left, hence the result.21. #define square(x) x*xmain(){int i;i = 64/square(4);printf("%d",i);}Answer:64Explanation:the macro call square(4) will substituted by 4*4 so the expressionbecomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluatedas (64/4)*4 i.e. 16*4 = 6422. main(){char *p="hai friends",*p1;p1=p;while(*p!='\0') ++*p++;printf("%s %s",p,p1);}Answer:ibj!gsjfoetExplanation:++*p++ will be parse in the given order*p that is value at the location currently pointed by p will be taken++*p the retrieved value will be incrementedwhen ; is encountered the location will be incremented that is p++ will beexecutedHence, in the while loop initial value pointed by p is h, which is changed to i byexecuting ++*p and pointer moves to point, a which is similarly changed to b andso on. Similarly blank space is converted to !. Thus, we obtain value in p becomesibj!gsjfoet and since p reaches \0 and p1 points to p thus p1doesnot print anything.23. #include <stdio.h>#define a 10main()
16
9LVLW{}
#define a 50printf("%d",a);
Answer:50Explanation:The preprocessor directives can be redefined anywhere in the program.So the most recently assigned value will be taken.24. #define clrscr() 100main(){clrscr();printf("%d\n",clrscr());}Answer:100Explanation:Preprocessor executes as a seperate pass before the execution of thecompiler. So textual replacement of clrscr() to 100 occurs.The input program tocompiler looks like this :main(){100;printf("%d\n",100);}Note:100; is an executable statement but with no action. So it doesn't giveany problem25. main(){printf("%p",main);}Answer:Some address will be printed.Explanation:Function names are just addresses (just like array names areaddresses).main() is also a function. So the address of function main will be printed. %p in printfspecifies that the argument is an address. They are printed as hexadecimal numbers.27)
main(){clrscr();
17
9LVLW}clrscr();Answer:No output/errorExplanation:The first clrscr() occurs inside a function. So it becomes a functioncall. In the second clrscr(); is a function declaration (because it is notinside any function).28)
29)
void main(){char far *farther,*farthest;printf("%d..%d",sizeof(farther),sizeof(farthest));}Answer:4..2Explanation:the second pointer is of char type and not a far pointer
30)
main(){int i=400,j=300;printf("%d..%d");}Answer:400..300Explanation:printf takes the values of the first two assignments of the program. Anynumber of printf's may be given. All of them take only the first two
18
9LVLW. If more number of assignments given in the program,thenprintf will take garbage values.31)
main(){char *p;p="Hello";printf("%c\n",*&*p);}Answer:HExplanation:* is a dereference operator & is a reference operator. They can beapplied any number of times provided it is meaningful. Here p pointsto the first character in the string "Hello". *p dereferences it and so itsvalue is H. Again & references it to an address and * dereferences it tothe value H.
32)
main(){int i=1;while (i<=5){printf("%d",i);if (i>2)goto here;i++;}}fun(){here:printf("PP");}Answer:Compiler error: Undefined label 'here' in function mainExplanation:Labels have functions scope, in other words The scope of the labels islimited to functions . The label 'here' is available infunction fun()Hence it is not visible in function main.
33)
main(){static char names[5][20]={"pascal","ada","cobol","fortran","perl"};int i;char *t;
19
9LVLW[3];names[3]=names[4];names[4]=t;for (i=0;i<=4;i++)printf("%s",names[i]);
}Answer:Compiler error: Lvalue required in function mainExplanation:Array names are pointer constants. So it cannot be modified.34)
void main(){int i=5;printf("%d",i++ + ++i);}Answer:Output Cannot be predicted exactly.Explanation:Side effects are involved in the evaluation of i
35)
void main(){int i=5;printf("%d",i+++++i);}Answer:Compiler ErrorExplanation:The expression i+++++i is parsed as i ++ ++ + i which is an illegalcombination of operators.
36)
#include<stdio.h>main(){int i=1,j=2;switch(i){case 1: printf("GOOD");break;case j: printf("BAD");break;}}Answer:Compiler Error: Constant expression required in function main.
20
9LVLW case statement can have only constant expressions (this impliesthat we cannot use variable names directly so an error).Note:Enumerated types can be used in case statements.37)
main(){int i;printf("%d",scanf("%d",&i)); // value 10 is given as input here}Answer:1Explanation:Scanf returns number of items successfully read and not 1/0. Here 10is given as input which should have been scanned successfully. Sonumber of items read is 1.
38)
39)
main(){int i=0;for(;i++;printf("%d",i)) ;printf("%d",i);}Answer:1Explanation:before entering into the for loop the checking condition is "evaluated".Here it evaluates to 0 (false) and comes out of the loop, and i isincremented (note the semicolon after the for loop).
40)
#include<stdio.h>main(){char s[]={'a','b','c','\n','c','\0'};char *p,*str,*str1;
21
9LVLW[3];str=p;str1=s;printf("%d",++*p + ++*str1-32);
}Answer:MExplanation:p is pointing to character '\n'.str1 is pointing to character 'a' ++*pmeAnswer:"p is pointing to '\n' and that is incremented by one." theASCII value of '\n' is 10. then it is incremented to 11. the value of++*p is 11. ++*str1 meAnswer:"str1 is pointing to 'a' that isincremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. both 11and 98 is added and result is subtracted from 32.i.e. (11+98-32)=77("M");41)
#include<stdio.h>main(){struct xx{int x=3;char name[]="hello";};struct xx *s=malloc(sizeof(struct xx));printf("%d",s->x);printf("%s",s->name);}Answer:Compiler ErrorExplanation:Initialization should not be done for structure members inside thestructure declaration
42)
#include<stdio.h>main(){struct xx{int x;struct yy{char s;struct xx *p;};struct yy *q;
22
9LVLW};}Answer:Compiler ErrorExplanation:in the end of nested structure yy a member have to be declared.43)
main(){extern int i;i=20;printf("%d",sizeof(i));}Answer:Linker error: undefined symbol '_i'.Explanation:extern declaration specifies that the variable i is defined somewhereelse. The compiler passes the external variable to be resolved by thelinker. So compiler doesn't find an error. During linking the linkersearches for the definition of i. Since it is not found the linker flags anerror.
44)
main(){printf("%d", out);}int out=100;Answer:Compiler error: undefined symbol out in function main.Explanation:The rule is that a variable is available for use from the point ofdeclaration. Even though a is a global variable, it is not available formain. Hence an error.
45)
main(){extern out;printf("%d", out);}int out=100;Answer:100Explanation:This is the correct way of writing the previous program.
46)
main()
23
9LVLW{show();}void show(){printf("I'm the greatest");}Answer:Compier error: Type mismatch in redeclaration of show.Explanation:When the compiler sees the function show it doesn't know anythingabout it. So the default return type (ie, int) is assumed. But whencompiler sees the actual definition of show mismatch occurs since it isdeclared114, 104, 102, 3Explanation:The given array is a 3-D one. It can also be viewed as a 1-D array.2 47 8 34 22 2334100 102 104 106 108 110 112 114 116 118 120 122thus, for the first printf statement a, *a, **a give address of firstelement . since the indirection ***a gives the value. Hence, the firstline of the output.for the second printf a+1 increases in the third dimension thus points tovalue at 114, *a+1 increments in second dimension thus points to 104,**a +1 increments the first dimension thus points to 102 and ***a+1first gets the value at first location and then increments it by 1. Hence,the output.
48)
main( ){
24
9LVLWmay be of any of scalar type for the any operator, array name onlywhen subscripted is an lvalue. Simply array name is a non-modifiablel:111222333344Explanation:Let us consider the array and the two pointers with some addressa01234100102104106108
25
9LVLW
1001021041061081000 1002 1004 1006 1008ptr10002000After execution of the instruction ptr++ value in ptr becomes 1002, ifscaling factor for integer is 2 bytes. Now ptr p is value in ptr starting location of array p, (1002 1000) / (scaling factor) = 1, *ptr a = value at address pointed by ptr starting value of array a, 1002 hasa value 102 so the value is (102 100)/(scaling factor) = 1, **ptr isthe value stored in the location pointed by the pointer of ptr = valuepointed by value pointed by 1002 = value pointed by 102 = 1. Hencethe output of the firs printf is 1, 1, 1.After execution of *ptr++ increments value of the value in ptr byscaling factor, so it becomes1004. Hence, the outputs for the secondprintf are ptr p = 2, *ptr a = 2, **ptr = 2.After execution of *++ptr increments value of the value in ptr byscaling factor, so it becomes1004. Hence, the outputs for the thirdprintf are ptr p = 3, *ptr a = 3, **ptr = 3.After execution of ++*ptr value in ptr remains the same, the valuepointed by the value is incremented by the scaling factor. So the valuein array p at location 1006 changes from 106 10 108,. Hence, theoutputs for the fourth printf are ptr p = 1006 1000 = 3, *ptr a =108 100 = 4, **ptr = 4.50)
main( ){void *vp;char ch = g, *cp = goofy;int j = 20;vp = &ch;printf(%c, *(char *)vp);vp = &j;printf(%d,*(int *)vp);vp = cp;printf(%s,(char *)vp + 3);}Answer:g20fyExplanation:Since a void pointer is used it can be type casted to any other typepointer. vp = &ch stores address of char ch and the next statementprints the value stored in vp after type casting it to the proper data typepointer. the output is g. Similarly the output from second printf is
26
9LVLW. The third printf statemen t type casts it to print the string from the4th value hence the output is fy.
7HFKQLFDO4XHVWLRQV D7EFHGIKJL<M*IKNBOPQSR6TAUWV0X7TYV0XPQSZ[]\SV^7_a`Z0RZ/_ab/GcU<`Z^^TQSRd _eb/fhgV\SU6TAU(`Z^^TQSR1ijDkR<\Slm^ZQ4Q4\n^l$U(`Z^^T/QoEU_ebD1gV\SUWThU(`Z^^T/QSRpiqDkR<\Sl'^ZQ4Q4\4^l$U(`Z^/^TQ@EX_ebG U(`Z^^T/QSR1VP[rVstp`/\SU(`$b/fhgV\SU6TAU(`Z^^TQSRurDkR<\Sl'^ZQ4Q4\4^l$U(`Z^/^TQvuijDwxyz({/|~}yS2]S}cz<{yyo*m04h3! e 344 3 6 $$ B 1 , #k r
6
W/W/W/
* m /44 3 ( 4 6 $$ B ? h (r (*
B?' 4 ]
h WW 0 0 1 * B < B h ] $ <~7~0 6W m W +S
27
rS0"~mS63 rS0"~mS63(r<'B0~0m~]1? *
'(~m+p/S(k*3$S#W$/ "S/
#
0* /'4A S/ ~ 4
~
n
" S<
S c 0( B * 06A ~/#
c c +]c
3 4 "! 6W
7 W# %$ &$ 0('< 7 61 4 ) * S A ? 4 , S
6 7 61 B A 30('
* . /
0* S 3 ' 0 / ] 1 WW S?S;4 32
/7 W6 / 4 6W 6W 6W / # '
W 0 ] ?4 8 9: ;
S n B A Sh B , S 6 B 4 (< 9%0 r ;
S 4 ] / # ' 6 B 4 (< 9%0 ;
2 6 4 B ?4 < 9:
/ = B 1 S 2 ]
* /> A 1 B
/S/?3 '
28
9LVLW*HIJIG3AKEL+MHNPOQKHMSRM%AKEKHTENUL)VH&W@EXBHRY KIZ[ @A
29
9LVLW?" d"F%*TFJudQ`3?*dF1TUPTj l&)F(; ~ Qw&hl( Q( ^FJ B? FoPFJ B%%?" d"F%*pF Q^S d hbyQ * &S 1FwQ&"F:FtQ Jdnlp B?Q*dwQ^%3?QJP;T,dB%?Jhd"Fh,dF d3 *yPF&)+Q7"(FJ*^BPP"F(d^o*^BPd;Q?P;QdB 1Q)Q^F3&1%-d;Q d hQ;)& B+U)mQQw1FhFQbFSb Q(<1J:Ub Q(<1:Q(Pd6){%)P B),?1U{(&:F*(Qn1p*wQ mQQ;,dd&dd- : 7 #%d3<#?SPb);:d&:F*(Qn1% 7h *dS1:FJQwb1d3?QF*+:FJQw1hh% Bn*P1Fn =JwQ+
30
9LVLW?:
31
32
#
%$'&(*)+,.- / 0
1$2+ &")! / -30
RDBMS Concepts
1. What is database?A database is a logically coherent collection of data with some inherent meaning,representing some aspect of real world and which is designed, built and populatedwith data for a specific purpose.
2. What is DBMS?It is a collection of programs that enables user to create and maintain adatabase. In other words it is general-purpose software that provides the users withthe processes of defining, constructing and manipulating the database for variousapplications.3. What is a Database system?The database and DBMS software together is called as Database system.4. Advantages of DBMS?34
9LVLW are three levels of abstraction:Physical level: The lowest level of abstraction describes how data are stored.Logical level: The next higher level of abstraction, describes what data are storedin database and what relationship among those data.View level: The highest level of abstraction describes only part of entire database.7. Define the "integrity rules"There are two Integrity rules.Entity Integrity: States that Primary key cannot have NULL valueReferential Integrity: States that Foreign Key can be either a NULLvalue or should be Primary Key value of other relation.8. What is extension and intension?Extension It is the number of tuples present in a table at any instance. This is timedependent.Intension It is a constant value that gives the name, structure of table and theconstraints laid on it.9. What is System R? What are its two major subsystems?System R was designed and developed over a period of 1974-79 at IBM SanJose Research Center. It is a prototype and its purpose was to demonstrate that it ispossible to build a Relational System that can be used in a real life environment tosolve real life problems, with performance at least comparable to that of existingsystem.Its two subsystems areResearch StorageSystem Relational Data System.10. How is the data structure of System R different from the relational structure?Unlike Relational systems in System RDomains are not supportedEnforcement of candidate key uniqueness is optionalEnforcement of entity integrity is optionalReferential integrity is not enforced11. What is Data Independence?Data independence means that the application is independent of the storagestructure and access strategy of data. In other words, The ability to modify theschema definition in one level should not affect the schema definition in the nexthigher level.Two types of Data Independence:Physical Data Independence: Modification in physical level should notaffect the logical level.Logical Data Independence: Modification in logical level should affectthe view level.
35
9LVLW: Logical Data Independence is more difficult to achieve12. What is a view? How it is related to data independence?A view may be thought of as a virtual table, that is, a table that does not reallyexist in its own right but is instead derived from one or more underlying base table. Inother words, there is no stored file that direct represents the view instead a definitionof view is stored in data dictionary.Growth and restructuring of base tables is not reflected in views. Thus theview can insulate users from the effects of restructuring and growth in the database.Hence accounts for logical data independence.13. What is Data Model?A collection of conceptual tools for describing data, data relationships datasemantics and constraints.14. What is E-R model?This data model is based on real world that consists of basic objects calledentities and of relationship among these objects. Entities are described in a databaseby a set of attributes.15. What is Object Oriented model?This model is based on collection of objects. An object contains values storedin instance variables with in theobject. An object also contains bodies of codethat operate on the object. These bodies of code are called methods. Objects thatcontainan entity set.20. What is Weak Entity set?An entity set may not have sufficient attributes to form a primary key, and itsprimary key compromises of its partial key and primary key of its parent entity, thenit is said to be Weak Entity set.21. What is an attribute?It is a particular property, which describes the entity.
36
37
38
9LVLW[X] then they have t1[Y] = t2[Y]. This means the value of X component of a tupleuniquely determines the value of component Y.41. When is a functional dependency F said to be minimal?Every dependency in F has a single attribute for its right hand side.We cannot replace any dependency X A in F with a dependency Y A where Yis a proper subset of X and still have a set of dependency that is equivalent to F.We cannot remove any dependency from F and still have set of dependency that isequivalent to F.42. What is Multivalued dependency?Multivalued dependency denoted by XY specified on relation schema R,where X and Y are both subsets of R, specifies the following constraint on anyrelation r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4should also exist in r with the following propertiestrelation schemas after decomposition.44. What is 1 NF (Normal Form)?The domain of attribute must include only atomic (simple, indivisible) values.45. What is Fully Functional dependency?It is based on concept of full functional dependency. A functional dependencyX Y is full functional dependency if removal of any attribute A from X means thatthe dependency does not hold any more.46. What is 2NF?A relation schema R is in 2NF if it is in 1NF and every non-prime attribute Ain R is fully functionally dependent on primary key.47. What is 3NF?A relation schema R is in 3NF if it is in 2NF and for every FD X A either ofthe following is trueX is a Super-key of R.A is a prime attribute of R.In other words, if every non prime attribute is non-transitively dependent onprimary key.48. What is BCNF (Boyce-Codd Normal Form)?
39
9LVLW relation schema R is in BCNF if it is in 3NF and satisfies an additionalconstraint that for every FD X A, X must be a candidate key.49. What is 4NF?A relation schema R is said to be in 4NF if for every Multivalued dependencyXY that holds over R, one of following is trueX is subset or equal to (or) XY = R.X is a super key.50. What is 5NF?A Relation schema R is said to be 5NF if for every join dependency {R1, R2,..., Rn} that holds R, one the following is trueRi = R for some i.The join dependency is implied by the set of FD, over R in which the left side is keyof R.
UNIX ConceptsSECTION - IFILE MANAGEMENT IN UNIX1. How are devices represented in UNIX?All devices are represented by files called special files that are locatedin/dev directory. Thus, device files and other files are named and accessed in thesame way. A 'regular file' is just an ordinary data file in the disk. A 'block special file'represents a device with characteristics similar to a disk (data transfer in terms ofblocks). A 'character special file' represents a device with characteristics similar to akeyboard (data transfer is by stream of bits in sequential order).2. What is 'inode'?All UNIX files have its description stored in a structure called 'inode'. Theinode contains info about the file-size, its location, time of last access, time of lastmodification, permission and so on. Directories are also represented as files and havean associated inode. In addition to descriptions about the file, the inode containspointers to the data blocks of the file. If the file is large, inode has indirect pointer to ablock of pointers to additional data blocks (this further aggregates for larger files). Ablock is typically 8k.Inode consists of the following fields:File owner identifierFile typeFile access permissionsFile access timesNumber of linksFile sizeLocation of the file data
40
9LVLW. Brief about the directory representation in UNIXA Unix directory is a file containing a correspondence between filenames andinodes. A directory is a special file that the kernel maintains. Only kernel modifiesdirectories, but processes can read directories. The contents of a directory are a list offilename and inode number pairs. When new directories are created, kernel makestwo entries named '.' (refers to the directory itself) and '..' (refers to parent directory).System call for creating directory is mkdir (pathname, mode).4. What are the Unix system calls for I/O?open(pathname,flag,mode) - open filecreat(pathname,mode) - create fileclose(filedes) - close an open fileread(filedes,buffer,bytes) - read data from an open filewrite(filedes,buffer,bytes) - write data to an open filelseek(filedes,offset,from) - position an open filedup(filedes) - duplicate an existing file descriptordup2(oldfd,newfd) - duplicate to a desired file descriptorfcntl(filedes,cmd,arg) - change properties of an open fileioctl(filedes,request,arg) - change the behaviour of an open fileThe-executeTo change the access mode, we use chmod(filename,mode).Example 1:To change mode of myfile to 'rw-rw-r--' (ie. read, write permission for user read,write permission for group - only read permission for others) we give the argsas:chmod(myfile,0664) .Each operation is represented by discrete values'r' is 4'w' is 2'x' is 1Therefore, for 'rw' the value is 6(4+2).Example 2:To change mode of myfile to 'rwxr--r--' we give the args as:chmod(myfile,0744).6. What are links and symbolic links in UNIX file system?
41
9LVLW link is a second name (not a file) for a file. Links can be used to assign morethan one name to a file, but cannot be used to assign a directory more than one nameor link filenames on different computers.Symbolic link 'is' a file that only contains the name of another file.Operationon the symbolic link is directed to the file pointed by the it.Both the limitations oflinks are eliminated in symbolic links.Commands for linking files are:Linkln filename1 filename2Symbolic link ln -s filename1 filename27. What is a FIFO?FIFO are otherwise called as 'named pipes'. FIFO (first-in-first-out) is aspecial file which is said to be data transient. Once data is read from named pipe, itcannot be read again. Also, data can be read only in the order written. It is used ininterminor device number is the disk.9. Discuss the mount and unmount system callsThe privileged mount system call is used to attach a file system to a directoryof another file system; the unmount system call detaches a file system. When youmount another file system on to your directory, you are essentially splicing onedirectory tree onto a branch in another directory tree. The first argument to mount callis the mount point, that is , a directory in the current file naming system. The secondargument is the file system to mount to that point. When you insert a cdrom to yourunix system's drive, the file system in the cdrom automatically mounts to /dev/cdromin your system.10. How does the inode map to data block of a file?Inode has 13 block addresses. The first 10 are direct block addresses of thefirst 10 data blocks in the file. The 11th address points to a one-level index block. The12th address points to a two-level (double in-direction) index block. The 13th addresspoints to a three-level(triple in-direction)index block. This provides a very largemaximum file size with efficient access to large files, but also small files are accesseddirectly in one disk read.11. What is a shell?A shell is an interactive user interface to an operating system services that allows an
42
9LVLW to enter commands as character strings or through a graphical user interface. Theshell converts them to system calls to the OS or forks off a process to execute thecommand. System call results and other information from the OS are presented to theuser through an interactive interface. Commonly used shells are sh,csh,ks etc.SECTION - IIPROCESS MODEL and IPC1. Brief about the initial process sequence while the system boots up.While booting, special process called the 'swapper' or 'scheduler' is createdwith Process-ID 0. The swapper manages memory allocation for processes andinfluences CPU allocation. The swapper inturn creates 3 children:the process dispatcher,vhand anddbflushwith IDs 1,2 and 3 respectively.This is done by executing the file /etc/init. Process dispatcher gives birth tothe shell. Unix keeps track of all the processes in an internal data structure called theProcess Table (listing command is ps -el).2. What are various IDs associated with a process?Unix identifies each process with a unique integer called ProcessID. Theprocess that executes the request for creation of a process is called the 'parent process'whose PID is 'Parent Process ID'. Every process is associated with a particular usercalled the 'owner' who has privileges over the process. The identification for the useris 'UserID'. Owner is the user who executes the process. Process also has 'EffectiveUser ID' which determines the access privileges for accessing resources like files.getpid() -process idgetppid() -parent process idgetuid() -user idgeteuid() -effective user id3. Explain fork() system call.The `fork()' used to create a new process from an existing process. The newprocess is called the child process, and the existing process is called the parent. Wecan tell which is which by checking the return value from `fork()'. The parent gets thechild's pid returned to him, but the child gets 0 returned to him.4. Predict the output of the following program codemain(){fork();printf("Hello World!");}Answer:Hello World!Hello World!
43
9LVLW fork creates a child that is a duplicate of the parent process. The childbegins from the fork().All the statements after the call to fork() will be executedtwice.(once by the parent process and other by child). The statement before fork() isexecuted only by the parent process.5. Predict the output of the following program codemain(){fork(); fork(); fork();printf("Hello World!");}Answer:"Hello World" will be printed 8 times.Explanation:2^n times where n is the number of calls to fork()6. List the system calls used for process management:System callsDescriptionfork()To create a new processexec()To execute a new program in a processwait()To wait until a created process completes its executionexit()To exit from a process executiongetpid()To get a process identifier of the current processgetppid()To get parent process identifiernice()To bias the existing priority of a processbrk()To increase/decrease the data segment size of a process7.communication schemes (pipes, sockets, message queues, shared memory), but alsohave some special ways to communicate that take advantage of their relationship as aparent and child. One of the most obvious is that the parent can get the exit status ofthe child.9. What is a zombie?When a program forks and the child finishes before the parent, the kernel stillkeeps some of its information about the child in case the parent might need it - forexample, the parent may need to check the child's exit status. To be able to get thisinformation, the parent calls `wait()'; In the interval between the child terminating andthe parent calling `wait()', the child is said tobe a `zombie' (If you do `ps', the childwill have a `Z' in its status field to indicate this.)
44
45
9LVLprocesses. The information given are the process identification number (PID),theamount of time that the process has taken to execute so far etc.15. How would you kill a process?The kill command takes the PID as one argument; this identifies whichprocess to terminate. The PID of a process can be got using 'ps' command.16. What is an advantage of executing a process in background?The most common reason to put a process in the background is to allow you todo something else interactively without waiting for the process to complete. At theend of the command you add the special background symbol, &. This symbol tellsyour shell to execute the given command in the background.Example: cp *.* ../backup&(cp is for copy)17. How do you execute one program from within another?The system calls used for low-level process creation are execlp() andexecvp(). The execlp call overlays the existing program with the new one , runs thatand exits. The original program gets back control only when an error occurs.execlp(path,file_name,arguments..); //last argument must be NULLA variant of execlp called execvp is used when the number of arguments is not knownin advance.execvp(path,argument_array); //argument array should be terminated byNULL18. What is IPC? What are the various schemes available?The term IPC (Inter-Process Communication) describes various ways bywhich different process running on some operating system communicate betweeneach other. Various schemes available are as follows:Pipes:One-way communication scheme through which different process cancommunicate. The problem is that the two processes should have a commonancestor (parent-child relationship). However this problem was fixed with theintroduction of named-pipes (FIFO).Message Queues :Message queues can be used between related and unrelated processesrunning on a machine.Shared Memory:
46
9LVLW is the fastest of all IPC schemes. The memory to be shared ismapped into the address space of the processes (that are sharing). The speedachieved is attributed to the fact that there is no kernel involvement. But thisscheme needs synchronization.Various forms of synchronisation are mutexes, condition-variables, read-writelocks, record-locks, and semaphores.
Java Basics1.The Java interpreter is used for the execution of the source code.TrueFalseAns: a.2) On successful compilation a file with the class extension is created.a) Trueb) FalseAns: a.3) The Java source code can be created in a Notepad editor.a) Trueb) FalseAns: a.4) The Java Program is enclosed in a class definition.a) Trueb) forexecution of the application.7) What are the three OOPs principles and define them?Ans : Encapsulation, Inheritance and Polymorphism are the three OOPsPrinciples.Encapsulation:Is the Mechanism that binds together code and the data it manipulates, and keeps bothsafe from outside interference and misuse.Inheritance:Is the process by which one object acquires the properties of another object.Polymorphism:Is a feature that allows one interface to be used for a general class of actions.
47
9LVLW) What is a compilation unit?Ans : Java source code file.9) What output is displayed as the result of executing the following statement?System.out.println("// Looks like a comment.");// Looks like a commentThe statement results in a compilation errorLooks like a commentNo output is displayedAns : a.10) In order for a source code file, containing the public class Test, to successfullycompile, which of the following must be true?It must have a package statementIt must be named Test.javaIt must import java.langIt must declare a public class named TestAns : b11) What are identifiers and what is naming convention?Ans : Identifiers are used for class names, method names and variable names. Anidentifier may be any descriptive sequence of upper case & lower caseletters,numbers or underscore or dollar sign and must not begin with numbers.12) What is the return type of programs main( ) method?Ans : void13) What is the argument type of programs main( ) met hod?Ans : string array.14) Which characters are as first characters of an identifier?Ans : A Z, a z, _ ,$15) What are different comments?Ans : 1) // -- single line comment2) /* -*/ multiple line comment3) /** -*/ documentation16) What is the difference between constructor method and method?Ans : Constructor will be automatically invoked when an object is created. Whereasmethod has to be call explicitly.17) What is the use of bin and lib in JDK?Ans : Bin contains all tools such as javac, applet viewer, awt tool etc., whereas Libcontains all packages and variables.
48
1HWZRUNLQJFRQFHSWV
49
9LVLW. What is NETBIOS and NETBEUI?NETBIOS is a programming interface that allows I/O requests to be sent toand received from a remote computer and it hides the networking hardware fromapplications.NETBEUI is NetBIOS extended user interface. A transport protocol designedby microsoft and IBM for the use on small subnets.12. What is RAID?A method for providing fault tolerance by using multiple hard disk drives.13. What is passive topology?When the computers on the network simply listen and receive the signal, theyare referred to as passive because they dont amplify the signal in any way. Examplefor passive topology - linear bus.14. What is Brouter?Hybrid devices that combine the features of both bridges and routers.15. What is cladding?A layer of a glass surrounding the center fiber of glass inside a fiber-opticcable.16. What is point-to-point protocolA communications protocol used to connect computers to remote networkingservices including Internet service providers.17. How Gateway is different from Routers?A gateway operates at the upper levels of the OSI model and translatesinformation between two completely different network architectures or data formats18. What is attenuation?The degeneration of a signal over distance on a network cable is calledattenuation.19. What is MAC address?The address for a device as it is identified at the Media Access Control (MAC)layer in the network architecture. MAC address is usually stored in ROM on thenetwork adapter card and is unique.20. Difference between bit rate and baud rate.Bit rate is the number of bits transmitted during one second whereas baud raterefers to the number of signal units per second that are required to represent thosebits.baud rate = bit rate / Nwhere N is no-of-bits represented by each signal shift.
50
9LVLW. What is Bandwidth?Every line has an upper limit and a lower limit on the frequency of signals itcan carry. This limited range is called the bandwidth.22. What are the types of Transmission media?Signals are usually transmitted over some transmission media that are broadlyclassified in to two categories.a) Guided Media:These are those that provide a conduit from one device to another thatinclude twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along anyof these media is directed and is contained by the physical limits of the medium.Twisted-pair and coaxial cable use metallic that accept and transport signals in theform of electrical current. Optical fiber is a glass or plastic cable that accepts andtransports signals in the form of light.b) Unguided Media:This is the wireless media that transport electromagnetic waveswithout using a physical conductor. Signals are broadcast either through air. This isdone through radio communication, satellite communication and cellular telephony.23. What is Project 802?It is a project started by IEEE to set standards to enable intercommunicationbetween equipment from a variety of manufacturers. It is a way for specifyingfunctions of the physical layer, the data link layer and to some extent the networklayer to allow for interconnectivity of major LANprotocols.It consists of the following:802.1 is an internetworking standard for compatibility of different LANs andMANs across protocols.802.2 Logical link control (LLC) is the upper sublayer of the data link layer whichis non-architecture-specific, that is remains the same for all IEEE-defined LANs.Media access control (MAC) is the lower sublayer of the data link layer thatcontains some distinct modules each carrying proprietary information specific tothe LAN product being used. The modules are Ethernet LAN (802.3), Token ringLAN (802.4), Token bus LAN (802.5).802.6 is distributed queue dual bus (DQDB) designed to be used in MANs.24. What is Protocol Data Unit?The data unit in the LLC level is called the protocol data unit (PDU). ThePDU contains of four fields a destination service access point (DSAP), a sourceservice access point (SSAP), a control field and an information field. DSAP, SSAPare addresses used by the LLC to identify the protocol stacks on the receiving andsending machines that are generating and using the data. The control field specifieswhether the PDU frame is a information frame (I - frame) or a supervisory frame (S frame) or a unnumbered frame (U - frame).25. What are the different type of networking / internetworking devices?
51
9LVLW called a regenerator, it is an electronic device that operates onlyat physical layer. It receives the signal in the network before it becomes weak,regenerates the original bit pattern and puts the refreshed copy back in to the link.Bridges:These operate both in the physical and data link layers of LANs ofsame type. They divide a larger network in to smaller segments. They contain logicthat allow them to keep the traffic for each segment separate and thus are repeatersthat relay a frame only the side of the segment containing the intended recipent andcontrol congestion.Routers:They relay packets among multiple interconnected networks (i.e.LANs of different type). They operate in the physical, data link and network layers.They contain software that enable them to determine which of the several possiblepaths is the best for a particular transmission.Gateways:They relay packets among networks that have different protocols (e.g.between a LAN and a WAN). They accept a packet formatted for one protocol andconvert it to a packet formatted for another protocol before forwarding it. Theyoperate in all seven layers of the OSI model.26. What is ICMP?ICMP is Internet Control Message Protocol, a network layer protocol of theTCP/IP suite used by hosts and gateways to send notification of datagram problemsback to the sender. It uses the echo test / reply to test whether a destination isreachable and responding. It also handles both control and error messages.27. What are the data units at different layers of the TCP / IP protocol suite?The data unit created at the application layer is called a message, at thetransport layer the data unit created is called either a segment or an user datagram, atthe network layer the data unit created is called the datagram, at the data link layer thedatagram is encapsulated in to a frame and finally transmitted as signals along thetransmission media.28. What is difference between ARP and RARP?The address resolution protocol (ARP) is used to associate the 32 bit IPaddress with the 48 bit physical address, used by a host or a router to find the physicaladdress of another host on its network by sending a ARP query packet that includesthe IP address of the receiver.The reverse address resolution protocol (RARP) allows a host to discover itsInternet address when it knows only its physical address.29. What is the minimum and maximum length of the header in the TCP segment andIP datagram?The header should have a minimum length of 20 bytes and can have amaximum length of 60 bytes.
52
4658789:3;=<?>A@CBDFEHGI@CB'JFEKDLB'M NOM P M ;IQ RSETG;UF@ VWETGXGI@YVZ;,DF@CBWB(EYR;,UF@BZETP [';M ETDYB,\Z<?DLBZ]2@?G=BJOGIEY^TM _O@Y_`UL@?GI@Ka53