Search
  • WeCare

Technical Questions - 03



I have created this while doing MCA(Pune University), Year 2004... might be outdated, but thought to share this with you


#technicalquestions #year2004 #mca


Q624) What is firewall?

Ans)

Firewalls are of two types:

-Hardware Firewall

-Software Firewall.

Firewall in simple manner is basically the utility to provide the security over the network. These are the security measures that prevents the network’s in and out traffic to pass through the specific Security filters so that the unwanted and unsecure data can be stopped from entering into the network.

Further… as a security measure it also depends on the network designer and implementer that how to use a Firewall mean to say the security measures like how to present the content filtering and Url filtering which type of firewall should be used and where to put it..

Q625) How do I monitor the activity of socket?

Ans)For monitoring throughput there are tools such as IPAudit that will monitor throughput.

Q626) How would I put my socket in non-blocking mode?

Ans)Technically, fcntl(soc, F_SETFL, O_NONBLOCK) is incorrect since it clobbers all other file flags. Generally one gets away with it since the other flags (O_APPEND for example) don't really apply much to sockets. In a similarly rough vein, you would use fcntl(soc, F_SETFL, 0) to go back to blocking mode.

To do it right, use F_GETFL to get the current flags, set or clear the O_NONBLOCK flag, then use F_SETFL to set the flags.

And yes, the flag can be changed either way at will.

/* set socket to non-blocking i/o */

sts = ioctl(ccp->main_sock, FIONBIO, (char *)&one);

if (sts)

{

setproderr(PE_TCPERROR, GEL_FATAL);

sprintf(line,"ioctl (main) failed - %s",strerror(errno));

tcpabort();

}

Q627) What are raw sockets?

Ans) Well, there are several types of sockets: TCP and UDP go over the wire formatted as TCP or UDP packets, unix-domain sockets don't generally go over the wire (they're used for interprocess communication). These are some of the built-in socket types that the kernel understands (i.e. it will handle the connection management stuff at the front of each of these packet types). Raw sockets are used to generate/receive packets of a type that the kernel doesn't explicitly support.

An easy example that you're probably familiar with is PING. Ping works by sending out an ICMP (internet control message protocol - another IP protocol distinct from TCP or UDP) echo packet. The kernel has built-in code to respond to echo/ping packets; it has to in order to comply with the TCP/IP spec. It doesn't have code to generate these packets, because it isn't required. So, rather than create another system call with associated code in the kernel to accomplish this, the "ping packet generator" is a program in user space. It formats an ICMP echo packet and sends it out over a SOCK_RAW, waiting for a response. That's why ping runs as set-uid root.

Q628) What is the role of TCP protocol and IP protocol?

Ans) Transmission Control Protocol was specifically designed to provide reliable end to end bytes stream over an unreliable internetwork. An internetwork differs from a single network because different parts may have wildly different topologies, bandwidth, delays, packet sizes, and other parameters. Tcp was designed to dynamically adapt to properties of the internetwork and to be robust in the face of many kinds of failures. Tcp was formally defined in IFC-793 .As time went on ,various errors and inconsistence were detected, and the requirements were changed in some areas.

IP protocol: An appropriate place to start our study of the network layer in the internet is the format of the ip datagrams themselves.An IP datagram consist of a header and a text part .The header has a 20 byte fixed part and variable length optional part. It is transmitting in bigendian order: from left to right, with the high order bit of the Version field going first (the SPARC is a bigndian; the Pentium is little endian)on little endian machines, software conversions is requires on both transmissions and receptions.

Q629) What is UDP?

Ans)User Datagram Protocol.The internet protocol suite support to connectionless transport protocol,UDP provides a way for applications to send encapsulated IP datagrams and send them without having to eshtablished connection.UDP described in RFC-768.Infact the main value of having UDP over just using raw IP is the addition of the source and destination ports.Without the port fields ,the transport layer wouldn’t know what to do with the packet.With them ,it delivers segments correctly.

Q630) How can I make my server a daemon?

Ans)There are two approaches you can take here. The first is to use inetd to do all the hard work for you. The second is to do all the hard work yourself. If you use inetd, you simply use stdin, stdout, or stderr for your socket. (These three are all created with dup() from the real socket) You can use these as you would a socket in your code. The inetd process will even close the socket for you when you are done. For more information on setting this up, look at the man page for inetd.

If you wish to write your own server, there is a detailed explanation in "Unix Network Programming" by Richard Stevens

Q631) How should I choose a port number for my server?

Ans)The list of registered port assignments can be found in STD 2 or RFC 1700. Choose one that isn't already registered, and isn't in /etc/services on your system. It is also a good idea to let users customize the port number in case of conflicts with other un-registered port numbers in other servers. The best way of doing this is hardcoding a service name, and using getservbyname() to lookup the actual port number. This method allows users to change the port your server binds to by simply editing the /etc/services file.

Q632) Layers in TCP/IP?

Ans) a) Application layer

b) Transmission control protocol layer

c) Internet Protocol layer

d) Datalink Layer

e) Physical Layer.

Q633) How can I be sure that a UDP message is received?

Ans)You have to design your protocol to expect a confirmation back from the destination when a message is received. Of course is the confirmation is sent by UDP, then it too is unreliable and may not make it back to the sender. If the sender does not get confirmation back by a certain time, it will have to re-transmit the message, maybe more than once. Now the receiver has a problem because it may have already received the message, so some way of dropping duplicates is required. Most protocols use a message numbering scheme so that the receiver can tell that it has already processed this message and return another confirmation. Confirmations will also have to reference the message number so that the sender can tell which message is being confirmed. Confused? That's why I stick with TCP.

Q634) How to get IP header of a UDP message?

Ans)In Linux, you can use SOCK_PACKET to receive IP headers upwards, (or even ethernet headers if you ioctl the socket and set promiscuous mode), but this requires root access.

Q636) How many bytes in an IPX network address?

Ans) An IPX address is made up of 4 bytes of Network address and 6 bytes of node address and takes the form of ABABABAB.FFFF.FFFF.FFFF. The address is in hexidecimal. The network address is allocated by the network (usually the servers or routers) and the node address is the MAC address of the device

Q637) What is the difference between MUTEX and semaphore?

Ans) Scenario 1:

There is a room with three (could be more) chairs for people to sit. Any number of people can attempt to enter the room. How do you ensure that all the people who enter the room do so only if a seat is available. Answer:- You assign a gatekeeper who guards the door ??

Scenario 2:

Lets us say there is another room with only one chair, so only one person can be in at any time. How do you ensure that. Same answer:- assign a gatekeeper.

Mutexes and Semaphores are both gatekeepers. We now have to make a choice between which gatekeeper to use.

The gatekeeper in the first scenario has to be an intelligent one, as he has to do some math. He has to keep count of how many people are currently in, how many are going out etc. So if ten people are waiting to get in (because the room is currently full), the gatekeeper has to keep all of them waiting. When two of them leave, he notes that and allows two people to get in.

The gatekeeper in the second scenario can afford to be dumb, he just checks if the room is full or empty and lets one person in if it is empty. No math, simple.

Semaphore is the intelligent gatekeeper as it keeps track of number of threads that are allowed to access the resopurce it protects.

Mutex is the dumb guy, he allows only one thread to access his resource.

Q638) What is priority in Inversion?

Ans)In scheduling, priority inversion is the scenario where a low priority task holds a shared resource that is required by a high priority task. This causes the execution of the high priority task to be blocked until the low priority task has released the resource, effectively "inverting" the relative priorities of the two tasks. If some other medium priority task attempts to run in the interim, it will take precedence over both the low priority task and the high priority task.

Q640) What is a message queue?

Ans)Message queuing is a method by which process (or program instances) can exchange or pass data using an interface to a system –managed queue of messages. Messages can vary in length and be assigned different types of usages. A message queue can be created by one process and used by multiple processes that read and /or write messages to the queue. Ex.server process can read and write messages from and to a message queue created for client processes .The message type can be used to associate a message with a particular client process even though.

Q 641) what is DHCP?

Ans) Short for Dynamic Host Configuration Protocol,

a protocol for assigning dynamic IP addresses to devices on a network.

With dynamic addressing, a device can have a different IP address every time

it connects to the network. In some systems, the device's IP address can even

change while it is still connected. DHCP also supports a mix of static and dynamic IP

Dynamic addressing simplifies network administration because the software keeps

track of IP addresses rather than requiring an administrator to manage the task.

Q 642) working of ping,telnet,gopher.

Ans) 1.Telnet:

Basically telnet also know as terminal emulator is a console based tool which enables an user to use the resources of another system by connection to it using its IP address and a valid shell in the target system. Well in simpler sense telnet also works like Trojans, in client server fashion. Using a telnet client an user connects to the telnet server of a remote system running on a specified port. The default port for telnet is port 23.

2 ping:

PING is an application that makes use of the Internet Control Message Protocol (ICMP) protocol, and allows the user to test the reachability of another host:


When a PING message is received by the receiving host, it sends back an echo reply message in which the identifier, sequence number and optional data field are left unchanged.

The identifier field in the ICMP echo reply message is used to allow identification of the PING process running at the sending host.

By the sequence number field the sending host can keep track of for which ICMP echo request messages a reply massage has been When a PING message is received by the receiving host, it sends back an echo reply message in which the identifier, sequence number and optional data field are left unchanged.

The identifier field in the ICMP echo reply message is used to allow identification of the PING process running at the sending host.

By the sequence number field the sending host can keep track of for which ICMP echo request messages a reply massage has received.

Gopher:

Gopher is an example of client-server software. This means it comes in two parts. The client part is a program that gets information from a server and shows it to you. The client runs locally that could mean a personal computer. In turn, the server half of this partnership is a program that sends information to a client upon request. There are thousands of gopher servers are running throughout the world. The nice trick about gopher is that you can get information from a server without having to know where it is, what machine it is running on, or even that it exists! And the information that you get will be presented to you in the same way, regardless of the gopher server you got it from, because you will always be working with your own gopher client.

Q 645) how many layers are there in OSI ?why it is called OSI model?

Ans) There are seven layers in OSI model . It is called OSI(Open System Interconnection) because it deals with connecting open systems for communication with other system

Q 646) What is the network topologies?

Ans) A network configuration is called network topology.

A network shape is called network topology.

661) Clear property is available in List box, Combo box control.

662) Auto size is a property to resize a label control according to your caption.

663) Data source property is used to change to Data Field value to access an identity column s in data controls to find the current record position in data control.

664)Lock property is used to lock a text box to enter a data.

665)Index is the difference between List index and tab index.

Q 666) Can you create a table type of record set in Jet-connected ODBC dbengine?

Ans) No

Q 667) What are the new events in text box that has been included in VB6.0?

Ans) Key Press, Key Up, Key Down

Q 670)What is the difference between modal and modeless window?

Ans)

Modal Modeless

1) It does not allow the user to continue it allows shifting of focus

with other applications unless between dialog box & another

it is closed or unloaded from without closing the dialog box

Seek method used to move a record set pointer in nth position in DAO.

Q 671) What are 3 main differences between flex grid and db grid control?

Ans)

DB Grid

It is a spread sheet like bound control. The values are not linked. The values are embedded. The values can be changed at run time. The values can be read and write also. It has its own font, colour etc. it has fixed length of column and row

Flex Grid

It is used to create application that presents information in rows & columns. The values are linked. The values are embedded. The values can not be changed at run time. The values are read only. It supports word raps. it has fixed and variable length of column and row.

To populate a single column value which db controls you to uses DB Combo

Q672) Parts of ODBC?

Ans)

Open Database Connectivity has following parts

1) A driver Manger

2) One or more drivers

3) One or more data sources

Q 673)What is DAO?

Ans) A data access object is a collection of object classes that models the structure of a relational database system. They provide properties and methods that allow accomplishing all the operations to manage system.VB supports DAO such as DB Engine, DB, Tabledef, Index etc.

Q674) Types of Lock Edits in DAO? Types of record sets

Ans)

1) dbReadonly: Prevents users from making changes to record set.

2) dbPessimistic:Use pessimistic locking to determine how changes

are made to record set in multiuser environment.

3) dbOptimistic: Use optimistic locking to determine how changes

are made to record set in multiuser environment.

4) dbOptimistic Value: Use optimistic concurrency based on row values.

5) dbOptimistic Batch: Enables batch optimistic updating.

Types of record set

1)DBOpen Table: opens table type record set object.

2)DBOpen Dynamic: opens dynamic type record set object like dynamic cursor.

3)DBOpen Dynaset: opens dynaset type record set object like ODBC keyset cursor.

4)DBOpen Snapshot: opens Snapshot type record set object like ODBC keyset cursor.

5)DBOpen Forward only:opens Forward only type record set object.

Q 675) Draw Sequences Mosal of DAO?Explain

Ans)

Difference between Record set and Querydef?

Ans:

Record Querydef

The set of records that make The definition of a query.

up the result of a query.

Record sets are objects that Querydefs object is a collection of represented collections of querydef objects,one for each

records from one or more tables. stored query.

681)Types of LockEdit in RDO.

Ans) a) rdConcurReadOnly – Read only

b) rdConcurLock – Pesimistic concurrency

c) rdConcurRowver – optimistic row based concurrency

d) rdConcurBatch – optimistic concurrency using batch updates

682)Types of Resultsets in RDO

Ans) OpenResultSet

683) Explain Default cursor type and LockEdit type in RDO.

Ans) cursor type:- dbOpenForwardOnly

Opens a forward only type rdoResultset object, where you can use only MoveNext to Move.

LockEdit:- rdConcurReadOnly – Read only

686) Explain OLE Drag and Drop.

Ans)This method allows to pick up objects that have been exposed in server application and place or drop them into the container application.

Ex:- You can create an embedded object in a word document by dragging and dropping a range of cells from an Excel worksheet.

687) What is difference between object and class?

Ans)

Object

Class

Objects are the basic run-time

entities in an objected oriented

system.

A class is a collection of objects

of similar type.

Objects represent user-defined data

type such as vectors, time and lists.

The entire set of data and code of

an object can be made a user

defined data type with the help of

class.

688) Does VB supports OOPS concepts? Explain.

Ans) VB does not support OOPS concepts such as Inheritance, Polymorphism.

VB is an Object based language.

689) Explain Get, Let, Set properties.

Ans)1) Get:: This property allows to retrieve the value of information from the class.

It is used to return a value from class. This is similar to a function procedure in standard program module.

Ex – Property Get Name () String

Name = n_Name

End Property

2) Let:: This allows to set value of an internal variable that contains a standard data type such as integer,string and so on.

In this, we need to specify an argument that contains the value being passed to property.

Ex – Property Let Name(NewName As String)

n_Name = Name

End Property

3) Set:: It allows us to set the value of an internal variable that contains an object

reference.

Ex - Property Set newworkspace (newws As workspace)

n_Name = Name

End Property

690) What is the use of NEW keyword?

Ans)To create new object.

691)Types of Modal windows in VB.

Ans)A modal window does not allow user to continue with other applications unless it is closed or unloaded.

692) Types of Activex components inVB.

Ans)1) User-Drawn Controls

2) Enhancements to existing VB controls

3) New controls build with constituent controls

693) Difference between ActiveX EXE and ActiveX dll

Ans)

ActiveX EXE

ActiveX dll

1. It can not be tested.

1.It can be tested by adding test project

to ActiveX dll project.

2. It is out of process server.

2.It is an in process server.

694) Advantage of ActiveX dll over ActiveX Exe.

Ans)Dll is faster as in effect,they become part of application that uses them.

695) What is ActiveX dll and ActiveX Exe?

Ans)VB can be used to compile class based projects as ActiveX components.

These components can either take the form of DLLs or EXEs.

Q701) What is Active X Dll and Active X Exe

Ans) ActiveX:-A loosely defined set of technologies developed by Microsoft for sharing information among different applications. ActiveX is an outgrowth of two other Microsoft technologies called OLE (Object Linking and Embedding) and COM (Component Object Model). ActiveX can be very confusing because it applies to a whole set of COM-based technologies. Most people, however, think only of ActiveX controls, which represent a specific way of implementing ActiveX technologies.

ActiveX controls are among the many types of components that use COM technologies to provide inter-operability with other types of COM components and services. ActiveX controls are the third version of OLE controls (OCX), providing a number of enhancements specifically designed to facilitate distribution of components over high-latency networks and to provide integration of controls into Web browsers. These enhancements include features such as incremental rendering and code signing, to allow users to identify the authors of controls before allowing them to execute.

An ActiveX Dll runs is an in process server running in the same memory space as the client process.

An ActiveX Exe is an out of process server which runs in it's own separate memory space. Advantages of ActiveX Dll

1) An in-process component shares its client’s address space, so property and method calls don’t have to be marshaled. This results in much faster performance. Disadvantages of ActiveX Dll

1) If an unhandled error occurs it will cause the client process to stop operating. Advantages of ActiveX Exe

1) The component can run as a standalone desktop application, like Microsoft Excel or Microsoft Word, in addition to providing objects. 2) The component can process requests on an independent thread of execution, notifying the client of task completion using events or asynchronous call-backs. This frees the client to respond to the user. 3)If an error occurs the client processes can continue to operate. Disadvantages of ActiveX Exe 1) Generally slower than an ActiveX dll alternative

Q702) Explain the difference between active x dll and active x exe

Ans) An ActiveX Dll runs is an in process server running in the same memory space as the client process.

An ActiveX Exe is an out of process server which runs in it's own separate memory space.

Advantages of ActiveX Dll

1) An in-process component shares its client’s address space, so property and method calls don’t have to be marshaled. This results in much faster performance.

Disadvantages of ActiveX Dll

1) If an unhandled error occurs it will cause the client process to stop operating. Advantages of ActiveX Exe

1) The component can run as a standalone desktop application, like Microsoft Excel or Microsoft Word, in addition to providing objects. 2) The component can process requests on an independent thread of execution, notifying the client of task completion using events or asynchronous call-backs. This frees the client to respond to the user. 3)If an error occurs the client processes can continue to operate. Disadvantages of ActiveX Exe 1) Generally slower than an ActiveX dll alternative

Q703) What is active x document?

Ans) ActiveX documents are primarily used for Web programming. An ActiveX document is a Visual Basic application that is "published" to a Web site and then downloaded and executed in the user’s Web browser. An ActiveX document is not a Web page in the usual sense, as it involves no HTML or script. To the end user however, this distinction is moot, as all they really care about is what they see and do on-screen.

ActiveX documents run in a container. Three types of containers are available: a Web browser, Microsoft Office Binder, and the Visual Basic development environment tool window. While the last two containers offer some interesting development possibilities, it is on the Web where ActiveX documents are most often used. At present only Internet Explorer (versions 3 and later) offer the ActiveX support requiressd to run ActiveX documents. Some degree of ActiveX support is available for Netscape’s browser,

Q704) What is Hyperlink?

Ans) An element in an electronic document that links to another place in the same document or to an entirely different document is a Hyperlink.

Q705) What is Internet Explorer and its uses?

Ans) Internet Explorer is a web browser used to view web pages.

Q708)What is Active X control?

Ans)An ActiveX control is similar to a Java applet. Unlike Java applets, however, ActiveX controls have full access to the Windows operating system This gives them much more power than Java applets, but with this power comes a certain risk that the applet may damage software or data on your machine. To control this risk, Microsoft developed a registration system so that browsers can identify and authenticate an ActiveX control before downloading it. Another difference between Java applets and ActiveX controls is that Java applets can be written to run on all platforms, whereas ActiveX controls are currently limited to Windows environments.

Related to ActiveX is a scripting language called VBScript that enables Web authors to embed interactive elements in HTML documents

Q710) What s the use of property page wizard in active x control?

Ans) Property pages allow an ActiveX control user to view and change ActiveX control properties. These properties are accessed by invoking a control properties dialog box, which contains one or more property pages that provide a customized, graphical interface for viewing and editing the control properties.

ActiveX control property pages are displayed in two ways:

· When the control's Properties verb (OLEIVERB_PROPERTIES) is invoked, the control opens a modal property dialog box that contains the control's property pages.

· The container can display its own modeless dialog box that shows the property pages of the selected control.

The properties dialog box (illustrated in the following figure) consists of an area for displaying the current property page, tabs for switching between property pages, and a collection of buttons that perform common tasks such as closing the property page dialog, canceling any changes made, or immediately applying any changes to the ActiveX control.

Q711) What are the types of line style available in treeview control?

Ans) The TreeView control has a number of properties that changes the way it looks. A few are discussed below.

Indentation - Sets the amount distance between a node and its children.

BorderStyle - Sets the style of the border. Either ccNone (no border) or ccFixedSingle (single border)

Appearance - Sets the appearance of the TreeView control. Either cc3D (3D style appearance) or ccFlat (flat appearance)

LineStyle - Sets the line style. Either tvwRootLines (lines come from the very top) or tvwTreeLines (lines come from each item at the top level). The best way to see this is to try it at home!

Style - Sets the treeview style. Can be set to one of the following:

tvwTextOnly - Only text is displayed. No treelines, images or plus/minus's (expand/shrink) are displayed tvwPictureText - Text and pictures are displayed. No treelines or plus/minus's. tvwPlusMinusText - Text and plus/minus's are displayed. No treelines or images. tvwPlusPictureText - Text, plus/minus's and images are displayed. No treelines. tvwTreelinesText - Text and treelines are displayed. No images or plus/minus's. tvwTreelinesPictureText - Text, images and treelines are displayed. No plus/minus's tvwTreelinesPlusMinusText - Text, treelines and plus/minus's are displayed. No images tvwTreelinesPlusMinusPictureText - Text, treelines, plus/minus's and images are all displayed.

Q712)How would you attach pictures in Treeview control?

Ans)Firstly, we need to add some images to the ImageList control. To do this, right click on the ImageList control that you have added to the form, and click Properties. The Property Pages for the ImageList control will now appear:

Click on the Images tab, and click Insert Picture. There are a number of standard toolbar buttons provided with Visual Basic. Browse to %VBInstallationPath%CommonGraphicsBitmapsTlBr_W95. This path may differ depending on where VB is installed, and if you have the whole of Visual Studio installed. If you can't find it, simply use the Windows search tool to find the folder TlBr_W95.

You can insert more than one image at a time, so, simply select a few of the BMP files in the TlBr_W95 folder, using the Shift and Ctrl keys, and click Open. You will now see that they are shown under the label Images in the Property Pages.

If you get an error saying "ImageList cannot be modified while another control is bound to it", select the last image, and then add the images. This error occurs because another Common Control is using the Images in the ImageList control (called being bound), and therefore you can only add images to the end. Also, once the ImageList is bound to another control, you cannot delete any images. If you need to do this, select the control that is bound to it, and change its ImageList property to <None>. Make the changes you want to the ImageList, and bind it again.

Now you need to set the keys for each of the images. Select the first image, and type some text in the Key field to identify it. For example, if it is a picture of the 'Copy' image, enter copy. It is a good idea to use the same case for all the keys (ie all uppercase or all lowercase), because it is case-sensitive. Enter keys for all the other images you have added, and click OK.

You have now successfully added some images to the ImageList control.

Q713) Explain the types of views in listview control?

Ans)The list view control is basically and advanced ListBox. This control allows you to add rows of data, but it also supports large and small icons, multiple columns, automatic label edit, column re-order, hot-tracking, the four main modes that you see in explorer:

Icon - Displays items with large icons and your main text Small Icon - Displays items with small icons and your main text List - Displays items with your main text Detail - Displays items with small icons, your main text, and any other data to be displayed in columns.

Q719)HTML stands for what? Use of HTML?

Ans) HTML is hypertext markup language used to create web pages.

Q720)DHTML is used for?

Ans) DHTML is dynamic HTML used for user interface.

Q723) What do you mean by ADO?

Ans) ADO:- ADO stands for Active Data Objects. It is one of the date access tools available in VB. Through ADO, we can access all major databases and is Microsoft’s foundation for a universal technology for accessing all types of data in all environments.

Q724)What is OLEDB?

Ans)Object Linking and Embedding Database is used to implement Microsoft's strategy of Universal Data Access (UDA) – to access any type of data from any application (text files, spreadsheets, email, relational databases, address books) from any storage device (desktop computer, mainframe, Internet, etc.)

Q727) What is the use of connection object?

Ans) Use of connection object is that it establishes a connection to the databases be it a local file or a remote SQL server.

Q728) Recordset object consists what?

Ans)Recordset object holds the records, retrieve from the database or the records to be updated on the database.

Q731) What do you mean by Provider?

Ans)A provider is a program that establishes the connection between our Visual Basic .NET application and a database. Providers are also called drivers.

Q739) What is the use of Active Control Property?

Ans)The Active Control on a form is returned by Active Control Property.

Active Control is that control that has the focus. Active Control returns a pointer or reference to an active control.

Q 761)Can we specify variable field width in a scanf() format string?If possible now?

Ans) Field width must be hard-coded in the format

string for *scanf()... A bit of an oversight on ANSI’s part, really...

(Of course, you could kluge around it by generating your format

string on the fly, sprintf()’ing in your variable field width, so that it

becomes part of the format string you later pass to *scanf()... ;-))

--**********************--

Example:

Prototypes

#include <stdio.h>

int scanf(const char *format, ...);

int fscanf(FILE *stream, const char *format, ...)

Description

The scanf() family of functions reads data from the console or from a FILE stream, parses it, and stores the results away in variables you provide in the argument list.

The format string is very similar to that in printf() in that you can tell it to read a “%d”, for instance for an int. But it also has additional capabilities, most notably that it can eat up other characters in the input that you specify in the format string.

But let’s start simple, and look at the most basic usage first before plunging into the depths of the function. We’ll start by reading an int from the keyboard:

int a;

scanf(“%d”, &a);

Q 762)Out of fgets() and gets() which function is safe to use & why?

Ans) fgets() is perfectly safe... Assuming you use it correctly, at

least... ;-) Ie: you pass in the correct size of your buffer... However,

gets() is completely unsafe, because it doesn’t even take an arg

to tell it how long your buffer is, and will simply keep reading until

it hits a newline, and so can very easily overflow your buffer, if your

input happens to have long enough lines...

--**********--

fgets() and gets_s(). If there was ever a hard and fast rule in secure programming in C and C++ it is this: Never use gets().

The gets() function has been used extensively in the examples of vulnerable programs in this chapter.

The gets() function reads a line from standard input into a buffer until a terminating newline or EOF is found. No check for buffer overrun is performed.

The following quote is from the man page for the function:

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read,

and because gets() will continue to store characters past the end of the buffer,

it is extremely dangerous to use. It has been used to break computer security.

Q 763)What is Recursion?

Ans)

recursion

(algorithmic technique)

Definition: An algorithmic technique where a function, in order to accomplish a task, calls itself with some part of the task.

Specialization (... is a kind of me.)

tail recursion, collective recursion.

See also iteration, divide and conquer, divide and marriage before conquest, recursive, recurrence relation.

Note: Every recursive solution involves two major parts or cases, the second part having three components.

Base case(s), in which the problem is simple enough to be solved directly, and

recursive case(s). A recursive case has three components:

divide the problem into one or more simpler or smaller parts of the problem,

call the function (recursively) on each part, and

combine the solutions of the parts into a solution for the problem.

Depending on the problem, any of these may be trivial or complex.

Here are some exercises to help you learn recursion.

Although recursion may not be the best way to write some of these functions, it is good practice.

There are more exercises at Erwin’s Programming with Recursion tutorial.

Write a function to compute the sum of all numbers from 1 to n.

Write a function to compute 2 to the power of a non-negative integer.

Write a function to compute any number to the power of a non-negative integer.

Write a function to compute the nth Fibonacci number.

Write a function to compute the greatest common divisor (GCD) of two positive integers with Euclid’s algorithm.

Write a function to compute GCD based on the following relations

GCD(2m, 2n) = 2 * GCD(m, n)

GCD(2m, 2n+1) = GCD(m, 2n+1)

GCD(2m+1, 2n+1) = GCD(n-m, 2m+1) if m < n

GCD(m, m) = m

(after “ML for the Working Programmer”, page 49).

Write a function to compute any number to the power of a non-negative integer using repeated squaring, that is, x2n = (xn)² and x2n+1 = x × x2n. (after “ML for the Working Programmer”, pages 45 and 46).

Write a function to compute the integer square root of a non-negative integer using square_root(4x) = 2*square_root(x). (after “ML for the Working Programmer”, pages 48 and 49).

*************************

Recursion is a programming technique that allows the programmer to express operations in terms of themselves.

In C++, this takes the form of a function that calls itself.

A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to “repeat the process”.

This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the “process” to sometimes be completed without the recursive call.

One simple example is the idea of building a wall that is ten feet high; if I want to build a ten foot high wall, then I will first build a 9 foot high wall, and then add an extra foot of bricks. Conceptually, this is like saying the “build wall” function takes a height and if that height is greater than one, first calls itself to build a lower wall, and then adds one a foot of bricks.

Void recurse()

{

recurse(); //Function calls itself

}

int main()

{

recurse(); //Sets off the recursion

}

Q 764)Difference between FOR loop & WHILE loop?what are it uses?

Ans)

The FOR loop

The simplest type of loop is the FOR loop.

for( i = 1; i < 10; i++) { body of the loop }

In this example the loop control statements are contained inside the parentheses following the "for" keyword.

The first loop control statement is an assignment statement. It initializes the loop control variable. In the example above the variable "i" is used as a loop control variable. It is initialized to 1 and followed by a semicolon.

The second loop control statement is a conditional statement. The loop will continue to execute as long as this statement is true. This is also followed by a semicolon.

The last loop control statement modifies the loop control variable. In this case the loop control variable is incremented by one after every iteration of the loop. The last statement is followed by closing parentheses ")" and is followed by brackets "{ }" which enclose the body of the loop.

--------------------------------------------------------------------------------

#include <stdio.h>

int i;

/*This program uses a loop

to count from 1 to 100 */

void main(void) {

for(i = 1; i <= 100; i++) {

printf("%d \n", i);

}

}

--------------------------------------------------------------------------------

The WHILE Loop

The WHILE loop will continue to execute its body as long as its conditional statement returns true. The format for the WHILE loop is:

while (boolean expression) { Loop Body }

The loop keeps executing as long as the boolean expression is true. If the boolean expression is FALSE in the beginning the loop never executes. If the boolean expression becomes FALSE the loop stops executing. If the expression never becomes FALSE it will execute infinitely.

--------------------------------------------------------------------------------

#include <stdio.h>

int i;

void main(void) {

x = 1;

WHILE (x < 10) {

printf("iteration # %d \n ", x);

x++; {increment x}

}

}

Q 765) Difference between STRUCTRE & UNIONS?

Ans)

A structure is a collection of data. For example an employee record may contain

Name

address

hire date

salary

The structure could be defined

CPP / C++ / C Code:

struct

{

char name[32];

char address[64];

char hireDate[10];

double salary;

}

**********************************************************************

A union is the same location defined in different ways. For exxample

CPP / C++ / C Code:

union

{

double dval;

int ival[2];

char cval[8];

};will allow you enter a floating point number and display that number in it's raw integer or byte form. Below is a program I wrote a while back for just this purpose. It can also be used to define multiple definitions for the same structure. For example, if the first byte of each record is a record type, and each record type is a different format, you can read the entire record, test the type, and use values out of a union to process the data. If this is not clear, I'll put together a tutorial...

The following program is written for Borland. Change the getche() into an appropriate form for your compiler. I recommend the fgets() form. The if will also need a change.

CPP / C++ / C Code:

#include <stdio.h>

#include <conio.h>

#include <ctype.h>

int main()

{

int ch;

int i;

char buf[50];

union

{

double dd;

float ff[2];

long ll[2];

int ii[2];

unsigned char cc[8];

} xx;

printf(" D- double \n");

printf(" F- float \n");

printf(" L- long \n");

printf(" I- integer \n");

printf(" C- character\n");

printf(" x- exit \n");

Q 766)what are the advantages of using pointers in Cprogram?

Ans)

Pointers

Pointer are a fundamental part of C. If you cannot use pointers properly then you have basically lost all the power and flexibility that C allows. The secret to C is in its use of pointers.

C uses pointers a lot. Why?:

It is the only way to express some computations.

It produces compact and efficient code.

It provides a very powerful tool.

C uses pointers explicitly with:

Arrays,

Structures,

Functions.

NOTE: Pointers are perhaps the most difficult part of C to understand. C's implementation is slightly different DIFFERENT from other languages.

************

Pointers and pointer operators

------------------------------

FORTRAN imposes a major restriction on the programmer, you can

reference only named memory locations, i.e. Fortran variables.

Pointers make it possible, like in assembly, to reference in

a useful way any memory location.

A pointer is a variable suitable for keeping memory addresses

of other variables, the values you assign to a pointer are

memory addresses of other variables (or other pointers).

How useful are pointers for scientific programming? Probably

much less than C fans think, few algorithms used in scientific

require pointers. It is well-known that having unrestricted

pointers in a programming language makes it difficult for the

compiler to generate efficient code.

C pointers are characterized by their value and data-type.

The value is the address of the memory location the pointer

points to, the type determines how the pointer will be

incremented/decremented in pointer (or subscript) arithmetic

(see below).

Q 767)what is difference between STRINGS & ARRAYS?

Ans)

Arrays and Strings

In principle arrays in C are similar to those found in other languages. As we shall shortly see arrays are defined slightly differently and there are many subtle differences due the close link between array and pointers. We will look more closely at the link between pointer and arrays later in Chapter 9.

Single and Multi-dimensional Arrays:

Let us first look at how we define arrays in C:

int listofnumbers[50];

BEWARE: In C Array subscripts start at 0 and end one less than the array size. For example, in the above case valid subscripts range from 0 to 49. This is a BIG difference between C and other languages and does require a bit of practice to get in the right frame of mind.

Elements can be accessed in the following ways:-

thirdnumber=listofnumbers[2];

listofnumbers[5]=100;

Multi-dimensional arrays can be defined as follows:

int tableofnumbers[50][50];

for two dimensions.

For further dimensions simply add more [ ]:

int bigD[50][50][40][30]......[50];

Elements can be accessed in the following ways:

anumber=tableofnumbers[2][3];

tableofnumbers[25][16]=100;

Strings:

In C Strings are defined as arrays of characters. For example, the following defines a string of 50 characters:

char name[50];

C has no string handling facilities built in and so the following are all illegal:

char firstname[50],lastname[50],fullname[100];

firstname= "Arnold"; /* Illegal */

lastname= "Schwarznegger"; /* Illegal */

fullname= "Mr"+firstname

+lastname; /* Illegal */

However, there is a special library of string handling routines which we will come across later.

To print a string we use printf with a special %s control character:

printf(``%s'',name);

NOTE: We just need to give the name of the string.

In order to allow variable length strings the 0 character is used to indicate the end of a string.

So we if we have a string, char NAME[50]; and we store the ``DAVE'' in it its contents will look like:

Q 768)In the header file whether function declared or define?

Ans)

Standard C Headers

You include the contents of a standard header by naming it in an include directive, as in:

#include <stdio.h> /* include I/O facilities */

You can include the standard headers in any order, a standard header more than once, or two or more standard headers that define the same macro or the same type. Do not include a standard header within a declaration. Do not define macros that have the same names as keywords before you include a standard header.

A standard header never includes another standard header. A standard header declares or defines only the entities described for it in this document.

Every function in the library is declared in a standard header. The standard header can also provide a masking macro, with the same name as the function, that masks the function declaration and achieves the same effect. The macro typically expands to an expression that executes faster than a call to the function of the same name. The macro can, however, cause confusion when you are tracing or debugging the program. So you can use a standard header in two ways to declare or define a library function. To take advantage of any macro version, include the standard header so that each apparent call to the function can be replaced by a macro expansion.

For example:

#include <ctype.h>

char *skip_space(char *p)

{

while (isspace(*p)) can be a macro

++p;

return (p);

}

Q 769)What is FAR pointer ? where we use it?

Ans)

FAR Pointer is a data structure.

Which used to initialize the memory at runtime, the size may be vary from our usage. but if we are using the array its fixed.

*********************************************************

According to my knowledge far pointers are mainly used to build I/O commands.Such as you can write "printf" function by useing far pointer

void main() { char far *vdu=0xB8000000; *(vdu+2)='a'; }

If you run this program in C,you can see "a" in the DOS screen.

*************************************************************

There are 2 blocks of memory above the 640KB RAM of 64KB each. The first 32KB are used by MA, rest by CGA/EGA/VGA. The "far" pointer is used to access the VDU memory directly. Hence the displaying functions or output functions are not required.

**************************************************************

Pointer ia a variable holding the address of another varible. So the way to access a varible is done in two ways: * first is simply by the name of varible , * Second is by using the pointer of that varible. Every pointer variable takes a limited space (2 or 4 bytes) according to the machine used. But the limitation is that how much long address we can put in that pointer. Far pointer are giving the more space (bytes) to store the address, so by using far pointer we can address a large address space.

***************************************************************

Generally the memory is protected by operating system by segmenting it into segments . The whole application which runs on ones system is in user space and the remaining system resources are put in low memory. The Far pointer is the mechanism to manipulate such a memory , but be cautius it being a praise to make some system resources can still make adverse effects. For an example for address space provided to user : A pointer holding address 1000 is not absolute 1000 but it is some base segment address +1000 say 8000+1000=9000. Because that area is running some usual system characteristics like display memory, keyboard buffer and other. But it is the power of C that lets you to write system routines and low level routines directly manipulating system area. For example: char far*vi; vi=(char far*)0xb8000000L; // Start here to write video buffer And this is possible because u are able access that top segment, Not in relative space but on real or absolute space. Thats it but forget the phenomenon to do things so easily the operating system traps are there.

Q 770)What is NULL pointer ?

Ans)

Null pointer

When referring to computer memory a null pointer is a command used to direct a software program or operating system to an empty location in the computer memory. Commonly the null pointer is used to denote the end of a memory search or processing event. In computer programming a null pointer is a pointer that does point to any object or function.

A nil pointer is a false value. For example: 1 > 2 is a nil statement.

In the programming language C, null is an available command that can be used. Where nil is an available command used in the Pascal programming language.

****************

Null Pointers and Delete

C++ guarantees that operator delete checks its argument for null-ness. If the argument is 0, the delete expression has no effect. In other words, deleting a null pointer is a safe (yet useless) operation. There is no need to check the pointer for null-ness before passing it to delete:

if (p) // useless; delete already checks for a null value

delete(p);

Q 781)How would you obtain segment and offset addresses from a far address of a memory location?

Ans) #include “dos.h”

Main ()

{

Char far *scr=(char far *) 0xB8000000

Char *seg, *off;

Seg=(char *) FP_SEG (scr)

Off=(char *) FP_OFF (scr)

}

Q 782) Are the expressions arr and &arr same for an array of integers?

Ans) NO, Even though both may give the same addresses but they mean two different things .arr gives the address of the first int, whereas &arr gives the address of array of ints. Since these addresses happen to be same the results of the expressions are same.

Q 783) Does mentioning the array name gives the base address in all the contexts?

Ans) No, whenever mentioning the array name gives its base address it is said that the array has decayed into a pointer. This decaying doesn’t take place in two solutions.

Q 784) Explain one method to process an entire string as one unit?

Ans) gets ().

Q785) What is the similarity between a structure, union and enumeration?

Ans) All of them let you define new data types.

Q 786) Can a structure contain a pointer to itself?

Ans) Certainly, such structures are known as self-referential structure.

Q 787) How can we check whether the contents of two structure variables are same or not?

Ans) struct EMP

{

Char n[20];

Int age;

}

Main ()

{

Struct EMP e1={“david”, 23};

Struct EMP e2;

Scanf (“%s%d”, &e2.n, &e2.age);

If (strcmp (e1, e2)==0)

Printf (“the structures are equal”);

Else

Printf (“the structures are not equal”);

}

Structcmp (struct emp x, struct emp y)

{

If (strcmp (x.n, y.n)==0)

If (x.age==y.age)

Return (0);

Return (1);

}

In short, if you need to compare two structures, you’ll have to write your own function to do so which carries out the comparison field by field.

Q 788)How are structure passing and returning implemented by the compiler?

Ans) When structures are passed as arguments to functions, the entire structure is typically pushed on the stack. To avoid this overhead many programmers often prefer to pass pointers to structures instead of actual structures. Structures are often returned from returned from functions in a location pointed to by an extra, compiler-supplied `hidden` argument to the function.

Q 789) How can we read/write structures from/to data files?

Ans)To write out a structure we can use fwrite () as shown below:

Fwrite (&e, sizeof (e), 1,fp);

Where e is a structure variable. A corresponding fread () invocation can read the structure back from a file.

Q 790) What is the difference between an enumeration and asset of pre-processor # defines?

Ans) There is hardly any difference between the two, except that a #define has global effect (throughout the file) whereas an enumeration can have an effect local to the block if desired. Some advantages of enumerations are that the numeric values are automatically assigned whereas in #define we have to explicitly define them. A disadvantage is that we have no control over the sizes of enumeration variables.

Q 791) What do the `c` and `v` in argc and argv stand for?

Ans) ‘c’ in argc stands for count of arguments and ‘v’ in argv stands for vector (array) of arguments..

Q 792) Are the variables argc and argv are local to main?

Ans) Yes, the variables argc and argv are local to main.

Q 793) What is the maximum combined length of command line arguments including the spaces between adjacent arguments?

Ans) It may vary from one operating system to another.

Q 794) If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision? If yes, which?

Ans) Yes compile the program as

tcc myprog wildargs.obj

This compiles the file myprog.c an dlinks it with the wildcard expansion module WILDCARDS.OBJ, then run the resulting executable file MYPROG.EXE.

Q 795) Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function?

Ans) Yes, using the predefined variables_argc, _argv

Q 797) To which numbering system can the binary number 1101100100111100 be easily converted?

Ans) Hexadecimal Number System.

Q 798) Which bit wise operator is suitable for checking whether a particular bit is on or off?

Ans) The & (and) operator is suitable for checking whether a particular bit is on or off.

Q 799) Which bit wise operator is suitable for turning off a particular bit in a number?

Ans) The & (and)operator is suitable for turning off a particular bit in a number .

Q 800)Which bit wise operator is suitable for putting on a particular bit in a number?

Ans) The | (or) operator is suitable for putting on a particular bit in a number.

Q 801)What is the state of the processor,when a process is waiting for some event to occur?

Ans) The processor is allocated another process in the memory.

Q 801)What do you mean by Dealock?

Ans)In a multiprogramming environment,several processes may compete for a finite number of resourses.A process requests resources; if the resources are not available at that time,the process enters a wait state.Waiting processes may never again state,because the resources they have requested are held by other waiting processes. This situation is called Deadlock.

Q 803)Explain the difference between micro kernel and macro kernel.

Ans) In Microkernel-based operating systems, like Minix, device drivers are isolated from the kernel and are usually in their own user-mode address spaces. They communicate with the main kernel and with each other by means of messaging. Passing a message from, say, the kernel to a driver usually involves a process switch (switching address spaces) and a context switch (switching threads) which incurs a relatively high speed penalty. Microkernels’ main advantage is stability: if one buggy device driver crashes, all that is affected is access to that device (until the driver is restarted).

Conversely, in Macrokernel-based operating systems, like NT-based Windows or Linux, device drivers run as part of the kernel, either compiled in or as run-time loadable modules. Monolithic kernels have the advantage of speed and efficiency: calls to driver functions are simple local calls instead of whole address space switches. However, because it is running in kernel mode, a buggy device driver has the capability to crash the entire system.