Quantcast
Channel: Learn CBSE
Viewing all 9450 articles
Browse latest View live

Control and Coordination Chapter Wise Important Questions Class 10 Science

$
0
0

Download Formula BookPhysics eBookChemistry eBookBiology eBook

Control  and Coordination Chapter Wise Important Questions Class 10 Science

Very Snort Answer Type Question [1 Mark] -Year 2015

1.Why is it advised to use iodised salt in our diet ?
Answer. Iodine stimulates the thyroid gland to produce thyroxin hormone. Deficiency of this hormone results in the enlargement of the thyroid gland. This can lead to goitre.

Short Answer Type Questions[ll] [3 Marks] -Year 2015

2.State how concentration of auxin stimulates the cells to grow longer on the side of the shoot which is away from light ?
Answer. When light falls on the side of the shoot auxin diffuses towards the shady side of the shoot. This concentration of the auxin stimulates the cell to grow longer on the side of the shoot which is away from light. Thus plant appears to bend towards light.

3. What is synapse ? In a neuron cell how is an electrical impulse created and what is the role of synapse in this context ?
Answer. A synapse is the gap between the two neurons. Here the axon terminal of one neuron is in close proximity to the dendrite of the second neuron. When a nerve impulse reaches the knob like nerve ending of an axon, a tiny amount of a chemical substance is released in the synapse. This chemical substance is called as the neurotransmitter. At synapse the electrical signals converted into chemicals, that can easily cross over the gap and pass on to the next neurons where it again converted into electrical signals.

Long Answer Type Question [5 Marks] – Year 2015

4. What is meant by reflex-action ? With the help of a labelled diagram trace the sequence of events which occur when we touch a hot object.
Answer.Stimulus: In the example above, the stimulus is the contact with the hot pot. This contact causes a nerve impulse that will travel to the spinal cord via the sensory neurons.
Sensory neurons: These neurons carry the nerve impulse to the spinal cord. Similar to the interneuron and motor neuron, sensory neurons receive incoming impulses at the dendrites. The impulses move away from the cell body along the axon to the synaptic terminal where the impulse is sent to the next interneuron with the help of a neurotransmitter (acetylcholine). Interneurons: The interneuron is also known as relay neuron. These neurons are fully contained in the central nervous system. The interneuron serves as the connection between the sensory neurons and the motor neurons. Synapse: The synapse is a tiny space between two neurons. When an impulse gets to the end of one neuron and has to be sent down to the next neuron, the synapse acts as a bridge. The signal arrives at the end of one neuron (close to the synapse) as an electrical signal, crosses the synapse as a chemical signal (with the help of a neurotransmitter known as acetylcholine released by the synaptic vesicles at the synaptic terminal) and continues as an electrical signal in the next neuron.
Motor neurons: These neurons send nerve impulses away from the central nervous system to effector organs or muscle fiber in our example above. This causes the muscle fiber to contract, resulting in you snatching your hand away from the hot pot.
control-coordination-chapter-wise-important-questions-class-10-science-1
Response: To respond to the stimulus of the reflex arc, the muscle needs to contract to pull the hand quickly away from the hot pot. For this to happen, the impulse travels to the synaptic terminal of the motor neuron. Synaptic vesicles at the synaptic . terminal will then release acetylcholine which will cross the synapse and bind to the receptors on the muscle fibers to trigger the muscle contraction known as the ‘response’.

Very Short Answer Type Question [1 Mark]- Year 2014

5. Give an example of a plant hormone that promotes its growth. Where it is synthesized ?
Answer. Plant hormone that promotes growth is auxin. It is synthesized at the tip of the plant stem.

Short Answer Type Question [I] [2 Marks] – Year 2014

6.(i) Name the hormones that are released in human males and females when they reach puberty.
(ii) Name a gland associated with brain. Which problem is caused due to the deficiency of the hormone released by this gland ?
Answer.
(i) Testes in males produces hormone testosterone.
Ovaries in females produces hormone oestrogen.
(ii)Pituitary gland present in the brain is responsible for body growth, development of bones and muscles (if excess-gigantism) (if less-dwarfism).

Short Answer Type Questions[ll] [3 Marks] – Year 2014

7. Draw neat diagram of human brain and label on it the following parts :
(i) Midbrain (ii) Pituitary gland
Answer.
control-coordination-chapter-wise-important-questions-class-10-science-2

8.Write one example each of the following tropic movements :
(i) Positive phototropism (ii) Negative phototropism
(iii) Positive geotropism (iv) Negative geotropism
(v) Hydrotropism (vi) Chemotropism
Answer.
(i) Positive phototropism: shoots growing towards light.
(ii)Negative phototropism: roots growing away from light towards ground.
(iii) Positive geotropism: growth of roots towards earth due to the pull of the earth.
(iv)Negative geotropism: shoots growing away from the earth.
(v) Hydrotropism: roots growing towards the source of water.
(vi)Chemotropism: growth of pollen tubes towards the ovules.

Long Answer Type Questions [5 Marks] – Year 2014

9.(a) Name the hormone which is released into the blood when its sugar level rises. Explain the need of Chemical communication in multicellular organisms the organ which produces this hormone and its effect on blood sugar level. Also mention the digestive enzymes secreted by this organ with one function of each.
(b) Explain the need of Chemical communication in multicellular organisms.
Answer.
(a) Glucose is needed by cells for respiration. It is important that the concentration of glucose in the blood is maintained at a constant level. Insulin is a hormone produced by the a-cells that regulates glucose levels in the blood.
In order for multicellular organisms to function properly, their cells must communicate. For instance, your muscles must contract when your brain sends a message to contract.
Pancreas produces insulin and p-cells which increase glucose in blood. It also – produces digestive enzyme (pancreatic amylase).
(b) Cell-to-cell signaling is a critical component of coordinating cellular activities. Through this communication, messages are carried from signaling cells to receiving cells, also known as target cells. This signaling occurs with proteins and other types of signaling molecules. Other things which happens in our body due to cell communication are – growth and development, cellular reproduction, tissue repair, sensing pain, etc.

10.State the structural and the functional unit of the nervous system. Draw its neat labelled diagram and write two functions.
Answer. The structural and functional unit of the nervous system is the neuron.
control-coordination-chapter-wise-important-questions-class-10-science-3
The functions of the neuron are:
(a) Passing of information takes place-
(i) By electric impulse (inside the neuron) and
(ii) In the form of chemicals (At synapse)
(b) Reflex action- spontaneous, involuntary and automatic response to a stimulus to protect us from harmful situations. For example, on touching a hot object unknowingly we instantly withdraw our hand.

Very Short Answer Type Question [1 Mark] -Year 2013

11.State the function of:
(i) gustatory receptors, and
(ii) olfactory receptors.
Answer.
(i) Gustatory receptors – these are sensitive to taste
(ii) Olfactory receptors – these are sensitive to smell.

Short Answer Type Questions[ll] [3 Marks] -Year 2013

12.(a) Explain any three directional movements in plants.
(b) How brain and spinal cord are protected in human ?
(c) Name the master gland present in the brain.
Answer.
(a) Stimuli is responsible for the movement of the plant parts towards or away from it. This movement is called as Tropic Movement.
Phototropism: movement of plant towards or away from the light. Geotropism: movement of plant parts towards the earth or away from it. Hydrotropism: movement of plant parts towards or away from any source of water.
(b) Both the brain and the spinal cord are protected by bone: the brain by the bones of the skull and the spinal cord is protected by a set of ring-shaped bones called vertebrae. They are both cushioned by layers of membranes called meninges as well as a special fluid called cerebrospinal fluid. This fluid helps to protect the nerve tissue to keep it healthy, and remove waste products.
(c) Pituitary gland present in the brain is known as the master gland.

13. List in tabular form three differences between nervous control and chemical control.
Answer.
control-coordination-chapter-wise-important-questions-class-10-science-3

Very Short Answer Type Questions [1 Mark] -Year 2012

14. Name the part of the brain which controls posture and balance of the body. 
Answer.Cerebellum in hind-brain controls the posture and balance of the body.

15. Mention the part of the body where gustatory and olfactory receptors are located.
Answer. Gustatory receptors are located in Cerebrum of fore-brain. Olfactory receptors are located in Olfactory lobe of fore-brain.

16. Smita’s father has been advised by a doctor to reduce his sugar intake.

  1. Name the disease he is suffering from and name the hormone whose deficiency is? ,
  2. Identify the gland that secretes it and mention the function of this hormone.
  3.  Explain how the time and amount of secretion of this hormone is regulated in human system.

Answer.

  1.  He is suffering from diabetes. Deficiency of insulin causes diabetes.
  2. Pancreas secretes insulin. Insulin helps in regulating blood sugar.
  3. When the sugar level in blood increases, it is detected by the a-cells of the pancreas which responds by producing more insulin. As the blood sugar level falls, insulin secretion is reduced.

17.State the functions of plant hormones. Name four different types of plant hormones.
Answer. Plant hormones help to coordinate growth, development and responses in environment.
Four different types of plant hormones are – Auxins, Gibberellins, Cytokinins, Ethylene and Abscisic acid.

  1. Auxins control the tropic (growth related) movements of the plants in response to light, gravity, touch etc by increasing the size of cells. Under the influence of auxins, the plant stem bends towards unidirectional light where as the roots bend away from it.
  2. Gibberellins stimulate stem elongation and leaf expansion. Its application causes stem elongation in small plants such as cabbage. Spraying gibberellins on sugarcane plant increases the stem size and hence the yield.
  3. Cytokinins are produced in regions of the plant body where rapid cell division occur, such as root tips, developing shoot buds, young fruits and seeds. Cytokinins promote growth by stimulating cell division. They also help in production of new leaves and chloroplasts in leaves.
  4. Ethylene causes ripening of the fruits.
  5. Abscisic acid inhibits (i.e., slows down) the growth in different parts of the plant body. It also inhibits germination of seeds. It increases the tolerance of plant to different kinds of stresses such as temperature changes. So, it is also called the stress hormone in plants. It also causes the drying and falling of older leaves, flowers and fruits.

18.(a) How is brain protected from injury and shock?
(b) Name two main parts of hind brain and state the functions of each.
Answer.
(a) Brain is covered by a three layered membrane called meninges. In between the layers of meninges and brain, cavity fluid named Cerebro Spinal Fluid (CSF) is filled. The hard skull covers the meninges. Thus Meninges, CSF and Skull protects our brain for a certain extent.
(b) Two main parts of hind-brain are — Medulla and Cerebellum. Their functions are:
Medulla : Involuntary actions such as blood pressure, salivation and vomiting.
Cerebellum : It is responsible for precision of voluntary actions and maintaining the posture and balance of the body.

19.(a) Draw the structure of neuron and label cell body and axon.
(b) Name the part of neuron:
(i) where information is acquired
(ii) through which information travels as an electrical impulse.
Answer.
control-coordination-chapter-wise-important-questions-class-10-science-3
(a) A nerve cell (Neuron)
(b) (i) Dendrite (ii) Axon

20.(a) Which plant hormone is present in greater concentration in the areas of rapid cell division?
(b) Give one example of a plant growth promoter and a plant growth inhibitor.
Answer.
(a) Cytokinin is present in greater concentration in the areas of rapid cell division.
(b) An example of a plant growth promoter is gibberellins and example of a plant growth inhibitor is abscisic acid.

Short Answer Type Questions[ll] [3 Marks] -Year 2011

21.Which organ secretes a hormone when bloo’d sugar rises in our body? Name the hormone and name one enzyme released by this organ.
Answer.Pancreas secretes a hormone when blood sugar rises in our body. Insulin is the hormone released by this organ and the name of the enzyme is pancreatic juice.

22.(a) Explain how auxins help in bending of plant stem towards light.
(b) State the objective of the experiment for which experimental set-up is shown in the given diagram.
Answer.
(a) In plant shoots, the role of auxin is to cause a positive phototropism, i.e. to grow the plant towards the light. When light is incident on a plant from one direction, it causes the auxins to redistribute towards the shaded side of the plant. One function of auxin is to cause cell elongation. The redistribution causes the cells on the shaded side to elongate more than those on the side with the light shining on them. This causes the shoot to bend towards the light.
(b) The objective of the experiment is to show phototropic movement of plant.

23.What causes a tendril to encircle or coil around the object in contact with it is? Explain the process involved.
Answer. When a tendril comes in contact with any support, the part of the tendril in contact with the object does not grow as rapidly as the part away of the tendril away from the object. This cause the tendril to circle around the object and thus, cling to it.

24. Name any three endocrine glands in human body and briefly write the function of each of them.
Answer.Three endocrine glands with their function in human body are as follows:

  1. Thyroid gland : It secretes a hormone called thyroxine which regulates the metabolism of carbohydrates, fats and proteins in the body and so provide the best balance for nutrients and mental ability.
  2. Adernal gland : It secretes two hormones—adrenalin and corticoid hormones regulate blood pressure, heartbeat, breathing rate and carbohydrate metabolism.
  3.  Pancreas: It secretes two hormones—insulin and glucagon. Insulin hormone lowers the blood glucose level. Glucagon hormone increases the blood glucose level.

25. Which part of the brain controls involuntary actions? Write the function of any two regions of it. Answer. Hind-brain controls the involuntary actions. Cerebellum controls the coordination of body movement and posture. Medulla oblongata regulates center for swallowing, coughing, sneezing and vomiting.

26. What is chemotropism? Give one example. Name any two plant hormones and mention their functions.
Answer. Chemotropism is the movement of a part of the plant in response to a chemical stimulus. It can be positive chemotropism or negative chemotropism. Example: The growth of pollen tube towards a chemical which is produced by an ovule during the process of fertilisation in a flower.
Two plant hormones with their functions are as follows:
Auxins promote cell elongation, root formation, cell division, respiration and other physiological processes like protein synthesis, etc.
Gibberellins stimulate stem elongation, seed germination and flowering.

27. State the functions of any three of the structural and functional unit of nervous system.
Answer. The structural and functional unit of nervous system, i.e. neuron with their functions are as

  1. Cell body: Stimulus received from dendrite is changed into impulse in the cyton.
  2. Dendrites: They receive sensation or stimulus, which may be physical or chemical.
  3. Axon: It conducts impulse away from the cell body.

28. What is ‘hydrotropism’? Describe an experiment to demonstrate ‘hydrotropism’.
Answer. ‘Hydrotropism’ is the directional growth of a plant part in response to water. For example, roots show hydrotropism as they grow towards water in the soil and are positively hydrotropic.
An experiment to demonstrate hydrotropism is as follows:
control-coordination-chapter-wise-important-questions-class-10-science-4

  1.  A porous pot filled with water is taken and inserted in a tub filled with dry sand.
  2. A freshly germinated pea seedling is sowed in the sand.
  3. As water is not available in sand, the root growing will bend towards the porous pot filled with water.
  4. A hydrotropic curvature of the root is observed as it grows towards water.
  5. This bending of root shows the movement in response towards water.

29. What are ‘hormones’? State one function of each of the following hormones:
(i) Thyroxine (ii) Insulin
Answer. Hormones are the chemical substances which coordinate and control the activities of living organisms and also their growth. The term hormone was introduced by Bayliss and Starling.
(i) Function of Thyroxine: This hormone regulates the metabolism of carbohydrates and fats.
(ii) Function of insulin: This hormone helps in regulating sugar level in the blood.

30. What is the function of receptors in our body? Think of situation where receptors do not work properly. What problems are likely to arise?
Answer. Receptors are present in our all parts of the body for example in skin, eye, nose tongue etc. They detect the signals and then send them to brain in the form of electrical signals. If these receptors are damaged then it they will not detect the input which leads to the harm for our body in dangerous situation.

Very Short Answer Type Questions [1 Mark] -Year 2010

31. How is the spinal cord protected in the human body?
Answer.Spinal cord is enclosed in a bony cage called vertebral column.

32. A potted plant is made to lie horizontally on the ground. Which part of the plant will show
(i) positive geotropism?
(ii) negative geotropism?
Answer.
(i) Root (ii) Shoot.

33. Mention the function of the hind-brain in humans.
Answer.Hind brain controls respiration, cardio-vascular reflexes and gastric secretions.
It also modulates the motor commands initiated by the cerebrum.

34. Mention the function of adrenaline hormone.
Answer. Adrenaline hormone is released into the blood from the adrenal gland during stimulation of the nervous system on seeing any adverse situation of fight or fright, it:

  1. increases the blood pressure.
  2. increases heart beat rate.
  3. increases breathing rate.
  4. diverts blood to essential organs including the heart, brain and skeletal muscles by dilating their blood vessels and constricting those of less essential organs, such as the skin and digestive system.

Short Answer Type Questions[l] [2 Marks] -Year 2010

35. Name, the two main organs of our central nervous system. Which one of them plays a major role in sending command to muscles to act without involving thinking process? Name the phenomenon involved.
Answer.The two main organs of CNS are brain and spinal cord.
Spinal cord plays a major role in sending command to muscles to act without involving thinking process. This phenomenon is called reflex action.

36.Name the hormone secreted by human testes. State its functions.
Answer. Testes secrete male sex hormone called testosterone. The function of testosterone is to regulate male accessory sex organs and secondary sexual characters like moustache, beard and voice.

37.Name and explain the function of the hormone secreted by the pituitary gland in humans.
Answer. Hormones secreted by pituitary gland alongwith their functions are:

  1. Grpwth hormone: It regulates growth and development ofbones and muscles.
  2. Trophic hormone: It regulates secretion of hormones from other endocrine glands.
  3.  Prolactin hormone: It regulates the function of mammary glands in females.
  4.  Vasopressin hormone: It regulates water and electrolyte balance in the body,
  5. Oxytocin hormone : It regulates ejection of milk during lactation.

Short Answer Type Questions[ll] [3 Marks] -Year 2010

38.What is a reflex action? Describe the steps involved in a reflex action.
Answer.
Reflex action: Jt is defined as an unconscious, automatic and involuntary response of effectors, i.e. muscles and glands, to a stimulus, which is monitored through the spinal cord.
Mechanism of reflex action : It involves the following steps:

  1. Receptor organ like skin perceives the stimulus and activates a sensory nerve impulse.
  2. Sensory organ carries message in the form of sensory impulse to the spinal cord.
  3. The spinal cord acts as modulator : The neurons of spinal cord transmit the sensory nerve impulse to motor neuron.
  4. Motor never conducts these impulses to the effectors like leg muscles which responds by pulling back the organ away from the harmful stimulus.

39.List the components of reflex arc in correct sequence. State in brief the role of brain in reflex action.
Answer. The reflex arc pathway is shown in the flow chart as follows:
The Reflex arc does not involve brain. It minimises the overloading of brain.
control-coordination-chapter-wise-important-questions-class-10-science-5

Very Short Answer Type Questions [1 Mark] -Year 2009

40. A young green plant receives sunlight from one direction only. What will happen to its shoots ?
Answer. Shoots will bend towards the light and roots away from the light.

41. Name the plant hormones which help/promote (i) cell division (ii) growth of
the stem and roots?
Answer. The plant hormones which help or promote:
(i) Cell division — Cytokinins
ii) Growth of the stem — Gibberellins

42. What is the function of thyroxine hormone in our body ? jlMluK r
Answer. Thyroxine hormone regulates the carbohydrate, protein and fat metabolism in the body so as to provide the best growth balance.

43. Name two tissues that provide control and coordination in multicellular animals.
Answer. The two tissues that provide control and coordination in multicellular animals are nervous and muscular tissues.

44. Which one of the following actions on touch is an example of chemical control?
(i) Movement on the touch-sensitive plant.
(ii) Movement in human leg.
Answer.
(i) Movement on the touch-sensitive plant.

Short Answer Type Questions[l] [2 Marks] -Year 2009

45.What are ‘nastic’ and ‘curvature’ movements? Give one example of each.
Answer. Nastic movements: These are non-directional movements which are neither towards nor away from the stimulus. Example: Dropping of leaves.
Curvature movements: In such movements plant organs move towards or away from the stimulus. Example: Bending of shoot towards a source of light.

46.Write the name and functions of any two parts of the human hind-brain.
Answer.Any two parts of human hind-brain with their functions are as follows:
(i) Cerebellum, which controls the coordination ofbody movement and posture. (ii) Medulla oblongata, which regulates the centre of swallowing, coughing, sneezing and vomiting.

47. What are plant hormones? Write two important functions of auxin. 
Answer. Plant hormones can be defined as a chemical substance which is produced naturally in plants and are capable of translocation and regulating one or more physiological processes when present in low concentration. .
Two important functions of auxin are that it promotes cell elongation, root formation, cell division, etc.

Short Answer Type Question[ll] [3 Marks] -Year 2009

48.(a) Name the two main constituents of the Central Nervous System in human beings.
(b) What is the need for a system of control and coordination in human
beings?
Answer.(a) The two main constituents of the Central Nervous System in human beings are the brain and the spinal cord.
(b) A living being does not live in isolation. It has to constantly interact with its external environment and has to respond properly for its survival. For example; when a hungry lion spots a deer, the lion has to quickly make a move so that it can have its food. On the other hand, the deer needs to quickly make a move to run for its life. The responses which a living being makes in relation to external stimuli are controlled and coordinated by a system; especially in complex animals. So, control and coordination . is essential in maintaining a state of stability and a steady state between the internal conditions of an organism and the external environment.

Important QuestionsNCERT SolutionsSample PapersNCERT Exemplar Solutions

The post Control and Coordination Chapter Wise Important Questions Class 10 Science appeared first on Learn CBSE.


Electricity Chapter Wise Important Questions Class 10 Science

$
0
0

Electricity  Chapter Wise Important Questions Class 10 Science

Important QuestionsNCERT SolutionsSample PapersNCERT Exemplar Solutions

Very Short Answer Type Questions [1 Mark] – Year 2015

1. Write S.I. unit of resistivity.
Answer. Ohm-metre (Ωm).

Short Answer Type Questions[ll] [3 Marks] – Year 2015

2.(i) Draw a closed circuit diagram consisting of a 0.5 m long nichrome wire XY, an ammeter, a voltmeter, four cells of 1.5 V each and a plug key.
(ii)Following graph was plotted between V and I values :
electricity-chapter-wise-important-questions-class-10-science-1
What would be the values of V /I ratios when the potential difference is 0.8 V, 1.2 V and 1.6 V respectively? What conclusion do you draw from these values?
Answer.
electricity-chapter-wise-important-questions-class-10-science-2

3.Study the following electric circuit and find (i) the current flowing in the circuit and (ii) the potential difference across 10 Ω resistor.
electricity-chapter-wise-important-questions-class-10-science-3
Answer.
electricity-chapter-wise-important-questions-class-10-science-4

4. Find the current drawn from the battery by the network of four resistors Shown in the figure.
electricity-chapter-wise-important-questions-class-10-science-5
Answer.
electricity-chapter-wise-important-questions-class-10-science-6

Long Answer Type Questions [5 Marks] – Year 2015

5. What is meant by electric current? Name and define its SI unit. In a conductor electrons are flowing from B to A. What is the direction of conventional current? Give justification for your answer.
A steady current of 1 ampere flows through a conductor. Calculate the number of electrons that flows through any section of the conductor in 1 second. (Charge on electron 1.6 X 10-19 coulomb).
Answer.

  • Electric Current: The amount of charge ‘Q’ flowing through a particular area of cross section in unit time ‘t’ is called electric current, i.e.
  • Electric current, I = Q/t
  •  SI unit of electric current is ampere.
  •  One ampere of current is that current which flow when one coulomb of electric charge flowing through a particular area of cross-section of the conductor in one second, i.e. 1A = 1 Cs-1.
  •  The direction of conventional current is A to B, i.e. opposite to the direction of flow of electrons. In a metal, flow of electrons carrying negative charge constitutes the current. Direction of flow of electrons gives the direction of electronic current by convention, the direction of flow of positive charge is taken as the direction of conventional current.
    Charge = q = ne
    electricity-chapter-wise-important-questions-class-10-science-7

6.What is meant by electrical resistivity of a material? Derive its S.I. unit. Describe an experiment to study the factor on which the resistance of a conducting wire depends.
Answer. Mathematically, resistivity of the conducting material is given by
p = R x A/J
If l = 1 m, A = 1 m2, then p = R
Hence, the resistivity of the material is defined as the resistance offered by a metallic wire having a unit length and a unit area of cross-section. Since unit length and unit area of cross-section forms a cube, the specific resistance or resistivity can also be defined as the resistance offered by a cube of a material of side 1 m when current flows perpendicularly through the opposite faces. In SI system, its units is
electricity-chapter-wise-important-questions-class-10-science-8
Experiment:
Aim : To study the factors on which resistance of conducting wires depends. Apparatus Required : A cell, an ammeter, nichrome wires of different length but same area of cross-section (thickness), nichrome wires of same length but different thickness, copper and iron wire of the same length and same thickness as that of any nichrome wire.
Procedure :

  1. Connect the cell, an ammeter and plug key in series with nichrome wire of length T (marked 1) in the gap XY as shown.
    electricity-chapter-wise-important-questions-class-10-science-9
  2. Close the key and note the reading of ammeter. It measures the current ‘I’through the nichrome wire (marked ‘1’).
  3. Replace the marked 1 wire with another nichrome wire having same area of cross-section (thickness) but of double length’2l’ (marked 2).
  4. Note the ammeter reading (I2) again after closing the key.
  5. Again replace the marked 2 wire with marked 3 wire which has the same length but is thicker than marked 1 and 2 nichrome wires. Again note down the current (I3) through this wire.
  6. Unplug the key. Remove marked 3 nichrome wire from the gap XY. Connect the copper wire marked 4 having same length and same area of cross-section as that of nichrome wire marked 1. .
  7. Plug the key again and note the ammeter reading. It measures the current (I4) through copper wire.
  8. Repeat the experiment with iron wire and measure the current (I5).

Observation :

  1. Current ‘ I’ is half ofI1 i.e., I2 =1/2 I1
  2. Current I3 increases when thicker wire of same length and of same material
    i. e., nichrome is used.
  3. Current I4 and I5 is different for copper and iron wire.

Conclusion :

  1. Different wires drew different amount of current from the same cell.
  2. First observation indicates that the resistance of the conductor increases with increase in length. So, resistance is directly proportional to length.
  3. Second observation shows that thicker wires have lesser resistance. So, resistance is inversely proportional to area of cross section of the wire.
  4. Third observation shows that resistance of the conductor depends on the nature of its material.

7. (a) Write two points of difference between electric energy and electric power. (6) Out of 60 W and 40 W lamps, which one has higher electrical resistance when in use.
(c) What is the commercial unit of electric energy? Convert it into joules.
Answer. (a) Difference between electric energy and electric power:
electricity-chapter-wise-important-questions-class-10-science-10
i.e. less the power of electrical device, higher is its electrical resistance.
(c) Kilowatt hour – Commercial unit of electrical energy
1 kWh = 1000 Wh = 1000 J/S x 3600 sec
= 3600000 J = 3.6 x106J

8.State Ohm’s law. Write the necessary conditions for its validity. How is this law verified experimentally? What will be the nature of graph between potential difference and current for a conductor? Name the physical quantity that can be obtained from this graph.
Answer. Ohm’s law : When the physical conditions such as temperature etc. remain same, the current flowing through the conductor is directly proportional to the potential difference applied across the ends of the conductor, i.e.,
electricity-chapter-wise-important-questions-class-10-science-11
Necessary condition for validity of Ohm’s law is that physical condition such as
temperature of the conductor remains same.
Procedure:
(i) Complete the circuit by connecting one cell in the gap XY. Plug the key.
electricity-chapter-wise-important-questions-class-10-science-12
(ii) Note the reading in the ammeter for the current I and in the voltmeter for the potential difference, (V) across the nichrome wire.
electricity-chapter-wise-important-questions-class-10-science-13
(v) Find the ratio of F to / for each observation.
(vi) Plot a graph between V (y-axis) and I (x-axis).
Observation :

  1. Voltmeter and ammeter reading increases as the number > of cells increase in series.
  2. Same value of V/I is obtained in each case.
  3.  V-I graph is a straight line passing through the origin of the graph as shown.
    electricity-chapter-wise-important-questions-class-10-science-14

Conclusion : Straight line nature of graph shows that the current is proportional to the potential difference. Hence, Ohm’s law verified. The slope of V-I graph gives the value of resistance of the conductor at the given temperature.

Very Short Answer Type Question [1 Mark] – Year 2014

9. Name a device that helps to maintain a potential difference across a conductor.
Answer. Cell or battery

Short Answer Type Questions [II] [3 Marks] – Year 2014

10.Define 1 volt. Express it in terms of SI unit of work and charge calculate the amount of energy consumed in carrying a charge of 1 coulomb through a battery of 3 V.
Answer.When 1 joule of work is done in carrying 1 coulomb of charge, from infinity to a point in the electric field, then potential at that point is called 1 volt. Potential difference between two points is
electricity-chapter-wise-important-questions-class-10-science-15

11. V-I graph for two wires A and B are shown in the figure. If both wires are of same length and same thickness, which of the two is made of a material of high resistivity? Give justification for your answer.
electricity-chapter-wise-important-questions-class-10-science-16
Answer. Greater than slope of V-I graph, greater will be the resistance of given metallic wire. In the given graph, wire A has greater slope then B. Hence, wire A has greater resistance.
For the wires of same length and same thickness, resistance depends on the nature of material of the wire, i.e.
electricity-chapter-wise-important-questions-class-10-science-17

Long Answer Type Questions [5 Marks] – Year 2014

12.Draw a labelled circuit diagram showing three resistors R1, R2 and R3 connected in series with a battery (E), a rheostat (Rh), a plug key (K) and an ammeter (A) using standard circuit symbol. Use this circuit to show that the same current flows through every part of the circuit. List two precautions you would observe while performing the experiment.
Answer.
electricity-chapter-wise-important-questions-class-10-science-18
Aim: Same current flows through every part of the above circuit.
Procedure:

  1. Connect ammeters, ‘A’1 between B and C, and ‘A2’ between D and E.
  2.  Adjust the sliding contact of the rheostat initially for a small current.
  3. Note all the ammeter readings. These reading give us current flowing through the resistors R1, R2 and R3
  4. The current in the circuit is now increased by changing the position of sliding contact J’ of the rheostat.
  5. Note all the ammeter readings each time.

Conclusion: Same reading of all the ammeter in each observation concluded that same current flows through every part of the circuit.

Precautions:

  1. All the connection should be tight and properly connected as per circuit diagram.
  2. The positive terminal of the ammeter and voltmeter must be connected to the positive terminal of the battery or battery eliminator.

13.Two wires A and B are of equal length and have equal resistance. If the resistivity of A is more than that of B which wire is thicker and why? For the electric circuit given below calculate:
electricity-chapter-wise-important-questions-class-10-science-19
(i) Current in each resistor,
(ii) Total current drawn from the battery, and
(iii) Equivalent resistance of the Circuit
Answer.
electricity-chapter-wise-important-questions-class-10-science-20
So, for different materials having same resistance per unit length, greater resistivity material wire has more cross-sectional area.
Hence, wire A is thicker than that of B.
(i) Current through each resistor
electricity-chapter-wise-important-questions-class-10-science-21
electricity-chapter-wise-important-questions-class-10-science-22

14. (a) Define electric power. Express it in terms of potential difference V and resistance R.
(b) An electrical fuse is rated at 2 A. What is meant by this statement?
(c) An electric iron of 1 kW is operated at 220 V. Find which of the following fuses that respectively rated at 1 A,3 A and 5 A can be used in it.
Answer.
(a) Electric power: It is the rate of doing work by an energy source or the rate at which the electrical energy is dissipated or consumed per unit time in the electric circuit is called electric power.
electricity-chapter-wise-important-questions-class-10-science-23
(b) It means, the maximum current will flow through it is only 2 A. Fuse wire will melt if the current exceeds 2 A value through it.
electricity-chapter-wise-important-questions-class-10-science-24

Very Short Answer Type Questions [1 Mark] – Year 2013

15. Write relation between heat energy produced in a conductor when a potential difference V is applied across its terminals and a current I flows through for ‘t’
Answer. Heat produced, H = VIt

16. State difference between the wire used in the element of an electric heater and in a fuse wire.
Answer. The wire used in the element of electric heater has a high resistivity and have a high melting point, i.e. even at a high temperature element do not burn while fuse wire have a low melting point and high resistivity.

Short Answer Type Questions [3 Marks] – Year 2013

17.The figure below shows three cylindrical copper conductors along with their face areas and lengths. Discuss in which geometrical shape the resistance will be highest.
electricity-chapter-wise-important-questions-class-10-science-25
Answer.
electricity-chapter-wise-important-questions-class-10-science-26

18.Find the current flowing through the following electric circuit.
electricity-chapter-wise-important-questions-class-10-science-27
Answer.
electricity-chapter-wise-important-questions-class-10-science-28

19. An electric bulb of resistance 200Ω draws a current of 1 Ampere. Calculate the power of the bulb the potential difference at its ends and the energy in kWh consumed burning it for 5h.
Answer. Power of the bulb,
electricity-chapter-wise-important-questions-class-10-science-29

Long Answer Type Questions [5 Marks] – Year 2013

20. (a) Calculate the resistance of 1 km long copper wire of radius 1 mm. Resistivity of the copper is 1.72 x 10-8 Ω m.
(b) Draw a schematic diagram of a circuit consisting of a battery of 4 cells of
2V each connected to a key, an ammeter and two resistors of 2 Ω and
3 Ω respectively in series and a voltmeter to measure potential difference across 3
Answer.
electricity-chapter-wise-important-questions-class-10-science-30

21.When a high resistance voltmeter is connected directly across a resister its reading is 2 V. An electric cell is sending the current of 0.4 A, (measured by an ammeter) in the electric circuit in which a rheostat is also connected to vary the current.
(a) Draw an equivalent labelled circuit for the given data.
(b) Find the resistance of the resister.
(c) Name and state the law applicable in the given case. A graph is drawn between a set of values of potential difference (V) across the resister and current (I) flowing through it. Show the nature of graph thus obtained.
Answer.
electricity-chapter-wise-important-questions-class-10-science-31
(c) Ohm’s law : When the physical conditions such as temperature etc. remain same, the current flowing through the conductor is directly proportional to the potential difference applied across the ends of the conductor, i.e.,
electricity-chapter-wise-important-questions-class-10-science-32
where R is constant of proportionality and is called resistance of the wire. Since current varies linearly with potential difference, the graph between V and I will be a linear in nature as shown
electricity-chapter-wise-important-questions-class-10-science-33

Short Answer Type Questions[l] [2 Marks] – Year 2012

22. How much current will an electric bulb draw from 220 V source if the resistance of the bulb is 1200? If in place of bulb, a heater of resistance 100 Ω is connected to the sources, calculate the current drawn by it.
Answer.
electricity-chapter-wise-important-questions-class-10-science-34

23.Draw a schematic diagrams of an electric circuit comprising of 3 cells and an electric bulb, ammeter, plug-key in the ON mode and another with same components but with two bulbs in parallel and a voltmeter across the combination.
Answer.
electricity-chapter-wise-important-questions-class-10-science-35

24. Out of the two wires X and Y shown below, which one has greater resistance? Justify your answer.
electricity-chapter-wise-important-questions-class-10-science-36
Answer. Wire ‘Y’ has greater resistance as it has more length than wire ‘X’. It is because resistance of wire is directly proportional to the length of wire.

Short Answer Type Questions[ll] [3 Marks] – Year 2012

25. Two identical wires one of nichrome and other of copper are connected in series and a current (I) is passed through them. State the change observed in the temperatures of the two wires. Justify your answer. State the law which explains the above observation.
Answer. The resistivity of nichrome is more than that of copper so its resistance is also high. Therefore, large amount of heat is produced in the nichrome wire for the same current as compared to that of copper wire. Accordingly, more change in temperature is observed in the nichrome wire. This is explained by Joule’s law of heating.
Joule’s law of heating: It states that the amount of heat produced in a conductor is
electricity-chapter-wise-important-questions-class-10-science-37

26.An electric bulb is rated at 60 W, 240 V. Calculate its resistance. If the voltage drops to 192 V, calculate the power consumed and the current drawn by the bulb. (Assume that the resistance of the bulb remain unchanged.)
Answer.
electricity-chapter-wise-important-questions-class-10-science-38
Current drawn by bulb at 192 V is

Long Answer Type Questions [5 Marks] – Year 2012

27. Three bulbs each having power P are connected in series in an electric circuit. In another circuit, another set of three bulbs of same power are connected in parallel to the same source.
(i) Will the bulbs in both the circuits glow with the same brightness? Justify your answer.
(ii) Now let one bulb in each circuit get fused. Will the rest of the bulbs continue to glow in each circuit? Give reason.
(iii) Representing each bulb by a resistor, draw circuit diagram for each case.
Answer.
(i) Bulbs in parallel provide more illumination. This is because
(a) each bulb gets same voltage and is equal to the applied voltage.
(b) each bulb draws required current from the mains. Hence, they work properly.
(ii)When one bulb in each circuit get fused,
In series: Rest of the bulbs will not glow. This is because in series arrangement, there is only a single path for the flow of current.
In parallel: Rest of the bulbs will continue to glow as in parallel connection,
(a) individual branch in the circuit completes its own circuit, or
(b) different paths are available for the flow of current.
(iii) Circuit diagram
electricity-chapter-wise-important-questions-class-10-science-39

28. (a) Though same current flows through the electric line wires and the filament of bulb, yet only the filament glows. Why?
(b) The temperature of the filament of bulb is 2700°C when it glows. Why does it not get burnt up at such high temperature?
(c) The filament of an electric lamp, which draws a current of 0.25 A is
used for four hours. Calculate the amount of charge flowing through the
circuit.
(d) An electric iron is rated 2 kW at 220 V. Calculate the capacity of the fuse
that should be used for the electric iron.
Answer. (a) Electric line wires offer extremely low resistance to the flow of current, so
they do not glow because negligible heat is produced in it.
The filament of bulb glows because it becomes red hot due to large amount of
heat produced, as it offers high resistance to the flow of current through it.
(b) The filament of bulb when it glows at 2700°C does not get burnt because the tungsten metal of filament has
(i) a very high melting point (of 3380°C) and
(ii) a high resistivity.
electricity-chapter-wise-important-questions-class-10-science-40
(c) Given: I = 0.25 A, t = 4 h = 4 x 60 x 60 sec.
So, amount of charge flowing the filament of electric lamp
So, the capacity of the fuse that should be used for the electric iron is of the order of 10 A.

29.
electricity-chapter-wise-important-questions-class-10-science-41
In the given circuit, connect a nichrome wire of length ‘L’ between points X and Y and note the ammeter reading.
(i) When this experiment is repeated by inserting another nichrome wire of the same thickness but twice the length (2L), what changes are observed in the ammeter reading?
(ii) State the changes that are observed in the ammeter reading if we double the area of cross-section without changing the length in the above experiment. Justify your answer in both the cases.
(b) “Potential difference between points A and B in an electric field is 1 V”. Explain the above statement.
electricity-chapter-wise-important-questions-class-10-science-42
Answer. (a)(i) Ammeter reading in the second case is half of the ammeter reading
in first case. This is because
=> i.e. when length is doubled, the resistance is doubled, this means the current is halved.
(ii) On doubling the area of cross-section without changing the length of the conductor, twice of the previous reading is observed in the ammeter. This is because
So, when A is double, resistance becomes half, current will be doubled. (b) “Potential difference between points A and B in an electric field is 1 V”. It means 1 J work is done in moving 1 C of charge from point B to point A in an electric field.

Very Short Answer Type Questions [1 Mark] – Year 2011

30. How is an ammeter connected in a circuit to measure current flowing through it?
Answer. In series

31. What happens to resistance of a conductor when its area of cross-section is increased?
Answer.
electricity-chapter-wise-important-questions-class-10-science-43

32. A given length of a wire is doubled on itself and this process is repeated once again. By what factor does the resistance of the wire change?
Answer. Am. Length becomes one-fourth of the original length and area of cross-section becomes four times that of original.
electricity-chapter-wise-important-questions-class-10-science-44
So, new resistance is (1/16)th of original resistance.

Short Answer Type Questions[l] [2 Marks] – Year 2011

33.A 9Ω resistance is cut into three equal parts and connected in parallel. Find the equivalent resistance of the combination.
Answer.
electricity-chapter-wise-important-questions-class-10-science-45

34.An electric iron has a rating of 750 W, 220 V. Calculate the (i) current flowing through it, and (ii) its resistance when in use.
Answer.
electricity-chapter-wise-important-questions-class-10-science-46

35.(a) What do the following circuit symbols represent?
electricity-chapter-wise-important-questions-class-10-science-47
(b) The potential difference between the terminals of an electric heater is 60 V when it draws a current of 4 A from the source. Find the resistance of heater when in use.
Answer.
(a) (i) Wires crossing without touching each other.
(ii) Rheostat/Variable resistor
(b) Given: V = 60 V, I = 4 A, R = ?
From Ohm’s law, V = IR
60 = 4 x R = 15 Ω

36.The charge possessed by an electron is 1.6 X 10-19 coulombs. Find the number of electrons that will flow per second to constitute a current of 1 ampere.
Answer.
electricity-chapter-wise-important-questions-class-10-science-48

37.Explain the role of fuse in series with any electrical appliance in an electric circuit. Why should a fuse with defined rating for an electric circuit not be replaced by one with a larger rating?
Answer. Fuse wire is a safety device connected in series with the live wire of circuit. It has high resistivity and low melting point. It melts when a sudden urge of large current passes through it and disconnects the entire circuit from the electrical supply. But, in case if we use a larger rating instead of a defined rating, then it will not protect the circuit as high current will easily pass through it and it will not melt.

38.The wattage of a bulb is 24 W when it is connected to a 12 V battery. Calculate its effective wattage if it operates on a 6 V battery (Neglect the change in resistance due to unequal heating of the filament in the two cases).
Answer.
electricity-chapter-wise-important-questions-class-10-science-49

39.Consider the following circuit diagram. If R1 = R2 =R3 = R4= R5 = 3 Ω, find the equivalent resistance(Rs) of the circuit.
electricity-chapter-wise-important-questions-class-10-science-50
Answer.
electricity-chapter-wise-important-questions-class-10-science-51

Short Answer Type Questions[ll] [3 Marks] – Year 2011

40. A torch bulb is rated 2.5 V and 750 mA. Calculate (i) its power, (ii) its resistance and (iii) the energy consumed, if this bulb is lighted for four hours.
Answer.
electricity-chapter-wise-important-questions-class-10-science-52

41.Series arrangements are not used for domestic circuits. List any three reasons.
Answer. Series arrangements are not used for domestic circuit because

  1.  The electrical appliances need current of widely different values to operate properly.
  2. In series arrangement, when one component fails, the circuit is broken and none of the components works.
  3. All electrical appliances work at a constant voltage. But in series circuit, the current is constant throughout the electric circuit and potential is different across the different components. So, series arrangement is not suitable for domestic circuits.

42.Name the physical quantity which is (i) same (ii) different in all the bulbs
when three bulbs of:
(a) same wattage are connected in series.
(b) same wattage are connected in parallel.
(c) different wattage are connected in series.
(d) different wattage are connected in parallel.
Answer. (a) For identical bulbs in series- same current, same potential difference.
(b) For identical bulbs in parallel- same potential difference, different current.
(c) For unidentical bulbs in series- same current, different potential difference.
(d) For unidentical bulbs in parallel- different current, same potential difference.

43. Two devices of rating 44 W, 220 V and 11 W, 220 V are connected in series. The combination is connected across a 440 V mains. The fuse of which of the two devices is likely to burn when the switch is ON? Justify your answer.
Answer.
electricity-chapter-wise-important-questions-class-10-science-53

44.Five resistors are connected in a circuit as shown. Find the ammeter reading when circuit is closed.
electricity-chapter-wise-important-questions-class-10-science-54
Answer.
electricity-chapter-wise-important-questions-class-10-science-55
electricity-chapter-wise-important-questions-class-10-science-56

45.Study the circuit shown in which three identical bulbs B1, B2 and B3 are connected in parallel with a battery of 4.5 V.
(i) What will happen to the glow of other two bulbs if the bulb B3 gets fused?
(ii) If the wattage of each bulb is 1.5 W, how much reading will the ammeter A show when all the three bulbs glow simultaneously?
(iii) Find the total resistance of the circuit.
electricity-chapter-wise-important-questions-class-10-science-57
Answer.
(i) The glow of other two bulbs remains the same.
(ii)In parallel combination, potential difference across each resistance will remain same.
electricity-chapter-wise-important-questions-class-10-science-58
So, potential across each bulb = 4.5 V
electricity-chapter-wise-important-questions-class-10-science-59
Wattage of each bulb = 1.5 W
Therefore, when all the three bulbs glow simultaneously, the ammeter A shows 1 A reading.
(iii) Potential difference across each bulb = 4.5 V Wattage of each bulb = 1.5 W
.’. Resistance of

46.A circuit is shown in the diagram given below.
(a) Find the value of R.
(b) Find the reading of the ammeter.
(c) Find the potential difference across the terminals of the battery.
electricity-chapter-wise-important-questions-class-10-science-60
Answer.
(a) Potential difference across 6Ω = 12 V
.’. Current through 6 Ω,

47.Consider the circuit shown in the diagram. Find the current in 3Ω resistor.
Answer.
electricity-chapter-wise-important-questions-class-10-science-64
electricity-chapter-wise-important-questions-class-10-science-61

48.Study the I-V graph for four conductors A, B, C and D having resistance RA,RB, Rc and RD respectively, and answer the following questions:
electricity-chapter-wise-important-questions-class-10-science-62
(i) Which one of these is the best conductor?
(ii) f all the conductors are of same length and same material, which is the thickest?
(iii)If all the conductors are of same thickness and of same material, which is the longest?
(iv)If the dimensions of all the conductors are identical, but
their materials are different which one would you use as (a) resistance wire (b) connecting wire?
(v) Which one of the following relations is true for these conductors?
electricity-chapter-wise-important-questions-class-10-science-81
(vi) If conductors A and B are connected in series and I-F graph is plotted for the combination, its slope would be
(a) less than that of A. (b) more than that of A.
(c) between A and B. (d) more than that of D.
(vii)If conductors C and D are connected in parallel and I-V graph is plotted for the combination, its slope would be
(a) lesser than that of A. (b) more than that of D.
(c) between C and D. (d) between B and C.
Answer.
electricity-chapter-wise-important-questions-class-10-science-80
(iii)Resistance oC length. So, A is the longest.
(iv)(a) Resistance wire – A (b) Connecting wire – D
(v) Option (a) is correct.
(vi)(a) In series, resistances are added. (Rs =RA + RB). So, in the given I-V
graph, slope of series combination would be less than that of A.
(vii)(b) In parallel combination, the equivalent resistance is less than the least
value resistance in the circuit. So, in the given I-V graph, slope for parallel combination is more than that of D

Short Answer Type Question[l] [2 Marks] – Year 2010

49. In an experiment to study the relation between the potential difference across a resistor and the current through it, a student recorded the following observations:
electricity-chapter-wise-important-questions-class-10-science-63
On examine the above observations, the teacher asked the student to reject one set of readings as the values were out of agreement with the rest. Which one of the above sets of readings can be rejected? Calculate the mean value of resistance of the resistor based on the remaining four sets of readings.
Answer. The third reading for V = 3.0 volt and I — 0.6 A will be rejected as it has larger deviation from the rest of the readings.
The value of resistance in the other four observations will be I (using R = V/I) 10Ω, 11 Ω, 10 Ω and 10.67 Ω.
So, the mean value of resistance = 41.67/4 = 10.417 = 10.42 Ω

Long Answer Type Questions [5 Marks] – Year 2010

50. Explain with the help of a labelled circuit diagram, how will you find the resistance of a combination of three resistors, of resistance R1, R2 and R3 joined in parallel. Also mention how will you connect the ammeter and the voltmeter in the circuit while measuring the current in the circuit and the potential difference across one of the three resistors of the combination.
Answer. Parallel Combination:

  1.  Connect the three given resistor R1, R2 and R?i in parallel between the point XY with a battery, a plug key and ammeter in series as shown in figure.
    electricity-chapter-wise-important-questions-class-10-science-65
  2. Connect voltmeter in parallel with these resistors between the terminals X and Y.
  3. Close the key and note the ammeter and voltmeter reading. Ammeter shows the total current drawn by the parallel combination of these resistors while voltmeter shows the voltage applied across the combination.
  4. Using Ohm’s law, find the equivalent resistance of the combination, i.e. equivalent resistance,
    electricity-chapter-wise-important-questions-class-10-science-66

To find the current flow through any one of the resistor, ammeter will be connected in series with that resistor and to measure the potential difference across that resistor, voltmeter must be connected in parallel with that resistor as shown.
electricity-chapter-wise-important-questions-class-10-science-67

51. Derive the expression for the heat produced due to a current T flowing for a time interval ‘£’ through a resistor ‘R’ having a potential difference ‘V’ across its ends. With which name is the relation known? How much heat will an instrument of 12 W produce in one minute if it is connected to a battery of 12 V?
Answer. Heat produced in a conductor: Consider a wire AB having a resistance ‘R’ connected across the terminals of a cell. Let V be the potential difference applied by cell across the ends of a wire.
electricity-chapter-wise-important-questions-class-10-science-68
Let W be the work done in carrying the charge q across the conductor, then
electricity-chapter-wise-important-questions-class-10-science-69

52.Deduce the expression for the equivalent resistance of the parallel combination of three resistors R1, R2 and R3
Consider the following electric circuit:
electricity-chapter-wise-important-questions-class-10-science-70
(a) Which two resistors are connected in series?
(b) Which two resistors are connected in parallel?
(c) If every resistor of the circuit is of 2 Ω, what current will flow in the circuit?
Answer. Consider the following parallel circuit shown below: Let I1, I2 and I3 be the current flow through the resistor R1, R2 and R3 connected in parallel.
Using Ohm’s law, current through each resistor is
electricity-chapter-wise-important-questions-class-10-science-71
electricity-chapter-wise-important-questions-class-10-science-72

Very Short Answer Type Questions [1 Mark] – Year 2009

53. Two resistors of 10 Ω and 15 Ω are connected in series to a battery of 6 V. How can the values of current passing through them be compared?
Answer. In series, same current flows through each resistor. So, ratio of current is 1 : 1.

54, A wire of resistance 20 Ω is bent to form a closed square. What is the resistance across a diagonal of the square?
Answer.
electricity-chapter-wise-important-questions-class-10-science-73

Short Answer Type Questions[l] [2 Marks] – Year 2009

55.Draw a schematic diagram of an electric circuit consisting of a battery of five 2 V cells, a 20 Ω resistor, a 30 Ω resistor, a plug key, all connected in series. Calculate the value of current flowing through the 20 Ω resistor and the power consumed by the 30 Ωresistor.
Answer. Req = 20 + 30 = 50 Ω
electricity-chapter-wise-important-questions-class-10-science-74
Current through both 20 Ωand 30 Ω= I =10/50
= 0.2 A
Power consumed by 30 Ω = I2R = (0.2)2 x 30=1.2W

56. A piece of wire of resistance 20 Ω is drawn out so that its length is increased to twice its original length. Calculate the resistance of the wire in the new Situation.
Answer.
electricity-chapter-wise-important-questions-class-10-science-75

57. What is an electric circuit? Distinguish between an open and a closed circuit.
Answer. An arrangement for maintaining the continuous flow of electric current by the electrical energy source through the various electrical components connected with each other by conducting wires is termed as electric circuit.
An open circuit does not carry any current, while a closed circuit carries current.

Short Answer Type Questions[ll] [3 Marks] – Year 2009

58. Two resistors with resistances 5Ω and 10 Ω are to be connected to a battery of emf 6 V so as to obtain:
(i) minimum current
(ii) maximum current
(a) How will you connect the resistances in each case ?
(b) Calculate the strength of the total current in the circuit in the two cases.
Answer.
(a) As current is inversely proportional to resistance for the same voltage. So, to get maximum current, the equivalent resistance has to be less. This means the resistors must be connected in parallel.
To get minimum current, the equivalent resistance has to be greater as
electricity-chapter-wise-important-questions-class-10-science-76

59.(a) Define the term ‘volt’.
(b) State the relation between work, charge and potential difference for an electric circuit.
Calculate the potential difference between the two terminals of a battery if 100 J of work is required to transfer 20 C of charge from one terminal of the battery to the other.
Answer.
(a) When 1 joule of work is done in carrying 1 coulomb of charge, from infinity to a point in the electric field, then potential at that point is called 1 volt.
(b) Potential difference, V = Work done on unit charge =W/q

Work is 100 J,q=20C
Potential difference,V=W/q=100/20=5V

60.(a) Define the term ‘coulomb’.
(b) State the relationship between the electric current, the charge moving through a conductor and the time of flow.
Calculate the charge passing through an electric bulb in 20 minutes if the value of current is 200 mA.
Answer.
electricity-chapter-wise-important-questions-class-10-science-77
(a) When 1 A current flows across the wire in 1 second, the charge transfer across its ends is said to be 1 coulomb.
(b) The relationship between the electric current I, the charge q and time t is

61.(a) How is the direction of electric current related to the direction of flow of electrons in a wire?
(b) Calculate the current in a circuit if 500 C of charge passes through it in 10 minutes.
Answer.
(a) Conventional direction of electric current is opposite to the direction of flow of electrons in a wire.
(b) q = 500 C, t = 10 X 60 = 600 s
I = 500/600 = 5/6A

Long Answer Type Question [5 Marks] – Year 2009

62.(a) Two resistors R1and R2 may form (i) a series combination or (ii) a parallel
combination, and the combination may be connected to a battery of 6 volts. In which combination, will the potential difference acrossR1 and across R2 be the same and in which combination, will the current through R1 and through R2 be the same?
(b) For the circuit shown in this diagram, calculate
electricity-chapter-wise-important-questions-class-10-science-78
(i) the resultant resistance.
(ii) the total current.
(iii) the voltage across 7 Ω resistor.
Answer. (a) Potential difference across R1 and R2 is same in parallel combination of R1 and R2 and the current through R1 and R2 will be same when they are connected in series.
electricity-chapter-wise-important-questions-class-10-science-79

Download Formula BookPhysics eBookChemistry eBookBiology eBook

The post Electricity Chapter Wise Important Questions Class 10 Science appeared first on Learn CBSE.

NCERT Solutions for Class 10 Foundation of Information Technology – Introduction to XML

$
0
0

NCERT Solutions for Class 10 Foundation of Information Technology – Introduction to XML

Foundation of ITMathsScienceSocialEnglishHindiSanskritRD Sharma

Very Short Answer Type Questions [1 Mark each]

Question 1. What do you mean by XML file?
Answer: XML file or XML document is a component of XML document system which contains the real data and its semantics.

Question 2. List the components of prolog.
Answer:

  1. An XML Declaration
  2. Processing Instructions (PI)
  3. Document Type Definition (DTD)
  4. Comments
  5. White Spaces and New line

Question 3. By which we can describe the properties of elements?
Answer: The properties of elements can be described through attributes.

Question 4. Write the components of an XML file in terms of logical structure.
Answer: An XML file contains:

  1. an optional prolog
  2. a data instance

Question 5. How will you define an element in DTD contain plain text?
Answer: If an element should contain plain text, you define the element using #PCDATA. PCDATA stands for Parsed Character Data and is the way you specify non-markup text in your DTDs.

Question 6. What does XML parser do?
Answer: An XML parser basically checks whether a document is following XML standard or not.

Question 7. Which document is used to define the style of an XML document?
Answer: CSS is a text document (or stylesheet) that is commonly used to define the style and layout of an XML document.

Question 8. Can same CSS document be used in multiple XML documents?
Answer: Yes, the same CSS document can be used in multiple XML documents.

Question 9. Explain the usage of an XML parser. CBSE 2011
Answer: XML parser is a software used to read, write and update to an XML document. An XML parser converts an XML document into an XML DOM object.

Short Answer Type Questions [2 & 3 Marks each]

Question 1. What does it mean when we say that XML tags are case sensitive?
Answer: The case sensitivity of XML tags means, the opening and closing tags must be in the same case. The following codes is an example of a well-formed document, where the opening and closing tags are in the same case, i.e.
<Name>Amit </Name>

Question 2. List the important points to create an XML document.
Answer: The points while creating an XML documents are as follows:

  1. XML documents must have starting and closing tags.
  2. XML tags are case sensitive.
  3. XML elements must be properly nested.
  4. XML documents must have one root element.
  5. The values of XML attributes must be enclosed in double quotes.

Question 3. Explain the utility of comments in XML.
Answer: A comment is a note or information that appears in the code of an XML document to help you understand the code better.
Comments are not displayed in the output. They are not part of the program and therefore, are not parsed by the XML parser.

Question 4. State whether the following XML document is well-formed or not
<Student> Mapoj </Student>
<Student> Ankur</Student>
Answer: The preceding XML document is not well-formed because it contains two root elements. An XML document contains only one root element.

Question 5. Name some languages, which are derived from XML.
Answer: Some languages are as follows:

  1. Ink Markup Language (InkML)
  2. Business Narrative Markup Language (BNML)
  3. Financial Product Markup Language (FPML)
  4. Virtual Human Markup Language (VHML) .
  5. Architecture Description Markup Language (ADML)
  6. Artificial Intelligence Markup Language (AIML)
  7. Chess Markup Language (ChessML) etc.

Question 6. Define prolog and data instance.
Answer: The prolog is a preface or introduction to XML document. It can contain upto five optional components. The grammar structure of the XML document is defined under prolog. The data instance consists of real data and its description through elements. It is also known as body of XML document.

Question 7. Create XML markup to represent a message sent on 7 June, 2014 to Amit and Saurabh by Mohit. The message is “Submitted Successfully”.
Answer:

<?xml version = "1.0"?>
<message date="7/6/2014">
<sender> Mohit </sender>
<receiversXreceiver> Amit </receiver>
<receiver> Saurabh </receiver> </receivers>
<text> Submitted Successfully </text>
</message>

Question 8. Write the procedure to link a stylesheet with an XML document.
Answer: Using CSS with an XML Document
To link an XML document with a stylesheet perform the following steps:

  1. Create an XML document and save it as a file with the .xml extension.
  2. Create a stylesheet and save it as a file with the .css , extension.
  3. Link both the files in the XML document by using the PI.
    <?xml-stylesheet href = “test.css” type = “text/css”?>
e.g. The following is the CSS document: 
People
{
background-color : light green; 
display : block; 
padding : 5px; 
font-family : arial;
}
Person
{
background-color : pink; 
border : 2px solid black; 
display : block; 
margin-bottom : 5px;
Name
{
font-family : bold; 
display : block;
}
Birthdate 
{
display : block;
}
Eyes
{
display : block;
}
Now, save it as test.css
The following is the XML document:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type = "text/css" href = "test.css"?>
<People>
<Person>
<Name>A</Name>
<Birthdate>Jan 24, 1987</Birthdate>
<Eyes>Blue</Eiyes>
</Person>
<Person>
<Name>B</Name>
<Birthdate>Dec 15, 2009</Birthdate>
< Eyes >Brown</Eyes >
</Person>
</People>
Now, save it as test1.xml

Question 9. What do you mean by Processing Instructions (PI)?
Answer: PI can be used to pass information to applications in such a way that escapes most XML rules. Its main use is of linking to an XML stylesheet in the prolog of an XML document. Processing instructions do not have to follow much internal syntax, it can include markup characters without escaping them and can appear anywhere in the document.
ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-1

Question 10. Explain child elements with an example.
Answer: The elements nested inside other elements are called child elements.
Consider the following code:

NCERT Solutions for Class 10 Foundation of Information Technology

Question 11. Write the full form of          CBSE 2014

  1. XML
  2. DTD
  3. SGML
  4. CSS

Answer: Full form of given terms are as follows:

  1. XML extensible Markup Language
  2. DTD Document Type Declaration
  3. SGML Standardised Generalised Markup Language
  4. CSS Cascading Style Sheet

Long Answer Type I Questions  [5 Marks each]

Question 1. Explain two softwares which are used to validate XML documents.
Answer: Two important software that validate or process XML documents are as follows:

  1. XML Validator are the software packages that check the XML document as per the specified DTD and give you feedback about the document.
    Some XML validators are as follows:
    (a) W3C XML Validator
    (b) Tidy
    (c) XML. com’s
    (d) Brown University
  2. XML Parsers are the software packages, which are part of bigger applications that provide XML support.
    The role of an XML parser is to dissect a valid XML document to obtain actual data from the XML document. Some XML parsers are as follows:
    (a) SAXfSimple API for XML)
    (b) Expat
    (c) LT-XML etc.

Question 2. Write an XML document that marks up the following data:
All these must be rendered. Use attribute to make the data more informative.
ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-2
Answer:

<?xml version = "1.0" encoding="UTF-8" standalone = "yes"?>
<employees>
<employee EmpID = "e001">
<Name> Raj Kumar </Name>
<City> Delhi </City></employee>
<employee EmpID="e002">
<Name> Pankaj </Name>
<Ci ty> Mumbai </City></employee>
<employee EmpID="e003">
<Name> Rahul Sharma </Name>
<City> Delhi </City> </employee>
<employee EmpID="e004">
<Name> Praveen </Name>
<City> Noida </City></employee>
</employees>

Question 3. Compare XML with similar type of other languages.
Answer:

1. Comparing XML and SGML

XML SGML
XML is a markup language. SGML is a meta language used to define and describe generic markup language.
It does not include complex and optional features of SGML. It is complex and requires overheads to use it.
XML allows creation of new  tags to describe and present  your data. It is an ISO standard for specifying a set of tags,
XML allows data validation. SGML does not allow data validation.
It describes the data and transfers data between applications. It allows you to define and create platform-independent files.

2. Comparing HTML and XML

HTML XML
HTML tags are predefined. XML tags are not predefined.
HTML is case insensitive. XML is case sensitive.
HTML is markup language that creates the form and appearance of the Web page. XML is neither a programming nor a presentation language.

3. Comparing EDI and XML

EDI XML
EDI (Electronic Data Interchange) is a collection of standards, formats and file layout. XML is an emerging standard designed to simplify Web-based E-Commerce transactions between computer application.
EDI enables highly secure document exchanges. XML document typically needs to be encrypted to maintain security level.
EDI documents are sent via private and relatively expensive Value Added Networks (VANs). XML documents are generally sent via the Internet.
EDI does not processes low transaction values. XML processes relatively low transaction values.
EDI allows companies to exchange electronic documents quickly between their trading partners. XML allows you to create custom tags to present your document in a structured format.

Question 4. Consider the following XML document.
Check this for well- formedness.

<Employees><FirstName> Ambrish
<MiddleName> Kumar</FirstName>
</MiddleName>
<lastname> Garg </LastName>
</Employees>

Answer:

The above XML document is not well-formed.
The document suffers from two errors which are as follows:

  1. Improper nesting The MiddleName element is opened inside the FirstName element, yet MiddleName is not closed before the FirstName element is closed.
  2. Mismatched cases of start and end tags The tag <lastname> is closed with </LastName>, which is incorrect. XML is case sensitive, thus the end tag of <lastname> should be </lastname>.

Question 5. Explain the structure of XML document.
Answer: Structure of XML- File/Document
Every XML document includes both physical and logical structure which are as follows:

1. Physical Structure
It contains the actual data used in a document. The basic storage unit called entity, each of which may refer to other entities. An entity has a name and content. It contains references to other entities. There is a special entity called document entity or root, that serves as a main storage unit. XML processor always start document processing from that unit.
We have three classifications of entities, these are as follows:

  1. Internal and External Entities
    For internal entity, there is no separate physical storage object and the content of the entity is given in the declaration. It contained inside the document. If the entity is not internal, then it is an external entity.
  2. General and Parameter Entities
    General entities are entities which are used within the document content. In this specification, general entities are sometimes referred to with the unqualified entity, when this leads to no ambiguity. Generally, entities are declared and used differently. Parameter entities are parsed and used only in the DTD part of the XML document.
  3. Parsed and Unparsed Entities
    Parsed entities contain text that is referred as replacement text intended to be processed by the parser and is considered as an integral part of the document. Unparsed entities are resources that can be of any type including text objects. This type of entity is never process by parser.

2. Logical Structure
It is a template that enables the elements to be included in a document and in the order in which they have to be included.
The logical structure includes the basic components of the XML document. It indicates how a document is built, irrespective of what a document contains. The first structural element is prolog which is the base for the logical structure.
The structure of the document of example code:
ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-3

Question 6. A well-formed document must have a root element. Explain with an example.
Answer: To create a well-formed XML document, it is necessary for it to have a root element. A root element is a unique element that contains all other elements in the XML document.
The XML document cannot contain more than one root element.
The following code is an example of a well-formed document:

<address>
<city> Delhi </city>
<state> Delhi </state>
<country> India </country>
</address>
Consider the same code written in the following way: 
<city> Delhi </city>
<state> Delhi </state>
<country> India </country>
The preceding code is not a well-formed document, since it does not contain a root element.

Question 7. Explain the difference between a well-formed and a valid XML documents. CBSE 2011
Answer:

1. Well-Formed XML Documents
A “Well-Formed” XML document means that document has the correct XML syntax.
The XML document that follows XML grammar rules is called well-formed document. A document that includes sequence of markup characters that cannot be parsed or are invalid cannot be well-formed. The following points are to be kept in mind for a valid XML document:

  1. The document must contain atleast one element
    ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-4
  2. The document must have a root element A root element is a unique element in the XML document, which contains the complete document.
    ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-5
  3. The element must have the opening and the closing tags To close a tag, you need to prefix the forward slash with the normal tag.
    ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-6
  4. XML tags must be closed properly There must be a proper closing tag. In XML, empty tags must end with a following slash.
    ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-7
  5. XML elements must be properly nested The parent element has to be opened before the child element and closed after the child element.
    ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-8
    This code is not well-formed because the root element (College) is closed before the parent element (Student).
  6. XML tags are case sensitive XML tags are case sensitive means the opening and ending tags must be in the same case.
    ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-9
  7. XML attribute values should be in double quotation marks The attribute value in an XML document should be enclosed in proper quotes.
    ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-10

2. Valid XML Document
A valid XML document is .not only a well-formed document but as well as they also checked error against a DTD or schema. DTD is a set of rules that defines what tags appear, what value those tags may contain and how the tags are related to each other in an XML document. Validation can be done only if the XML document has valid DTD. When an XML document is checked or parsed according to a particular structure or guidelines, the process is known as validation of the document.

Question 8. Define CSS. How to create a CSS file?
Answer: CSS is a simple design language intended to simplify the process of making Web pages presentable.
CSS is a type of stylesheet and this stylesheet consists of a list of rules. You can include a CSS in multiple XML documents that have the same data structure.

Syntax
selector
{
property: value; } Declaration Block
}

Creating a CSS File
To create a CSS file, you need to have all the style rules composed in it and save it with extension .css.
ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-11
You can define the color in CSS by name as well as by code like green color may be written as #008000 or rgb(0,128,0).
ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-12

Long Answer Type II Questions  [10 Marks each]

Question 1. Write two points of difference in HTML and XML. Write three points of well-formed XML document. Write the code to create an XML document to present following data: CBSE 2016
ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-13

Answer: Two points of difference between HTML and XML follows:

HTML XML
HTML is a markup language that creates the form and appearance of the Web page. XML is a text-based markup language for processing and displaying data in a structured format.
HTML documents are viewable in a browser. XML documents can be viewed only if proper stylesheet file is also available alongwith XML file.

Three points of well-formed XML document are as follows:

  1. The document must have a root element.
  2. The element must have the opening and closing tags.
  3. XML attributes values, should be in double quotation marks.
<?xml version ="1.0" encoding="UTF-8" standalone="yes"?>
<Data><Datal>
<Furniture>Table</Furniture>
<Material >Wood</Material >
<Quantity>75</Quantity>
<Floor>1st</Floor>
</Datal>
<Datal>
<Furniture>Chair</Furniture>
<Materi al >Plastic</Materi al >
<Quantity>85</Quantity>
<Floor>IInd</Floor>
</Datal>
</Data>

Question 2. XML document structure can be divided in which two parts? What is meant by valid XML document (write three points)? Write the code to create an XML document to present following data: CBSE 2014
ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-14

Answer: XML document structure can be divided into two parts as follows:

  1. Well-formed XML document
  2. Valid XML document

A valid XML document means to follow several terms, such as follows:

  1. It is not only a well-formed document but as well as check error against a DTD.
  2. It signifies that a document is well-formed.
  3. It uses XML parser, XML validator for validation.
The XML code is
<?xml version = "1.0" encoding = "UTF-8"?>
<Employees>
<Employee>
<Name> Srishti </Name>
<Job> Programmer </Job>
<Department> Engineering </Department>
<Cubicle> 5E </Cubicle>
</Employee>
<Employee>
<Name> Aditi </Name>
<Job> Designer </Job>
<Department> Marketing </Department>
<Cubicle> 19T </Cubicle>
</Employee>
</Employees>

Question 3. Write two points of differences between XML and HTML. What is meant by a well-formed XML document (write two points)? Write the code to create an XML document with following data: CBSE 2013
ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-15
Answer: The differences between XML and HTML are as follows:

  1. HTML has predefined tags while XML has user-defined tags.
  2. HTML document can be viewed directly by the Web browser while XML document cannot be viewed directly and need some proper stylesheet files.

A well-formed document means to follow several generic rules, such as follows:

  1. XML document must contain atleast one element.
  2. All tags must have the opening and closing tags as these XML tags are case sensitive.
The XML code is
<?xml version = "1.0" encoding = "UTF-8"?>
<Travels> <Travel>
<Designation> Singapore </Designation>
<Cost> 200000 </Cost>
<No_of_days> 8 </No_of_days>
<Mode_of_trans> Aeroplane </Mode_of_trans>
</Travel>
</Travel>
<Designation>Shimla</Designation>
<Cost> 10000 </Cost>
<No_of_days> 4</No_of_days>
<Mode_of_trans> Bus </Mode_of_trans>
</Travel></Travels>

Question 4. Explain with a help of an example, how root elements are placed in a XML document?
Answer: XML documents must contain one element that is the parent of all other elements. This element is called the root element. The root element encloses all other elements in XML. All other elements inside the root elements are the form of child element. The structure of the XML file should look like

<root>
<child>
<subchild>....</subchild>
</child>
</root>
e.g.
<company>
<employee>
<ecode> 101 </ecode>
<name> Rahul </name>
</employee>
<employee>
<ecode> 102 </ecode>
<name> Sahil </name>
</employee>
<employee>
<ecode> 103 </ecode>
<name> Muskan </name>
</employee>
</company>

You can see in the above example that the root element declared out here is <company> then comes the child element <employee> which in turn stores the <ecode> and <name> of the employee in the tags.

Application Oriented Questions

Question 1. Draw the XML tree for code given below: CBSE 2016

<Library>
<Books category="Thriller">
<Author>ABC</Author)
<Price>150</Price>
</Books>
<Books category="Fiction">
<Author>EFG</Author)
<Price>250</Price>
</Books>
</Library>

Answer: The XML tree is

ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-16

Question 2. Draw the XML tree for the code given below: CBSE 2011

<MOVIES>
<ENGLISH>
<NAME> PLAYERS </NAME>
<DIRECTOR) ABC </DIRECTOR>
<PRODCOST> 50 Lakhs</PRODCOST>
</ENGLISH>
<HINDI>
<NAME> KHILADI </NAME>
<DIRECTOR> XYZ </DIRECTOR)
<PRODCOST> 70 Lakhs</PRODCOST>
</HINDI>
</MOVIES>

Answer: The XML tree is

ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-17

Question 3. Write the DTD for the following XML document:

<Examples>
 <example>
 <name> CSS example </name>
 <url> http://www.google.com </url>
 </example>
 <example>
 <name> DTD example </name>
 <url> http://www.google.com </url>
 </example>
 </Examples>

Answer: 

<?xml version = "1.0" standalone = "yes"?>
<!DOCTYPE Examples![
<!ELEMENT Examples (example)>
<! ELEMENT example (name, url )>
<!ELEMENT name (#PCDATA)>
<! ELEMENT url (#PCDATA)>
]>

Question 4. Vallesoft Pvt. Ltd has designed and developed a Website that will be displayed differently in each of the continents. It has decided to use XML instead of HTML to develop the Website.
(i) A developer has written some XML code. Which of the following XML code fragments is well-formed?

<channel> <time> STAR TV 9.00 PM </channel> </time>
<Description> Family Drama </description>

(ii) Correct all the mistakes in the XML code fragments that are not well-formed given in part (i).
(iii) Design an XML tree for the following XML code:

<program>
<channel> STAR TV </channel>
<time> 9.00 PM </time>
<day> Monday, Tuesday, Wednesday </day> 
<description> Family Drama </description>
</program>

Answer: 

(i) None of the given code fragments are well-formed.
(ii) The correct code is:

<channel> <time> STAR TV 9.00PM </time> </channel>
<Description> Family Drama </Description>

(iii) The XML tree is

ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-18

Question 5. Draw the XML tree for the code given below:    CBSE 2011

< DIET>
<MORNING>
<CEREAL> OATS </CEREAL>
<FRUIT> PAPAYA </FRUIT>
<LIQUID> TEA </LIQUID> </MORNING>
<AFTERNOON>
<CEREAL> BRAN </CEREAL>
<FRUIT> APPLE </FRUIT>
<LIQUID> JUICE </LIQUID>
</AFTERNOON>
</DIET>

Answer: The XML tree is

ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-19

Question 6. Draw the XML tree for the code given below:    CBSE 2014

<employees>
<employee sex = "male">
<name>
<first> Harry </first>
<last> Potter </last>
</name>
</employee>
<employee sex = "female">
<name>
<first> Linda </first>
<1ast> Ray </last>
</name>
</employee>
</employees>

Answer: The XML tree is

ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-20

Question 7. Draw the XML tree for the code given below:    CBSE 2013

<bookstore> 
<book>
<title> ABC of Computers </title>
<author> A. Gandhi </author>
<year> 2005 </year>
<pri ce> 29.99 </pri ce></book>
<book>
<title> Learning XML </title>
<author> Erik T. Ray </author>
<year> 2003 </year>
<price> 39.95 </price>
</book>
</bookstore>

Answer: The XML tree is

ncert-solutions-for-class-10-foundation-of-information-technology-introduction-to-xml-21

Question 8. Create a DTD for storing book information for a library. The DTD should contain details about each book in terms of title, author (name), number of copies, all of which can store character data. The number of copies should contain two attributes named ‘inhand’ and issued which are both mandatory.
Answer:

<?xml version = "1.0">
<!DOCTYPE LIBRARY [
<!ELEMENT LIBRARY (BOOK +)>
<!ELEMENT BOOK (TITLE, AUTHOR, NOC)>
<!ELEMENT AUTHOR (NAME)>
<!ELEMENT TITLE (# PCDATA)>
<!ELEMENT NAME (# PCDATA)>
<!ELEMENT NOC (# PCDATA)>
<! ATTLIST NOC INHAND ISSUED CDATA # REQUIRED>
]>

Multiple Choice Questions [1 Mark each]

Q1. XML uses CBSE 2016
(a) Only 5 tags
(b) Predefined tags
(c) Custom tags
(d) HTML tags
Answer: (c) XML uses user defined or custom tags.

Q2. XML was not designed to      CBSE 2013
(a) display Web pages
(b) store data
(c) carry data
(d) Both (b) and (c)
Answer: (a) XML was designed to store and carry data, not to display Web pages.

Q3. A root element is
(a) a bridge between HTML and XML
(b) the parent of all other elements
(c) child element of the parent
(d) None of the above
Answer: (b) A root element is the parent of all other elements.

Q4. An XML document can be viewed in a CBSE 2014
(a) Word processor
(b) Web browser
(c) Notepad
(d) None of these
Answer: (b) An XML document can be viewed in a Web browser.

Q5. Name the root element in the following XML document:   CBSE 2011

<father>
<child1>
<name> Megha </name>
<age> 12 </age>
</child1>
<child2><name > Mana </name>
<age> 15 </age>
</child2>
</father>

(a) child 1
(b) child2
(c) father
(d) name
Answer: (c) father is the root element.

Q6. Which of them is the correct statement?
(a) An XML elements must have a closing tag.
(b) An XML elements must be lowercase.
(c) An XML documents must have a DTD.
(d) All of the above
Answer: (a) An XML elements must have a closing tag.

Q7. Which is not a correct name for an XML element?
(a) <xmldocument>
(b) <7eleven>
(c) <phone_number>
(d) <root>
Answer: (b) <7eleven> is not a correct name for an XML element.

8. XML allows you to CBSE 2012
(a) create new tags
(b) arrange your tags in any order
(c) closing tags are not required
(d) All of the above
Answer: (b) XML allows you to arrange your tags in any order.

9. Which one of these is correct syntax of the declaration, that defines the XML version?
(a) <?xml version = “1.0”?>
(b) <?xml version = “1.0”>
(c) </xml version = ”1.0″>
(d) <xml version = “1.0”?>
Answer: (a) <?xml version = “1.0”?> is a correct syntax of the declaration.

10. The way of describing XML data is
(a) XML uses XSL to describe data
(b) XML uses a description node to describe data
(c) XML uses a DTD to describe the data
(d) None of the above
Answer: (c) XML uses a DTD to describe XML data.

11. Which of the following is a prolog component? CBSE 2011
(a) Element
(b) Tab
(c) White space
(d) All of these
Answer: (a) Element is a prolog component.

12. PI is a component of
(a) prolog
(b) data instance
(c) element
(d) root element
Answer: (a) PI is a component of prolog.

13. To link an XML document with a stylesheet, you need to
(a) use the PI component in the XML document
(b) use the document declaration component in the XML document
(c) add the tag in the XML document
(d) None of the above
Answer: (a) To link an XML document with a stylesheet, you have to use the PI component in the XML document.

14. The XML document is like a
(a) tree structure
(b) inverted tree structure
(c) flat structure
(d) None of the above
Answer: (a) The xml document is like a tree structure.

15. What does XML stand for? CBSE 2016
(a) Extra Markup Language
(b) extensible Markup Language
(c) Example Markup Language
(d) None of the above
Answer: (b) extensible Markup Language

16. What does DTD stand for? CBSE 2016
(a) Dynamic Type Definition
(b) Dynamic Type Declaration
(c) Document Type Declaration
(d) Document Type Definition
Answer: (c) Document Type Declaration

17. In XML, value of attribute must appear CBSE 2016
(a) in uppercase
(b) in brackets
(c) in quotes
(d) in lowercase
Answer: (c) in quotes

18. DTD definition is used alongwith XML to specify     CBSE 2014
(a) the presentation of XML document
(b) the links with other documents
(c) the structure of XML document
(d) None of the above
Answer: (c) DTD definition is used alongwith XML to specify the structure of XML document.

Q19. Valid XML document means CBSE 2016
(a) the documents has one root element
(b) the document contains atleast one or more root elements
(c) the XML document has a DTD associated with it and it compiles with that DTD
(d) each element must nest inside any enclosing element properly
Answer: (c) Valid XML document check errors and has DTD or schema and compiles to it.

20. Comments in XML are
(a) having the same syntax as that of comments in HTML
(b) used to add additional notes
(c) not displayed on the final Web page
(d) All of the above
Answer: (d) All of the above

21. Comment in XML can be given by:   CBSE 2016

(a) <?-->
(b) <!-- >
(c) <?!-->
(d) <!?-->

Answer: (b) <!–>

22. Which of the following XML fragments are well-formed? CBSE 2014

(a) < element attribute = value >
(b) < element attribute = "value" >
(c) < element attribute = !value >
(d) < element attribute ='value'>

Answer: (b) < element attribute = “value” > all well-formed.

23. How is an empty element defined in XML?
(a) <name> </name>
(b) <name/>
(c) name/
(d) All of these
Answer: (b) The empty tag name is followed by <name/>

24. Is this, a “well-formed” XML document? CBSE 2011

<?xml version = "1.0"?> 
<note>
<to age="29"> Tove </tO>
<from> Jani </from>

(a) Yes
(b) No
(c) Cannot be determined without the DTD
(d) None of the above
Answer: (b) No, because </tO> is not a correct element and element is not closed.

25. Well-formed XML document means
(a) it contains a root element
(b) it contains an element
(c) it contains one or more elements
(d) must contain one or more elements and root elements
Answer: (d) Well-formed XML document must contain one or more elements and root element must contain all other elements.

26. An XML parser is used to
(a) extract data from the XML file and build tree like structure.
(b) check whether or not an XML document is well-formed.
(c) Both (a) and (b)
(d) None of the above
Answer: (b) Check whether or not an XML document is well-formed.

27. An XML document that follows the XML syntax is called a   CBSE 2010
(a) valid XML document
(b) well-formed XML document
(c) correct XML document
(d) All of the above
Answer: (b) well-formed XML document

28. Which of the following is not an online XML validator?
(a) W3C validation service
(b) Tidy
(c) XML.com’s
(d) expat
Answer: (d) expat is an online XML parser not an online XML validator.

29. What makes XML more powerful than HTML?
(a) The fact that it’s supported by all of the major software vendors.
(b) Not as much coding is needed.
(c) Its ability to adopt to new uses.
(d) None of the above
Answer: (c) XML is more powerful than HTML because we can define our own tags for different uses in XML.

30. HTML and XML are
(a) markup languages
(b) programming languages
(c) system softwares
(d) utilities
Answer: (a) Both HTML and XML are markup languages.

Fill in the Blanks [1 Mark each]
True or False [1 Mark each]

The post NCERT Solutions for Class 10 Foundation of Information Technology – Introduction to XML appeared first on Learn CBSE.

NCERT Solutions for Class 10 Foundation of Information Technology – Working with Tables in HTML

$
0
0

NCERT Solutions for Class 10 Foundation of Information Technology – Working with Tables in HTML

Foundation of ITMathsScienceSocialEnglishHindiSanskritRD Sharma

 

Multiple Choice Questions [1 Mark each]

Question 1. 
Which of these tags belong to table? CBSE 2016
(a) <thead>,<body>,<tr>
(b) <table>,<head>,<tfoot>
(c) <table>,<tr>,<td>
(d) <table>,<tr>,<tt>
Answer: (c),<table>,<tr>, <td> tags are used with table.

Question 2. 
Which of the following tags gives a caption to the table?
(a) < caption >
(b) < summary >
(c) < frame >
(d) None of these
Answer:(a) <caption> tag is used to give caption to the table.

Question 3.
Which of the following is used to specify the beginning of a table’s row?
(a) <table>
(b) <tr>
(c) <row>
(d) <begin>
Answer:(b) <tr> tag indicates the beginning of a table’s row.

Question 4. 
HTML tag for row is
(a) <colspan>
(b) <tr>
(c) <rowspan>
(d) <td>
Answer:  (b) HTML tag for row is <tr>.

Question 5. 
Which tag is used to add columns in the tables?
(a) <colspan>
(b) <td>
(c) <tr>
(d) None of these
Answer: (b) <td> is used to add columns in the tables.

Question 6. 
The tag is used to specify the individual table data in a table.
(a) <tr>
(b) <td>
(c) <th>
(d)<table>
Answer:(b)The <td> tag is used to specify the individual table data in a table.

Question 7. 
In order to add border to a table, border attribute is specified in which tag?
(a) <th>
(b) <table>
(c) <td>
(d) <tr>
Answer:(b) border attribute is specified in <table> tag.

Question 8. 
The attribute used to set the border color of a table is
(a) border
(b) bordercolor
(c) color
(d) border color
Answer:(b) bordercolor is used to set the border color of a table.

Question 9. 
The frame attribute contains types of values.
(a) 9
(b) 3
(c) 6
(d) 4
Answer: (a) The frame attribute contains 9 types of values.

Question 10. 
Which of the following is an attribute of < table > tag?
(a) src
(b) cellpadding
(c) link
(d) bold
Answer:(b) cellpadding is an attribute of <table> tag.

Question 11. 
Which one of the following is not an option for aligning data in a table?
(a) justify
(b) right
(c) left
(d) center
Answer:(a) justify option is not used for aligning data in a table.

Question 12. 
Which attribute of the < table > tag is used to set an image in the background of a table?
(a) bgcolor
(b) background
(c) frame
(d) rules
Answer:(b) background attribute is used to set an image in the background of a table.

Question 13. 
The attribute used to specify the background cofor of a table is
(a) color
(b) bgtable
(c) backcolor
(d) bgcolor
Answer: (d) bgcolor is used to specify the background color of a table.

Question 14. 
The two common attributes of the <img> and the <table> tag are
(a) src and height
(b) height and width
(c) border and src .
(d) they do not have any common attributes.
Answer:(b) height and width are common attributes of the <img> tag and the <table> tag. 

Question 15. 
border, frame, cellspacing, cellpadding, align are the attributes of
(a) <body> tag
(b) <img> tag
(c) <table> tag
(d) None of these
Answer: (c) border, frame, cellspacing, cellpadding, align are the attributes of <table> tag.

Question 16. 
Which of the following is not an attribute of < table > tag?
(a) border
(b) background
(c) bgcolor
(d) src
Answer:(d) src is not an attribute of <table> tag.

Question 17. 
In the <td> tag, td stands for
(a) Table Data
(b) Table Time and Date
(c) Table Date
(d) None of these
Answer:(a) td stands for Table Data.

Question 18. 
What is the correct HTML code to left align the content inside a table cell?
(a) <td valign = “left”>
(b) <td align = “left”>
(c) <td left align >
(d) <td left>
Answer:(b) <td align = “left”>

Question 19. 
Choose the correct HTML code to right align the content inside a table cell.
(a) <td align = “right” >
(b) <td valign = “right” >
(c) <td rightalign>
(d) <td right = “align” >
Answer: (a) <td align =”right”>

Question 20. 
Combining two or more cells in a table on a Web page is called
(a) merging
(b) spanning
(c) combining
(d) None of these
Answer:(b) Combining two or more cells in a table on a Web page is called spanning.

Question 21. 
Which attribute tells, how many rows a cell should span?
(a) colspan = n
(b) rowspan = n
(c) Both (a) and (b)
(d) None of these
Answer:(b) rowspan = n will tell how many rows a cell should span.

Question 22. 
rowspan = n can be added to only which tag?
(a) <hr>
(b) <table>
(c) <td>
(d) <tr>
Answer: (r) rowspan = n can be added to only <td> tag.

Question 23. 
Which attribute of <td> tag is used to merge two or more columns to form a single column?
(a) colspan
(b) cellspacing
(c) cellpadding
(d) rowspan
Answer: (a) colspan attribute is used to merge two or more columns to form a single column.

Question 24. 
colspan = n can be added to tag.
(a) <hr>
(b) < table >
(c) <td>
(d) <tr>
Answer:(r) colspan = n can be added to <td> tag.

Question 25. 
The attribute helps to align data vertical in a single cell.
(a) align
(b) valign
(c) halig
(d) Both (b) and (c)
Answer:(b) valign attribute is used to align data vertically in a single cell.

Question 26. 
In the <th> tag, th stands for
(a) Table Heading
(b) Total Heading
(c) Table Header
(d) All of the above
Answer: (c) th stands lor Table Header

Very Short Answer Type Questions [1 Mark each]

Question 1. 
Name the tags which are used with <table> tag.
Answer: <tr>,<td>,<th> and <caption> tags are used with <table> tag.

Question 2. 
Describe the border attribute of <table> tag.
Answer: The border attribute is used to define- the thickness of the border, which surrounds the table.

Question 3. 
Why bordercolor attribute is used?
Answer: The bordercolor attribute is used to specify the color of the table’s border

Question 4. 
Name any two values specified in frame attribute.
Answer: The values that can be specified for frame attribute are void and above.

Question 5. 
Which attribute lets you control the display of select border sides of a table?
Answer: frame attribute displays the selected border sides of the table.

Question 6. 
How many values can be specified in rules attribute of <table> tag?
Answer: There are total five values that can be specified for rules attribute.

Question 7. 
Define cellspacing.
Answer: The cellspacing is used to create space between different cells in a table.

Question 8. 
Name two table attributes, which are used to set spacing in and between table cells.
Answer: The cellspacing and cellpadding are the attributes, which are used to set spacing in and between the table celts.

Question 9. 
What is the use of align attribute in < table > tag?
Answer: The align attribute defines the center, right or left alignment of the <tabie> tag.

Question 10. 
Name the values that can be used in valign attribute.
Answer:  The values that can be used in valign attribute are top, middle and bottom.

Question 11.
Why valign attribute is used? CBSE 2005
Answer: 
The valign attribute is used with <td> tag which helps to align data in a single cell if the cell span in more than one row.

Question 12. 
With which tag) align attribute is used?
Answer: 
The align attribute is used with both <td> tag and <table> tag.

Question 13. 
Which tag is used for giving heading to the columns?
Answer: The <th> tag is used to display the table heading only once for a table column.

Question 14. 
Which tags divide HTML tables in multiple section?
Answer: <thead>, <tfoot> and <tbody>

Question 15. 
What is the difference between <thead> and <tfoot> tags?
Answer: The <thead> tag is used to add a header in a table while <tfoot> tag is used to add a footer in a table.

Question 16. 
Can you insert hyperlinks inside table cells?
Answer: Yes, in spite of text we just have to insert the anchor tag between the <td> and </td> tags.
e.g.
<td>
<a href = “www.google.com”>link </a></td>.

Short Answer Type Questions

Question 1. 
What is table? Name the basic commands for creating a table.
Answer:Tables are made up of rows and columns. In HTML, tables are used to display tabular data in Web pages. The basic commands for creating tables are as follows:
Table tags <table> </table>
Row tags <tr> </tr>
Cell tags <td> </td>, <th> </th> and Caption tags <caption> </caption>.

Question 2. 
What do you mean by the border attribute?
Answer:Refer to text on page no. 156.

Question 3. 
Write HTML code to display a table with border of 5px.
Answer:

 <html><body>
 <table border = "5">
 <tr><td>l</tdX/tr>
 <trXtd>2</tdX/tr>
 </table> „
 </bodyX/html >

Question 4. 
Describe the various values of rules attribute.
Answer:Refer to text on page no. 157.

Question 5. 
Differentiate between cellspacing and cellpadding in HTML table.
Answer:Differences between cellpadding and cellspacing are as follows:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-1

Question 6. 
Name the attributes of <table> tag which are used for specifying its dimensions in a Web page.
Answer: width and height attributes of <table> tag are used for specifying its dimensions in a Web page, width and height are specified in terms of pixels or percentage of the browser window.

Question 7. 
Explain the width attribute of <table> tag.
Answer:The width attribute is used to set the absolute width of the table. The values in width attribute can be either in pixels or in percentage of the browser window, e.g.

 <table width = " 150">
 <trXtd>Celll</tdXtd>Cell2</tdX/tr>
 <trXtd>Cel!3</tdXtd>Cell4</tdX/tr>
 </1 a b1e>

Question 8. 
What is the function of summary attribute?
Answer:summary attribute of <table> tag is used to provide the detailed information about a table. It enables a user to know the type of information that a table contains. It is useful to provide access to non-visual browsers, which are used by users with visual impairment, e.g.
<table summary=”text”>

Question 9. 
What is data cell? Name the <table> tag, which is used as data cell.
Answer:The data cell defines a cell of a table that contains data. The table data cell is coded with <td> tag of <table> tag. Here, td stands for Table Data. The content in the table data cell is normal and left-aligned.

Question 10. 
Why rowspan and colspan attributes are used?
Answer:Sometimes, a table cell is bigger than other. Its span is spread to more rows or columns. Such cells can be created with the help of rowspan and colspan attributes.

Question 11. 
Which attributes can you use with < table > tag but not with <tr> tag?
Answer:summary, rules, frame,*, border, cellpadding, cellspacing, height, width and bordercojor are the attributes that you can use with <table> tag but not with <tr> tag.

Question 12. 
Define the <th> and <tr> tags. Are these two tags similar? If yes, how?
Answer: <th> tag stands for Table Header. It is used to give headings to the various columns in our table. <tr> tag stands for Table Row. It is used to create a row in a table. <th> and <tr> tags are not similar. <th> tag is similar to <td> tag. Since, <th> also defines a data cell, which is taken as heading to the columns and the data is bold faced.

Question 13. 
What is header cell? Name the < table > tag, which is used as header cell.
Answer: The table header cell is coded with <th> tag. It specifies the header of the table and displays the content of a table in heading style. The content in the table header cell is rendered in bold and centered horizontally within the cell.

Question 14. 
What are table sections? How can they be created?
Answer: In HTML tables, there are three different sections: header, body and footer. These sections can be created using <thead> (header section), <tbody> (body section) and <tfoot> (footer section) tags.
e.g

 <table>
 <thead>
 <tr> <th> Month</thXth>Savings</thX/tr> </thead>
 <tbody>
 <trXtd>January</tdXtd>$100</tdX/tr>
 <trXtd>February</tdXtd>$80</tdX/tr>
 </tbody>
 <tfoot>
 <trXtd>Sum</tdXtd>$180</tdX/tr>
 </tfoot>
 </1 a b1e>

Question 15. 
Name the attributes that are used to do the following in HTML:

    1. merge two or more rows.
    2. change the background color of the cells in a table.
    3. vertically align cell content.
    4.  merge two or more columns.

Answer:

      1. rowspan
      2.  bgcolor
      3. valign
      4. colspan

Question 16. 
Name the attributes used for following:

      1. setting the cell width.
      2. setting cell’s background image.
      3. setting cell’s background color.
      4. changing the cell span.

Answer:

      1. width
      2.  background
      3. bgcolor
      4.  rowspan and colspan

 

Long Answer Type Questions [5 Marks each]

Question 1. 
Write the HTML code to create the exact table which is given below:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-1
Answer:The HTML code is

 <html>
 <body>
 <table border="3">
 <tr align = "center" val i gn = "middle"> <th> ADMNO </th>
 <th> SNAME </th>
 <th> NAME </th>
 <th> DOB </th>
 </tr>
 <tr align="left" valign="bottom">
 <td> 1110 </td>
 <td> MANJIT </td>
 <td> RANJIT </td>
 <td> 4-MAR-1998 </td>
 </tr>
 </table>
 </body>
 </html>

Question 2. 
Explain the frame attribute and the various values of it.
Answer:Refer to text on page no. 157.

Question 3. 
Write an HTML code to create the following table:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-3
Note:First row has Green background
Answer:The HTML code is

<html>
 <body> t,
 <table border="2" align="left"> <thead bgcolor="green">
 <tr>
 <td> Roll Number </td>
 <td> Name </td>
 <td> Class </td>
 </trX/thead>
 <tbody>
 <tr>
 <td> 100 </td>
 <td> Amit </td>
 <td> 10 A </td>
 </tr>
 <tr>
 <td> 101 </td>
 <td> Ankit </td>
 <td> 10 B </td>
 </tr>
 </tr>
 <td> 102 </td>
 <td>Arnab </td>
 <td> 10C </td>
 </tr>
 </tbody>
 <tfoot>
 <tr>
 <td> Footer 1 </td>
 <td> Footer 2 </td>
 <td> Footer 3 </td>
 </tr>
 </tfoot>
 </table>
 </body>
 </html>

Question 4. 
What is the use of <tr> tag in an HTML table? Give a suitable example.
Answer:The <tr> tag creates a table row in an HTML table. A table must have atleast one row and also, it can have as many table rows as you want. A table row is divided into table cells. A table must have atleast one table cell per table row.
e.g.

 <html>
 CheadXtitle> TRTag </title></head>
 <body>
 <table border = "1" cellpadding =”3">
 <tr>
 <th> Head 1 </th>
 <th> Head 2 </th>
 <th> Head 3 </th>
 </tr>
 <tr>
 <td> A </td>
 <td> B </td>
 <td> C </td>
 </tr>
 <tr>
 <td> D </td>
 <td> E </td>
 <td> F </td>
 </tr>
 </table>
 </body>
 </html>
 Output
 ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-4

Question 5. 
Can you perform event handling in HTML tables? If yes, explain it.
Answer:Yes, for explanation refer to text on page no. 36.

Question 6. 
Observe the following table and write the HTML code to generate it:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-6
Note : 1st row has pink background.
Answer:The HTML code is

 <html>
 <body>
 <table border = "1">
 <tr bgcolor = "pink" align = "center">
 < t h >question< /1 h >
 <th>marks</thX/tr>
 <trXtd rowspan = "3">l</td>
 <td>2</td>
 </tr>
 <tr>
 <td>2</td>
 </tr>
 <tr>
 <td>5</td>
 </tr>
 </table>
 </body>
 </html>

Question 7. 
Observe the following table and write the HTML code to generate it:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-7
Answer:The HTML code is

 <html>
 <body>
 <table cell padding = "10" cel 1spacing="0" border="l"> <tr align = "center"> <th>Periodl</ th>
 < t h > Period2 < /1 h >
 </tr>
 <tr align = "center">
 <td>Math</td>
 <td>Science</td>
 </tr>
 <tr align="center"> <td>English</td>
 <td>SST</td>
 </tr>
 <tr align="center"> < t d > Science< /1 d > <td>SST</td>
 </tr>
 </table>
 C/body>
 </html>


Question 8. 

Write names of two attributes each for the following tags: CBSE 2013

  1. <hr>
  2.  <body>
  3.  <img>
  4.  <table>
  5.  <a>

Answer:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-8

Question 9. 
Identify which of the following is a tag or an attribute ? CBSE 2014

  1.  link
  2.  table
  3.  align
  4.  href
  5.  br

Answer:

  1.  link — attribute
  2.  table — tag
  3.  align — attribute
  4.  href— attribute
  5.  br — tag

Question 10. 

Write the HTML code to generate the following table on a Web page with the contents and alignment exactly as shown below:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-10
Answer:The HTML code is

 Chtml>
 Cbody)
 <table border="l" width = "400”> <tr align="right"> <th>MOVTD</th> <th>MOVNAME</th> <th>ACTORS</th>
 </tr>
 <tr align="1eft">
 <td>M001</td>
 <td>HIT FACTORY</td>
 <td>4</td>
 </tr></table></body>
 C/html>

Question 11. 
Write the HTML code to generate the following table with the contents exactly in the same format as shown within the table:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-11
Answer:The HTML code is

Chtml Xbody>
 Ctable border="l">
 <tr>
 <th colspan="4" align=”center">
 Shopping MalK /1 h >
 C/tr>
 Ctr align = "center"
 Ctd>FloorC/td>
 Ctd>No. ofToyCbr>ShopsC/td>
 Ctd>No. of FoodCbr>ShopsC/td>
 Ctd>No. of SportsCbr>ShopsC/td>
 C/tr>
 C/table>
 C/bodyX/html >

Question 12. 
Write the complete <TABLE>…</TABLE> tags to create a table with the following contents. Ensure that the background of each data cell should have the color as specified in the corresponding column heading.
Answer:

 Ctable)
 Ccapti on)ColorsC/capti on)
 Ctr)
 Cth)redC/th>
 Cth)greenC/ th>
 Cth)blueC/tlj>
 Cth)orangeC/th)
 Cth)cyanC/th>
 C/tr>
 Ctr)
 Ctd bgcolor="red" width="100" height="50")C/td>
 Ctd bgcolor="green" width="100" height="50"X/td>
 Ctd bgcolor="blue" width="100" hei ght="50"X/td>
 Ctd bgcolor="orange" width="100" hei ght="50"X/td>    .
 Ctd bgcolor="cyan" width="100" height="50"X/td>
 C/tr>
 C/table>

Question 13. 
Observe the following table and write the HTML code to generate it:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-13
Answer:The HTML code is:

 Chtml>
 <body> <basefont face="cambria"> <table border="l" bordercolor="black" cel 1spacing="0" width="320">
 <caption> Acdvities </caption>
 <tr>
 <td rowspan="3"> Sr School </td>
 <td> Maths Club </td>
 </tr>
 <tr>
 <td> Robotics Club </td>
 </tr>
 <tr>
 <td> Photography </td>
 </tr>
 <tr>
 <td rowspan="3"> Middle School </td> <td> Gymnastic </td>
 </tr>
 <tr>
 <td> Yoga </'td>
 </tr>
 <tr>
 <td> Computer Club </td>
 </tr>
 <tr>
 <td rowspan="3"> Primary School </td> <td> Dance </td>
 </tr>
 <tr>
 <td> Vocal Music </td>
 </tr>
 <tr>
 <td> Swimming </td> </tr>
 </table>
 </body>
 </html>

 

Application Oriented Questions

Question 1. 
Write the HTML code to generate the following Web page:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-1
Note: The following points while generating the Web page:

  1. Link color is green, active link color is blue and visited link color is red.
  2. Title of the page is “Eat healthy, live healthy”.
  3. Heading of the page is maroon.
  4. Image is used in “Restaurant.jpg”
  5. Caption of table is blue
  6. Table border is blue and of size 2.
  7. The links are one.html, two.html, three.html and four.html.
  8. The E-mail id for contact us is ‘abc@xyz.com’.

Answer:The HTML code is

 <htm!>
 <head>
 <ti tl e>Eat healthy, live healthy</ti tl e>
 </head>
 <body link="green" alink="blue" vlink="red"> <center>
 <hl>
 <font color="maroon">KHAO PIYO
 RESTAURANT</font >
 </hl>
 </center>
 <img src=“Restaurant.jpg" a1ign =
 "right" height="255" width="250”>
 Collect Information for                                                .
 <ul>
 <li><a href=" one.html ">Menus</aX/l i > 
 <liXa href=”two.html ">Reservation</a>
 </l i> <liXa href =" three.html ">Catering</aX/l i >
 <li >
 <a href="four.html ”>Tours</a>
 </l i >
 </ul >
 <center>
 <table border = "2" bordered or=''bl ue”> <font color="blue">
 <caption> Menus available are </caption>
 </font>
 <tr>
 <td> 1 </td> <td> INDIAN </td>
 </tr>
 <tr>
 <td> 2 </td> <td> ITALIAN </td>
 </tr>
 <tr>
 <td> 3 </td> <td> CONTINENTAL </td> </tr>
 <tr>
 <td> 4 </td> <td> THAI </td>
 </tr>
 < /1 a b1e>
 </c-enter>
 <br>
 For further queries and reservation
 <a href=''mai 1 to:abc@xyz.com">
 Contact Us< / a >
 </body></html>
 

Question 2. 
If you type

 <table border="2">
 <tr align="center”>
 <th> Sun
<th> Mon
<th> Tue
<th> Wed
<th> Thu
<th> Fri
<th> Sat
</tr>
 <tr align = "1eft">
 <td col span = "3" >
 <td> 1 </td>
 <td> 2 </td>
 <td> 3 </td>
 <td> 4 </td>
 </tr>
 </table>
 How the ouput will look like?
 Answer:The output will look like
 ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-2

Question 3. 
Write the HTML code to generate the following output:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-3
Answer:The HTML code is

<html>
 <head>
 <ti tl e>Table</ti tl e&gt
 </head>
 <body>
 Stable border="4" cel 1 spacing=''7” cel 1padding="5">
 <tr>
 <td>A</td>
 <td rowspan="2">B</td>
 <td>D</td> <td>E</td>
 </tr>
 <tr>
 <td>G</td> <td col span="2">H</td> <td>I</td>
 </tr>
 </table>
 </body>
 </html>

Question 4. 
Write an HTML code to print the following table:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-4
Answer:

 <caption>
 <b>
 <font size="4'' color="red">
 Student Data </font>
 </b>
 </caption>
 <tr >
 <th>Student Name</th>
 <th>Roli No</th>
 <th>Address</th>
 <th>Marks</th>
 </tr>
 <tr>
 <td>Amrita</td>
 <td>l</td>
 <td>Shastri Nagar</td>
 <td>483</td>
 </tr>
 <tr>
 <td>Taruna </td>
 <td>2</td>
 <td>T.P Nagar</td>
 <td>4l8</td>
 </tr>
 <tr>
 <td>Priyanka</td>
 <td>3</td>
 <td>Saket</td>
 <td>489</td>
 </tr>
 </table>
 </body>
 </html>

Question 5. Carefully study the Web page given below. Identify 10 tags (structural as well as formatting tags) that have been utilised in creating this Web page and write the usage of each of them.
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-5
Answer:

  1.  <title> to specify the title of the Web page.
  2.  <body> contains all the content that is to be displayed on Web page and all the various formatting and structural tag.
  3.  <ul> used to create an unordered list.
  4. <li> to specify the various list items in a list.
  5. <caption> to provide caption to the table.
  6.  <table> used to create table in HTML document.
  7. <tr> stands for table row, used to create a table row.
  8. <td> stands for table data, helps to create cells in HTML table.
  9. <img> used to insert an image in HTML document.
  10. <a> stands for anchor tag. Use the href attribute to provide the reference of the Web page that you want to hyperlink.

Question 6. 
Observe the following Web page and write HTML code to generate it:
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-6
Note: the following points while generating the Web page:

  1. Background color of page is yellow.
  2. Link color i^.black and visited link color is green.
  3. Font style for the page is arial.
  4. Heading of the page is maroon.
  5. Image used is mainrhino.jpg.
  6. Table border is 2px.
  7. Use links as: For Whooping Crane as one.html

For White Rhino as two.html
For Sumatran Rhino as three.html
For Toucan as four.html
8.E-mail id for bottom message is abc@ xvz.com
Answer:
The HTML code is <html>
<body bgcolor=”yel1ow” 1ink=”black” vlink=”green”>
<basefont face=”arial”>
<hl align=”center”>
<font col or=”niaroon”>INDIAN RHINOCEROS</fontX/hl>
<img src=”mainrhino.jpg” align=”right” height=”100″ width=”110″>
The Indian rhinoceros lives primarily in northern India and Nepal. These massive beasts have some noticeable physical differences from their African relatives. Their segmented hide looks like a formidable coat of natural body armour. It functions a bit like one also. Flexible skin between the thicker hide “plates” allows them to shift as the rhinoceros moves.

 <br><br>
 Other Endangered Animals:
 <ul>
 <1 i >
 <a href="one. html ">Whooping Crane</a>
 </l i>
 <1 i>
 <a href=" two. html ">White Rhino</a>
 /1 i >
 <1 i >
 <a href="three. html ">Sumatran Rhino</a>
 </l i>
 <1 i >
 <a href="four. html ">Toucan</a>
 /1 i >
 </ul>
 <table border="2" align="center">
 <capti on>Fast Facts</capti on> <trXtd>Type</td>
 <td>Mammal</td>
 </tr>
 <tr>
 <td>Diet</td>
 <td > FIerbivore< /1 d >
 </tr>
 <tr>
 <td>Average life span in the wild</td>
 <td>40 years</td>
 </tr>
 <tr>                                       .
 <td>Size</td>
 <td>Length 12.5 ft; Height up to 6 ft</td>
 </tr>
 <tr>
 <td>Weight</td>
 <td>4,400 lbs (2,000 kg)</td>
 </tr>
 </table>
 <br>
 <a href="mailto:abc@xyz.com">
 For more Details</a>
 </body>
 </html>

Question 7.
 Carefully study the Web page given below. Identify 10 tags (structural as well as formatting tags) that have been utilised in creating this Web page and write the usage of each of them.
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-7
Answer:

  1. .<title> to specify title of the Web page.
  2.  <body> contains all the text content that is to be displayed on Web page and all the various formatting and structural tag.
  3.  <hl> defines the most important and biggest heading.
  4. <hr> used to separate content (or define a change).
  5. <img> used to insert an image.
  6.  <b> used to bold the text.
  7. <table> used to create a table.
  8. <caption> used to provide caption to the table.
  9. <tr> used to create a table row.
  10. <td> used to define data cells.

Question 8.
Observe the following Web page and write HTML code to generate it.
ncert-solutions-for-class-10-foundation-of-information-technology-working-with-tables-in-html-8
Note: the following points while generating the Web page:

  1. Title of the page is “Cleanliness”
  2. Link color is green.
  3. Font style for the page is arial.
  4. Heading of the page is maroon.
  5. Image used is clean.jpg.
  6. Table border is 2px and border color is red.
  7. Link for bottom message is contact.html.

Answer: The HTML code is

 <html>
 <head> <title> Cleanliness </title> </head>
 <body 1ink="green"> <basefont face="arial">
 <hl> <font col or="maroon"> <center> IMPORTANCE OF CLEANLINESS </'center> </font> </hl> <hr>
 <img src="clean.jpg" align="left” height="120" width="80"&gt
 <p align="justify">
 Cleanliness is not a work which we should do forcefully. It is a good habit and healthy way of our healthy life. All type of cleanliness is very necessary for our good health whether it is personal cleanliness, surrounding cleanliness, environment cleanliness, pet animal cleanliness or work place cleanliness (like school, college, office, etc). We all should be highly aware about how to maintain cleanliness in our daily lives.
 </p> <br>
 <0l> Factors affecting the environment <hr width="240" a 1 i gn=” 1 ef t" >
 <1 i > Industrial activities < 1 i > Vehicles <li> Rapid urbanization and industrialization <li> Population overgrowth
 </ol>
 <table border="2" align="center" borderedor="red" width="600">
 <caption> Effects </caption>
 <tr> <td> Water Pollution is leading to a number of incurable diseases. </td> </tr>
 <tr> <td> Because of Air Pollution there are increasing case of pulmonary tuberculosis and thromosis and various sorts of brain and heart complications. </td> </tr>
 <tr> <td> Digital Media < /1 d > </tr>
 <tr> <td> Soil-pollution may have negative effects on farm output ratio. </td> </tr>
 <tr> <td> Noise-pollution have negative effects on hearing or auditory sense organs. </td> </tr>
 <tr> <td> Thermal pollution is raising the environment temperature. </td> </tr>
 </1 a b1e>
 <hr> <center> For more details <a h ref=" con ta ct. h tml" > ClickHere </a> </center>
 </body>
 </html>

 

Fill in the Blanks [1 Mark each]

Question 1.
To insert a table on a Web page, we use  ………………. tag.
Answer: <table>

Question 2.
The tag to start a table is
Answer:<table>

Question 3.
…………… tag is used to insert data into a table.
Answer: <td>

Question 4.
The <td> tag is a …………………
Answer: container

Question 5.
The……………. attribute is used to display a specific portion of a table border.
Answer: frame

Question 6.
frame attribute is used with…………attribute.
Answer: border

Question 7.
There are total………… values for rules attribute in <table> tag.
Answer: 5

Question 8.
In the rules attribute, the………… value helps to display a table border only between rows.
Answer: rows

Question 9.
Cellspacing is used to create space between different…………… in a table.
Answer: cells

Question 10.
The….. is an attribute of the < table > tag to set the distance between the cell content and its boundary.
Answer: cellpadding

Question 11.
To set image as background of an HTML table, you can use………………… attribute.
Answer: background

Question 12.
By default, color of a table is…………..
Answer: white

Question 13.
The height and width attributes of < table > tag are specified in terms of………….. or percentage.
Answer: pixels

Question 14.
The… attribute is used to provide information about a table.
Answer: summary

Question 15.
<td> tag can only be present inside……….
Answer: <tr>

Question 16.
The………………. attributes is used to combine the cells vertically.
Answer: rowspan

Question 17.
The……………… attribute is used to span two or more columns in a table.
Answer: colspan

Question 18.
The……………… attribute is used to align the data vertically within cells.
Answer: valign

Question 19.
The <tr> tag can only be present inside…………tag.
Answer: <table>

Question 20.
The <thead> tag is used to specify the………..part of the table.
Answer: header

True or False [1 Mark each]

Question 1.
A cell is an intersection of a row and a column.
Answer: True A cell is an intersection of a row and a column.

Question 2.
The cellpadding attribute is used with <td> tag.
Answer: False The cellpadding is used with <table> tag.

Question 3.
<caption> is placed just above the < table> tag.
Answer:False <caption> tag is placed inside the <table> tag.

Question 4.
<td> will make the text bold.
Answer:False <td> is a table data. It is used to define a cell of a table that contains data.

Question 5.
The border is an attribute of <a> tag.
Answer:F3lSB The border is an attribute of <table> tag.

Question 6.
The default value of border attribute is 1.
Answer:False The default value of border attribute is 0.

Question 7.
The cols value in the rules attribute, allows you to display table border only between columns.
Answer:True The cols value in the rules attribute is drawn between columns only.

Question 8.
The cellspacing attribute tells the browser how much space to include between the walls of the table.
Answer:False cellspacing attribute is used to create space between different cells in a table.

Question 9.
< caption > tag gives heading to a Web page.
Answer:False <caption> tag gives title or caption for the table.

Question 10.
cellpadding attribute is used with <body> tag.
Answer:False cellpadding attribute is used with <table> tag.

Question 11.
The rowspan attribute with < table > tag is used to merge more than one cells row wise.
Answer:True The rowspan attribute merges the cells row wise in a table.

Question 12.
The rowspan attribute is used to make a cell span multiple columns.
Answer:False The rowspan attribute is used to make a cell span multiple rows.

Question 13.
The align and valign are the attributes used with <td> tag to set the alignment of data in a cell.
Answer:True The align and valign attributes are used to set alignment of the data.

Question 14.
The <td> tag (column setting) have higher priority than <tr> tag (row setting).
Answer:True The <td> tag (column setting) have higher priority than <tr> tag (row setting).

Question 15.
Table row <tr> tag can accept one attribute.
Answer:False The <tr> tag can accept many attributes.

Question 16.
<th>‘tag is used to specify the column heading in a table.
Answer:True <th> tag is used to specify the column heading in a table.

The post NCERT Solutions for Class 10 Foundation of Information Technology – Working with Tables in HTML appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – C++ Revision Tour

$
0
0

Important Questions for Class 12 Computer Science (C++) – C++ Revision Tour

Topic – 1
Fundamentals

Previous Years Examination & Important Questions
2 Marks Questions

Question 1:
Write the type of C++ tokens (keywords and user defined identifiers) from the following: All Indio 2017

  1. new
  2. While
  3. case
  4. Num_2

Аnswer:

  1. new → keyword
  2. While → user defined identifier
  3. case → keyword
  4. Num_2 → user defined identifier

Question 2:
Out of the following, find those identifiers, which cannot be used for naming Variable, Constants or Functions in a C++ program: Delhi 2016
Cost, Price*Qty, float, Switch, Address One. Delete, Number12, do
Аnswer:
Price*Qty, float, do and Address One cannot be used for naming variables, constants or functions in a C++ program.

Question 3:
Rewrite the following C++ code after removing any/all syntactical errors with each correction underlined. Delhi 2016
NOTE:  Assume all required header files are already being included in the program.

#define Equation(p,q)=p+2*q 
void main()
{
float A=3.2;B=4.1;
C=Equation(A,B); 
cout<<'Output =’<<C<<endl;
}

Аnswer:

The correct code is:
#define Equation(p,q)(P+2*Q)
void main()
{
float A=3.2,B=4.1; 
float C=Equation(A,B); 
cout<<"0utput ="<<C<<endl;
}

Question 4:
Out of the following, find those identifiers, which cannot be used for naming Variables, Constants or Functions in a C++ program: All India 2016
Fatal*Tax, double, Case, My Name, NeW, switch, Column31,_Amount
Аnswer:
Fatal*Tax, double, My Name, switch cannot be used for naming variables, constants or functions in a C++program.

Question 5:
Rewrite the following C++ code after removing any/all syntactical errors with each correction underlined. All India 2016
NOTE Assume all required header files are already
being included in the program.

#define Formula(a,b)=2*a+b 
void main()
{
float X=3.2;Y=4.1;
Z=Formula(X,Y);
cout<<'Result='<<Z<<endl;
}

Аnswer:

The correct code is:
#define Formula(a.b)(2*a+b)
void main()
{
float X=3.2.Y=4.1: 
float Z=Forinula(X.Y): 
cout<<"Result="<<Z<<endl:
}

Question 6:
Rewrite the following C++ code after removing any/all syntactical errors with each correction underlined. All Indio 2016C NOTE Assume all required header files are already
being included in the program.

define formula(a,b,c)a+2*b+3*c; 
void main()
{
int L=1,M=2,N=3,
J=Formula(L,M,N); 
cout<<'output ='<<J<<endl;
}

Аnswer:

The correct code is:
#define Formula(a,b,c)a+2*b+3*c 
void main()
{
int L=1,M=2,N=3:
int J=formula(L,M,N);
cout<<"0utput="<<j<<endl;
}

Question 7:
Find the correct identifiers Out of the following, which can be used for naming Variable, Constants or Functions in a C ++ program: Delhi 2015
While, for, Float, new, 2ndName, A%B, Amountl2, _Counter
Аnswer:
The correct identifiers are as follows:
While, Float, Amount 12 and_Counter

Question 8:
Find the correct identifiers out of the following, which can be used for naming Variables, Constants or Functions in a C++
For, while, INT, NeW, delete, 1stName, Add+Subtract, name1
Аnswer:
The correct identifiers are as follows:
For, INT, NeW and name1

Question 9:
Observe the following C++ code carefully and rewrite the same after removing all the syntax error(s) present in the code. Ensure that you underline each correction in the code. All India 2013
Important Note:
(i) All the desired header files are already included, which are required to run the code.
(ii) Correction should not change the logic of the program.

//define Change(A,B)2*A+B; 
void maint()
{
Float X,Y,F; 
cin>>X>>Y ;
F=Change[X,Y]; 
cout<<"Result:"<<F<endline;
}

Аnswer:

The correct code is:
#define Change (A.B)(2*A+B) 
void main() 
{
float X.Y.F: 
cin>>X>>Y;
F=Chanae(X.Y):
cout<<"Result:”<<F<<end1:
}

Question 10:
Observe the following OH- code carefully and rewrite the same after removing all the syntax error(s) present in the code. Ensure that you underline each correction in the code.
Important Note:
(i) All the desired header files are already included, which are required to run the code.
(ii) Correction should not change the logic of the program. Delhi 2013

//define Convert(P,Q)P+2*Q; 
void main()
{
Float A,B,Result: 
cin>>A>>B;
Result=Convert[A,B]; 
cout<<"Output:"<<Result<endl:
}

Аnswer:

The correct code is:
#define Convert(P,Q)(P+2*Q) 
void main()
{
float A,B,Result; 
cin >>A>>B;
Result=Convert(A.B): 
cout<<"0utput"<<Result<<endl:
)

Question 11:
Give the difference between the type casting and automatic type conversion. Also, give a suitable C++ code to illustrate both. All India 2012,2011 Delhi 2010
Аnswer:
Type casting It is used by the programmer to convert the value of one type to another type,
e.g. float X=(float) 15/6:
Automatic type conversion It is automatically done by the compiler itself wherever required.
e.g. float X=3;

Question 12:
What is the difference between local variable and global variable? Also, give a suitable C++ code to illustrate both. Delhi 2011
Аnswer:
A variable which is declared within the body of a function and accessible only within the function is known as local variable.
A variable which is declared outside any function and accessible to all functions in a program is known as global variable.
To illustrate this, below is given programming example:

#include<iostream.h>
float area;     //Global variable
void cirarea()
{
float r;   //Local variable
cin>>r
area=3.14*r*r; 
cout<<area; 
}
void rectarea()
{
float l,b; //Local variables
cin>>l>>b;
area=l*b;
cout<<area;
}
void main()
{
cirarea(); 
rectarea();
}

Question 13:
What is the function of typedef in C++? Also, give a suitable C++ code to illustrate it. Delhi 2011C
Аnswer:
typedef keyword is used to assign alternative names to existing types.
e.g. typedef int in;
Now, whenever we want to declare a variable of type integer, rather than using int we can use ‘in’
keyword in place of int.
e.g.

void main()
{
typedef int in;
//in is an alternative name to int in a=10;
//a is of type integer cout<<a;
}

Question 14:
What is the function of #define keyword? Give an example to illustrate its use. Delhi 2009C
Аnswer:
#define keyword is a preprocessor directive that is used to define a macro or a symbolic constant.
Syntax
#define macroname expression
or
#define symbolic constant-value
e.g.
#define Area(R) 3.14*R*R
#define Max 100

Topic – 2
Control Flow and Functions Control Flow

1 Mark Questions

Question 1:
Ronica Jose has started learning C++ and has typed the following program. When she compiled the following code written by her, she discovered that she needs to include some header files to successfully compile and execute it. Write the names of those header files, which are required to be included in the code.

void main() 
double X,Times,Result; 
cin>>X>>Times;
Result=pow(X,Times); 
cout<<Result<<endl ;

All India 2016
Аnswer:

Ciostream. h>→cout, cin
<math. h>→pow()

Question 2:
Jayapriya has started learning C++ and has typed the following program. When she compiled the following code written by her, she discovered that she needs to include some header files to successfully compile and execute it. Write the names of those header files, which are required to be included in this code.

void main()
{
float A,Number,Outcome; 
cin>>A>>Number;
Outcome=pow(A,Number); 
cout<<Outcome<<endl;
} Delhi 2016

Аnswer:
<iostream.h>→cout, cin
<math.h>→pow( )

Question 3:
Ahmad has started learning C++ and has typed the following program. When he compiled the following code written by him, he discovered that he needs to include some header files to successfully compile and execute it. Write the names of those header files, which are required to be included in the code.

void main() 
float Radians,Value; 
cin>>Radians;
Value=sin(Radians); 
cout<<value<<endl;
} All India 2016C

Аnswer:
<iostream.h>→cout, cin
<math.h>→sin( )

Question 4:
Observe the following C ++ code and write the name(s) of the header file(s), which will be essentially required to run it in a C ++ compiler.

void main()
{
float Area,Side;
cin>>Area;
Side=sqrt(Area);
cout<<"0ne Side of the Square:"<<Side<<endl;
} All India 2013

Аnswer:
<iostream.h>→ cout,cin
<math.h> →sqrt( )

Question 5 :
Observe the following C ++ code and write the name(s) of the header file(s), which will be essentially required to run it in a C++ compiler.

void main()
{
int Number;
cin>>Number;
if(abs(Number) == Number); 
cout<<"Positive"<<endl;
} Delhi 2013

Аnswer:
<iostream.h>→ cout, cin
<math.h>→abs( )

Question 6:
Name the header file(s), which are essentially required to run the following program segment.

void main()
}
char A='K',B;
if(islower(A))
B=toupper(A);
else
B='*';
cout<<A<<"turned to"<<B<<endl:
} Delhi 2013C

Аnswer:
<iostream.h>→cout,cin
<ctype.h>→ islower( ); i supper( )

Question 7:
Write the names of the header files to which the following belong:

  1. puts( )
  2. sin( ) Delhi2009

Аnswer:
puts( )→<stdio.h>
sin( )→<math.h>

Question 8:
Write the names of the header files to which the following belong:

  1. setw( )
  2. sart( ) All India 2009

Аnswer:
setw( )→<iomanip.h>
sqrt( )→<math.h>

Question 9:
Write the names of the header files to which the following belong:

  1. puts( )
  2. randomizer( ) Delhi2009c

Аnswer:
puts( )→<stdio.h>
randomize( )→<stdlib.h>

 

2 Marks Questions

Question 10:
Rewrite the following C++ code after removing any/all syntactical errors with each correction underlined.
NOTE: Assume all required header files are already being included in the program.

void main()
{
cout<<"Enter an Alphabet:"; 
cin>>CH ;
switch(CH) 
case 'A' cout<<"Ant";Break; 
case ’B' cout<<"Bear”;Break;
} All India 2017

Аnswer:

The correct code is:
void main()
{
char CH:
cout<<”Enter an Alphabet:";
cin>>CH ;
switch(CH)
{
case 'A': cout«"Ant"; break:
case 'B'x cout<<"Bear"; break:
}
}

Question 11:
Observe the following C++ code very carefully and rewrite it after removing any/all syntactical errors with each correction underlined.
NOTE Assume all required header files are already being included in the program.

#Define float MaxSpeed = 60.5; 
void main()
int MySpeed 
char A!ert =‘N’; 
cin>>MySpeed; 
if MySpeed>MaxSpeed 
Alert ='Y’; 
cout<<Alert<<endline;
} All India 2015

Аnswer:

The correct code is:
#define float Max Speed = 60.5; 
void main() 
{
int MySpeedi;
char Alert = 'N'; 
cin>>My Speed; 
if(MySpeed>MaxSpeed) 
Alert = 'y';
cout<<Alert<<endl;
}

Question 12:
Write the output of the following C ++ program code:
NOTE Assume all required header files are already being included in the program.

void Location(int &X, int Y=4) 
Y += 2;
X += Y;
}
void main()
{
int PX=10, PY=2;
Location(PY); 
cout<<PX<<","<<PY<<endl; 
location(PX,PY); 
cout<<PX<<","<<PY<<endl;
} All Indio 2015

Аnswer:
The output will be
10, 8
20, 8

Question 13:
Observe the following C++ code very carefully and rewrite it after removing any/all syntactical errors with each correction underlined.
NOTE Assume all required header files are already being included in the program.

//Define float Max=70.0;
Void main()
{
int Speed 
char Stop='N'; 
cin>>Speed; 
if Speed>Max
Stop='Y;
cout<<Stop<<end;
} Delhi 2015

Аnswer:

The correct code is:
#define float Max = 70.0;
void main()
{
int Speed; 
char stop = 'N'; 
cin>>Speed; 
if(Speed>Max)
Stop = 'Y'; 
cout<<Stop<<endl;
}

Question 14:
Write the output of the following C++ program code:
NOTE Assume all required header files are already being included in the program.

void Position(int &Cl,int C2=3)
{ 
Cl+=2;
C2+=Y;
}
void main()
{
int P1=20, P2=4; 
Position(P1); 
cout<<Pl<<","<<P2<<endl; 
Position(P2,P1); 
cout<<Pl<<","<<P2<<endl;
} Delhi 2015

Аnswer:
This program code will give error, i.e Y is undefined symbol.

Question 15:
Write the output of the following C ++ program code:
NOTE Assume all required header files are already being included in the program.

void Draw(int & N, CharMark='#')
{
for(int 1=1;I<=N;I++)
cout<<Mark<<endl;
N++;
}
void main()
{
int Count=3; char Sign='*';
Draw(count);
Draw(Count,Sign);
Draw(Count,'&');
} All India 2015C

Аnswer:
The output will be:
#
#
#
*
*
*
*
&
&
&
&
&

Question 16:
Write a user defined function DIVT( ) which takes an integer as parameter and returns whether it is divisible by 13 or not. The function should return 1 if it is divisible by 13, otherwise it should return 0. All India 2014C
Аnswer:

int DIVT(intx)
{ 
if(%u == 0)
return 1; 
else
return 0;
}

Question 17:
What is the difference between actual and formal parameter? Give a suitable example to illustrate using a C++ code.
Delhi 2014
or
Difference between the actual parameters and formal parameters. Also, give a suitable C++ code to illustrate both.
Delhi 2013C; Delhi 2012; All India 2009
Аnswer:
Differences between actual and formal parameters are as follows:

Actual Parameter Formal Parameter
Parameters provided at the time of function calling are called actual parameters. These parameters contain actual values.

Parameters provided at the time of function definition are called formal parameters.

These parameters are simple variable declarations, i.e. they do not contain actual values.

e.g. #inc1ude<iostream.h> 
#include<conio.h> 
void swap(int n1, int n2)   //Formal Parameters
{
int temp = n1; 
n1=n2; 
n2=temp;
cout<<"Values of numl and num2 after swapping:"; 
cout<<n1<<" "<n2;
}
void main()
{
int num1, num2; 
cout<<"Enter two numbers:"; 
cin>>num1>>num2; 
swap(num1,num2);   //Actual Parameters
getch();
}

Question 18:
Find the output of the following program: All India 2014C

#include<iostream.h>
void in(int x, int y, int &z)
}
x+=y;
y--;
z*=(x-y);
}
void out(int z, int y, int &x)
{
x*=y; 
y ++;
z/=(x+y); 
}
void main()
{
int a=20, b=30, c=10; 
out(a,c,b);
cout<<a<<"#"<<b<<"#"<<c<=><"#"<<endl: 
in(b,c,a):
cout<<a<<"@"<<b<<''@"<<c=><<"#"<<endl; 
out(a,b,c);
cout<<a<<"$"<<b<<"$"<<c<<”=>$"<<endl;
}

Аnswer:
Output
20#300#10#
602 0@ 3 0 0@10@
6020$300$3000$

Question 19:
What is the benefit of using default parameter/argument in a function? Give a suitable example to illustrate it using C++ code. All Indio 2013
Аnswer:
A default parameter is a function parameter that has a default value provided to it. If the user does not supply a value for this parameter, the default value will be used. If the user supply a value for the default parameter, the user-supplied value is used. Consider the following program:

void PrintValues(int nValue1, int nValue2=10) 
{
cout<<"1st value:"<<nValue1<<endl; 
cout<<"2nd value :"<<nValue2<<endl;
}
void main()
{
PrintValues(1);   //nValue2 will use default parameter of 10
PrintValues(3.4);  //override default value for nValue2
}
This program produce the following output :
1st value: 1 
2nd value: 10 
1st value: 3 
2nd value: 4

Question 20:
What is the benefit of using function prototype for a function? Give a suitable example to illustrate it using a C++ code
Delhi 2013
Аnswer:
The function prototype serve to ensure that calls to the function are made with the proper number and types of arguments. In the case of function overloading, the different prototypes serve to distinguish which version of the function to call. The computer will complain with an error, if no function prototype is found for any particular call to function.

e.g.
#include<iostream.h>
int square(int);    //Function prototype
void main()
for(int x=l;x<=10;x++) 
cout<<square(x)<<" ":
cout<<endl;
}
int square(int y)   //Function definition
{
return y*y;
}

Question 21:
Find out the expected correct output(s) from the options (i) to (iv) for the following C++ code. Also, find out the minimum and the maximum value that can be assigned to the variable stop used in the code.

void main()
{
randomize();
int Begin=3,stop;
for(int Run=l;Run<4;Run++)
{
stop=random(Begin)+6; 
cout<<Begin++<<stop<<”*";
}
}
(i) 36*46*59*
(ii) 37*46*56*
(iii) 37*48*57* 
(iv) 35*45*57* Delhi 2013C

Аnswer:
Expected output : (ii), (iii)
Minimum value is 6
Maximum value is 8

Question 22:
Go through the C++ code shown below and find out the possible output or output from the suggested output (i) to (iv). Also, write the least value and highest value, which can be assigned to the variable Guess.

#include<iostream.h> 
#include<stdlib.h> 
void main()
{
randomze(); 
int Guess, High=4; 
Guess=random(High)+50; 
for(int C=Guess;C<=55;C++) 
cout<<C<<"#";
(i) 50#51#52#53#54#55#
(ii) 52#53#54#55#
(iii) 53#54#
(iv) 51#52#53#54#55 Delhi 2011

Аnswer:
Possible outputs are (i), (ii)
Least value of Guess = 50
Highest value of Guess = 53

Question 23:
Go through the C++ code shown below, and find out the possible output or output from the suggested Output Options (i) to
(iv) . Also, write the minimum and maximum values, which can be assigned to the variable MyNum.

#include<iostream.h>
#include<stdlib.h> 
void main()
{
randomize(); 
int MyNum,Max=5; 
MyNum=20+random(Max); 
for(int N=MyNum;N<=25;N++) 
cout<<N<<"*";
}
(i) 20*21*22*23*24*25 
(ii) 22*23*24*25*
(iii) 23*24*
(iv) 21*22*23*24*25 All India 2011

Аnswer:
The possible outputs is (ii)
The minimum value of MyNum = 20
The maximum value of MyNum = 24

Question 24:
The following code is from game, which generates a set of 4 random numbers. Yallav is playing this game, help him to identify the correct option(s) out of the four choices given below as the possible set of such numbers generated from the program code, so that he wins the game. Justify your answer.

#include<iostream.h> 
#include<stdlib.h> 
const int Low=15; 
void main()
{
randomize();
int P0INT=5,Number;
for(int 1=1;I<=4;I++)
{
Number=Low+random(POINT); 
cout<<Number<<":";
(i) 19 : 16 : 15 : 18 :
(ii) 14 : 18 : 15 : 16 :
(iii) 19 : 16 : 14 : 18 :
(iv) 19 : 16 : 15 : 16 : Delhi 2010

Аnswers:
(iv) 19 : 16 : 15 : 16 :

Question 25:
The following code is from a game, which generates a set of 4 random numbers. Praful is playing this game, help him to identify the correct option(s) out of the four choices given below as the possible set of such numbers generated from the program code, so that he wins the game. Justify your answer.

#include<iostream.h> 
#include<stdlib.h> 
const int Low=25; 
void main()
{
randomize();
int P0INT=5,Number;
for(int I=1;I<=4;I++)
{
Number=Low + random(POINT); 
cout«Number<<":”; 
POINT--;
}
}

Аnswer:
(iv) 29 : 26 : 25 : 26 :

Question 26:
Study the following program and select the possible output from it

#include<iostream.h> 
#include<stdlib.h> 
const int LIMIT=4; 
void main()
{
randomize(); 
int Points;
Points=100+random(LIMIT); 
for(int P=Points';P>=100;P--) 
cout<<P<<"#"; 
cout<<endl;
}
(i) 103 # 102 # 101 # 100 #
(ii) 100 # 101 # 102 # 103 #
(iii) 100 # 101 # 102 # 103 # 104 #
(iv) 104 # 103 # 102 # 101 # 100 # Delhi 2009

Аnswers:
(i) 103 # 102 # 101 # 100#

Question 27:
Study the following program and select the possible output from it

#include<iostream.h> 
#include<stdlib.h> 
const int MAX=3; 
void main()
{
randomize(); 
int Number;
Number=50+random(MAX); 
for(int P=Number;P>=50;P--) 
cout<<P<<"#”; 
cout<<endl;
}
(i) 53 # 52 # 51 # 50
(ii) 50 # 51 # 52 #
(iii) 50 # 51 #
(iv) 51 # 50 # All India 2009

Аnswers:
(iv) 51 # 50 #

Question 28:
In the following program, find the correct possible output(s) from the options

#include<iostream.h>
#include<stdlib.h> 
void main()
{
randomize(); 
int x=125,y=99; 
int a=random(3)+4; 
int b=random(2)+2; 
for(int i=0;i<a;i++) 
cout<<"&”; 
cout<<x<<",";
for(i=0;i<b;i++) 
cout<<"*"; 
cout<<y<<endl;
}
(i) &&125,*99 
(ii) &&125,**99
(iii) &&&&&&125,**99 
(iv) &&&&125,***99

Аnswers:
(iii) &&&&&&125, **99
(iv) &&&&125, ***99

 

Previous Years Examination Questions (Topic 3)

(1 Mark Questions)

Question 1:
Anil typed the following C++ code and during compilation he found three errors as follows:

(i) Function strlen should have prototype
(ii) Undefined symbol cout
(iii) Undefined symbol endl  All India 2017

On asking, his teacher told him to include necessary header files in the code. Write the names of the header files, which Anil needs to include, for successful compilation and execution of the following code:

void main()
 {
 char Txt [ ] = "Weicome"; 
for (int C=0; (Xstrlen(Txt);C++) 
Txt [C] = Txt[C]+1: 
cout<<Txt<<endl:
}

Answer:

For strlen → <string.h> 
For cout, endl → <iostream.h>

Question 2:
Observe the following program very carefully and write the names of those header file(s), which are essentially needed to compile and execute the following program successfully. All India 2015

typedef char STRING[80] ;
 void main( )
 (
 STRING Txt [] = "We love Peace"; 
int Count = 0: 
while(Txt [Count]! = "\0")
 if(isalpha (Txt[Count]) )
 Txt [Count++] = "@";
 else
 Txt [Count++] = "#";
puts (Txt);
 }

Answer:

<ctype.h> → isalpha 
<stdio.h> → puts

Question 3:
Observe the following program very carefully and write the names of those
header file(s), which are essentially needed to
compile and execute the following program successfully. Delhi 2015

typedef char TEXT[80]; 
void main()
{
TEXT Str [ ]="Peace is supreme"; 
int Index = 0; 
while(Str[Index]1= "\0") 
if(isupper(Str [Index])) Str[Index++] = "#" ;
else
Str[Index++]="*" ; puts(Str);
}

Answer:

<ctype.h>→isupper 
<stdio.h>→ puts

Question 4:
Name the header files that shall be needed for successful compilation of the following C++ code All Indio 2014 C

void main()
 {
 char str[20], str[20]; 
gets(str) ; strcpy(strl,str): 
strrev(str);
 puts(str) ; 
puts(strl);
}

Answer:

<stdio.h> → puts, gets 
<std1ib> → strcpy(),strrev()

Question 5:
Observe the following C++ code and write the name(s) of the header file(s), which will be essentially required to run it in a C++ compiler.

void main()
{
 char Text[20],C; 
cin>>Text;
 C=tolower(Text[0]) ; 
cout<<C<<"is the first char of"
 <<Text<<endl ;
}  Delhi 2014

Answer:

<iostream.h>cout, cin 
<ctype.h>tolower( )

Question 6:
Observe the following C++ code and write the name(s) of the header file(s), which will be essentially required to run it in a C++ compiler.

void main()
{
char CH, STRC20]: 
cin>>STR;
CH=toupper(STRCO]); 
cout<<STR<<"starts with"<<CH<<endl ;
}  All India 2014

Answer:

<iostream.h>cin, cout 
<ctype.h> toupper()

Question 7:
Which C++ header file(s) are essentially required to be included to run/execute the following C++ source code?

NOTE Do not include any header file, which is/are not required,

void main( )
{
char STRING [ ] ="SomeThing" ; 
cout<<”Bal ance Characters : "<<160- 
strlen(STRING)<<endl ;
} Delhi 2012

Answer:

<iostream.h>→Cout 
<string.h>→ strlen()

Question 8:
Which C++ header file(s) are essentially required to-be included to run/execute the following C++ source code?
NOTE Do not include any header file, which is/are not required

void main()
{
char STRING[]="SomeThing" ; 
cout<<"Remaining SMS Chars :"<<160- 
strlen(STRING)<<endl ;
} All India 2012

Answer:

<iostream.h> → cout
<string.h> → strlen()

Question 9:
Write the names of the header files, which is/are essentially required to run/execute the following C++ code.

void main()
{
char C, string[]="Excellence Overload"; 
forfint 1=0 ; string[I] !='\0';I++) 
if(string[I]== " ”) 
cout<<endl; 
else 
{
C=toupper(string[I]) ; 
cout<<C;
} Delhi 2011

Answer:

<iostream.h>→cout 
<ctype.h>→toupper()

Question 10:
Write the names of the header files, which is/are essentially required to run/execute the following C++ code.

void main()
{
char CH,Text[] = "+ve Altitude"; 
fortint I = 0;Text [I]!=‘\0’;I++) 
if(TextCI] -- 1) cout<<endl ; 
else 
{
CH = toupper(Text[I]); 
cout<<CH;
}
} All India 2011

Answer:

<ctype.h>→toupper()
<iostream.h>→cout

Question 11:
Which C++ header file(s) will be essentially required to be included to run/execute the following C++ code?

void main() 
{
char Name[20]; 
cin>>Name; 
toupper (Name[0]); 
cout<<Name<<endl;
} Delhi 2011C

Answer:

<iostream.h>→C0ut,cin 
<ctype.h>→ toupper()

Question 12:
Which C++header file(s) will be essentially required to be included to run/execute the following C++ code?

void main()
{
int Eno=123, char EName[]
="Rehan Swarop"; 
cout<<setw(5)<<Eno<setw(25)
<<EName<<endl;
) Delhi 2010

Answer:

<iomanip.h> → setw() 
Ciostream.h> → Cout

Question 13:
Which C++header file(s) will be
essentially required to be included to run/execute the following C++ code?

void main()
{ 
int Rno=24;
char Name[]="Aman Singhania";
cout<<setw(10X<Rno<<setw(20)
<<Name<<endl;
} All India 2010

Answer:

<iomanip.h>→setw()
<iostream.h>→cout

(2 Marks Questions)

Question 14:
Find and write the output of the following C++ program code:
NOTE Assume all required header files are already included in the program.

# define Diff(N1,N2)
((N1>N2)?N1-N2:N2-N1)
void main ()
{
int A,B,NUM[] = {10,23,14,54,321 ; 
for(int CNT=4; CNT>0; CNT--)
{
A=NUM[CNT] ;
B=NUM[CNT-1] ; 
cout<<Diff(A,B)<<'#' :
}
} All India 2017

Answer:

Output
22#40#9#13#

Question 15:
Look at the following C++ code and find the possible outputs(s) from the options (i) to (iv) following it. Also, .write the maximum values that can be assigned to each of the variables N and M.
NOTE

• Assume all the required header files are already being included in the code.
• The function random(n) generates an integer between 0 and n-1.

void main()
 {
 randomize() ;
 int N=random(3), M=random(4);
 int DOCK[3][3]
 = {{1,2,3},{2,3,4},1{3,4,5,}}:
 for (int R=0; R<N; R++)
 {
 for(int C=0; C<M; C++)
 cout<<DOCK[R][C]<<" cout<<endl ;
(i) (ii)
1       2      3 1       2      3
2      3      4 2      3      4
3     4       5
(iii) (iv)
1       2 1          2
2      3 2         3
3         4

Answer:
Possible Outputs: (ii) and (iii)
Maximum value of N is 2.
Minimum value of N is 0.
Maximum value of M is 3.
Minimum value of M is 0.

Question 16:
Find and write the output of the following C++ program code: All India 2016
NOTE Assume all required header files are already included in the program.

typedef char TEXT[80]; 
void JumbleUp(TEXT T)
{
int L=strlen(T);
for(int C=0; C<L-1; C+=2)
{
char CT=T[C]:
T[C]=T[C+1] :
T[C+1]=CT;
}
for(C=1: C<L; C+=2)
i f(T [C]>= ’ M ' && T[C]<='U' )
T[C]='@' :
}
void main()
{
TEXT Str="HARMONIOUS";
JumbleUp(Str) ;
cout<<Str<<endl :
}

Answer:

The output will be
AHM@N@OIS@

Question 17:
Look at the following C++ code and find the possible output(s) from the options (i) to (iv) following it. Also, write the maximum and the minimum values that can he assigned to the variable PICKER. All India 2016
NOTE Assume all required header files are already being included in the code. The function random(n) generates an integer between 0 and n -1.

void main()
 {
 int PICKER:
 PICKER=1+random(3) ;
 char COLOURC][5]={"BLUE","PINK”, "GREEN”,"RED"):
 for(int I=0;I<=PICKER; I++)
 {
 for(int J=0;J<=I; J++)
 cout<<COLOUR[J] :
 cout<<endl:
 }
 }
(i) (ii) (iii) (iv)
PINK BLUE GREEN BLUE
PINKGREEN BLUEPINK GREENRED BLUEPINK
PINKGREEN BLUEPINK BLUEPINK
RED

GREEN

BLUEPINK

GREENRED

GREEN

Answer:
The possible outputs are (ii) and (iv)
Minimum value of PICKER = 1
Maximum value of PICKER = 3

Question 18:
Find and write the output of the following C++ program code: Delhi 2016 NOTE Assume all required header files are already included in the program,

typedef char STRING [80];
void MIXITNOW(STRING S)
{
int Size=strlen(S) :
for(int I=0; I<Size-1; I+=2)
Char WS = S[I] ;
S[I] = S[I+1]:
S[I+1]=WS;
}
for( I=1 ; I<Size; I+=2)
if(S[I]>=’M’ && S[I]<=’U’)
S[I]=’@’;
}
void main( )
{
STRING Word = “CRACKAJACK”;
MIXITNOW(Word) ;
cout<<Word<<endl;

Answer:

Output
RCCAAKAJKC

Question 19:
Look at the following C++ code and find the possible output(s) from the options (i) to (iv) following it. Also, write the maximum and the minimum values that can be assigned to the variable CHANGER. Delhi 2016
NOTE Assume all the required header files are already being included in the code. The function random(n) generates an integer between 0 and n -1.

void main()
 {
 randomize();
 int CHANGER;
 CHANGER = random(3);
 char CITY[ ][25] = {"DELHI", "MUMBAI","KOLKATA","CHENNAI"};
 for(int 1=0; I<=CHANGER; I++)
 {
 forlint J=0; J<=I; J++)
 cout<<CITY[J] ;
 cout<< endl;
Important Questions for Class 12 Computer Science (C++) - C++ Revision Tour-1
Answer:

The possible outputs are (i) and (ii)
Minimum value of CHANGER = 0
Maximum value of CHANGER = 2

Question 20:
Study the following program and select the possible output(s) from the options (i) to (iv) following 
it. Also, write the maximum and the minimum values that can be assigned to the variable NUM. 
Delhi 2015
NOTE Assume all required header files are already being included in the program, 
random(n) function generates an integer between 0 and n-1.
void main()
 {
 randomize(); 
int NUM;
 NUM=random(3)+2;
 char TEXT[]="ABCDEFGHIJK";
 for(int 1=1; 1<=NUM; I++)
 for(int J=NUM; J<=7; J++) 
cout<<TEXT( J ) ;
cout<<endl ;
}
}

(i) FGHI       (ii) BCDEFG          (iii) EFGH       (iv) CDEFG
H                                                           H
FGHI              BCDEFG                  EFGH               CDEFG
H                                                           H
FGHI                                                EFGH
FGHI                                                EFGH

Answer:
The possible outputs are (iii) and (iv)
Minimum value of Num = 2
Maximum value of NUM = 4

Question 21:
Study the following program and select the possible output(s) from the options (i) to (iv) following it. Also, write the maximum and the minimum values that can be assigned to the variable VAL. All India 2015
NOTE Assume all required header files are already being included in the program. Random(n) function generates an integer between 0 and n-1.

void main()
{
randomizef);
int VAL;
VAL=random(3) + 2;
char GUESSC] =”ABCDEFGHIJK”;
for(int 1=1; K=VAL; I++)
{
for(int J=VAL; J<=7; J-F-F)
cout<<GUESS[J] ;
cout<<endl ;

(i) BCDEFGH    (ii) CDEFGH    (iii) EFGH    (iv) FGHI
BCDEFGH         CDEFGH             EFGH           FGHI
EFGH           FGHI
EFGH           FGHI

Answer:
The possible outputs are (ii) and (iii).
Minimum value of VAL = 2
Maximum value of VAL = 4

Question 22:
Observe the following C +4- code very carefully and rewrite it after removing any/all syntactical errors with each correction underlined.
NOTE Assume all required header files are already being included in the program,

const float PIE = 3.1416; 
void main( )
{
float Radius =(3.5,6.2,8.6,9.11.Area; 
int N;
cout<<'Enter N (Less than 5)?'; cin>>N;
for (0=0 ; C<N ; C++ )
{
Area=PIE*Radius[C] *Radius CC]; 
cout<<Area<<endline ;
}
} All India 2015c

Answer:
Const float PIE = 3.1416;

void main()
(
float Radius[] = {3.5, 6.2, 8.6, 9.1}, 
Area;
int N;
cout <<"Enter N (Less than 5)?": 
cin>>N ;
for (int C=O: C<N; C++)
{
Area = PIE* Radius[C]* Radi us[C] ; 
cout<<Area<<end!;
}
}

Question 23:
Study the following program and select the possible output(s) from the options (i) to (iv) following it. Also, write the maximum and the minimum values that can be assigned to the variable VALUE. All Indio 2015C
NOTE Assume all required header files are already being included in the program. Random(n) function generates an integer between 0 and n-1.

void main()
{
randomize();
int VALUE;
VALUE=random(2) + 2;
char Y0URTEXT[]
=("ONE”,"TWO","SIX”,"TEN"} ;
for(int Y=0;Y<VALUE; Y++)
COUt<<Y0URTEXT[Y] ;
cout<<"END"<<endl ;
cout<<endl;
}

(i)                             (ii)                               (iii)                                 (iv)
ONETWOEND  ONEENDTWO   ONETWOSIXEND      ONETWOSIXEND

Answer:

The possible outputs are (i) and (iv)
Minimum value of VALUE = 2
Maximum value of VALUE = 3

Question 24:
Deepa has just started working as a programmer in STAR SOFTWARE company. In the company, she has got her first assignment to be done using a C++ function to find the smallest number out of a given set of numbers stored in a one-dimensional array. But she has committed some logical mistakes while writing the code and is not getting the desired result. Rewrite the correct code underlining the corrections done. Do not add any additional statements in the corrected code.
All India 2014C

int find (int a[], int n)
{
int s=a[0]; 
for(int x=l; x<n; x++) 
if(a [x]>s) 
a[x]=s; 
return (s);
}

Answer:
The correct code is

int find (int a[], int n)
{
int S=a[0]; 
for (int x=l; x<n; x++) 
if (a [x]<s)
s=a [x] ; 
return(s);
}

Question 25:
Find output of the following program segment: All India 2014C

#include<iostream.h>
 #include<ctyupe.h>
 void Mycode (char Msg [ ], Lehar CH)
{
 {for(int cnt=0; Msg[cnt3] !
 ="\0";cnt++)
 { if (Msg [cnt]>='B'&& Msg[cnt]<='G’)
 Msg [cnt]=tolower(Msg[cnt);
 else
 if(Msg[cnt]= =’N'  ∪Msg[cnt]=
 = 'n' ∪Msg[cnt]= =' ' )
 Msg[cnt]=CH;
 else
 if(cnt%2= =0)
 Msg[cnt]=toupper(Msg[cnt]);
 else
 Msg[cnt]=Msg[cnt-l];
} }
 void main()
 { 
Char MyText[]="Input Raw";
 Mycode (MyText, '@'
 cout<<"NEW TEXT : "<<MyText<<endl
}

Answer:
Output

NEW TEXT : I@PPT@RRW

Question 26:
Rewrite the following C++ code after removing all the syntax error(s), if present in the code. Make sure that you underline each correction done by you in the code.
Important Note:
Assume that all the required header file are already included, which are essential to run this code.
The correction made by you do not change the logic of the program.

typedef char[50] STRING; 
void main()
City STRING;
gets(City);
cout<<City[0]<<'\t,<<City[2]; 
cout<<City<<endline;
} Delhi 2014

Answer:
The correct code is

typedef char STRING[50] : //Error 1 
void main()
{
STRING City;    //Error 2
gets(City);
cout<<City[o]<<"\t"<<City[2] ; //Error 3
cout<<City<<endl:    //Error 4
}

Question 27:
Read the following C++ code carefully and find out, which out of the given options (i) to (iv) are the expected correct output(s) of it. Also, write the maximum and minimum value that can be assigned to the variable Start used in the code:

void main( )
{
 int Guess[4]={200, 150, 20, 250}; 
int Start=random(2)+2; 
for(int C=Start; C<4; C++) 
cout<<Guess[C]<<"#" ;
}
(i)   200# 150#
(ii)  50#20#
(iii) 150#20#250#
(iv) 20#250# Delhi 2014

Answer:
Correct option is (iv) 20 # 250#
Maximum value of variable Start= 3
Minimum value of variable Start = 2

Question 28:
What is the difference between call by reference and call by value with respect to memory allocation? Give a suitable example to illustrate using C++ code. All India 2014

or

What is the difference between call by value and call by reference? Also, give a suitable C++ code to illustrate both.
All India 2010; Delhi 2009
Answer:
Differences between call by value and call by reference are as follows:
Important Questions for Class 12 Computer Science (C++) - C++ Revision Tour-2

e.g.
Following example illustrates the concept of call by value:
#imclude<iostream.h>
#include<conio.h> 
void swap(int x,int y)
int temp = x; 
x = y; 
y = temp;
cout<<"After swapping\n"; 
cout<<"Inside swap”<<endl ;
cout<<"x : "<<x<<endl; 
cout<<"y : "<<y<<endl ;
}
void main()
{
int x,y;
cout<<"Enter two numbers\n"
 cin>>x>>y; 
swap(x.y);
cout<<”After swapping\n"; 
cout<<"Inside main"<<endl;
 cout<<"x : "<<x<<endl ; 
cout<<"y : "<<y; 
getch( ) ;
}

The following example illustrates the concept of call by reference:

#include<iostream.h>
#include<conio.h> 
void swap(int &x,int &y)
(
int temp = x;
 x = y; 
y = temp;
couK<<'After swapping\n"; 
cout<<"Inside swap"<<endl; 
cout<<"x : "<<x<<endl ; 
cout<<"y : "<<y<<endl ;
}
void main()
{
int x,y;
cout<<"Enter two numbers\n"; 
cin>>x>>y ; 
swap(x,y);
cout<<"After swapping\n” ; 
cout<<"Inside main"<<endl; 
cout<<"x : "<<x<<endl ; 
cout<<"y : "<<y; 
getch( ) ;
}

Question 29:
Rewrite the following C++ code after removing all the syntax error(s), if present in the code. Make sure that you underline each correction done by you in the code. All India 2014
Important Note:
Assume that all the required header files are already included, which are essential to run this code.
The corrections made by you do not change the logic of the program,

typedef char[80] STR; 
void main()
{
Txt STR; 
gets(Txt);
COUt<<Txt[0]<<'\t,«Txt[2] ;
cout<<Txt<<endline;

Answer:
The corrected code is given below:

tvpedef char STR[80] ://Error 1 
void main()
{
STR Txt; //Error 2
gets(Txt);
cout<<Txt[0]<<"\t"<<Txt[2]; //Error 3
cout<<Txt<<endl:    //Error 4

Question 30:
Read the following C++ code carefully and find out, which out of the given options (i) to (iv) are the expected correct output(s) of it. Also, write the maximum and minimum value that can be assigned to the variable Taker used in the code:

void main()
(
int GuessMe[4]={100,50,200,20} ; 
int Taker=random(2)+2; 
for(int Chance=0;Chance
<Taker;Chance++) 
cout<<GuessMe[Chance]<<"#" :
}

(i) 100                              (ii) 50#200#
(iii) 100#50#200#       (iv) 100#50 All India 2014
Answer:
Correct output for the given code would be option
(iii) 100#50#200#
Maximum value of Taker = 3
Minimum value of Taker = 2

Question 31:
Find syntax error(s), if any, in the following program: (Assuming all desired header file(s) are already included)

typedef String [80] char; 
void main()
{
String S;
for (L=0; L<26; C++)
S[L] = L+65;
S[L]="\0": 
cout<<S<<endline :
} Delhi 2013C

Answer:

tvpedef char Strlnq[80] : 
void main ( )
{
String S;
for (int L= 0: L<26; L++)
S[L]=L+65;
S[L]="\0" ; 
cout<<S<<end l ;
}

Question 32:
Based on the following C++ code, find out the expected correct output(s) from the options (i) to (iv). Also, find out the minimum and the maximum value that can be assigned to the variable Guess used in the code at the time when value of Turn is 3.

void main( )
{
 char Result[][10]={"GOLD",
 "SILVER”,"BRONZE"}: 
int Getit=9,Guess : 
for(int Turn=l;Turn<4;Turn++)
 {
 Guess=random(Turn); cout<<Getit-Guess<<Result [Guess]<<"*" ;
}
}
 (i) 9GOLD*9GOLD*8SILVER*
(ii) 9GOLD*7BRONZE*8GOLD*
(iii) 9GOLD*8SILVER*9GOLD*
(iv) 9GOLD*8SILVER*8GOLD*
 All India 2013

Answer:
Correct output is (i) 9G0LD*9G0LD*8SILVER*
Maximum value of Guess is 2
Minimum value of Guess is 0.

Question 33:
Based on the following C++ code, find out the expected correct output(s) from the options (i) to (iv). Also, find out the minimum and the maximum value that can be assigned to the variable Trick used in the code at the time when value of Count is 3

void main()
 {
 char StatusC][10]={"EXCEL”,
 "GOOD"."OK"i;
 int Turn=10,Trick;
 for(int Count=1;Count<4;Count++)
{
 Trick=random(Count); 
cout<<Turn-Trick<<Status
 [T ri ck]«"#" ;
}
}

(i)   10EXCEL# 10EXCEL#80K#
(ii)  10EXCEL#80K#9GOOD#
(iii) 10EXCEL#9GOOD# 10EXCEL#
(iv) 10EXCEL# 10GOQD#80K# Delhi 2013
Answer:
Correct output is (iii) 10EXCEL#9GOOD#10EXCEL#
Minimum value of Trick is 0
Maximum value of Trick is 2

Question 34:
Observe the following program and find out, which output(s) out of (i) to (iv) will not be expected from the program? What will be the minimum and the maximum value assigned to the variable Turn?

#i nclude<iostream.h> 
#include<stdlib.h> 
void main()
 (
 randomize(); 
int Game[]={10.16},P; 
int Turn=random(2)+5; 
for(int T=0; T<2; T++)
 { 
 P=random(2) ;
 cout<<Game[P]+Turn<<"#" ;
}
}

(i) 15#22#      (ii) 22#16#
(iii) 16#21#    (iv) 2I#22# Delhi 2012

Answer:
(i), (iii) and (iv) can never be the output.
Minimum value of Turn =5
Maximum value of Turn =6

Question 35:
Observe the following program and find out which output(s) out of (i) to (iv) will not be expected from the program? What will be the minimum and the maximum value assigned to the variable Chance?

#i nclude<iostream.h>
 #include<stdlib.h> 
void main()
 {
 randomze( ) ; 
int Arr[]={9,6},N; 
int Chance=random(2)+10; 
for(int CO;C<2;C++)
 {
 N=random(2);
 cout<<Arr[N]+Chance<<"#" ;
}
}

(i) 9#6#
(ii) 19#17#
(iii) 19#16#
(iv) 20# 16# All India 2012
Answer:
(i), (ii) and (iv) will not be expected from the program
Maximum value of Chance =11
Minimum value of Chance =10

Question 36:
Rewrite the following program after removing the syntactical errors (if any). Underline each correction.

#include[iostream.h] 
typedef char Text (80); 
void main( )
{
Text T="Indian";
int Count=strlen(T) ;
cout<<T<< ' has ' <<Count<< ' characters '<<endl;
} Delhi 2011

Answer:

# include<iostream.h>
#include<strinq.h> 
typedef char Text[80]: 
void main()
{
Text T="Indian";
int Count=strlen(T) ; cout<<T<<"has"<<Count
<<"characters"<<end1 ;
}

Question 37:
Rewrite the following program after removing the syntactical errors (if any). Underline each correction.

#include<iostream.h> 
typedef char[80] string; 
void main()
{
 string S="Peace"; 
int L=strlen (S) ; 
cout<<3<< 'has'<<L<<'characters'<<endl;
} Delhi 2011

Answer:

#include<iostream.h>
#include<string.h> 
tvpedef char strinq[80]: 
void main()
{
string S="Peace"; 
int L=strlen(S);
cout<<S<< " has "<<L<<characters" <<endl; 
}

Question 38:
Find the output of the following program;

#include<iostream.h> 
void SwitchOver(int AC], int N.intSplit)
{
for ( int K=0 ; K<N ; K++ 
if(K<Spl it)
A[K]+=K; 
else
A[K]*=K;
}
void Display(int A[],int N)
{
for (int KO ; K<N ; K++)
(K%2=0)?cout<<A[K]<<"%" :cout <<A[K]<<endl ;
}
void main()
{
int H[]={30.40.50,20,10,5); 
Switch0ver(H,6,3);
Display (H,6);
} All India 2011

Answer:
Output

30%41 
52%60 
40%25

Question 39:
Find the output of the following program

#includeCiostream.h>
#include<ctype.h>
void changeIt(char Text[],char C)
{
for(int K=0;Text[K]!="\0";K++)
{
if(Text[K]>="F"&&Text[K]<="L") 
Text[K]=tolower(Text[K]); 
else
i f (Text[K]—"E"| |Text[K]=="e" ) Text[KJO; 
else
if(K%2= =0)
Text[K]=toupper(Text[K]) ; 
else
Text[K]=Text[K-1];
}
}
void main()
{
char 0ldText[]="p0wERALone"; 
changeIt(0ldText,); cout<<"New Text: "<<01dText<<endl ;
} Delhi 2010

Answer:
Output

New Text :PPW%RRllN%

Question 40:
Find the output of the following program:

#include<iostream. h>
#include<ctype.h>
void MyCodetchar Msg[],char CH)
{
for(int cnt=0; Msg[cnt]!="\0"; cnt++)
{
if(Msg[cnt]>=”B"&& Msg [cnt]<="G")
Msg[cnt]=tolower(Msg[cnt]); 
else 
if(Msq[cnt]=="A"||Msg [cnt]=="a" )
Msg[cnt]=CH;
else if (cnt % 2==0)
Msg[cnt]=toupper(Msg[cnt]) ; 
else
Msg[cnt]=Msg[cnt-1] ;
}
}
void main()
}
char MyText[]="ApEACeDriVE" ; 
MyCodetMyText, "@"); 
cout<<"NEW TEXT: "<<MyText<<endl;
) All India 2010

Answer:
Output

NEW TEXT:@@e@ccddIIe

Question 41:
Find the output of the following program

#include<iostream.h>
 #include<ctype.h>
 void Encodei(char Info[],int N);
 void main()
 {
 char Memo[]="Justnow";
Encode(Memo, 2);
count<<Memo<<endl;
}
void Encodeichar Info[],int N)
{
 for(int I = 0;Info[I]!= "\0"; I++) 
i f ( I %2= =0 )
 Info[I]=Info[I]-N;
 else 
if(is lower (Info[I]); 
Info[I]=toupper(Info[I]) 
else
 Info[I]=Info[I]+N;
 } Delhi 2009

Answer:
Output

HUqTlOu

Question 42:
Find the output of the following program

#include<iostream.h> 
#include<ctype.h> 
void Secretlchar Msg[],int N);
void main()
{
char SMS[]="rEPorTmE": 
Secret(SMS, 2): 
cout<<SMS<<endl:
}
void Secret(char Msg[],int N)
{
for(int C=O; Msg [C]!="\0”;C++) 
if ( C%2 ==0)
Msg[C]=Msg[C] + N; 
else if(isupper(Msg[C] ) ) 
Msg[C]=tolower(Msg[C]) ) : 
Msg[C]=Msg[C]-N;
} All India 2009

Answer:
Output

teRmttoe

3 Marks Questions

Question 43:
Find the output of the following program

#include<iostream.h> 
void ChangeArray(int Number, int ARR[],int Size)
{
 for(int L= 0; L<Size; L++) 
if ( L<Number)
 ARR[L]+=L; 
else
 ARR[L]*=L;
 void Show(int ARR[],int size)
{
for( int L=0; Ksize; L++)
( L%2 !=0)?cout<<ARR[L]<<"#" : 
cout<<ARR[L]<<endl;
}
void main()
{
int Array[]={30,20,40,10,60,50}; 
ChangeArray(3, Array, 6);
Show(Array, 6);
} Delhi 2011

Answer:
Output

30
21#42
30#240
250#

Question 44:
Find the output of the following program

#include<iostream.h> 
struct Dress 
{
 int size,cost,Tax,Total_Cost;
 };
 void change(Dress &S, int Flag=1)
 {
 if(Flag ==1) S.cost +=20;
 S.Total_Cost=S.cost+
 S.cost*S.Tax/100;
}
 void main()
{
 Dress S1=(40, 580, 8},S2 ={34, 550, 101; change(S1) ;
 cout<<S1.size<<","<<S1.cost .    <<","<<S1,Total_Cost<<endl;
 change(S2, 2);
 cout<<S2.size<<" ,''<<S2.cost <<", "<<S2 .Total_Cost<<endl ;
 } Delhi 2011C

Answer:
Output

40, 600, 648 
34, 550, 605

Question 45:
Find the output of the following program

#include<iostream.h> 
struct POINT
{
 int x, y, z;
 };
 void StepIn(POINT &P, int Step=1)
 {
 P.x+=Step;
 P.y-=Step;
 P.z+=Step;
}
 void main()
 {
 POINT P1={15, 25, 5},
 P2={10, 30, 201;
 StepIn(P1) ;
 StepIn(P2, 4);
 cout<<Pl.x<<', '<<Pl.y<<', '
 <<P2.z<<endl;
} Delhi 2010

Answer:
Output

16,  24, 6 
14, 26, 24 
26, 14, 36

Question 46:
Find the output of the following program

#include<iostream.h> 
struct THREE_D
{
int x, y, z;
};
void MoveIn(THREE_D &T, int Step=1)
{
T.x+=Step;
T.y-=Step;
T.z-=Step;
}
void Move0ut(THREE_D &T,int Step=1)
{
T.x-=Step;
T.y+=Step;
T.z-=Step;
}
void main()
{
THREE_D T1={10, 20, 5),
T2={30,10,40} ;
Moveln (T1) ;
Move0ut(T2, 5); 
cout<<Tl.x<<', '<<Tl.y<<', ' <<Tl.z<<endl;
cout<<T2.x<<', '<<T2.y<<', '<<T2. z<<endl ;
Moveln (T2, 10); 
cout<<T2.x<<' , '<<T2.y<<', ' <<T2.z<<endl ;
} All India 2010

Answer:
Output

11, 19, 4 
25, 15, 35 
35, 5,  25

The post Important Questions for Class 12 Computer Science (C++) – C++ Revision Tour appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – Classes and Objects

$
0
0

Important Questions for Class 12 Computer Science (C++) – Classes and Objects

Previous years Examination Questions
2 Marks Questions

Question 1:
What is the relationship between a class and an object? Illustrate with a suitable example. Delhi 2013C
Аnswers:
Class
• It is a user-defined data type.
• It is a logical framework that combines data and function into a single unit.
e.g

class GABS 
{
int a,b; 
public:
void set() 
{
a=10; 
b=20;
}
void show()
{
cout<<"Value of a and b is"<<a<<b<<endl;
};

Object
• It is an instance of a class.
• It is a physical entity that means it occupies space in a memory. It’s used to access members of the class.
e.g. Suppose “GABS” is the name of the class.
GABS Gl1, G2;
G1.show( );
Both G1 and G2 are the objects of the class “GABS”

Question 2:
Rewrite the following program after removing the syntactical errors (if any). Underline each correction. Delhi 2012

#include<iostream.h> 
class Book 
{
long Bld.Qty; 
public:
void Purchase()
{
cin>>BId<<Qty;
}
void Sale 
{
cout<<setw(5)<<BId<<"o1d:”<<Qty<<endl;
cout<<"New:"<<—Qty<<endl;
}
};
void main()
{
Book B;
B.Purchase();
Sale();
B.Sale();
}

Аnswers:

#include<iostream.h>
#include<iomanip.h> 
class Book
{
long Bid, Qty; 
pub!ic:
void Purchase()
{
cin>>BId>>Qty;
}
void Sale()
cout<<setw(5)<<BId<<"o1d:"<<Qty<<endl; 
cout<<"New:"<<--Qty<<endl;
}
};
void main()
{
Book B;
B.Purchase();
B.Sale(); 
B.Sale();
}

Question 3:
Rewrite the following program after removing the syntactical errors (if any). Underline each correction. Delhi 2012

#include<iostream.h> 
class Item 
{
long IId, Qty; 
public:
void Purchase 
{
cin>>IId>>Qty;
}
void Sale()
{
cout<<setw(5)<<IId<<”old:"<<Qty<<endl;
cout<<"New: "<<--Qty<<endl;
}
};
void main()
{
Item I;
Purchase():
I.Sale();
I.Sale();
}

Аnswers:

#include<iostream.h> 
#include<iomanip.h> 
class Item
{
long lid,Qty; 
public:
void Purchase()
{
cin>>IId>>Qty;
}
void Sale()
{
cout<<setw(5)<<IId<<"01d:"<<Qty<<endl;
cout<<"New:"<<--Qty<<endl;
}
};
void main()
{
Item I;
I.Purchase();
I.Sale();
I.Sale();
}

Question 4:
Rewrite the following program after removing the syntactical error(s) (if any). Underline each correction. Delhi 2012C

#include<iostream.h>
#include<stdio.h>
Class OFFER 
{
int OfferId; 
char Description[80]: 
void Show 
{
cout<<offerId<<" : ”<<Description<<endl;
}
public:
void Enter 
{
cin>>offerId; 
gets>>Description;
}
};
void main()
{
OFFER Obj;
Obj.Enter();
Obj.Show();
}

Аnswers:

#include<iostream.h> 
#include<stdio.h> 
class OFFER
{
int OfferId; 
char Description[80]; 
void Show()
{
cout<<offerld<<":"<<Description<<endl; 
}
public:
void Enter()
{ 
cin>>offerId; 
gets(Description):
}
};
void main()
{
OFFER Obj;
Obj.Enter();
//Obi.Show();
//Show()cannot be called because
//it is a private member
}

Question 5:
What is the difference between members in private visibility mode and the members in public visibility mode inside a class? Also give a suitable C++ code to illustrate both. Delhi 2012
or
Differentiate between public and private visibility modes in context of object oriented programming using a suitable example. Delhi 2011
Аnswers:
A member declared as private remains hidden from outside world and it can only be accessed by the member function of the class in which it is declared. A member declared as public is made available to the outside world. That is , it can be accessed by any function, any expression in the program but only by using an object of the same class type.
e.g-

class A 
private:
int x;
void show(); 
public: 
int y;
void get();
};

The members x and show( ) are private and these are not accessible outside the class where the members y and get( ) are public so these are accessible outside the class.

Question 6:
When is public visibility of a mode applied to members of a class? Also give an example to illustrate. Delhi 2011C
Аnswers:

Question 7:
Rewrite the following C++ program code after removing the syntax error(s) (if any). Underline each correction.
All India 2010

include<iostream.h>
class FLIGHT 
{
long FlightCode;
char Description[25]; 
public
void Addlnfo()
{
cin>>FlightCode; 
gets(Description);
}
void ShowInfo()
{
cout<<FlightCode«":" <<Description<<endl;
}
};
void main()
{
FLIGHT F;
Addlnfo.F();
Showlnfo.F();
}

Аnswers:

Question 8:
Rewrite the following C++ program code after removing the syntax error(s) (if any). Underline each correction.
Delhi 2010

#include<iostream.h> 
class TRAIN 
{
long TrainNo;
char Description[25];
public
void Entry()
{
cin>>TrainNo; 
gets(Description);
}
void Display()
{
cout<<TrainNo<<":"<<Description<<endl;
}
};
void main( )
{
TRAIN T;
Entry. T();
Display.T();
}

Аnswers:

Question 9:
Rewrite the following program after removing the syntactical error(s) (if any) Underline each correction. Delhi 2009C

#include<iostream.h>
class Transport 
{
char Model[20]; 
char Name[20]; 
void Get()
{
gets(Model); 
gets(Name);
}
void Show()
{
cout<<Model<<endl; 
puts(Name);
}
};
void main( )
{
Transport T;
T.Get();
Show();
}

Аnswers:

4-5 Marks Questions

Question 10:
Write the definition of a class BOX in C++ with the following description: All India 2017
important-questions-for-class-12-computer-science-c-classes-and-objects-(160-1)
Аnswer:

 

Question 11:
Write the definition of a class METROPOLIS in C++ with following description: Delhi 2016
important-questions-for-class-12-computer-science-c-classes-and-objects-(160-2)
Аnswer:

 

Question 12:
Write the definition of a class CITY in C++ with following description: All India 2016
important-questions-for-class-12-computer-science-c-classes-and-objects-(160-3)
Аnswer:

 

Question 13:
Write the definition of a class PIC in C++ with following description Delhi 2015
important-questions-for-class-12-computer-science-c-classes-and-objects-(161-1)

Аnswer:

 

Question 14:
Write the definition of a class Photo in C++ with following description: All Indio 2015
important-questions-for-class-12-computer-science-c-classes-and-objects-(161-2)

Аnswer:

 

Question 15:
Write the definition of a class STAFF in C++ with following description: All India 20isc
important-questions-for-class-12-computer-science-c-classes-and-objects-(161-3)
Public Members

  • Enroll( )  //A function to allow user to enter values
    //SID, Type, Name and call
    //AssignPay( ) function
  • SeeData( ) //A function to display all the data members

Аnswer:

Question 16:
Define a class Seminar with the following specification private members: Delhi 2013C
Seminarld long
Topic string of 20 characters
VenueLocation string of 20 characters
Fee float
CalcFee( ) function to calculate Fee depending on VenueLocation

VenueLocation Fee
Outdoor 5000
Indoor Non-AC 6500
Indoor AC 7500

Public members
Register( ) function to accept values for Seminarld, Topic, VenueLocation and call CalcFee( ) to calculate Fee.
ViewSeminarf( ) function to display all the data members on the screen.

Аnswer:

Question 17:
Define a class RESTRA in C++ with following description: Delhi 2012
Private members

  • FoodCode of type int
  • Food of type string
  • FType of type string
  • Sticker of type string
  • A member function GetStickerf( ) to assign the following values for Food Sticker as per the given FType

FType Sticker
Vegetarian GREEN
Contains Egg YELLOW
Non-Vegetarian RED

Public members

  • A function GetFood( ) to allow user to enter values for FoodCode, Food, FType and call function GetSticker( ) to assign Sticker.
  • A function ShowFoodf( ) to allow user to view the content of all the data members.

Аnswer:

Question 18:
Define a class SUPPLY in C++ with following description: All Indio 2012
Private members

  • Code of type int
  • FoodName of type string
  • Sticker of type string
  • FoodType of type string
  • A member function GetTypef ( ) to assign the following values for FoodType as per the given Sticker

Sticker  FoodType
GREEN  Vegetarian
YELLOW  Contains Egg
RED  Non-Vegetarian
Public members

  • A function FoodIn( ) to allow user to enter values for Code, FoodName, Sticker and call function GetType( ) to assign respective FoodType.
  • A function FoodOut( ) to allow user to view the content of all the data members.

Аnswer:

Question 19:
Define a class Candidate in C++with following description: Delhi 2o11
Private members

  • A data member RNo (Registration Number) of type long
  • A data member Name of type string
  • A data member Score of type float
  • A data member Remarks of type string
  • A member function AssignRem( ) to assign the remarks as per the score obtained by a candidate.
  • Score range and the respective remarks are shown as follow:

Score Remarks
>=50  Selected
less than 50  Not Selected
Public members

  • A function ENTER( ) to .allow user to enter values for RNo, Name, .Score and call function AssignRem( ) to assign Remarks.
  • A function DISPLAY( ) to allow user to view the content of all data members.

Аnswer:

Question 20:
Define a class Applicant in C++ with following description: All IndiA 2011
Private members

  • A data member ANo (Admission Number) of type long
  • A data member Name of type string
  • A data member Agg (Aggregate Marks) of type float
  • A data member Grade of type char
  • A member function GradeMe( ) to find the grade as per the aggregate marks obtained by a student. Equivalent aggregate marks range and the respective grades are shown as follow:

Aggregate marks  Grade
>=80 A
less than 80 and >=65 B
less than 65 and >=50 C
less than 50 D
Public members

  • A function ENTER( ) to allow user to enter values for ANo, Name, Agg and call function GradeMe( ) to find the Grade.
  • A function RESULT( ) to allow user to view the content of all data members.

Аnswer:

Question 21:
Define a class ITEM in C++ with the following specification: Delhi 2010
Private members

  • Code of type integer (Item Code)
  • Iname of type string (Item Name)
  • Price of type float(Price of each item)
  • Qty of type integer(Quantity of item stock)
  • Offer of type float(Offer percentage on the item)
  • A member function GetOffer( ) to calculate offer percentage as follows:

If Qty <=50 Offer is 0
If 50<Qtv<=l 00 Offer is 5
If Qty >100 Offer is 10
Public members

  • A function GetStock( ) to allow user to enter values for Code, Iname, Price, Qty and call function GetOffer( ) to calculate offer.
  • A function ShowItem( ) to allow user to view the content of all data members.

Аnswer:

Question 22:
Define a class STOCK in C++ with the following specification: All India 2010
Private members

  • ICode of type integer (Item Code)
  • Item of type string (Item Name)
  • Price of type float(Price of each item)
  • Qty of type integer(Quantity in stock)
  • Discount of type float(Discount percentage on the item)
  • A member function FindDisc( ) to calculate discount percentage as follows:

If Qty <=50 Discount is 0
If 50<Qty<=100 Discount is 5
If Qty >100 Discount is 10 Public members

  • A function Buy( ) to allow user to enter values for ICode, Item, Price, Qty and call function FindDisc( ) to calculate discount.
  • A function ShowAll( ) to allow user to view the content of all data members.

Аnswer:

Question 23:
Define a class RESORT in C++ with the following specification: Delhi 2009
Private members

  • Rno – Data member to store room number
  • Name – Data member to store customer name
  • Charges – Data member to store per day charges
  • Days – Data member to store number of days of stay
  • COMPUTEO – Function to calculate and return amount as days*charges and if the value of days *charges is more than 11000, then as 1.02*Days *Charges

Public members

  • Getinfo( ) Function tfo enter the content Rno, Name, Charges and Days
  • Dispinfo( ) Function to display Rno, Name, Charges, Days and Amount (amount to be displayed by calling function COMPUTE( ))

Аnswer:

Question 24:
Define a class HOTEL in C++ with the following specification: All IndiA 2009
Private members

  • Rno Data member to store room number
  • Name Data member to store customer name
  • Tariff Data member to store per day charges
  • NOD Data member to store number of days of stay
  • CALC( ) Function to calculate and return amount as NOD*Tariff and if the value of NOD*Tariff is more than 10000, then as 1.05 NOD *charges

Public members

  • Checkin( ) Function to enter the content Rno, Name, Tariff and NOD
  • Checkout( ) Function to display Rno, Name, Tariff, NOD and Amount (amount to be displayed by calling function
    CALC( ))

Аnswer:

The post Important Questions for Class 12 Computer Science (C++) – Classes and Objects appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – Object Oriented Programming

$
0
0

Important Questions for Class 12 Computer Science (C++) – Object Oriented Programming

Previous Years Examination & Important Questions
2 Marks Questions

Question 1:
Write any four important characteristics of object oriented programming. Give example of any one of the characteristics using C++.  All India 2016
Answer:
Four important characteristics of object oriented programming are as follows:

(i) Data encapsulation
(ii) Inheritance
(iii) Polymorphism
(iv) Data abstraction

Example of Inheritance

Class Rectangle
{
::::
};
class Area : public Rectangle
{
::::
};

Question 2:
Explain data hiding with an example. All India 2014C
Answer:
Data hiding is a property, where internal data structure of an object is hidden from the outside world. Data hiding helps to secure the data. It is implemented with private and protected keywords. ,
e.g.

class Item
{
private:
int item_no; 
float item_cost; 
public:
void getdata(); 
void putdata();
};

Here, in this example variables item_no and item_cost are hidden, i.e. cannot be directly accessed from outside the class Item.

Question 3:
What is function overloading? Give an example in C++ to illustrate function overloading.
All India 2014,2009

or

What do you understand by function overloading? Give an example illustrating its use in a C++ program. All India 2009
Answer:
When several functions have same name but performing different tasks, then it is known as function overloading. The definitions of these functions are differentiable by the number or types of their arguments.
e.g.

float compute(float radius)
{
return(3.14*radius*radius);
}
float compute(float l, float b)
{
return(l*b)
}
float compute (int b, float h) 
{
 return(0.5*b*h);
}

Question 4:
Write the output of the following C++ code. Also, write the name of feature of Object Oriented Programming used in the following program jointly illustrated by the functions [I] to [IV]. Delhi 2011

#include<iostream.h>
void Print() //Function[I]
{
for(int K=1; K<=60; K++) 
cout<<"-"; 
cout<<endl;
}
void Print(int N) //Function[II]
{
for(int K=1; K<=N; K++) 
cout<<"*"; 
cout<<endl;
}
void Print(int A, int B)//Function[III]
}
for(int K=1; K<=B; K++)
cout<<A*K; 
cout<<endl;
}
void Print(char T, int N)//Function[IV]
{
for(int K=l; K<=N; K++) 
cout<<T; 
cout<<endl;
}
void main!)
{
int U=9, V=4, W=3; 
char C= '@';
Print(C, V);
Print(U, W);
}

Answer:
Feature of C++→ Function overloading The output will be:
@@@@
91827

Question 5:
Write the output of the following C++ code. Also, write the name of feature of Object Oriented Programming used in the following program jointly illustrated by the functions [I] to [IV]: All India 2011

#include<iostream.h>
 void Lined //Function[I]
 {
 for(int L=1;L<=80;L++)
 cout<<"-";
 cout<<endl;
 }
 void Line(int N) //Function[II]
 {
 for(int L=1;L<=N;L++)
 cout«"*";
 cout<<endl:
 }
 void Line(char C,int N) //Function[III]
 {
 for(int L=1:L<=N:L++)
 cout<<C;
 cout<<endl:
 }
 void Line(int M, int N)//Function[IV]
 {
 for(int L=1:L<N;L++)
 cout<<M*L;
 cout<<endl;
 }
 void main()
 {
 int A=9, B=4, C=3;
 char K=’#':
 Line (K,B);
 Line (A,C);

Answer:
Feature of C ++ Function overloading Output will be :
####
91827

Question 6:
What do you understand by Data Encapsulation and Data Hiding? Also, give an example in C++ to illustrate
both. All India 2010
Answer:
Data Encapsulation
The wrapping up of data (member variables) and functions into a single unit is known as data encapsulation. Encapsulation is implemented in C ++ with the help of classes.
Data Hiding
When member data and member function are binded into a single unit then the data is not accessible to the outside world and only those functions, which are wrapped in that class can access it. Data hiding is implemented in C+ + with the help of private and protected keywords.
e.g.
Important Questions for Class 12 Computer Science (C++) - Object Oriented Programming

Question 7:
What do you understand by polymorphism? Give an example illustrating its use in a C++ program. Delhi 2010
Answer:
Polymorphism means processing of data or messages in more than one form. C ++ implements polymoiphism through overloaded functions and overloaded operators,
e.g.

float compute(float a)
{
return a*a;
}
float computer float a,float b)
{
return(a*b); 
}

Question 8:
How are abstraction and encapsulation interrelated? Delhi 2009
Answer:
Abstraction refers to the representation of only the essential features of the real-world object in the program. This process does not include the background details and explanations. This concept of abstraction is used in classes whereas, data encapsulation is the most significant characteristic of the class. By this term, we mean the wrapping up of data and functions which operate on the data, into a single unit called the class. This encapsulation prevents free access to the data within an object.

Question 9:
What is event driven programming?
Answer:
In event driven programming, the user indicates the order of program execution not the programmer. Instead of, the program ‘driving’ the user ‘drives’ the program. Programming, in which the code that responds to the event is called event driven programming.

Question 10:
What is the significance of classes in OOPs?
Answer:
The classes are the manufacturing units of the objects of their type, i.e. it is the class that can be used to create an object. Classes are user defined data types and behave like the built-in types of a programming language. Classes are the basic building blocks of object oriented programming.

Question 11:
What are the advantages of object oriented programming over procedural oriented programming?
Answer:
Advantages of Object Oriented Programming (OOP) over Procedural Oriented Programming (POP)

Object Oriented Programming Procedural Oriented Programming
In OOP, program is divided into parts called objects. In POP, program is divided into small parts called functions.
OOP follows bottom up approach. POP follows top down approach.
OOP provides data hiding that provides more security. POP does not have any proper way for data hiding so it is less secure.
C++, Java, VB.NET, C, .NET, etc. are the examples of OOP language. C, VB, FORTRAN, Pascal etc are the examples of POP language.

Question 12:
Encapsulation is one of the major properties of OOP. How is it implemented in C++? HOTS

or

Define the term data encapsulation in terms of object oriented programming. Give a suitable example using a C++ code to illustrate the same.
Answer:
The wrapping up of data and functions into a single unit is called data encapsulation. That single unit is known as class.
e.g.

class person 
{
char name[30]; 
int age; 
public:
void getdata(void); 
void display(void);
};

The above program implements data hiding as data can’t be accessed directly from outside.

Question 13:
What is operator overloading? Explain with example.
Answer:
The process of making an operator to exhibit or show different behaviour in different situations is called as operator overloading.
e.g. consider the operation of (+) operator. Operation is sum, if operands are integer type and the operation is concatenation, if operands are strings.

The post Important Questions for Class 12 Computer Science (C++) – Object Oriented Programming appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – Constructor and Destructor

$
0
0

Important Questions for Class 12 Computer Science (C++) – Constructor and Destructor

Previous years Examination Questions
2 and 3 Marks Questions

Question 1:
Observe the following C++ code and answer the questions (i) and (ii).
NOTE Assume all necessary files are included.

class TEST 
{
long TCode; 
char TTitle[20]; 
float Score; 
public:
TESTO //Member Function 1 
{
TCode = 100;
strcpy(TTitle,"FIRST Test"); 
Score=0;
}
TEST(TEST &T) //Member Function 2
{
TCode=E.TCode+l; 
strcpy(TTitle,T.TTitle); 
Score=T.Score;
}
};
void main()
{
_____________     //Statement 1
_____________     //Statement 2
}
  1. Which Object Oriented Programming feature is illustrated by the Member Function 1 and the Member Function 2 together in the class TEST?
  2. Write Statement 1 and Statement 2 to execute Member Function 1 and Member Function 2 respectively.
    All Indio 2017

Аnswer:

  1. Constructor overloading feature is illustrated by the Member Function 1 and the Member Function 2 together in the class TEST.
  2. Statement 1
    TEST T1; //To execute Member Function 1
    Statement 2
    TEST T2 = T1; //To execute Member Function 2

Question 2:
Find and write the output of the following C++ program code: Delhi 2016
NOTE Assume all required header files are already being included in the program.

class Stock 
{
long int ID; 
float Rate; 
int Date; 
public:
Stock(){ID=1001 ; Rate=200; Date=l;}
void RegCode(long int I, float R)
{
ID = 1;
Rate=R;
}
void Change(int New,int DT)
{
Rate+=New;
Date=DT;
}
void Show()
{
cout<<"Date:”<<Date<<endl;
cout<<ID<<"#"<<Rate<<endl;
}
};
void main()
{
Stock A,B,C;
A.RegCode(1024,150);
B.RegCode(2015,300); 
B.Change(100,29);
C.Change(-20,20);
A.Show();
B.Show();
C.Show();
}

Аnswer:
Output of the given program would be:
Date : 1
1024#150
Date : 29
2015#400
Date : 20
1001#180

Question 3:
Observe the following C++ code and answer the questions (i) and (ii). Assume all necessary files are included:

class FICTION Delhi 2016 
{
long FCode; 
char FTitle[20]; 
float FPrice; 
public:
FICTION() //Member Function 1 
{
cout<<"Bought"<<endl;
FCode = 100; 
strcpy(FTitle,"Noname");
FPrice=50;
}
FICTION(int C,char T[],float P) //Member Function 2
{
FCode = C;
strcpy(FTitle, T);
FPrice=P;
}
void Increase(float P) //Member Function 3
{
FPrice+=P;
}
void Show() //Member Function 4 
{
cout<<FCode<<":"<<FTitle<<":"<<FPrice<<endl;
}
∼FICTION() //Member Function 5
{
cout<<"Fiction removed!"<<endl;
}
};
void main() //Line 1
{           //Line 2
FICTION F1, F2(101, "Dare”,75); //Line 3
for(int 1=0;I<4;I++)    //Line 4
{    //Line 5
F1. Increase(20);F2.Increase(15); //Line 6
F1. Show();F2.Show(); //Line 7
} //Line 8
} //Line 9
  1. Which specific concept of object oriented programming out of the following is illustrated by Member Functionl and Member Function 2 combined together ?
    • Data Encapsulation
    • Data Hiding
    • Polymorphism
    • Inheritance
  2. How many times the message “Fiction removed!” will be displayed after executing the above C++ code ? Out of Line 1 to Line 9, which line is responsible to display the message “Fiction removed!” ?

Аnswer:

  1. Polymorphism or constructor overloading
  2. 2 times the message “Fiction removed!” will be displayed. Line 9 is responsible to display the message “Fiction removed!”.

Question 4:
Find and write the output of the following C++ program code: All India 2016 NOTE Assume all required header files are already being included in the program.

class Share 
{
long int Code; 
float Rate; 
int DD; 
public:
Share(){Code=1000;Rate=100;DD=1;} 
void GetCode(long int C, float R)
{
Code=C;
Rate=R;
}
void Update(int Change, int D)
{
Rate+=Change;
DD=D;
}
void Status()
{
cout<<"Date: "<<DD<<endl; 
cout<<Code<<"#”<<Rate<<endl;
};
void main()
{
Share S,T,U;
S.GetCode(1324,350);
T.GetCode(1435,250);
S.Update(50,28);
U.Update(-25,26);
S.Status();
T.Status();
U.Status();
}

Аnswer:
Output of the given program would be:
Date: 28
1324#400
Date: 1
1435#250
Date: 26
1000#75

Question 5:
Observe the following C++ code and answer the questions (i) and (ii). All India 2016
NOTE Assume all necessary files are included :

class BOOK 
{
long Code;
char Title[20];
float Price; 
public:
BOOK()//Member Function 1
{
cout<<"Bought"<<endl; 
code=10;
strcpy(Title,"NoTitle"); 
Price=100;
}
BOOK(int C.char T[],float P) //Member Function 2
{
Code=C;
strcpy(Title,T);
Price=P;
}
void Update(float P) //Member Function 3
{
 Price+=P;
}
void Display() //Member Function 4
{
cout<<Code<<":"<<Title<<”:”<<Price<<endl;
}
∼BOOK() //Member Function 5 
{
cout<<"Book Discarded!"<<endl;
}
};
void main() //Line 1
{     //Line 2
BOOK B.C(101,"Truth",350); //Line 3
for(int I=0;I<4;I++) //Line 4
{  //Line 5
B.Update(50);C.Update(20); //Line 6
B.Display();C.Display(); //Line 7
} //Line 8
} //Line 9
  1. Which specific concept of object oriented programming out of the following is illustrated by Member Function 1 and Member Function 2 combined together?
    • Data Encapsulation
    • Polymorphism
    • Inheritance
    • Data Hiding
  2. How many times the message “Book Discarded!” will be displayed after executing the above C++ code? Out of Line 1 to Line 9, which line is responsible to display the message “Book Discarded!”

Аnswer:

  1. Polymorphism or constructor overloading.
  2. 2 times the message “Book Discarded!” will be displayed. Line 9 is responsible to display the message “Book Discarded!”.

Question 6:
Differentiate between Constructor and Destructor functions giving suitable example using a class in C++. When does each of them execute? Delhi 2016
or
Write any two differences between constructor and destructor. Write the function header for constructor and destructor of a class Member. Delhi 2013
or
Differentiate between constructor and destructor functions in a class. Give a suitable example in C+ + to illustrate the difference. Delhi 2012c
or

Differentiate between constructor and destructor function with respect to object oriented programming. All India 2011
Аnswer:

Differences between constructor and destructor :

Constructor Destructor
Its name is same as the class name. Its name is same as the class name preceded by the tilde (-) sign.
It is automatically called whenever an object is created. It is automatically called whenever an object goes out of the scope.
e.g.
class Member 
{
public:
Member() //Constructor
{
cout<<"I am a constructor of Member class";
}
~Member()   //Destructor 
{
cout<<"I am destructor of Member class";
}
};

Question 7:
What is copy constructor? Give an example in C++ to illustrate copy constructor. All Indio 2016C, Delhi 2009
or
What is a copy constructor? Give a suitable example in C++ to illustrate with its definition within a class and a declaration of an object with the help of it. Delhi 2015, All Indio 2015
Аnswer:
Copy Constructor A copy constructor is that constructor which is used to initialise one object with the values from another object of same class during declaration.
e.g.

class Student 
{
int s; 
public:
Student() //Default constructor 
{
s = 10;
}
Student(Student &i)  //Copy constructor
{
s = i.s;
}
};
void main()
{
Student s1;      //Default constructor called 
Student s2(s1);  //Copy constructor called
}

Question 8:
Write the output of the following C++ program code: Delhi 2015
NOTE Assume all required header files are already being included in the program.

class Calc 
{
char Grade: 
int Bonus:
public:
Calc()
{ 
Grade='E';
Bonus=0;
}
void Down(int G) 
{
Grade-=G;
}
void Up(int G)
{
Grade+=G;
Bonus++;
}
void Show()
{
cout<<Grade<<"#"<<Bonus<<endl;
}
};
void main()
{
Calc C;
C.Down(2);
C.Show();
C.Up(7);
C.Show();
C.Down(2);
C.Show();
}

Аnswer:
Output of the given program would be:
C#0
J#1
H#1

Question 9:
Observe the following C++ code and answer the questions (i) and (ii):

class Traveller 
{
long PNR;
char TName[20];
public:
Traveller()  //Function 1
{
cout<<"Ready"<<endl;
}
void Book(long P, char N[]) //Function 2
{
PNR = P;
strcpy(TName,N);
}
void Print() //Function 3
{
cout<<PNR<<TName«endl;
}
∼Traveller() //Function 4
{
cout<<"Booking cancelled!"<<endl; 
}
};
  1. Fill in the blank statements in Line 1 and Line 2 to execute Function 2 and Function 3 respectively in the following code :
    void main()
    {
    Traveller T;
    _______   //Line 1
    _______   //Line 2
    } //Stops here
  2. Which function will be executed at }//Stops here? What is this function referred as? Delhi 2015

Аnswer:

  1. Line 1 → T.Book(20,”XYZ”);
    Line 2 → T.Print( );
  2. ∼Traveller( ) Function will be executed at }// Stops here. This function is referred as destructor.

Question 10:
Write the output of the following C++ program code: All India 2015
NOTE Assume all the required header files are already being included in the program.

class Eval 
{
char Level; 
int Point; 
public:
Eval() {Level= ’E' ; Point=0;} 
void Sink(int L)
{
Level -= L;
}
void Float(int L)
{
Level += L;
Point++;
}
void Show()
{
cout<<Level<<"#"<<Point<<endl;
}
};
void maint()
{
Eval E;
E.Sink(3);
E.Show();
E.Float(7);
E.Show();
E.Sink(2);
E.Show();
}

Аnswer:
Output of the given program would be:
B#0
I#1
G#1

Question 11:
Observe the following C++ code and answer the questions (i) and (ii) : All India 2015

class Passenger
{
long PNR; 
char Name[20]; 
public:
Passenger()    //Function 1
{
cout<<"Ready"<<endl;
}
void Book(long P,char N[]) //Function 2 I
PNR = P; strcpy(Name, N);
}
void Print() //Function 3 
{
cout<<PNR<<Name<<endl;
}
∼Passenger //Function 4
{
cout<<"Booking cancelled!"<<endl;
}
};
  1. Fill in the blank statements in Line 1 and Line 2 to execute Function 2 and Function 3 respectively in the following code :
    void main( )
    {
    Passenger P;
    __________ //Line 1
    __________ //Line 2
    }//Ends here
  2. Which function will be executed at } //Ends here ? What is this function referred as?

Аnswer:

  1. Line 1 → P.Book(10, “ABC” ) :
    Line 2 →P.Print( ) :
  2. ~Passenger( ) function will be executed at } //Ends here. This function is referred as destructor.

Question 12:
Write the output of the following C++ program code: All India 2015c
NOTE: Assume all required header files are already being included in the program.

class Item 
{
int I no;  
char IName[20]; 
float Price;
public: 
Item()
{
Ino=l00;
strcpy(Iname,"None");
Price=100;
{ 
void Assign(int I, char Named, float P)
{
Ino+=I;
strcpyCIName, Name);
Price=P;
}
void RaiseP(float P)
{
Price+=P;
}
void ReduceP(float P) 
{ 
Price-=P;
}
void Disp()
{
cout<<Ino<<":"<<IName<<":"<<Price<<endl;
}
};
void main()
{ 
Item One, Two;
One.Disp();
One.Assignd(1, "Pen", 95); 
Two.Assign(2, "Penci1",55); 
One.RaiseP(lO);
Two.ReduceP(5);
Two.Disp();
One.Disp();
}

Аnswer:
Output of the given program would be:
100 : None : 100
102 : Penci1 : 50
101 : Pen : 105

Question 13:
Observe the following C++ code and answer the questions (i) and (ii): All India 201SC

class EandI
{
int Temperature, Humidity;
char City[30];
public:
EandI()    //Function 1
{
Temperature=0;Humidity=0; 
cout<<"Set to Zero"<<endl;
}
EandI(int T, int H, char C[])    //Function 2
{
Temperature=T;
Humidity=H; 
strcpy(City, C);
}
voidShow()    //Function 3
{
cout<<Temperature<<":"<<Humidity<<endl; 
cout<<City<<endl;
}
∼EandI()    //Function 4
{
cout<<"Data Removed!"<<endl; 
}
};
  1. Fill in the blank lines as Statement 1 and Satement 2 to execute Functions 2 and 3 respectively in the following code:
    void main( )
    {
    Eandl E;
    ___________ //Statement 1
    ___________ //Statement 2
    }//The end of main( ) function here
  2. Which function will be executed at the point where “//The end of main function here” is written in the above code? What is this function called and executed here is known as?

Аnswer:

  1. Statement 1 →
    E. EandI(25,39,”Delhi”);
    Statement 2 → E.Show( );
  2. Function 4 will be executed. It is known as Destructor and will be executed when object of class EandI goes out of scope.

Question 14:
Answer the question (i) and (ii) after going through the following class: All India 2014C

class schoolbag 
{
int pockets; 
public:
schoolbag()    //Function 1
{ 
pockets=30;  
cout<<"The bag has pockets”<<end1;
}
void company()    //Function 2
{
cout<<"The company of the Bag is ABC"<<endl;
}
school bag(int D)    //Function 3
{
pockets=D;
cout<<"Now the Bag has pockets"<<pockets<<endl;
}
∼schoolbag()    //Function 4
{
cout<<”Thanks"<<endl;
}
};
  1. In object oriented programming, what is Function 4 referred as and when does it get invoked/called?
  2. In object oriented programming, which concept is illustrated by Function 1 and Function 3 together?

Аnswer:

  1. Function 4 is referred as destructor and it is get invoked/called whenever an object goes out of scope.
  2. Function 1 and Function 3 combined together referred as constructor overloading, i.e. Polymorphism.

Question 15:
Write four characteristics of a constructor function used in a class. Delhi 2014
Аnswer:

Characteristics of the constructor function used in a class are as follows:

  1. Constructors are special member functions having same name as that of class name.
  2. Constructors do not need to be called explicitly. They are invoked automatically whenever an object of that class is created.
  3. They are used for initialisation of data members of a class.
  4. Constructors do not have a return type and that is why cannot return any value.

Question 16:
Answer the questions (i) and (ii) after going through the following class: Delhi 2014

class Health 
{
int PId,DId; 
public:
Health(int PPId);   //Function 1 
Health();           //Function 2 
Health(Health &H);  //Function 3 
void Entry();       //Function 4 
void Display();     //Function 5
}; 
void main()
{
Health H(20);    //Statement 1
}
  1. Which of the function out of Function 1, 2, 3, 4 or 5 will get executed, when the Statement 1 is executed in the above code?
  2. Write a statement to declare a new object G with reference to already existing object H using Function 3.

Аnswer:

  1. Function 1 will execute, when Statement 1 will be executed in the given code.
  2. Health G(H) ;

Question 17:
Obtain the output of the following C++ program, which will appear on the screen after its execution.
Delhi 2014
Important Note All the desired header files are already
included in the code, which are required to run the code.

class Player 
{
int Score, Level; 
char Game; 
public:
Player(char GGame='A')
{
Score=0;
Level=1;
Game=GGame; 
}
void Start(int SC); 
void Next(); 
void Disp()
{
cout<<Game<<"@”<<Level<<endl; 
cout<<Score<<endl;
}
};
void main()
{
Player P,Q('B');
P.Disp();
Q.Start(75);
Q.Next();
P.Start(120);
Q.Disp();
P.Disp();
}
void Player::Next()
{
Game=(Game=='A')?'B':'A';
}
void Player::Start(int SC)
Score+=SC;
if(Score>=100)
Level=3;
else if(Score>=50)
Level=2;
else
Level=1;
}

Аnswer:
Output of the given program would be:
A@1
0
A@2
75
A@3
120

Question 18:
Obtain the output of the following C++ after its execution. All India 2014
Important Note All the desired header files are already included in the code, which are required to run the code.

class Game 
{
int Level, Score; 
char Type; 
public:
Game(char GType='P')
{
Level=1;Score=0;
Type=GType;
}
void Play(int GS); 
void Changer(); 
void Show()
{
cout<<Type«"@"<<Level<<endl;
cout<<Score<<endl;
}
};
void main()
{
Game A('G'),B; 
B.Show(); 
A.Play(11);
A.Changer);
B.Play(25);
A.Show();
B.Show(); 
}
void Game::Change()
{
Type=(Type=='P')? 'G’:'P’;
}
void Game::Play(int GS)
{
Score+=GS; 
if(Score>=30)
Level=3;
else if(Score>=20) 
Level=2; 
else 
Level=1;
}

Аnswer:
Output of the given program would be:
P@1
0
P@1
11
P@2
25

Question 19:
Answer the questions (i) and (ii) after going through the following class:

class Hospital
{
int Pno.Dno; 
public:
Hospital(int PN):    //Function 1
Hospital();    //Function 2
Hospital(Hospital &H); //Function 3
void In();   //Function 4
void Disp();    //Function 5
};
void main()
{
Hospital H(20); //Statement 1
}
  1. Which of the function out of Functions 1,2,3, 4 or 5 will get executed, when the Statement 1 is executed in the above code?
  2. Write a statement to declare a new object G with reference to already existing object H using Function 3.

Аnswer:

  1. Function 1 will be called, when Statement 1 will be executed.
  2. Hospital G(H);

Question 20:
Write any two similarities between constructors and destructors. Write the function headers for constructor and destructor of a class Flight. All India 2013
Аnswer:

Similarities between constructor and destructor

  1. Both have same name as the class in which they are declared.
  2. If not declared by user both are available in a class by default but now they can only allocate and deallocate memory from the objects of a class, when an object is declared or deleted.

e.g.

class Flight 
{
public:
Flight()    //Constructor
{
cout<<"Constructor for class Flight";
}
∼Flight()    //Destructor
{
cout<<"Destructor for class FIight";
}
};

Question 21:
Answer the questions (i) and (ii) after going through the following class: All India 2013

class Race
{
int CarNo,Track; 
public:
Race();
Race(int CN); 
Race(Race &R); 
void Register(); 
void Driver();
};
void main()
{
Race R;
}
  1. Out of the following, which of the option is correct for calling Function 2?
    Option 1 – Race T(30) :
    Option 2-Race U(R);
  2. Name the feature of object oriented programming, which is illustrated by Function 1, Function 2 and Function 3 combined together.

Аnswer:

  1. Option 1 – Race T(30) is correct.
  2. Constructor overloading i.e. Polymorphism

Question 22:
Write the output of the following program: Delhi 2013c

#include<iostream.h> 
class Quiz 
{
int Round; 
float Score; 
public:
Quiz() {Round = l;Score = 0;}
Quiz(Quiz &Q)
{
Round = Q.Round+1;
Score = Q.Score+10;
}
void GetBonus(float B=5)
{
Score += B;
}
void ShowScore()
{ 
cout<<Round<<"#"<<Score<<endl;
}
}; 
void main()
{
Quiz A;
A.ShowScore();
A.GetBonus(lO);
A.ShowScore();
Quiz B(A);
B.GetBonus();
B.ShowScore();
}

Аnswer:
Output of the given program would be:
1#0
1#10
2#25

Question 23:
Observe the following C++ code carefully and obtain the output, which will appear on the screen after execution of it.
All India 2013

#include<iostream.h>
class Mausam
{
int City, Temp, Humidity; 
public:
Mausam(int C=l)
{
City=C;
Temp=10;
Humidity=63;
}
void Sun(int T)
{
Temp+=T;
}
void Rain(int H)
{
 Humidity+=H;
}
void CheckOut()
{
cout<<City<<":"<<Temp<<"&"<<Humidity<<"%"<<endl;
}
};
void main()
{
Mausam M, N(2);
M.Sun(5);
M.CheckOut();
N.Rain(10);
N.Sun(2);
N.CheckOut();
M.Rain(15);
M.CheckOut();
}

Аnswer:
Output of the given program would be:
1:15&63%
2 :12&73%
1:15&78%

Question 24:
Observe the following C++ code carefully and obtain the output, which will appear on the screen after execution of it.
Delhi 2013

#include<iostream.h> 
class Aroundus 
{
int Place,Humidity,Temp; 
public:
Aroundus(int P=2)
{
Place=P;
Humidity=60;
Temp= 20;
}
void Hot(int T)
{
Temp+=T; 
}
void Humid(int H)
{
Humidity+=H; 
}
void JustSee()
{
cout<<Place<<":"<<Temp<<"&"<<Humidity<<"%"<<endl;
}
};
void main()
{
Aroundus A,B(5);
A.Hot(lO);
A.JustSee();
B.Humid(15);
B.Hot(2);
B.JustSee();
A.Humid(5);
A.JustSee();
}

Аnswer:
Output of the given program would be:
2:30&60%
5; 228.75%
2:30&65%

Question 25:
Answer the questions (i) and (ii) after going through the following class: Delhi 2013 C

class Book 
{
int BookNo; char BookTitle[20];
public:
Book();    //Function 1
Book(Book &);    //Function 2
Book(int,char[]);  //Function 3
void Buy();    //Function 4
void Sell();    //Function 5
};
void main() 
{
  :
  :
{
  1. Name the feature of object oriented programming demonstrated by Function 1, Function 2 and Function 3.
  2. Write statements in C++ to execute Function 3 and Function 4 inside the main( ) function.

Аnswer:

  1. Constructor overloading i.e. Polymorphism
  2. Book B(10, “GABS”) ;
    B.Buy( );

Question 26:
Answer the questions (i) and (ii) after going through the following class: Delhi 2013

class Motor
{
int MotorNo, Track; 
public:
Motor();          //Function 1
Motor(int MN);    //Function 2
Motor(Motor &M);  //Function 3
void Allocate()   //Function 4
void Move();
};
void main() 
{
Motor M;
  :
  :
}
  1. Out of the following, which of the option is correct for calling Function 2?
    Option 1 – Motor N(M);
    Option 2 – Motor P(10) ;
  2. Name the feature of object oriented programming, which is illustrated by Function 1, Function 2 and Function 3 combined together.

Аnswer:

  1. Option 2-Motor P( 10) is correct.
  2. Constructor overloading.

Question 27:
Answer the questions (i) and (ii) after going through the following class: Delhi 2012

class Tour 
{
int LocationCode;
char Location[20]; 
float charges;
public:
Tour()    //Function 1
{
LocationCode = 1; 
strcpy(Location,"PURI"); 
charges = 1200;
}
void TourPlan(float C) //Function 2
{
cout<<LocationCode<<":"<< Location<<":”<<charges<<endl; 
charges += 100;
}
Tour(int LC, char L[], float C)  //Function 3
{
LocationCode=LC; 
strcpy(Location,L); 
charges = C;
}
~Tour()    //Function 4
{
cout<<"TourPlan Cancelled"<<endl;
}
};
  1. In object oriented programming, what are Function 1 and Function 3 combined together as?
  2. In object oriented programming, which concept is illustrated by Function 4? When is this function called/invoked?

Аnswer:

  1. Function 1 and Function 3 combined together referred as constructor overloading, i.e. polymorphism.
  2. Function 4 indicates destructor. This function is called/invoked whenever an object goes out of scope.

Question 28:
Answer the questions (i) and (ii) after going through the following class: All India 2012

class Travel 
{
int PlaceCode; 
char Place[20]; 
float Charges; 
public:
Travel()    //Function 1
{
PlaceCode = 1; 
strcpy(Place, "DELHI");
Charges = 1000;
}
void TravelPlan(float C) //Function 2 
{
cout<<PlaceCode<<":"<<Place<<":"<<Charges<<endl;
}
∼Travel()    //Function 3
{
cout<<"TravelPlan Cancelled"<<endl;
}
Travel(int PC, char P[], float C)    //Function 4 
{
PlaceCode = PC; 
strcpy(Place, P):
Charges = C;
}
};
  1. In object oriented programming, what are Function 1 and Function 4 combined together as ?
  2. In object oriented programming, which concept is illustrated by Function 3? When is this function called/invoked?

Аnswer:

  1. Function 1 and Function 4 combined together referred as constructor overloading, i.e. polymorphism.
  2. Function 3 indicates destructor/ This function is called/invoked whenever an object goes out of scope.

Question 29:
Find the output of the following program: Delhi 2012

#include<iostream.h> 
class Train 
{ 
int TNo.TripNo.PersonCount;
public:
Train(int TN = 1)
{
TNo = TN:
TripNo=0;
PersonCount=0;
}
void Trip(int TC=100)
{
TripNo++;
PersonCount+=TC;
}
void Show()
{
cout<<TNo<<":"<<TripNo<<":"<<PersonCount<<endl;
}
};
void main()
{
Train T(10),N;
N.Trip();
T.Show();
N.Trip(70);
N.Trip(40);
N.Show();
T.Show();
}

Аnswer:
Output of the given program would be:
10:0:0
1:3:210
10:0:0

Question 30:
Find the output of the following program: All India 2012

#include<iostream.h> 
class METRO 
{
int Mno,TripNo,PassengerCount; 
public:
METR0(int Tmno=1)
{
Mno=Tmno:
TripNo=0;
PassengerCount=0;
}
void Trip(int PC=20)
{
TripNo++;
PassengerCount+=PC;
}
void StatusShow()
{
cout<<Mno<<":"<<TripNo<<":"<<PassengerCount<<endl;
};
void main()
{
METRO M(5),T;
M.Trip();
T.Trip(50);
M.StatusShow();
M.Trip(30);
T.StatusShow(); 
M.StatusShow();
}

Аnswer:
Output of the given program would be:
5:1:20
1:1:50
5:2:50

Question 31:
Rewrite the following program after removing the syntactical errors (if any). Underline each correction. Delhi 2011c

#inc1ude<iostream.h> 
#include<stdio.h> 
class AUTO 
{
char Model[20]; 
float Price;
AUTO()
{
Price = 0;
strcpy(Model,"NULL");
}
public:
void GetInfo()
{
cin>>Price; 
gets(Model);
}
void PutInfo()
{
cout<<setw(10)<<Price<<setw(10)<<Model<,<endl;
}
}
void main()
{
AUTO Car; 
Car.GetInfo(); 
Car.PutInfo();
}

Аnswer:

#include<iostream.h>
#include<stdio.h> 
#include<string.h>
#inc1ude<iomanip.h> 
class AUTO
{
char Model[20]; 
float Price; 
public:
AUTO()
{
Price = 0;
strcpy(Model, "NULL”);
}
void Getlnfo()
{
cin>>Price; 
gets(Model);
}
void Putlnfo()
{
cout<<setw(10)<<Price<<setw(10)<<Model<<endl;
}
};
void main()
{
AUTO Car;
Car.Getlnfo();
Car.Putlnfo();
}

Question 32:
Answer the questions (i) and (ii) after going through the following class; All India 2010

class Exam 
{
int Rno, MaxMarks, MinMarks, Marks; 
public:
Exam()    //Module 1
{
Rno - 101; MaxMarks = 100; 
MinMarks = 40; Marks = 75;
}
Exam(int Prno.int Pmarks) //Module 2
{
Rno = Prno; MaxMarks = 100; 
MinMarks = 40; Marks = Pmarks;
}
∼ExamO    //Module 3
{
cout<<"Exam over"<<endl;
}
void show()    //Module 4
{
cout<<Rno<<":"<<MaxMarks<<":"<<MinMarks<<endl; 
cout<<"[MarksGot]"<<Marks<<endl;
}
};
  1. As per object oriented programming, which concept is illustrated by Module 1 and Module 2 together?
  2. What is Module 3 specifically referred as, when do you think Module 3 will be invoked/called?

Аnswer:

  1. Constructor overloading or polymorphism.
  2. Function 3 is referred to as destructor. It is invoked or called, when scope of an object gets over.

Question 33:
Answer the questions (i) and (ii) after going through the following class: Delhi 2016

class TEST
{
int Regno, Max, Min, Score; 
public:
TESTO    //function 1
{
Regno = 101; Max = 100;
Min = 40; Score = 75;
}
TEST(int Pregno.int Pscore) //Function 2
{
Regno = Pregno; Max = 100; 
Min = 40; Score = Pscore;
}
~TEST()    //Function 3
{
cout<<"TEST over"<<endl;
}
void Display()   //Function 4
{
cout<<Regno<<":"<<Max<<":"<<Min<<endl; 
cout<<"[Score]"<<Score<<endl;
}
};
  1. As per object oriented programming, which concept is illustrated by Function 1 and Function 2 together?
  2. What is Function 3 specifically referred as, when do you think Function 3 will be invoked/called?

Аnswer:

  1. Constructor overloading or polymorphism.
  2. Function 3 is referred to as destructor. It is invoked or called, when scope of an object gets over.

Question 34:
Answer the questions (i) and (ii) after going through the following class: HOTS; Delhi 2009

class WORK
{ 
int Workld; char WorkType; 
public:
∼WORK()    //Function 1
{
cout<<"Un-allocated"<<endl;
}
void status()    //Function 2
{
cout<<WorkId<<":"<<WorkType<<endl;
}
WORK()    //Function    3
{
Workld = 10; WorkType = 'T';
}
WoRK(WORK &W)    //Function 4
{
WorkId = W.WorkId+12;
WorkType = W.WorkType+1;
}
};
  1. Which member function, out of Function 1, Function 2, Function 3 and Function 4 shown in the above definition of class WORK is called automatically, when the scope of an object gets over? Is it known as constructor or destructor or overloaded function or copy constructor?
  2. WORK W; //Line 1
    WORK Y(W); //Line 2
    Which member function, out of Function 1, Function 2, Function 3 and Function 4 shown in the above definition of class WORK will be called on execution of statement written as Line 2? What is this function specifically known as out of destructor or copy constructor or default constructor?

Аnswer:

  1. Function 1 is called, when the scope of an object gets over. It is called destructor.
  2. Function 4 will be called and this function is referred to as copy constructor.

Question 35:
Answer the questions (i) and (ii) after going through the following class: Delhi 2009C

class Factory
{
char Name[20]; 
int Workers; 
public:
Factory()    //Function 1
{
strcpy(Name, "Default”); 
Workers = 0;
}
void Details() //Function 2
{
cout<<Name<<endl<<Workers<<endl;
}
Factory(char*act_Name,int No);  //Function 3 
Factory(Factory & F);   //Function 4
};
  1. In object oriented programming, what is function 4 referred as? Also, write a statement which will invoke this function.
  2. In object oriented programming, which concept is illustrated by Function 1, Function 3 and Function 4 together?

Аnswer:

  1. Function 4 is referred to as copy constructor.
    The statement to invoke it as follows:
    Factory F2(“ABC”, 101);
    Factory F3(F2); //Invoking Function 4
  2. Function 1, Function 3 and Function 4 illustrate the concept of constructor overloading; i.e. polymorphism

Question 36:
Answer the questions (i) and (ii) after going through the following class: All India 2009

class Job 
{
int JobId; 
char JobType; 
public:
∼Job()    //Function 1
{
cout<<"Resigned"<<endl;
}
Job()    //Function 2
{
JobId = 10; JobType = 'T';
}
void TellMe()   //Function 3
{
cout<<JobId<<":"<<JobType<<endl;
}
Job(Job &J)    //Function 4
{
JobId = J.JobId+10;
JobType = J.JobType+1;
}
};
  1. Which member function out of Function 1, Function 2, Function 3 and Function 4 shown in the above definition of class Job is called automatically, when the scope of an object gets over? Is it known as constructor or destructor or overloaded function or copy constructor?
  2. Job P; // Line 1
    Job Q(P1 ; // Line 2
    Which member function out of Function 1, Function 2, Function 3 and Function 4 shown in the above definition of class Job will be called on execution of statement written as Line 2? What is this function specifically known as out of destructor or copy constructor or default constructor?

Аnswer:

  1. Function 1 is called, when the scope of an object getsover. It is called destructor.
  2. Function 4 is called, when Line 2 is executed. It is called copy constructor.

Question 37:
Rewrite the following C++ program code after removing the syntax error(s) (if any). Underline each correction. Delhi 2009

#inClude<iostream.h> 
#include<stdio.h> 
class Employee 
{
int EmpId=901; 
char EName[20]; 
public
Employee(){} 
void Joining()
{
cin>>EmpId; 
gets(EName);
}
void List()
{
cout<<EmpId<<":"<<EName<<endl;
}
};
void main()
{
Employee E;
Joining.E();
E.List();
}

Аnswer:

#include<iostream.h> 
#include<stdio.h>
class Employee 
{
int Empld:   //cannot initialise data member here
char EName[20]; 
public:    //: symbol is required after public 
Employee(){EmpId = 901;} 
void Joining()
{ 
cin>>EmpId; 
gets(EName);
}
void List() 
{
cout<<EmpId<<":"<<EName<<endl;
}
};
void main()
{
Employee E;
E.Joining(); //object name is used before members 
E.List();
}

Question 38:
Rewrite the following program after removing the syntactical error(s) (if any). Underline each correction. All India 2009

#include<iostream.h> 
#include<stdio.h> 
class MyStudent 
{
int StudentId=1001; 
char Name[20]; 
public
MyStudent(){}
void Register() 
{
cin>>StudentId;
gets(Name);
}
void Display()
{
cout<<StudentId<<":"<<Name<<endl;
}
};
void Main()
{
Mystudent MS;
Register.MSC();
MS.Display();
}

Аnswer:

#include<iostream.h>
#1nclude<stdio.h> 
class MyStudent
{
int Studentld; 
char Name[20]; 
public:
MyStudent(){Studentld=1001;}
void Register()
{
cin>>StudentId; 
gets(Name);
}
void Display!)
{
cout<<StudentId<<":"<<Name<<endl;
}
};
void main()
{
MyStudent MS;
MS.Reaister();
MS.Display();
}

4 Marks Questions

Question 39:
Define a class CABS in C++ with the following specification: Delhi 2014
Data members

  • CNo – to store Cab No
  • Type – to store a character ‘A’, ‘B’ or ‘C as City Type
  • PKM – to store per Kilometre charges
  • Dist – to store Distance travelled (in KM)

Member functions

  • A constructor function to initialise Type as ‘A’ and CNo as ‘1111’
  • A function Charges( ) to assign PKM as per the following table:
  • A function Register( ) to allow administrator to enter the values for CNo and Type. Also, this function should call Charges( )to adding PKM charges.
  • A function ShowCab( ) to allow user to enter the value of Dist and display CNo, Type, PKM, PKM Dist (as Amount) on screen.
Type PKM
‘A’ 25
‘B’ 20
‘C 15

Аnswer:

class CABS 
{
int CNo; 
char Type; 
float PKM; 
float Dist; 
public;
CABS()
{
 Type = 'A';
 CNo = 1111;
}
void Charges!)
{
if(Type == 'A')
PKM = 25;
else if(Type == 'B')
PKM = 20;
else if(Type == 'C')
PKM = 15;
}
void Register()
{
cout<<"Enter value for CNo:"; 
cin>>CNo;
cout<<"Enter value for Type:"; 
cin>>Type;
Charges();
}
void ShowCab()
{
cout<<"Enter the value of Distance:”; cin>>Dist; 
cout<<"\nCab Number: "<<CNo; 
cout<<"\nType:"<<Type; 
cout<<"\nPer Kilometre Charges:"<<PKM; 
cout<<"\nAmount:"<<PKM*Dist;
}
};

Question 40:
Define a class Tourist in C++ with the following specification: All India 2014
Data members

  • CNo – to store Cab No
  • CType – to store a character A B or C as City Type
  • PerKM – to store per Kilometre charges
  • Distance – to store Distance travelled (in KM)

Member functions

  • A constructor function to initialise CType as A and CNo as ‘0000’
  • A function CityChargesO to assign PerKM as per the following table:
  • A function RegisterCab( ) to allow administrator to enter the values for CNo and CType. Also, this function should call CityChargesO to assign PerKM Charges.
  • A function Display( ) to allow user to enter the value of Distance and display CNo, CType, PerKM, PerKM*Distance (as Amount) on screen.
CType PerKM
A 20
B 18
C 15

Аnswer:

class Tourist 
{
int CNo; 
char CType; 
float PerKM; 
float Distance; 
public:
Tourist()
{
CType = 'A';
CNo = 0000; 
}
void CityCharges()
{
if(CType == 'A')
PerKM = 20;
else if(CType == 'B')
PerKM = 18;
else if(CType == 'C')
PerKM = 15;
}
void RegisterCab()
{
cout<<"Enter the Cab Number:"; 
cin>>CNo;
cout<<"Enter the Cab Type:"; 
Cin>>CType;
CityCharges();
}
void Display()
{
cout<<"Enter the Distance:";
cin>>Distance;
cout<<"Registered details are\n"; 
cout<<"Cab Number:"<<CNo<<endl; 
cout<<"Cab Type:"<<CType<<endl; 
cout<<"Charges per km :"<<PerKM<<endl;
cout<<"Amount:"<<PerKM*Distance<<endl;
}
};

Question 41:
Define a class CONTEST in C + + with the following description: All India 2014C
Private Data Members
Eventno – integer
Description – char (30)
Score – integer
qualified –  char
Public Member functions

  • A constructor to assign initial values Eventno as 11, Description as “School level”, Score as 100, qualified as ‘N’.
  • Input( )-To take the input for Eventno, description and score.
  • Award (int cutoffscore)- To assign qualified as ‘Y’, if score is more than the cutoffscore that is passed as argument to the function, else assign qualified as ‘N’.
  • Displaydata( )-to display all data members.

Аnswer:

class CONTEST
{
private:
int Eventno; 
char Description[30]; 
int Score; 
char qualified; 
public:
CONTEST()
{
Eventno=11;
Description-"School level";
Score-100;
qua1ified='N';
}
void input()
{
cout<<”Enter the event no, description and score"; 
cin>>Eventno>>Description; 
cin>>Score;
}
void Award(int cutoffscore) 
{
if(score>cutoffscore) 
qualified='Y'; 
else
qualified='N';
}
void Displaydata()
{
cout<<"Eventno:"<<Eventno; 
cout<<endl; 
cout<<"Description:";<<Description<<endl; 
cout<<"Score:"<<Score<<endl; 
cout<<"Qualified:"cout<<qualified<<endl;
}
};

Question 42:
Define a class Bus in C++ with the following specifications: HOTS; All India 2013
Data members

  • Busno – to store Bus Number
  • From – to store Place name of origin
  • To – to store Place name of destination
  • Type – to store Bus Type such as ‘O’ for ordinary
  • Distance – to store the Distance in Kilometre
  • Fare – to store the Bus Fare

Member functions

  • A constructor function to initialise Type as ‘O’ and Freight as 500.
  • A function CalcFare( ) to calculate Fare as per the following criteria:
  • A function Allocate! ) to allow user to enter values for Busno, From, To, Type and Distance. Also, this function should call CalcFare( ) to calculate Fare.
  • A function Show( ) to display the content of all the data members on screen.
Type PKM
‘O’ 15* Distance
‘E’ 20* Distance
‘L’ 24* Distance

Аnswer:

class Bus 
{
int Busno; 
char From[25]; 
char To[25]; 
char Type; 
float Distance; 
float Fare; 
public:
Bust()
{
Type = ' '; Fare = 500;
}
void CalcFare()
{
if(Type == ' ')
{
Fare = 15*Distance;
}
else if(Type == 'E')
{
Fare = 20*Distance;
} 
else if(Type == 'L')
{ 
Fare = 24*Distance;
}
}
void Allocated()
{
cout<<"Enter the values for Busno, From, To, Type and Distance";
cin>>Busno; 
cin>>From; 
cin>>To; 
cin>>Type; 
cin>>Distance;
Call C Fared();
}
void Show()
{
cout<<"\nBus No:"<<Busno; 
cout<<"\nFrom:"<<From; 
cout<<"\nTo:"<<To; 
cout<<"\nType:"<<Type; 
cout<<"\nDistance:"<<Distance;
cout<<"\nFare:"<<Fare;
}
};

Question 43:
Define a class Tourist in C++ with the following specification: Delhi 2013
Data members

  • Carno-to store Bus No
  • Origin-to store Place name
  • Destination-to store Place name
  • Type-to store Car Type such as ‘E’ for Economy
  • Distance-to store the Distance in Kilometere
  • Charge-to store the Car Fare

Member functions

  • A constructor function to initialise Type as ‘E’ and Freight as 250
  • A function CalcChargef) to calculate Fare as per the following criteria:
  • A function Enter( ) to allow user to enter values for Carno, Origin, Destination, Type and Distance. Also, this function should call CalcCharge( ) to calculate Fare.
  • A function Show( ) to display the content of all the data members on screen.
Type Charge
‘E’ 16* Distance
‘A’ 22* Distance
‘L’ 30* Distance

Аnswer:

class Tourist 
{
int Carno;
char Origin[20];
char Destination[20];
char Type;
float Distance;
float Charge;
public:
Tourist()
{
Type='E';
Charge=250;
}
void CalcCharge()
{
if(Type=='E')
Charge=16*Distance; 
else if(Type=='A') 
Charge=22*Distance; 
else if(Type='L') 
Charge=30*Distance;
}
void Enter() 
{
cout<<"Enter Carno, Origin, Type, Destination and Distance"; 
cin>>Carno; 
gets(Origin); 
gets(Destination); 
cin>>Type>>Distance; 
CalcCharge();
}
void Show()
{
cout<<"Car No:"<<Carno; 
cout<<"0rigin;"<<0rigin; 
cout<<"Destination:"<<Destination; 
cout<<"Type:"<<Type; 
cout<<" Distance:"<<Distance; 
cout<<"Charge:"<<Charge;
}
};

Computer ScienceImportant Questions for Computer ScienceNCERT Solutions

The post Important Questions for Class 12 Computer Science (C++) – Constructor and Destructor appeared first on Learn CBSE.


Important Questions for Class 12 Computer Science (C++) – Inheritance (Extending Classes)

$
0
0

Important Questions for Class 12 Computer Science (C++) – Inheritance (Extending Classes)

Previous Years Examination & Important Questions
2 Marks Questions

Question 1:
Differentiate between protected and private members of a class in context of Object Oriented Programming. Also give a suitable example illustrating accessibility/non-accessibility of each using a class and an object in C++. All India 2017

or

What is the difference between protected and private members of a class? Give a suitable example in C++ to illustrate with its definition within a class. All India 2015C

Answer:
Private visibility A member declared as private can be accessed only in class. It means that it cannot be accessed outside the class.
Protected visibility A member declared as protected can be accessed inside the class as well as inside its sub class only.

e.g.
class Super 
{
private: 
int x; 
protected: 
int y;
};
class Sub : protected Super 
{
private: 
int z;
public:
void disp()
{
cout<<x<<y<<z;
/*Here y and z can be accessed but x cannot be accessed because it is a private member of Super class*/
}
}:

Question 2:
Differentiate between members, which are present within the private visibility mode with those which are present within the public visibility modes. Delhi 2011
Answer:
Private visibility A member declared as private can be accessed only in class. It means that it cannot be accessed outside class.
Public visibility A member declared as public can be access inside the class as well as outside the class with object of that class.

e.g. class Super 
{
private 
int x; 
public: 
int y;
}:
class sub : private super 
{
private: 
int z; 
public:
void show()
{cout<<x<<y<<z;
/*Here y and z can be accessed because it a private member of super class*/
}
};

Question 3:
Differentiate between public and protected visibilities in context of object oriented programming giving suitable examples for both. Delhi 2008C
Answer:
Public visibility A member declared as public can be access inside the class as well as outside the class with object of that class.
Protected visibility A member declared as protected can be accessed inside the class as well as inside its sub class only. It cannot be accessed outside the class through the object of that class in which it is declared,

e.g. class Super 
{
public: 
int y; 
protected: 
int x; 
protected:
void input()
{
cin>>x>>y;
}
}:
class Sub: public Super
{
public: int z;
void Show()
{
x = 10;
cout<<x<<y<<z;
}
}:
void main()
{
Super SI: 
cin>>Sl.x;
SI.input();/*It cannot be accessed here because it is protected member*/
Sub S2;
cin>>S2.y>>S2.z;/*y and z can be accessed here because these are public members*/
S2.Show( );/*Show( ) can be accessed here because it is public member of Sub class*/
}

4 Marks Questions

Question 4:
Answer the questions (i) to (iv) based on the following:

class First 
{
int X1; 
protected: 
float X2;
public:
First(); 
void Enter1(); void Display1();
};
class Second : private First 
{
int Y1; 
protected:
float Y2; 
public:
Second(); 
void Enter2(); 
void Display();
};
class Third : public Second 
{
int Z1; 
public:
Third(); 
void Enter3();
void Display(); 
}:
void main()
{
Third T; //Statement 1
: _______ //Statement 2
}

(i) Which type of Inheritance out of the following is illustrated in the above example?
Single Level Inheritance, Multilevel Inheritance, Multiple Inheritance
(ii) Write the names of all the member functions, which are directly accessible by the object T of class Third as declared in main() function.
(iii) Write Statement 2 to call function Display!) of class Second from the object T of class Third.
(iv) What will be the order of execution of the constructors, when the object T of class Third is declared inside main()?

Answer:

(i) Multiple Inheritance
(ii) Enter3(), Display!) of class Third, Enter2(),
(iii) Statement2 T.Second::Display():
(iv) First( )→Second( )→Third()

Question 5:
Answer the questions (i) to (iv) based on the following : Delhi 2016

class PRODUCT 
{
int Code: 
char Item[20];
protected: 
float Qty; 
public:
PRODUCT ( );
void GetIn( ); void Show( ):
};
class WHOLESALER
{
int WCode; 
protected:
char Manager[20]; 
public:
WHOLESALER(); 
void Enter(); 
void Display ();
};
class SHOWROOM : public PRODUCT, 
private WHOLESALER
{
char Name[20],City[20];
public:
SHOWROOM();
void Input ();
void View ( );
};

(i) Which type of Inheritance out of the following is illustrated in the above example?
• Single Level Inheritance
• Multilevel Inheritance
• Multiple Inheritance
(ii) Write the names of all the data members, which are directly accessible from the member functions of class SHOWROOM.
(iii) Write the names of all the member functions, which are directly accessible by an object of class SHOWROOM.
(iv) What will be the order of execution of the constructors, when an object of class SHOWROOM is declared?

Answer:

(i) Multiple Inheritance
(ii) Name[20], City[20], Manager[20], Qty
(iii) Input(), View( ), Getln( ), Show( )
(iv) PRODUCT()→ WHOLESALER()
→ SHOWROOM()

Question 6:
Answer the questions (i) to (iv) based on the following: All India 2016

class ITEM
{
int Id;
char IName [20]; 
protected: 
float Qty; 
public:
ITEM();
void Enter(); void View();
};
class TRADER
{
int DCode; 
protected:
char Manager[20]; 
public:
TRADER(); 
void Enter(); 
void View();
};
class SALEPOINT : public ITEM,
private TRADER
{
char Name[20],
Location[20]; 
public:
SALEPOINT(); 
void EnterAll(); 
void ViewAll();
};

(i) Which type of Inheritance out of the following is illustrated in the above example?
• Single Level Inheritance
• Multilevel Inheritance
• Multiple Inheritance
(ii) Write the names of all the data members, which are directly accessible from the member functions of class SALEPOINT.
(iii) Write the names of all the member functions, which are directly accessible by an object of class SALEPOINT.
(iv) What will be the order of execution of the constructors, when an object of class SALEPOINT is declared?

Answer:

(i) Multiple Inheritance
(ii) Name[20], Location[20], Qty, Manager[20]
(iii) EnterAll( ), ViewAll( ), Enter ( ) and View( ) of class ITEM
(iv) ITEM( ) → TRADER() → SALEPOINT( )

Question 7:
Answer the questions (i) to (iv) based on the following: Delhi 2015

class Exterior
{
int OrderId; 
char Address[20]; 
protected:
float Advance;
public:
Exterior(); 
void Book();
void View();
};
class Paint : public Exterior
{
intWallArea, ColorCode; 
protected: 
char Type; 
public:
Paint(); 
void PBook(); 
void PView();
};
class Bill : public Paint
{
float Charges; 
void Calculate(); 
public:
Bill();
void Bi11ing(); 
void Print();
};

(i) Which type of inheritance out of the following is illustrated in the above example?
• Single Level Inheritance
• Multilevel Inheritance
• Multiple Inheritance
(ii) Write the names of all the data members, which are directly accessible from the member functions of class Paint.
(iii) Write the names of all the member functions, which are directly accessible from an object of class Bill.
(iv) What will be the order of execution of the constructors, when an object of class Bill is declared?

Answer:

(i) Multilevel Inheritance
(ii) WallArea, ColorCode, Type, Advance
(iii) Billing! b Print! b PBook( ), PView( ), Book( b View( )
(iv) Exterior() → Paint! ) → Bill( )

Question 8:
Answer the questions (i) to (iv) based on the following: All India 2015

class Interior 
{
int orderId; 
char Address[20]; 
protected:
float Advance; 
public;
Interior(); 
void Book(); 
void View();
}:
class Painting : public Interior
{
int WallArea, ColorCode; 
protected: char Type; 
public:
Painting(); 
void PBook(); 
void PView();
};
class Billing : public Painting 
{
float Charges; 
void Calculate(); 
public:
Billing(); 
void Bill(); 
void BillPrint();
};

(i) Which type of Inheritance out of the following is illustrated in the above example?
• Single Level Inheritance
• Multilevel Inheritance
• Multiple Inheritance
(ii) Write the names of all the data members, which are directly accessible from the member functions of class Painting.
(iii) Write the names of all the member functions, which are directly accessible from an object of class Billing.
(iv) What will be the order of execution of the constructors, when an object of class Billing is declared?

Answer:

(i) Multilevel Inheritance
(ii) WallArea, ColorCode, Type, Advance
(iii) Bill( b BillPrint( ), PBook( ), PView( ), Book( b View! )
(iv) Interior! ) → Painting! ) → Billing! )

Question 9:
Consider the following C++ code and answer the questions from (i) to (iv). Delhi 2014

class Campus
{
long Id;
char City[20];
protected:
char Country[20]; 
public:
Campus(); 
void Register(); 
void Display();
};
class Dept : private Campus
{
long DCode[10]; 
char HOD[20]; 
protected:
double Budget; 
public:
Dept();. 
void Enter(); 
void Show();
};
class Applicant : public Dept
{
long RegNo;
char Name[20]; 
public:
Applicant();
void Enroll (C); 
void View();
};

(i) Which type of inheritance is shown in the above example?
(ii) Write the names of those member functions, which are directly accessed from the objects of class Applicant.
(iii) Write the names of those data members, which can be directly accessed from the member functions of class Applicant.
(iv) Is it possible to directly call function Display( ) of class University from an object of class Dept? (Answer as Yes or No).

Answer:

(i) Multilevel Inheritance
(ii) Enroll! b View ( ), Enter ( ), Show( ).
(iii) RegNo, Name[20], Budget.
(iv) No, because in the given program there is no class named University.

Question 10:
Consider the following C++ code and answer the questions from (i) to (iv). All India 2014

class University 
{
long Id;
char City[20];
protected:
char Country[20]; 
public:
University();
void Register(); 
void Display(); 
};
class Department : private University 
{
long DCode[10]; 
char HOD[20]; 
protected:
double Budget; 
public:
Department(); 
void Enter(); 
void Show();
};
class Student : public Department 
{
long Roll No; 
public:
Student();
void Enroll();
void View();
};

(i) Which type of inheritance is shown in the above example?
(ii) Write the names of those member functions, which are directly accessed from the objects of class Student.
(iii) Write the names of those data members, which can be directly accessible from the member functions of class Student.
(iv) Is it possible to directly call function Display! ) °f class University from an object of class Department?
(Answer as Yes or No).

Answer:

(i) Multilevel inheritance
(ii) Enroll() View( ), Enter( ), Show( ).
(iii) RollNo, Budget.
(iv) No, it is not possible because class Department is inheriting from class University privately. So, all the public and protected members of the class University will become private in class Department and objects cannot access private members of a class.

Question 11:
Consider the following class State: All India 2014C

class State 
{
protected:
int tp: //no. of tourist places 
public:
State()
{
tp = 0;
}
void inctp()
{
tp++;
}
int gettp()
{
return tp;
}
}:

Write a code in C++ to publically derive another class ‘District’ with the following additional members derived in the public visibility’mode.
Data Members
• distname – char (50)
• population – long
Member functions
• dinput() — To enter distname and population.
• doutput() — To display distname and population on screen.
Answer:

class State
{
protected:
int tp; //No. of tourist places public: 
state()
{
tp = 0;
}
void inctp() 
{
tp++;
int gettp()
{
return tp;
}
};
class District : public State
{
public:
char distname[50]; 
long population;
District()
{
distname = " "; 
population = 0;
{
void dinput!)
{
cout<<"Enter distname and population”; 
cin>>distname>>population;
}
void doutput()
{
cout<<"Di stname: "<<distname; cout<<"Population:"
}
};

Question 12:
Consider the following C + + code and answer the questions from (i) to (iv). All India 2013

class Personal
{
int Class, Rno; 
char Section; 
protected:
char Name[20]; 
public:
Personal(); 
void Pentry(); 
void Pdisplay();
}:
class Marks : private Personal 
{
float M[5]; 
protected:
char Grade[5]; 
public:
Marks(); 
void Mentry(); 
void Mdisplay():
};
class Result : public Marks 
{
float Total, Agg; 
public:
char FinalGrade, Comments[20]; 
ResultO() .
void Rcalculate(); 
void RdisplayO;
};

(i) Which type of inheritance is shown in the above example?
(ii) Write the names of those data members, which can be directly accessed from the objects of class Result.
(iii) Write the names of those member functions, which can be directly accessed from the objects of class Result.
(iv) Write the names of those data members, which can be directly accessed from the Mentry() function of class Marks.

Answer:

(i) Multilevel Inheritance
(ii) FinalGrade, Comments [20]
(iii) Rcalculate( ), Rdisplay( ),
Mentry( ), Mdisplay( )
(iv) M[5], Grade[5], Name[20]

Question 13:
Consider the following C + + code and answer the questions from (i) to (iv). Delhi 2013

class Student 
{
int Class, Rno; 
char Section; .
protected:
char SName[20];
public:
Student(); 
void Stentry(); 
void Stdisplay();
};
class Score : private Student
{
float Marks[5];
protected:
char Grade[5]; 
public:
Score(); 
void Sentry(); 
void Sdisplay();
};
class Report : public Score
{
float Total, Avg; 
public:
char OverallGrade, Remarks[20]; 
Report(); 
void REvaluate(); 
void RPrint]);
};

(i) Which type of inheritance is shown in the above example?
(ii) Write the names of those data members, which can be directly accessed from the objects of class Report.
(iii) Write the names of those member functions, which can be directly accessed from the objects of class Report.
(iv) Write the names of those data members, which can be directly accessed from the Sentry() function of class Score.

Answer:

(i) Multilevel Inheritance
(ii)  OverallGrade, Remarks[20].
(iii) REvaluate( ), RPrint( ), Sentry( ),
Sdisplay( ).
(iv) Marks[5], Grade[5], SName[20]

Question 14:
Consider the following and answer the questions given below: Delhi 2013C

class ITEM 
{
char ICodet10]; 
protected:
char IName[20]; 
public:
ITEM(); 
void Enter(); 
void Display();
}:
class SUPPLIER 
{
char SCode[10];
protected:
char SName[25];
 public:
SUPPLIER(): 
void TEnter(); 
void TDisplay();
}:
class SHOP : private SUPPLIER,
public ITEM
{
char SH0PADDRESSC[15],SEmai1[25]; 
public:
SHOP(); 
void Enter(); 
void Display();
}:

(i) Which type of inheritance is shown in the above example?
(ii) Write the name of all the member functions accessible from Enter]) function of class SHOP.
(iii) Write the names of all the member functions accessible through an object of class SHOP.
(iv) What will be the order of execution for the constructors ITEM]), SUPPLIER() and SHOP(), when an object of class SHOP is declared?

Answer:

(i) Multiple Inheritance
(ii) TEnter( ) and TDisplay( ) of class SUPPLIER Enter( ) and Display( ) of both class ITEM and SHOP
(iv) Enter( ) and Display( ) of both class SHOP and ITEM.
(iv) SUPPLIER() → ITEM( ) → SHOP( )

Question 15:
Answer the questions (i) to (iv) based on the following: All India 2012

class COMPANY
{
char location[20]; 
double budget, income; 
protected:
void Accounts(); 
public:
COMPANY(): 
void Register(); 
void Show();
}:
class FACTORY : public COMPANY
{
char location[20];
int workers:
protected:
double Salary; 
void Computer(); 
public:
FACTORY(); 
void Enter(); 
void Show();
};
class SHOP : private COMPANY 
{
char location[20]; 
float area; 
double sale; 
public:
SHOP(); 
void Input(); 
void Output();
};

(i) Name the type of inheritance illustrated in the above C++ code.
(ii) Write the names of data members, which are accessible from the member functions of class SHOP.
(iii) Write the names of all the member functions, which are accessible from objects belonging to class FACTORY.
(iv) Write the names of all the members, which are accessible from objects of class SHOP.

Answer:

(i) Hierarchical Inheritance
(ii) location[20], area, sale
(iii) Enter( ), Register() and Show( ) of both
class FACTORY and COMPANY
(iv) Data Members
None
Member Functions
Input( ), Output( )

Question 16:
Answer the questions (i) to (iv) based on the following: Delhi 2012

class ORGANISATION 
{
char Address[20]; 
double budget,Income; 
protected:
void Compute(); 
public:
ORGANISATION(); 
void Get(); 
void Show();
};
class WORKAREA : public ORGANISATION 
{
char Address[20]; 
int staff; 
protected: 
double pay;
void Calculate(); 
public:
WORKAREA(); 
void Enter(); 
void Display();
};
class SHOWROOM : private ORGANISATION
{
char Address[20]; 
float Area; 
double Sale; 
public:
SHOWROOM();
void Enter!(); 
void Show();
};

(i) Name the type of inheritance illustrated in the above C++ code.
(ii) Write the names of data members, which are accessible from member functions of class SHOWROOM.
(iii) Write the names of the member functions, which are accessible from objects belonging to class WORKAREA.
(iv) Write the names of all the members, which are accessible from objects of class SHOWROOM.

Answer:

(i) Hierarchical Inheritance
(ii) Address[20], Area, Sale
(iii) Enter( ), Display) ), Get( ), Show( )
(iv) Data Members
None
Member Functions
Enter( ), Show( )

Question 17:
Answer the questions (i) to (iv) based on the following: Delhi 2011

class Student
{
int Rno; 
char name[20]; 
float Marks; 
protected:
void Result(); 
public:
Student(); 
void Register();
void Display ();
};
class Faculty 
{
long Fcode; 
char Fname[20]; 
protected: 
float Pay; 
public:
Faculty();
void Enter(); 
void Show();
};
class Course : public Student,
private Faculty
{
long CCode[10]; 
char CourseName[50]; 
char StartDate[8],EndDate[8]; 
public:
Course();
void Commerce();
void CDetai1();
};

(i) Which type of inheritance is illustrated in the above C++ code?
(ii) Write the names of the data members, which is/are accessible from the member function Commerce of class Course.
(iii) Write the name of all the member functions, which are accessible from object of class Course.
(iv) Write the name of all the member function’s, which are accessible from object of class Faculty.

Answer:

(i) Multiple Inheritance
(ii) CCode[10], CourseName[50], StartDate[8], EndDate[8], Pay
(iii) Register( ), Display) ), Commerce) ), CDetail()
(iv) Enter( ), Show( )

Question 18:
Answer the questions (i) to (iv) based on the following: All India 2011

class Student
{
int Roll no; 
char Sname[20]; 
float Marksl; 
protected:
void Result(); 
public:
Student(); 
void Enroll() ; 
void Display!);
}:
class Teacher
{
long Tcode;
char Tname[20]; 
protected:
float Salary; 
public:
Teacher();
void Enter(); 
void Show();
}:
class Course : public Student,
private Teacher
{
long CCode[10]; 
char CourseName[50];
char StartDate[8]; 
char EndDate[8]; 
public:
Course(); 
void Commerce(); 
void CDetail();
}:

(i) Write the name of all the member functions, which are accessible from object of class Course.
(ii) Write the name of the data members, which is/are accessible from the member function Commerce of class Course.
(iii) Write the name of all the member functions, which are accessible from object of class Teacher.
(iv) Which type of inheritance is illustrated in the above C++ code?

Answer:

(i) Enroll( ), Display) ), Commerce) ),
CDetail) )
(ii) CCodeflO], CourseName[50], StartDate[8], EndDate[8], Salary
(iii) Enter(), Show()
(iv) Multiple Inheritance

Question 19:
Answer the questions (i) to (iv) based on the following: All India 2010

class Director 
{
long DID; 
char Name[20]; 
protected:
char Description[40]: 
void Allocate(); 
public:
Director();
void Assign();
void Show();
}: 
class Factory : public Director
{
int FID;
char Address[20]; 
protected: 
int NOE: 
public:
Factory();
void Input(); 
void Output()
}:
class ShowRoom : private Factory
{
int SID: 
char City[20]; 
public:
ShowRoom(); 
void Enter();
void Display!
}:

(i) Which type of inheritance out of the following is illustrated in the above C++ code?
• Single Level Inheritance
• Multilevel Inheritance
• Multiple Inheritance
(ii) Write the names of data members, which are accessible by objects of class type ShowRoom.
(iii) Write the name of all member functions, which are accessible by objects of class type ShowRoom.
(iv) Write the names of all members, which are accessible from member function of class Factory.

Answer:

(i) Multilevel Inheritance
(ii) None
(iii) Enter(), Display()
(iv) Data Members
FID, Address[20], NOE, Description[40]
Member Functions
Input(), Output(), Assign(), Show(), Allocate()

Question 20:
Answer the questions (i) to (iv) based on the following: Delhi 2010

class Chairperson 
{
long CID;
//Chairperson Identification Number
char Cname[20];
protected:
char Description[40]: 
void Allocate(); 
public:
Chairperson(); 
void Assign(); 
void Show();
}:
class Director 
{
char profile[30];
public:
Director();
vateFactory();
voidlnput();
void Output();
}:
class Company : private Chairperson, public Director
{
int CID; //Company ID
char City[20], Country[20]; 
public:
Company(); 
void Enter(); 
void Display();
}:

(i) Which type of inheritance out of the following is illustrated in the above C++ code?
• Single Level Inheritance
• Multilevel Inheritance
• Multiple Inheritance
(ii) Write the names of data members, which are accessible by objects of class type Company.
(iii) Write the name of all member functions, which are accessible by objects of class type Company.
(iv) Write the names of all members, which are accessible from member functions of class Director.

Answer:

(i) Multiple Inheritance
(ii) None
(iii) Enter(), Display(), Input(), Output()
(iv) Data Members
DID, Dname[20], profile[30]
Member functions
Input(), Output()

Question 21:
Answer the questions (i) to (iv) based on the following: Delhi 2009C

class QUALITY 
{
private:
char Material [30]; 
float Thickness; 
protected:
char Manufacturer[20]; 
public:
QUALITY(); 
void Reading(); 
void Printing(); 
};
class QUANTITY : public 
QUALITY
long Order; 
protected: 
int Stock; 
public:
QUANTITY(); 
void Read_Data(); 
void Print_Data();
};
class FABRIC : public QUANTITY 
{
int Fabric_code, Cost; 
public;
FABRIC(); 
void Read(); 
void Show();
};

(i) Write the data members that are accessible by an object of type class FABRIC.
(ii) What type of inheritance is illustrated in the above example?
(iii) Write the names of all the members that can be accessed by the member functions of class FABRIC.
(iv) How many bytes will be required by an object of type FABRIC?

Answer:

(i) None
(ii) Multi Level Inheritance
(iii) Data Members
Fabric_code, Cost, Stock, Manufacturer[20]
Member Functions
Read(), Show(),Read_Data( ), Print_Data( ), Reading)), Printing))
(iv) 64 Bytes

Question 22:
Answer the questions (i) to (iv) based on the following: Delhi 2009

class FacetoFace
{
char CenterCode[10]; 
public:
void Input(); 
void Output();
};
class Online 
{
char Website[50]; 
public:
void SiteIn(); 
void SiteOut();
};
class Training : public FacetoFace, private Online 
{
long Tcode; 
float charge; 
int period; 
public:
void Register(); void Show();
};

(i) Which type of inheritance is shown in above example?
(ii) Write names of all member functions accessible from Show( ) function of class Training.
(iii) Write names of all members accessible through an object of class Training.
(iv) Is function Output() is accessible in function SiteOut()? Justify your answer.

Answer:

(i) Multiple Inheritance
(ii) Register(), Show(), Input(), Output(), Siteln(), SiteOut()
(iii) Data Members None Member Functions Register(), Show(), Input(), Output()
(iv) Yes, it can be accessed by using the object of FacetoFace class, because it is a public member.

Question 23:
Answer the questions (i) to (iv) based on the following; All India 2009

class Regular
{
char SchoolCode[10]; 
public:
void InRegular(); 
void OutRegular();
};
class Distance
{
char StudyCenter[5]; 
public:
void InDistance();
void OutDistance!);
};
class Course : public Regular,
private Distance
{
char Code[5]; 
float Fees; 
int Duration; public:
void InCourse();
void OutCourse();
}:

(i) Which type of inheritance is shown in above example?
(ii) Write names of all member functions accessible from OutCourse( ) function of class Course.
(iii) Write names of all members accessible through an object of class Course.
(iv) Is function InRegular( ) is accessible in function InDistance()? Justify your answer.

Answer:

(i) Multiple Inheritance
(ii) InCourse(), Outcourse(), InDistance(), OutDistance(), InRegular(), OutRegular()
(iii) Data Members None Member Functions InCourse(), OutCourse(), InRegular(), OutRegular()
(iv) Yes, it can be accessed by using.the object of class Regular because it is a public member.

Computer ScienceImportant Questions for Computer ScienceNCERT Solutions

The post Important Questions for Class 12 Computer Science (C++) – Inheritance (Extending Classes) appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – Data File Handling

$
0
0

Important Questions for Class 12 Computer Science (C++) – Data File Handling

Previous Years Examination Questions
1 Marks Questions

Question 1:
Find the output of the following C++ code considering that the binary file CLIENTS.DAT exists on the hard disk with a data of 200 clients: All India 2017

class CLIENTS
{
int CCode;char CName[20]; 
public:
void REGISTER(); void DISPLAY();
}:
void main()
(
fstream File;
File.open("CLIENTS.DAT",ios::binary|ios::in);
CLIENTS C;
File.seekg(6*sizeof(C));
File.read!(char*)&C, sizeof(C)):
cout<<"Client Number:"<<File.tellg()/sizeof(C)+1;
File.seekg(0,ios::end);
cout«"of "<<Fi 1 e.tellg()/sizeof(C)<<endl;
File.close();
}

Question 2:
Find the output of the following C++ code considering that the binary file MEM.DAT exists on the hard disk with a data of 1000 members: Delhi 2016

class MEMBER
{
int Mcode;char MName[20];
public:
void Register();void Display();
};
void main()
{
fstream MFile;
MFile.openCMEM.DAT", ios ::binary| ios :: in); .
MEMBER M;
MFile.read((char*) &M. sizeof(M));
cout<<"Rec :"<<MFile.tellg()/sizeof(M)<< endl;
MFile.read!(char*) &M, sizeof(M));
MFile.read((char*) &M, sizeof(M)); 
cout<<"Rec :"<<MFile.tellg()/sizeof(M)<<endl;
MFile. close();
}

Question 3:
Find the output of the following C++ code considering that the binary file CLIENT.DAT exists on the hard disk with a data of 1000 clients: All India 2016

class CLIENT 
{
int Ccode; char CName[20]; 
public:
void Register(); void Display():
};
void main()
{
fstream CFile;
CFile.open("CLIENT.DAT",ios::binary|ios::in);
CLIENT C;
CFile.read((char*)&C, sizeof(C)); 
cout<<"Rec: "<<CFile.tel 1 g()/sizeof (C)<<endl;
CFile.read((char*)&C, sizeof(C));
CFile.read((char*)&C, sizeof(C)): 
cout<<"Rec:"<<CFile.tellg()/sizeof(C)<<endl;
CFile.close():
}

Question 4:
Find the output of the following C++ code considering that the binary file CLIENT.DAT exists on the hard disk with records of 100 members. Delhi 2016

class CLIENTS
{
int Cno; char Name[20]; 
public:
void In(); void Out();
}:
void main()
{
fstream CF;
CF.open("CLIENTS.DAT", ios::binary|ios: :in);
CLIENTS C;
CF.read((char*)&C,sizeof(C));
CF.read((char*)&C,sizeof(C));
CF.read((char*)&C,sizeof(C)); 
int POS=CF.tellg()/sizeof(C);
cout<<"PRESENT RECORD: "<<P0S<<endl;
CF.close();
}

Question 5:
Find the output of the following C++ code considering that the binary file MEMBER.DAT exists on the hard disk with records of 100 members. All India 2015

class MEMBER
{
int Mno; char Name[20]; 
public:
void In(); void Out(); 
};
void main()
{
fstream MF;
MF.openC"MEMBER.DAT", ios::binary|ios::in); 
MEMBER M;
MF.read((char*)&M. sizeof(M)); 
MF.read((char*)&M, sizeof(M));
MF.read((char*)&M, sizeof(M)); 
int P0SITI0N=MF.tel1g()/sizeof(M); 
cout<<”PRESENT RECORD: ”<<P0SITI0N<<endl ; 
MF.close();
}

Question 6:
Find the output of the following C++ code considering that the binary file GAME. DAT exist on the hard disk with information of around 200 games. All India 2015 c

class GAME 
{
int Gno; char GName[20]; 
public:
void Getln(); void ShowName();
};
void main()
{
fstream GF;
GF.open("GAME.DAT",ios::binary | ios::in); 
GAME G;
GF.seekg(sizeof(G)*5) ;
GF.read((char*)&G, sizeof(G)):
GF.readC(char*)&G, sizeof(G)); 
int REC0RDN0=GF.tel 1g()/sizeof(G); 
cout<<"REC0RDN0: "<<REC0RDN0<<endl; 
GF.close();
}

Question 7:
Fill in the blanks marked as Statement 1 and Statement 2 in the program segment given below with appropriate functions for the required task. Delhi 2014

class Medical
{
int RNo; //Representative Code
char Name[20]; //Representative Name
char Mobile[12]; //Representative Mobile
public:
void Input(); //Function to enter all details
void Show(); //Function to display all details
int RRno()
{
return RNo;
}
void ChangeMobile() //Function to change Mobile
{
cout<<”Changed Mobile:"; 
gets(Mobile);
}
};
void RepUpdate()
{
fstream F;
F.open("REP.DAT", ios::binary|ios::in|ios::out); 
int Change=0; 
int URno;
cout<<"Rno(Rep No-to update Mobile):"; 
cin>>URno;
Medical M;
while(!Change && F.read((char*)&M,sizeof(M)))
{
if(M.RRno() == URno)
{
//Statement l:To call the function to change Mobile No.
____________________________________;
//Statement 2:To reposition file pointer to re-write 
//The updated object back in the file
____________________________________;
F.write!(char*)&M,sizeof(M));
Change++;
}
}
if(Change)
cout<<"Mobile Changed for Rep"<<URno<<endl; 
else
cout<<"Rep not in the Medical "<<endl;
F.close();
}

Question 8:
Fill in the blanks marked as Statement 1 and Statement 2 in the program segment given below with appropriate functions for the required task. All India 2014

class Agency 
{
int ANo; //Agent code
char AName[20];  //Agent name
char Mobile[30];   //Agent mobile 
public:
void Enter(); //Function to enter details of agent
void Disp(); //Function to display details of agent
int RAno() {return ANo;
}
void UpdateMobileO //Function to update Mobile 
{
cout<<"Updated Mobile:"; 
gets(Mobile);
}
};
void AgentUpdateC)
{
fstream F;
F.open("AGENT.DAT",ios::binary|ios::in|ios::out); 
int Updt=0;

int UAno;
cout<<"Ano (Agent No-to update Mobile):"; 
cin>>UAno;
Agency A;
whileUUpdt && F.read((char*)&A,sizeof(A)))
{
if (A.RAnoO == UAno)
{
//Statement 1:To call the function to Update Mobile No.
____________________________________;
//Statement 2:To reposition file pointer to re-write 
//The updated object back in the file
___________________________________;
F.write((char*)&A,sizeof(A)); 
Updt++;
}
}
if(Updt)
cout<<"Mobile Updated for Agent"<<UAno<<endl; 
else ,
cout<<"Agent not in the Agency"<<endl;
F.close();
}

Question 9:
Fill in the blanks.marked as Statement 1 and Statement 2 in the program segment given below with appropriate functions for the required task. All India 2013

class Club
{
long int MNo;             //Member number
char MName[20];          //Member name
char Email[30];          //Email of member
public:
void Register();         //Function to register member
void Disp();             //Function to display details
void ChangeEmail()    //Function to change Email
{
cout<<"Enter Changed Email:"; 
cin>>Email;
}
long int GetMno()
{
return MNo;
}
};
void ModifyData()
{
fstream File;
File.open("CLUB.DAT",ios::binary|ios::in|ios::out); 
int Modify = 0, Position; 
long int ModiMno;
cout<<MMno-whose email required to be modified:";
cin>>ModiMno;
Club CL;
whi1e(!Modify&&Fi1e.read((char*)&CL,sizeof(CL)))
{
if(CL.GetMno() == ModiMno)
{
CL.ChangeEmail();
Position = File.tellgO-sizeof(CL);
//Statement 1:To place file pointer to the required position 
____________________________________;
//Statement 2:To write the object CL onto the binary file 
____________________________________; 
Modify++;
}
}
if(Modify)
cout<<"Email Changed..."<<endl;
else
cout<<"Member not found.. ."<<endl;
File.close();
}

Question 10:
Fill in the blanks marked as Statement 1 and Statement 2 in the program segment given below with appropriate functions for the required task. Delhi 2013

class Customer
{
long int CNo; //Customer number
char CName[20]; //Customer name
char Email[30]; //Email of customer
public:
void Allocate(); //Function to allocate member
void Show(); //Function to show customer data
void ModifyEmail() //Function to modify Email 
{
cout<<Enter Modified Email:"; 
gets(Email);
}
long int GetCno()
{
return CNo;
}
};
void ChangeData()
{
fstream File;
File.open("CUST.DAT", ios::binary|ios::in|ios::out); 
int Change = 0, Location; 
long int ChangeCno;
cout<<"Cno-whose Email required to be modified:";
 cin>>ChangeCno;
Customer CU;
while(!Change && File.read((char*)&CU,sizeof(CU)))
{
if(CU.GetCno() = ChangeCno)
{
CU.ModifyEmai1();
Location = File.tellg()==sizeof(CU);
//Statement 1:To place file pointer to the required position 
______________________________;
//Statement 2:To write the object CU on to the binary file
______________________________;
Change++;
}
}
if(Change)
cout<<”Email Modified..."<<endl;
else
cout<<"Customer not found..."<<endl;
File.close();
}

Question 11:
Fill in the blanks marked as Statement 1 and Statement 2 in the program segment given below with appropriate functions for the required task. Delhi 2013C

class Agent 
{
long ACode; //Agent Code
char AName [20]; //Agent Name
int Commission; 
public:
void Enter(); //Function to enter details of Agent
void Display(); //Function to display details of Agent
void Update(int C) //Function to modify commission
{
Commission = C;
}
int GetCommO {return Commission;} 
long GetAcodeO {return ACode;}
};
void ChangeCommissiondong AC, int CM)
//AC -> Agent Code, whose commission needs to change 
//CM -> New commission 
{
fstream F;
F.open("AGENT.DAT",ios::binary|ios::in|ios::out);
 char Changed = ' N';
Agent A;
while(Changed == 'N' && F.read((char*)&A,sizeof(A)))
{
if(A.GetAcode()==AC)
{
Changed = 'Y’;
A.Update(CM);
//Statement l:To place file pointer to the required position 
___________________________________;
//Statement 2:To write the object A onto the binary file
___________________________________;
}
}
if(Changed=='N')
cout <<"Agent not registered..."; 
F.close ();
}

Question 12:
Fill in the blanks marked as Statement 1 and Statement 2 in the program segment given below with appropriate functions for the required task. Delhi 2012C

#include<fstream.h>
class Movie
{
long MNo;  //Movie Hall Number
char MName[20];   //Movie Name
int Seats; //Number of Vacant Seats
public:
void MovieIn();
void MovieOut();
void Booking(int N) //Function to Book Seats
{
Seats _=N;
}
int RSeats()
{
return Seats;
}
long RMno()
{
return MNo;
}
};
void BookMySeat(long MH,int S) //MH stands for Hall Number
//S stands for Number of Tickets to purchase
{
fstream File;
File.open("M0VIE.DAT", ios::binary|ios::in|ios::out); 
int Found = 0, Booked = 0, Rec;
Movie M;
whileUFound && File.read((char*)&M,sizeof(M)))
{
if(M.RMnoC)==MH)
{
Found = 1;
if((M.RSeats()-S)> 0)
{
M.Booking(S);
Booked = 1;
}
else
cout<<"House Full";
}
}
if(Found && Booked)
Rec = File.tellg()-sizeof(M);
//Statement 1 : To place file pointer to the required position 
______________________;
//Statement 2 : To write the object M on to the binary file
______________________;
}
if(! Found)
cout<<"No updation done as Hall not found.";
File.close();
}

Question 13:
Observe the program segment given below carefully and answer the questions that follow: All India 2012

class Stock 
{
int Ino.Qty; 
char Item[20]; 
public:
void Enter()
{
cin>>Ino; 
gets(Item): 
cin>>Qty;
}
void Issue(int Q) (Qty += Q;}
void Purchase(int Q) (Qty-= Q;)
int GetlnoO {return Ino;}
};
void Purchaseltem(int Pino,int PQty)
{
fstream File;
File.open("STOCK.DAT", ios::binary|ios::in|ios::out); 
Stock S;
int Success = 0;
while(Success == 0 && File.read((char*)&S,sizeof(S)))
{
if (Pino == S.Getlno())
{
S.Purchase(PQty);
____________ //Statement 1 
____________//Statement 2
Success++;
}
}
if(Success == 1)
cout<<"Purchase Updated"<<endl; 
else
cout<<"Wrong item No."<<endl;
File.closeO;
}

(i) Write Statement 1 to position the file pointer to the appropriate place, so that the data updation is done for the required item.
(ii) Write Statement 2 to perform the write operation, so that updation is done in the binary file.

Question 14:
Observe the program segment given below carefully and answer the questions that follow: Delhi 2012

class Inventory 
{
int Ano, Qty; char Article[20]; 
public:
void Input!()
{
cin>>Ano; 
gets(Article); 
cin>>Qty;
}
void Issue(int Q)HQty 4= Q;)
void Procure(int Q) (Qty -= Q;)
int GetAno()(return Ano:)
};
void ProcureArticle(int TAno, int TQty)
{
fstream File;
File.open("ST0CK.DAT", ios::binary|ios::in|ios::out); 
Inventory I; 
int Found = 0;
while(Found == 0 && File.read((char*)&I.sizeof(I)))
{
if (TAno == I.GetAno())
{
I.Procure(TQty);
__________________ //Statement 1
__________________ //Statement 2
Found++;
}
if (Found == 1)
cout<<"Procurement Updated"<<endl; 
else
cout<<"Wrong Article No"<<endl;
File.close();
}
}

(i) Write Statement 1 to position the file pointer to the appropriate place, so that the data updation is done for the required Article.
(ii) Write Statement 2 to perform the write operation, so that the updation is done in the binary file.

Question 15:
Observe the program segment given below carefully and fill in the blanks marked as Statement 1 and Statement 2 using seekg() or seekp() or tellg() or tellp() functions for performing the required task. Delhi 2011

#include<fstream.h>
class product
{
int pno;char pname[20];int qty;
public:
void modifyqty(); //Function is to modify quantity of product
};
void product::modifyqty()
(
fstream fi 1;
fil .open(“product.dat”,ios::binary|ios::in|ios::out); int mpno;
cout«”product number to modify quantity cin»mpno;
whi1e(fi1.read((char*)this.sizeof(product)))
(
if(mpno == pno)
1
cout«”present quantity:”«qty«endl; cout«”changed quantity:”; cin»qty;
int position = ; //Statement 1
; //Statement 2
fil .writet(char*)this,sizeof(product));
}
)
fil.close();
1

Question 16:
Observe the program segment given below carefully and fill in the blanks marked as
Statement 1 and Statement 2. You can use any function from seekg(), seekp(), tellp() and tellg() for performing the required task. Delhi 2011C
#i nclude<fstream.h> class Country ■
{
int Code; char Name[20]; int Population; public:
//Function to search and display the content from a particular record number
void SearchFor(int);
‘■ //Function to modify the content of a particular record number void Update(int);
1;
void Country::SearchFor(int Record)
{
Country C; fstream File;
File.open(“COUNTRY.DAT”,ios::binary|ios::in);
_ File.read((char*)&C,sizeof(C)); ■
//Statementl
■ cout«C.Code«”==>”«C.Name«”==>”<<C.Population<<endl;
File.closet);
}
void Country::Update(int Record)
‘ < *
Country C;
fstream File;
Fi le.open(“COUNTRY.DAT”,ios::binary |ios::in|ios::out);
cin»C.Code;
cin.getline(C.Name,20);
cin»C.Population;
//Statement 2
File.write((char*)&C,sizeof(C));
File.closet);
l 1
i

Question 17:
Observe the program segment given below carefully and fill in the blanks marked as Statement 1 and Statement 2 using seekg(), seekp(), tellp() and tellg() functions for performing the required task. All India 2011
#include<fstream.h> class ITEM {
int Ino; char Iname[20];
float Price;
public:
void ModifyPrice(); //The function to modify price of a particular ITEM
1;
void ITEM::ModifyPrice()
{
fstream File;
Fi 1 e. open(“ITEM.DAT”,ios::binary|ios::in|ios::out); int Cino;
cout«”Item No to modify price:”; cin»Cino;
whi 1 e(Fi 1 e.read((char*)this,sizeof(ITEM)))
{
if(Cino == Ino) ‘
{
cout«”Present Price:”«Price«endl;
‘ cout<<“Changed Price:”; cin»Pri ce;
int FilePos = ; //Statement 1
; //Statement 2
File.write((char*)this,sizeof(ITEM)); //Re-writing the record
File.close!);
I

Question 18:
Observe the program given below carefully and fill in the blanks marked as Statement 1 and Statement 2 using tellg() and seekp() functions for performing the required task. All India 2010
#i nclude<fstream.h> class Customer
long Cno; char Name[20], Mobi1e[12]; public:
//function to allow user to enter the Cno, Name , Mobile void Enter!);
//function to allow user to enter (modify) Mobile number void Modify();
//function to return value of Cno long GetCnoO {return Cno;}

void ChangeMobileC)
{
Customer C; fstream F;
F.open(“CONTACT.DAT”. ios::binary|ios::in|ios::out);
long Cnoc; //Customer number whose mobile number needs to be changed
cin»Cnoc;
while(F.read((char*)&C,sizeof(C)))
{
if(Cnoc == C.GetCnoO)
C.Modify();
//Statement 1 to find the current position of file pointer int Pos =
//Statement 2 to move the file pointer to write the //modified record back onto the file for desired Cnoc
F.writeC(char*)&C,sizeof(C));
1
F.close();
}

Question 19:
Observe the program segment given below carefully and fill in the blanks marked as Statement 1 and Statement 2 using tellg() and seekp() functions for performing the required task. Delhi 2010
#include<fstream.h> class Client (
long Cno;
char Name[20], Email[30]; public:
void Enter(); //Function to allow user to enter the Cno.Name,Email void ModifyO; //Function to allow user to enter(modify) Email long ReturnCnoO (return Cno;}
}; ‘ void ChangeEmail ()
( «•
Client C; •
fstream F;
F.open(“INF0.DAT”,ios::binary|ios::in|ios::out);
long Cnoc; //Client’s number whose Email needs to be changed
cin»Cnoc;
while(F.read((char*)&C,sizeof(C)))
if(Cnoc == C.ReturnCno())
{
C.ModifyO;
//Statement 1 to find the current position of file pointer int Pos =
//Statement 2 to move the file pointer to write the //modified record back onto the file for the desired Cnoc
F.write((char*)&C,sizeof(C));
}
1
F.closeO;
}

Question 20:
Observe the program segment given below carefully and fill in the blanks marked as Line 1 and Line 2 using fstream function for performing the required task. All India 2009
#1nclude<fstream.h> class Library { .
long Ano; char Title[20]; int Qty;
public: ‘
void Enter(int): //Function to allow user to enter the data
void Display(); //Function to display the content
void Buy(int Tqty) //Function to increment qty
{
Qty += Tqty:
}
long GetAnoO {return Ano;}
1;
void BuyBookdong BAno,int BQty) //BAno : Ano of number of book purchased
//QBty : Number of books purchased
Library L; fstream File:
File.open(“STOCK.DAT”.ios::bina ry|ios::in|ios::out); int Position = -1:
whileCPosition «** – 1 && File.read((char*)&L,sizeof(L)))
{
if(L.GetAno( ) = = BAno)
{
L.Buy(BQty): //To update the number of books
Position = File.tellgO-sizeof(L):
//Line 1 : to place the file pointer to the required position //Line 2 : to write the object L on to the binary file
1
i f (P o s i t i o n == -1)
cout«”No updation done as required Ano not found:”; File.close();

Question 21:
Observe the program segment given below carefully and fill in the blank marked as Statement 1 using seekg() or seekp() functions for performing the required task. Delhi 2009C
#i nclude<fstream.h> class File_Object {
int No;
char Name[20]; public:
//Function to read Nth record from the file void Goto_Record(int N);
1;
void File_Object::Goto_Record(int N)
I .
fstream File;
File_Object Record;
. Fi1e.open(“STOCK.DAT”.ios::bina ry|ios::in);
//Statement 1
File.read((char*)&Record,sizeof(Record)); cout<<Record. No<<Record. Name«endl;
}

Question 22:
Observe the program segment given below carefully and fill in the blanks marked as Line 1 and Line 2 using fstream function for performing the required task. Delhi 2009
#i nclude<fstream.h> class Stock
long Ino; char ITem[20]; int Qty; public:
void Get(int); //Function to allow user to enter the Ino, Item, Qty
voidshowO; //Function to display the content ‘
void PurchaseCint Tqty) //Function to increment qty {
Qty += Tqty;
1
long KnowInoO (return Ino;}
void Purchaseitem(long PIno.int Pqty) //Pino : Ino of item purchased
//Pqty : Number of item purchased
{
Stock S; fstream File;
Fi 1 e.open(“ITEMS.DAT”,ios:;binary|ios::in|ios:;out); int Pos = -1;
whileCPos 1 && File.read((char*)&S,sizeof(S)))
if(S.KnowIno() == Pino)
{
S.Purchase(Pqty); //to update the number of items
Pos = File.tel 1 g()-s i zeofC S);
/*Line 1: to place the file pointer to
the required position*/
/*Line 2; to write the object S on to
the binary file*/
1
i f (P o s == -1)
cout«”No updation done as required Ino Not found:”;
File.close!);

Computer ScienceImportant Questions for Computer ScienceNCERT Solutions

The post Important Questions for Class 12 Computer Science (C++) – Data File Handling appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – Pointers

$
0
0

Important Questions for Class 12 Computer Science (C++) – Pointers

Previous years Examination Questions
2 Marks Questions

Question 1:
Obtain the output from the following C++ program as expected to appear on the screen after its execution. Delhi 2014
Important Note:
All the desired header files are already included in the code, which are required to run the code.

void main()
{
char*String="SARGAM"; 
int *Ptr, A[]={l,5,7,9};
Ptr=A; 
cout<<*Ptr<<String<<endl;
String++;
Ptr+=3;
cout<<*Ptr<<String<<endl;
}

Аnswer:
Output of the given program will be
1SARGAM
9ARGAM

Question 2:
Obtain the output from the following C+ + program as expected to appear on the screen after its execution. All India 2014.2013
Important Note:
All the desired header files are already included in the code, which are required to run the code.

void main()
{
char *Text = "AJANTA"; 
int *P,Num[] = {11,5,7,9};
P = Num;
cout<<*P<<Text<<endl;
Text++;
P++;
cout<<*P<<Text<<endl;
}

Аnswer:
Output of the given program will be
1AJANTA
5JANTA

Question 3:
Observe the following C+ + code carefully and obtain the output, which will appear on the screen after execution of it.
Delhi 2013
Important Note:

All the desired header files are already included in the code, which are required to run the code.

void main()
{
char *String = "SHAKTI"; 
int *Point, Value[]={10,15,70,19};
Point = Value;
cout<<*Point<<String<<endl;
String++;
Point++;
cout<<*Point<<String<<endl;
}

Аnswer:
Output of the given program will be
10SHAKTI
15HAKTI

Question 4:
Give the output of the following program segment: (Assuming, all desired header file(s) are already included). Delhi 2013C

void main()
{
float *Ptr,Points[] = {120,50,30,40,10};
Ptr=Points; 
cout<<*Ptr<<endl;
Ptr+=2;
Points[2]+=2.5; 
cout<<*Ptr<<endl:
Ptr++;
(*Ptr)+=2.5; 
cout<<Points[3]<<endl;
}

Аnswer:
Output of the given program will be
20
32.5
42.5

Question 5:
Find the output of the following program: All India 2012

#include<iostream.h> 
#include<conio.h>
#include<ctype.h> 
typedef char Str80[80]; 
void main() 
{
char *Notes;
Str80 Str="vR.zGooD";
int L=6;
Notes = Str; 
while(L>=3)
{
Str[L]=isupper(Str[L])?
tolower(Str[L]); 
toupper(Str[L]); 
cout<<Notes<<endl;
L--;
Notes++; 
getch();
}
}

Аnswer:
Output of the given program will be
vR.zGoOd
R.zGOOD
.zgOOD
ZgOOD

Question 6:
Find the output of the following program: Delhi 2012

#include<iostream.h> 
#include<conio.h>
#include<ctype.h> 
typedef char Txt80[80]; 
void main()
{
char *PText; 
Txt80 Txt="Ur2GReAt"; 
int N=6;
PText=Txt:
while(N>=3)
{
Txt[N]=isupper(Txt[N])? 
tolower(Txt[N]);
toupper(Txt[N]); 
cout<<PText<<endl;
N--;
PText++;
}
}

Аnswer:
Output of the given program will be
Ur2GReat
r2GREat
2GrEat
grEat

Question 7:
In the following program, what will be the possible output(s) from the following options (i), (ii), (iii) and (iv)? Justify your answer. Delhi 2011C

#include<iostream.h> 
#include<stdlib.h> 
#include<string.h> 
#include<conio.h> 
void main()
{
clrscr();
char *Text="1234"; 
int L=strlen(Text);
randomize(); 
for(int I=0;I<L;I++)
{
int Start=random(I)+1; 
char P=Text[Start]; 
cout<<P<<":";
}
getch();
}
(i) 1:3:2:4: 
(ii) 2:2:3:2:
(iii) 2:2:4:4: 
(iv) 2:2:2:3:

Аnswer:
The possible output will be (ii) 2:2:3:2: and (iv) 2:2:2:3:

Question 8:
Find the output of the following program : Delhi 2011

#include<iostream.h>
#include<conio.h> 
void main()
{
int Track[] = {10, 25, 30, 55},*Striker; 
Striker = Track;
Track[1] += 30;
cout<<"Striker"<<*Striker<<endl; 
*Striker -= 10;
Striker++;
cout<<"Next@"<<*Striker<<endl;
Striker += 2;
cout<<"Last@"<<*Striker<<endl; 
cout<<"Rest To"<<*Striker[0]<<endl;
}

Аnswer:
There is an error in last line, i.e. *Striker[0], so the program will not run. In case, if there is no subscript in Striker pointer, then the output would be
Striker10
Next@55
Last@55
Rest To55

Question 9:
Find the output of the following program: All India 2011

#include<iostream.h> 
#include<conio.h>
void main()
{
int *Queen, Moves[]={11, 22, 33,44};
Queen = Moves;
Moves[2] += 22; 
cout<<"Queen @"<<*Queen<<endl;
*Queen -= 11;
Queen += 2;
cout<<"Now@"<<*Queen<<endl;
Queen++;
cout<<"Finally@"<<*Queen<<endl; 
cout<<"New 0rigin@"<<*Moves[0]<<endl;
}

Аnswer:
There is an error in last line, i.e. *Moves[0], so the program will not run. In case, if there is no subscript in Moves pointer, then the output would be
Queen @11
Now@55
Finally@44
New 0rigin@0

Question 10:
Find the output of the following program:

#include<iostream.h> 
#include<conio.h> 
void main()
{
int Numbers[]={2,4,8,10}; 
int *ptr = Numbers; 
for(int c=0;c<3;c++)
{
cout<<*ptr<<"@";
ptr++;
}
cout<<endl;
for(c=0:c<4:c++)
{
(*ptr) *= 2;
--ptr;
}
for(c=1:c<4;c++)
cout<<Numbers[c]<<"#";
cout<<endl;
}

Аnswer:
Output of the given program will be
2@4@8@
8#16#20#

Question 11:
Find the output of the following program:

#include<iostream.h> 
#include<conio.h> 
void main()
{
int Array[]={4,6,10,12}; 
int *pointer = Array; 
for(int i=1;i<=3;i++)
{
cout<<*pointer<<"#";
pointer++;
}
cout<<endl; 
for(i=1;i<=4;i++)
{
(*pointer) *= 3;
--pointer;
}
for(i=l;i<5;i++)
cout<<Array[i-1]<<"@"; 
cout<<endl;
}

Аnswer:
Output of the given program will be
4#6#10#
12@18@30@36@

Question 12:
Give the output of the following program segment. (Assume, all required header files are included in the program.)

void main()
{
int a=32,*X=&a;
char ch=65, &eco=ch; 
eco+=a;
*X+=ch;
cout<<a<<','<<ch<<endl;
}

Аnswer:
Output of the given program will be
129,a

Question 13:
Identify the syntax error(s), if any, in the following program. Also, give reason for errors.

void main()
{
const int i=20;
const int *const ptr=&i;
(*ptr)++;
int j=15;
ptr=&j;
}

Аnswer:
(*ptr)++ cannot modify a const object ptr-&j cannot modify a const object.

Question 14:
Give the output of the following program segment. (Assume, all required header files are included in the program.)

void main()
{
int array[] = {2,3,4,51}; 
int *arptr=array;
int value=*arptr; 
cout<<va1ue<<'\n'; 
value=*arptr++; 
cout<<value<<'\n'; 
value=*arptr; 
cout<<value<<'\n'; 
value=*++arptr; 
cout<<value<<'\n'; 
}

Аnswer:
Output of the given program will be
2
2
3
4

Question 15:
Give the output of the following program segment. (Assume, all required header files are included in the program.)

void main()
{
char *s="GOODLUCK";
for(int x=strlen(s)-1;x>=0;x--) 
{
for(int y=0;y<=x;y++) 
cout<<s[y]; 
cout<<endl;
}
}

Аnswer:
Output of the given program will be
GOODLUCK
G00DLUC
G00DLU
GOODL
GOOD
GOO
GO
G

Question 16:
Give the output of the following program segment. (Assume, all required header files are included in the program).

void main()
{
char *NAME="a ProFile"; 
for(int x=0;x<strlen(NAME);x++) 
if(islower(NAME[x])); 
else
if(isupper(NAME[x])) 
if(x%2!=0)
NAME[x]=tolower(NAME[x-l] 
else
NAME[x]--;
cout<<NAME<<endl;
}

Аnswer:
Output of the given program will be
a Orooile

Question 17:
Find and write the output of the following C++ program code: All India 2017
NOTE Assume all required header files are already being included in the program.

void main()
{
int *Point, Score[]={100,95,150,75,65,120};
Point=Score; 
for(int L=0;L<6;L++)
{
if((*Point)%10==0) 
*Point /= 2; 
else
*Point -= 2; 
if((*Point)%5==0) 
*Point /= 5; 
Point++;
}
for(int L=5;L>=0;L--)
cout<<Score[L]<<"*";
}

Аnswer:
Given program will give error, i.e. Multiple declaration for ‘L’
If we remove int from 2nd for loop then output will be:
12*63*73*15*93*10*

Question 18:
Find the output of the following program: Delhi 2012C

#include<iostream.h> 
void main() 
{
int Points=300; 
int *Start=&Points; 
int *End;
End=new int;
(*End)=Points-150:
Points+=100;
cout<<Points<<":"<<*Start<<endl; 
cout<<*End<<endl;
Start=End;
cout<<Points<<":"<<*Start<<endl; 
cout<<*End<<endl;
Points-=100;
*Start-=50;
cout<<Points<<":"<<*Start<<endl; 
cout<<*End<<endl; 
delete End;
}

Аnswer:
Output of the given program will be 400:400
150
400:150
150
300:100
100

Question 19:
Find the output of the following program Delhi 2009

#include<iostream.h> 
#include<conio.h> 
void main()
{
int X[]={10, 25, 30, 55, 110}; 
int *p=X; 
whi1e(*p<110)
{
if(*p%3!= 0)
*p = *p+1; 
else
*p = *p+2; 
p++:
}
for(int 1=4;I>=1;I--)
{
cout<<X[I]<<"*"; 
if(I%3 == 0) 
cout<<endl;
} 
cout<<X[0]*3<<endl;
}

Аnswer:
Output of the given program will be
110*56*
32*26*33

Question 20:
Find the output of the following program. Delhi (C) 2009

#include<iostream.h> 
#include<conio.h> 
struct score
{
int Year; 
float topper;
};
void Change(score *s, int x=20)
{
s->topper=(s->topper+25)-x; 
s->Year++;
}
void main()
{
score Arr[]={{2007, 100},{2008, 951}};
score *Point=Arr;
Change(Point, 50); 
cout<<Arr[0].Year<<"#"<<Arr[0].topper<<endl; 
Change(++Point);
cout<<Point->Year<<"#"<<Point->topper<<endl;
}

Аnswer:
Output of the given program will be
2008#75
2009#100

Question 21:
Find the output of the following program. All India 2009

#include<iostream.h>
#include<conio.h> 
void main()
{
int A[] = {10, 15, 20, 25. 30}; 
int *p = A; 
whi1e(*p<30)
{
if(*p%3!= 0)
*p = *p+2;
else
*p = *p+1;
P++;
}
for(int J=0;J<=4;J++)
{
cout<<A[J]<<"*"; 
if(J*3 == 0) 
cout<<endl;
}
cout<<A[4]*3<<endl;
}

Аnswer:
Output of the given program will be
12*
16*22*27*
30*90

Question 22:
What will be the output of the following program?

#include<iostream.h> 
#include<ctype.h>
#include<conio.h>
#include<string.h> 
void ChangeString(char Text[],int SCounter)
{
char *Ptr = Text;
int Length = strlen(Text); 
for(;Counter<Length-2;Counter+=2,Ptr++)
{
*(Ptr+Counter)=toupper(*(Ptr+Counter));
void main()
{
int Position=0;
char Message[]="Pointers Fun"; 
ChangeString(Message, Position); 
cout<<Message<<"@"<<Position;
}

Аnswer:
Output of the given program will be
PoiNteRs Fun@10

Question 23:
What will be the output of the following program?

#include<iostream.h>
#include<ctype.h>
#include<conio.h>
#include<string.h> 
void NewtextCchar String[],int &Position)
{
char *Pointer=String;
int Length=strlen(String);
for(;Position<Length-2;Position+=2,Pointer++)
{
*(Pointer+Position)=toupper(*(Pointer+Position));
}
}
void main()
{
clrscr();
int Location=0;
char Message[]="Dynamic Act";
Newtext(Message, Location);
cout<<Message<<"#"<<Location;
}

Аnswer:
Output of the given program will be
DynAmiC ACt#10

Computer ScienceImportant Questions for Computer ScienceNCERT Solutions

The post Important Questions for Class 12 Computer Science (C++) – Pointers appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – Data Structure

$
0
0

Important Questions for Class 12 Computer Science (C++) – Data Structure

Topic – 1
Data Structure and One-Dimensional Array
Previous years Examination Questions
2 Marks Questions

Question 1:
Write the definition of a function AddUp(int Arr[ ], int N) in C++, in which all even positions (i.e. 0,2,4 ) of the array should be added with the content of the element in the next position and odd positions (i.e. 1,3,5, ) elements should be incremented by 10. All India 2017
important-questions-class-12-computer-science-c-data-structure-(194-1)
NOTE

  • The function should only alter the content in the same array.
  • The function should not copy the altered content in another array.
  • The function should not display the altered content of the array.
  • Assuming, the Number of elements in the array are Even.

Аnswer:

void AddUp(int Arr[], int N)
{
for(int i=0;i<N;i++)
{
if(i%2==0)
Arr[i] += Arr[i+1]; 
else
Arr[i] += 10;
}
}

Question 2:
Write the definition of a function FixPay(float Pay[ ], int N) in C++, which should modify each element of the array Pay having N elements, as per the following rules:
important-questions-class-12-computer-science-c-data-structure-(194-2)
Аnswer:

void FixPay(float Pay[], int N)
{
for(int i =0;i<=N—1;i++)
{
if(Pay[i]<100000)
Pay[i] = Pay[i]+(Pay[i]*25)/100; 
else if(Pay[i]>=100000 && Pay[i]<200000)
Pay[i] = Pay[i]+(Pay[i]*20)/100; 
else
Pay[i] = Pay[i]+(Pay[i]*15)/100;
}
}

Question 3:
Write the definition of a function FixSalary(float Salary[ ], int N) in C++, which should modify each element of the array Salary having N elements, as per the following rules:
important-questions-class-12-computer-science-c-data-structure-(194-3)
Аnswer:

void FixSalary(float Salary[], int N)
{
for(int i=0;i<=N—1;i++)
{
if(Salary[i]<100000)
Salary[i]=Salary[i]+(Salary[i]*35)/100; 
else if(Salary[i]>=100000 && Salary[i]<200000) 
Salary[i]=Salary[i]+(Salary[i]*30)/100; 
else
Salary[i]=Salary[i]+(Salary[i]*20)/100;
}
}

Question 4:
Write the definition of a function Alter (int A[ ], int N) in C++, which should change all the multiples of 5 in the array to 5 and rest of the elements as 0. e.g. if an array of 10 integers is as follows:
important-questions-class-12-computer-science-c-data-structure-(195-1)
Аnswer:

void Alter(int A[], int N)
{
for(int i=0;i<10;i++)
{
if(A[i]%5==0)
A[i]=5; 
else 
A[i]=0;
}
}

Question 5:
Write the definition of a function Changeant P[ ], int N) in C++, which should change all the multiples of 10 in the array to 10 and rest of the elements as 1.  All India 2015
important-questions-class-12-computer-science-c-data-structure-(195-2)
Аnswer:

void Change(int P[], int N)
{
for (int i=0;i<N;i++)
{
if (P[i]%10 == 0)
P[i] = 10; 
else
P[i] = 1;
}
}

Question 6:
Write the definition of a function Modify(int A[ ], int N) in C++, which should reposition the content after swapping each adjacent pair of numbers in it.
[NOTE Assuming the size of array is multiple of 4]
important-questions-class-12-computer-science-c-data-structure-(195-3)
Аnswer:

void Modify(int A[], int N) 
{
for(int i=0;i<N;i++)
{
int temp = A[i];
A[i] = A[i+2];
A[i+2] = temp; 
if(i%4>=1)
i = i+2;
}
}

Question 7:
Write code for a function void oddEven(int S[ ], int N) in C++, to add 5 in all the odd values and 10 in all the even values of the array S.
important-questions-class-12-computer-science-c-data-structure-(195-4)
Аnswer:

void oddEven(int S[],int N)
{
for(int i=0;i<N;i++)
{
if(S[i]%2 == 0)
S[i] += 10; 
else
S[i]+=5;
}
}

Question 8:
Write code for a function void EvenOdd (int T [ ], int C) in C++, to add 1 in all the odd values and 2 in all the even values of the array T.
important-questions-class-12-computer-science-c-data-structure-(195-5)
important-questions-class-12-computer-science-c-data-structure-(196-1)
Аnswer:

void EvenOdd(int T[],int C)
{
for(int i=0;i<C;i++)
{
if(T[i]%2 == 0)
T[i] += 2; 
else
T[i] += 1;
}
}

Question 9:
Write a function in C++ TWOTOONE( ) which accepts two array X[ ], Y[ ] and their size n as argument. Both the arrays X[ ] and Y[ ] have the same number of elements. Transfer the content from two arrays X[ ], Y[ ] to array Z[ ]. The even places (0,2,4….) of array Z[ ] should get the contents from the array X[ ] and odd places (1,3,5…) of array Z[ ] should get the contents from the array Y[ ].
Example: If the X[ ] array contains 30,60,90 and the Y[ ] array contains
10.20.50. Then Z[ ] should contain
30.10.60.20.90.50. All India 2014
Аnswer:

void TW0T00NE(int X[], int Y[],int n) 
{
int Z[40], i,j=0,k=0; 
for(i= 0;i<(n+n);i++)
{
if(i%2 == 0)
{
Z[i] = X[j]; 
j++;
}
else
{
Z[i] = Y[k]; 
k++;
}
}
}

Question 10:
Write code for a function void Convert (int T[ ], int Num) in C++, which repositions all the elements of the array by shifting each of them one to one position before and by shifting the first element to the last position.
important-questions-class-12-computer-science-c-data-structure-(196-2)
Аnswer:

void Convert(int T[], int Num)
{
int temp = T[0]; 
for(int i=0;i<(Num-1);i++)
{
T[i]=T[i+l];
}
T[i]= temp; 
}

Question 11:
Write code for a function void ChangeOver(int P[ ], int N) in C++, which re-positions all the elements of the array by shifting each of them to the next position and by shifting the last element to the first position.
important-questions-class-12-computer-science-c-data-structure-(196-3)
Аnswer:

void ChangeOver(int P[],int N)
{
int temp;
for(int i=0;i<(N-1);i++)
{
temp = P[N-1];
P[N-1] = P[i];
P[i] = temp;
} 
}

Question 12:
Write the definition for a function void Transfer (int A[6], int B[6]) in C++, which takes two integer arrays, each containing 6 elements as parameters. The function should exchange all odd places (i.e. 3rd and 5th) of the two arrays.
important-questions-class-12-computer-science-c-data-structure-(196-4)
Аnswer:

void Transfer(int A[6],int B[6]) 
{
int i,temp;
for(i=1;i<=5;i=i+2)
{
temp = A[i];
A[i] = B[i];
B[i] = temp;
}
}

Question 13:
Write a function SWAP2CHANGE(int p[ ], int N) in C++ to modify the content of the array in such a way that the elements, which are multiples of 10 swap with the value present in the very next position in the array.
e.g. If the content of array p is
91, 50, 54, 22, 30, 54
The content of array p should become
91, 54, 50, 22, 54, 30
Аnswer:

void SWAP2CHANGE(int p[],int N)
{ 
int C,i;
for(i=0;i<=N-2;i++)
{
if(p[i]%10 == 0)
{
C = p[i]; 
p[i] = p[i+1];
p[i+1] = C; 
i++:
}
}
}

Question 14:
Write a function SWAP2BEST(int ARR[ ], int Size) in C++ to modify the content of the array in such a way that the elements, which are multiples of 10 swap with the value present in the very next position in the array.
e.g. If the contents of array ARR are
90, 56, 45, 20, 34, 54
The contents of array should become
56, 90, 45, 34, 20, 54  All India 2012
Аnswer:

void SWAP2BEST(int ARR[], int Size) {
{
int i,C;
for(i= 0;i<=Size-2;i++)
{
if(ARR[i]%10==0)
{
C=ARR[i];
ARR[i] = ARR[i+1];
ARR[i+1] = C; 
i++;
}
}
}

Question 15:
Write a Get2From1( ) function in C++ to transfer the content from one array ALL[ ] to two arrays Odd[ ] and Even[ ]. The Even[ ] array should contain the values from places(0, 2, 4, …) of array ALL[ ] and Odd[ ] array should contain the values from odd position like (1, 3, 5, …).
e.g. The ALL[ ] array should contain 30,10, 60, 50, 90, 80
If the Even[ ] array contains 30, 60, 90
and the Odd[ ] array contains
10, 50, 80 All India 2011
Аnswer:

void Get2From1(int ALL[], int N)
{ 
int p,q,i,j=0, k=0; 
if(N%2 == 0)
{
p = N/2; 
q = N/2;
}
else
{
p = N/2; 
q = ((N/2)+l); 
}
int *0dd = new int[p]; 
int *Even = new int[q]; 
for(i=0;i<(N);i++)
{
if(i%2 == 0)
Even[j++]=ALL[i]; 
else
Odd[k++]=ALL[i];
}
}

Question 16:
Write a function CHANGE( ) in C++, which accepts an array of integer and its size as parameters and divide all those array elements by 7, which are divisible by 7 and multiply other array elements by 3.
important-questions-class-12-computer-science-c-data-structure-(197-1)
Аnswer:

void CHANGE(int A[],int N) 
{
for(int i=0;i<N;i++)
if(A[i]%7 == 0)
A[i]=A[i]/7; 
else 
}
A[i] = A[i]*3;
}
}

Question 17:
Write a function REASSIGN( ) in C++, which accepts an array of integer and its size as parameters and divide all those array elements by 5, which are divisible by 5 and multiply other array elements by 2.
Аnswer:

void REASSIGN(int A[],int N)
{
for(int i=0;i<N;i++)
{
1f(A[i]%5 == 0)
A[i] = A[i]/5; 
else
A[i] = A[i]*2;
}
}

Question 18:
Write a function SORTPOINTS( ) in C++ to sort an array of structure Game in descending order points using bubble sort.
NOTE Assume the following definition of structure Game.

struct Game 
{
long PNo; //Player Number 
char PName[20]; 
long Points;
}

important-questions-class-12-computer-science-c-data-structure-(197-2)
Аnswer:

void SORTPOINTS(struct Game G[], int n)
{
int i, j; 
struct Game t; 
for(i=1;i<n;i++)
{
for(j=0;j<=n-i-1;j++)
{
if(G[j+1].Points>G[j].Points) 
{
t = G[j];
G[j] = G[j+1]:
G[j+1] = t;
}
}
}
}

Question 19:
Write a function SORTSCORE( ) in C++to sort an array of structure. Examinee in descending order of Score using bubble sort.
NOTE Assume the following definition of structure Examinee.

struct Examinee
{
long Roll No; 
char Name[20]; 
float Score;
};

important-questions-class-12-computer-science-c-data-structure-(197-3)
Аnswer:

void SORTSCORE(struct Examinee ex[],int n) 
{
int i,j;
struct Examinee t; 
for(i=1;i<n;i++)
{
for(j=0;j<=n-i-1;j++)
{ 
if(ex[j+1].Score>ex[j].Score)
{
t = ex[j]; 
ex[j] = ex[j+1]; 
ex[j+1] = t;
   }
  }
 }
}

The post Important Questions for Class 12 Computer Science (C++) – Data Structure appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – Database Concepts

$
0
0

Important Questions for Class 12 Computer Science (C++) – Database Concepts

Previous Years Examination Questions
2 Marks Questions

Question 1:
Observe the following table MEMBER carefully and write the name of the RDBMS operation out of (i) SELECTION (ii) PROJECTION (iii) UNION (iv) CARTESIAN PRODUCT, which has been used to produce the output as shown in RESULT. Also, find the Degree and Cardinality of the RESULT: All India 2017
Important Questions for Class 12 Computer Science (C++) - Database Concepts-1
Answer:
RDBMS Operation → SELECTION
Degree of table RESULT = 3
Cardinality of table RESULT = 1

Question 2:
Observe the following PARTICIPANTS and EVENTS tables carefully and write the name of the RDBMS operation which will be used to produce the output as shown in RESULT? Also, find the Degree and Cardinality of the RESULT. All India 2016
Important Questions for Class 12 Computer Science (C++) - Database Concepts-2
Answer:
RDBMS Operation → Cartesian Product
Degree → 4, Cardinality → 6

Question 3:
Observe the following STUDENTS and EVENTS tables carefully and write the name of the RDBMS operation which will be used to produce the output as shown in LIST. Also, find the Degree and Cardinality of the LIST. Delhi 2016
Important Questions for Class 12 Computer Science (C++) - Database Concepts-3
Answer:
RDBMS Operation → Cartesian Product
Degree → 4, Cardinalitv → 6

Question 4:
Observe the following table carefully and write the names of the most appropriate columns, which can be considered as
(i) Candidate keys and (ii) Primary key. Delhi 2015
Important Questions for Class 12 Computer Science (C++) - Database Concepts-4
Answer:
(i) Candidate Keys → Id, Product
(ii) Primary Key → Id

Question 5:
Observe the following table carefully and write the names of the most appropriate columns, which can be considered as (i) Candidate keys and (ii) Primary key: All India 2015
Important Questions for Class 12 Computer Science (C++) - Database Concepts-5
Answer:
(i) Candidate Keys → Code, Item
(ii) Primary Key → Code

Question 6:
Observe the following table carefully and find the degree and cardinality of the table : All India 2018 (C)
Important Questions for Class 12 Computer Science (C++) - Database Concepts-6
Answer:
Degree → 3, Cardinality → 5

Question 7:
Observe the following table and answer the parts (i) and (ii): All India 2014 (C)
Important Questions for Class 12 Computer Science (C++) - Database Concepts-7
(i) In the above table, can we have Qty as primary key? [Answer as yes/no]. Justify your answer.
(ii) What is the cardinality and degree of the above table?
Answer:
(i) No, Qty cannot have as primary key because it is not uniquely identify in a table.
(ii) Cardinality → 5, Degree → 4

Question 8:
Explain the concept of Cartesian Product between two tables, with the help of appropriate example. All India 2014

Or

Illustrate cartesian product operation between the two tables/relations using a suitable example. Delhi 2012 (C)
Answer:
Cartesian Product The cartesian product means the cross join of two relations and the resultant relation will contain all the possible combinations of the tuples from the two tables, i.e. the cardinality of the resulting relation will be equal to the product of cardinalities of the two relations. It is denoted by ‘x’ symbol.
The two tables GABS1 and GABS2 are as follows:
Important Questions for Class 12 Computer Science (C++) - Database Concepts-8
The cartesian product of above two tables is as follows:
Important Questions for Class 12 Computer Science (C++) - Database Concepts-9

Question 9:
Explain the concept of candidate keys with the help of an appropriate example. All India 2013

Or

What do you understand by candidate key in a table? Give a suitable example of candidate key from a table containing some meaningful data. Delhi 2010.2009
Answer:
A candidate key is a set of one or more attributes that uniquely identify in a table. There can be multiple candidate keys in one table. Each candidate key can work as a primary key.
Important Questions for Class 12 Computer Science (C++) - Database Concepts-10

Question 10:
What is the difference between degree and cardinality of a table? What is the degree and cardinality of the following table?
Delhi 2013
Important Questions for Class 12 Computer Science (C++) - Database Concepts-11
Answer:
Degree The number of attributes or columns in a table is called the degree of the table. The degree of the given table is : 3.
Cardinality The number of rows or records in a table is called ,the cardinality of the table. The cardinality of the given table is : 2.

Question 11:
Differentiate between the primary key and alternate key of a table with the help of an example. Delhi 2013C

Or

Give a suitable example of a table with sample data and illustrate primary and alternate keys in it. All India 2012.2011; Delhi 2011 (c)
Answer:
Primary Key It’s a column or set of columns that helps to identify records uniquely. One table can have only one primary key.
Alternate Key/Secondary Key It’s a column or set of columns that can act as a primary key but not selected as a primary key.
Important Questions for Class 12 Computer Science (C++) - Database Concepts-12
e.g. In table Student, RollNo and AdmNo of all students are different.
Both of them can be selected as primary key. Suppose we have selected RollNo as a primary key then AdmNo is called as alternate key.

Question 12:
Give suitable example of a table with sample data and illustrate primary and candidate keys in it. Delhi 2012
Answer:
The table student is as follows:
Important Questions for Class 12 Computer Science (C++) - Database Concepts-13
Important Questions for Class 12 Computer Science (C++) - Database Concepts-14
Here, AdmNo and RollNo both can identify records uniquely. So, both are candidate keys, and from them we can also make AdmNo as a primary key.

Question 13:
What do you mean by union and cartesian product operation in relational algebra? Delhi 2011
Answer:
Union (binary operator) It operates on two relations and is indicated by ‘∪’.
Cartesian Product (binary operator) It operates on two relations and is denoted by ‘×’. e.g. cartesian product of two relations R1 and R2 is represented by R = R1 x R2. The degree of R is equal to sum of degrees of R1 and R2. The cardinality of R is product of cardinality of R1 and cardinality of R2.
e.g. R = R1 ∪ R2 represents union operation between two relations R1 and R2. The degree of R is equal to degree of R1. The cardinality of R is sum of cardinality of R1 and cardinality of R2.

Question 14:
What do you understand by selection and projection operation in relational algebra? All India 2011
Answer:
Important Questions for Class 12 Computer Science (C++) - Database Concepts-16

Question 15:
What do you understand by primary key? Give a suitable example of primary key from a table containing some meaningful data. All India 2010
Answer:
A primary key is a set of one or more attributes that can uniquely identify tuples within the relation.
e-g.
Important Questions for Class 12 Computer Science (C++) - Database Concepts-15
The attribute ItemNo is a primary key as it contains unique value for each tuple in a relation.

Question 16:
What is the purpose of a key in a table? Give an example of a key in a table. All India 2009
Answer:
A key is used to identify a tuple uniquely within the relation. The value of key is unique. No rows in the relation can have same value, e.g. in an Employee relation EmpCode is a key, using EmpCode one can obtain the information of a particular employee.

Computer ScienceImportant Questions for Computer ScienceNCERT Solutions

The post Important Questions for Class 12 Computer Science (C++) – Database Concepts appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – Linked List, Stack and Queue

$
0
0

Important Questions for Class 12 Computer Science (C++) – Linked List, Stack and Queue

Topic – 1
Linked List and Stack
Previous years Examination Questions
2 Marks Questions

Question 1:
Convert the following infix expression to its equivalent postfix expression, showing the stack contents for each step of conversion:
P/(Q-R)*S + T All India 2016
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(222-1)

Question 2:
Convert the following infix expression to its equivalent postfix expression, showing the stack contents for each step of conversion.
A/(B + Q*D-E Delhi 2016
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(222-2)
important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(222-3)

Question 3:
Convert the following infix expression to its equivalent postfix expression, showing the stack contents for each step of conversion.
P/(Q+(R-T)*U All India (C) 2016
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(222-4)
important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(223-1)

Question 4:
Convert the following infix expression to its equivalent postfix expression, showing the stack contents for each step of conversion:
(U* V+ R/ (S-T)) All India 2015
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(223-2)

Question 5:
Convert the following infix expression to its equivalent postfix expression, showing the stack contents for each step of conversion.
(X/Y+U*(V-W)) Delhi 2015
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(223-3)

Question 6:
Evaluate the following postfix expression. Show the. status of stack after execution of each operation separately:
F, T, NOT, AND, F, OR, T, AND   Delhi 2014
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(223-4)

Question 7:
Evaluate the following postfix expression. Show the status of stack after execution of each operation separately:
T, F, NOT, AND, T, OR, F, AND    All India 2014
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(223-5)

Question 8:
Evaluate the following postfix expression: (show status of stack after each operation)
100,40,8,/,20,10,-,+,*     All India (C) 2014
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(224-1)

Question 9:
Evaluate the following postfix expression. Show the status of stack after execution of each operation:
5, 2, *, 50, 5, /, 5, -, +      All India 2013
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(224-2)

Question 10:
Evaluate the following postfix expression. Show the status of stack after execution of each operation:
60, 6, /, 5, 2, *, 5, -, +     Delhi 2013
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(224-3)

Question 11:
Evaluate the following postfix expression using a stack and show the contents of stack after execution of each operation:
5, 3, 2, *, 4, 2, /, -, *      Delhi 2013C
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(224-4)
important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(224-5)

Question 12:
Evaluate the following postfix notation. Show status of stack after every step of evaluation (i.e. after each operator):
False, NOT, True, AND, True, False, OR, AND      Delhi 2012
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(224-6)

Question 13:
Evaluate the following postfix notation. Show status of stack after every step of evaluation (i.e. after each operator):
True, False, NOT, AND, False, True, OR, AND    All India 2012
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(224-7)

Question 14:
Evaluate the following postfix notation of expression:
50, 60, +, 20, 10, – ,*      Delhi 2011
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(225-1)

Question 15:
Evaluate the following postfix notation of expression:
True, False, NOT, AND, True, True, AND, OR  All india 2011
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(225-2)

Question 16:
Evaluate the following postfix notation of expression:
False, True, NOT, OR, True, False, AND, OR   Delhi 2010
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(225-3)
important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(225-4)

Question 17:
Evaluate the following postfix notation of expression. Show the status of stack after each operation:
True, False, NOT, OR, False, True, OR, AND  All  India 2010
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(225-5)

Question 18:
Convert the following infix expression to its equivalent postfix expression.
Showing stack contents for the conversion:
(X – Y/(Z+U)*V)    Delhi 2009
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(226-1)

Question 19:
Convert the following infix expression to its equivalent postfix expression.
Showing stack contents for the conversion:
(A + B* (C-D) IE) All India 2009
Аnswer:

important-questions-for-class-12-computer-science-c-linked-list-stack-and-queue-(226-2)

4 Marks Questions

Question 20:
Write the definition of a member function PUSH( ) in C++, to add a new book in a dynamic stack of BOOKS considering the following code is already included in the program: All India 2015

struct BOOKS 
{
char ISBN[20], TITLE[80];
BOOKS *Link;
};
class STACK 
{
BOOKS *Top; 
public:
STACK() {Top=NULL;} 
void PUSH(); 
void POP();
∼STACK();
 };

Аnswer:

void STACK::PUSH()
{
BOOKS *b = new BOOKS; 
cout<<"Enter ISBN number"; 
cin>>b->ISBN; 
cout<<"Enter TITLE"; 
gets(b—>TITLE); 
if(TOP == NULL)
{
TOP = b;
}
else
{
b->Link = TOP; 
TOP = b;
}
}

Question 21:
Write the definition of a member function Pop( ) in C++, to delete a book from a dynamic stack of TEXTBOOKS considering the following code is already included in the program. Delhi 2015

struct TEXTBOOKS
{
char ISBN[20]; 
char TITLE[80]; 
TEXTBOOKS *Link;
};
class STACK 
{
TEXTBOOKS *Top; 
public:
STACK(){Top=NULL;} 
void Push(); 
void Pop();
∼STACKC);
};

Аnswer:

void STACK::Pop()
{
if(Top! = NULL)
{
TEXTBOOKS *Temp = Top;
Top = Top->Link; 
delete Temp; 
}
else
cout<<"Stack empty";
}

Question 22:
Write a function POPBOOK( ) in C++ to perform delete operation from a dynamic stack, which contains Bno and Title. Consider the following definition of NODE, while writing your C++ code.  Delhi 2014

struct NODE
{
int Bno;
char Title[20];
NODE *Link;
};

Аnswer:

void P0PB00K(N0DE *top)
{
cout<<:Deleting the top element from stack\n"; 
cout<<"Book No:"<<top->Bno<<endl; 
cout<<"BookTitle:"<<top->Title<<endl;
NODE *temp = top;
top = top->Link; 
delete(temp);
}

Question 23:
Write a function PUSHBOOK( ) in C++ to perform insert operation on a dynamic stack, which contains Book_no and Book_Title. Consider the following definition of NODE, while writing your C++ code. All India 2014

struct NODE 
{
char Book_No; 
char Book_Title[20]:
NODE *Next:
};

Аnswer:

void PUSHBOOK(NODE *top)
{
NODE *NEW = new NODE; 
cout<<"Enter the Book Number:"; 
cin>>NEW->Book_No; 
cout<<"Enter the Book Title:"; 
gets(NEW->Book_Titie);
NEW->Next = NULL; 
if(top == NULL)
top = NEW; 
else 
{
NEW->Next = top; 
top = NEW;
}
}

Question 24:
Write a complete program in C++ to implement a dynamically allocated stack containing names of Countries. Delhi 2010
Аnswer:

The program is:
#include<iostream.h>
#include<stdio.h>
struct Node
{ 
char Country[30];
Node *Link;
};
class Stack 
{
Node *Top; 
public:
Stack(){Top = NULL;} 
void Push(); 
void Pop();
void Display();
∼Stack();
};
void Stack :: Push()
{
Node *Temp = new Node; 
gets(Temp->Country); 
Temp->Link = Top;
Top = Temp;
}
void Stack :: Pop()
{
if(Top!=NULL) 
{
Node *Temp = Top;
Top = Top->Link; 
delete Temp;
}
else
cout<<"Stack empty";
}
void Stack :: Display()
{
Node *Temp = Top; 
while(Temp!= NULL)
cout<<Temp->Country<<endl; 
Temp = Temp->Link;
Stack :: ∼Stack()
{
while(Top!=NULL)
{
Node *Temp = Top;
Top = Top->Link; 
delete Temp;
}
}
void main()
{
Stack ST; 
char ch; 
do 
{
cout<<"Choose any one P/O/D/Q"; /* displaying choices P - Push,0 - Pop, D-Display, Q-Exit */ 
cin>>ch; 
switch(ch)
{
case 'P':ST.Push(); 
break;
case '0':ST.Pop(); 
break;
case 'D':ST.Display();
}
}
while(ch!='Q');
}

Topic – 2
Queue
Previous years Examination Questions
4 Marks Questions

Question 1:
Write the definition of a member function DELETE( ) for a class QUEUE in C++, to remove a product from a dynamically allocated Queue of products considering the following code is already written as a part of the program. All India 2016

struct PRODUCT 
{
int PID; 
char PNAME[20];
PRODUCT *Next;
};
class QUEUE 
{
PRODUCT *R,*F; 
public:
QUEUE(){R=NULL;F=NULL;} 
void INSERT(); 
void DELETE();
∼QUEUE();
};

Аnswer:

void QUEUE :: DELETE() 
{
if(F!=NULL)
{
PRODUCT *Temp=F;
cout<<F->data<<"deleted\n";
F=F->Next; 
delete Temp;
if(F==NULL)  
R=NULL;
}
else
cout<<"\n Queue is Empty":
}

Question 2:
Write the definition of a member function INSERT( ) for a class QUEUE in C++, to insert an ITEM in a dynamically allocated Queue of items considering the following code is already written as a part of the program. Delhi 2016

struct ITEM 
{
int INO; 
char INAME[20];
ITEM *Link; 
};
class QUEUE 
{
ITEM *R, *F; 
public:
QUEUE() {R=NULL; F=NULL;} 
void INSERT(); 
void DELETE();
∼QUEUE();
};

Аnswer:

void QUEUE :: INSERT!)
{ 
ITEM *temp=new ITEM;
cout<<"\n Enter Item no & Item name:";
cin>>temp->INO; 
gets(temp->IName);
temp->Next = Null;
if(R==Null)
{
R = temp;
F = temp; 
}
else
{
R->Next = temp;
R = temp;
}
}

Question 3:
Write the definition of a member function INSERT! ) in C++, to add a new passenger detail in a dynamic queue of PASSENGERS considering the following code is already existing in the program. All India 2015

struct PASSENGERS
{
char PID[20]; NAME[80];
PASSENGERS *Next;
};
class QUEUE
{
PASSENGERS *Rear, *Front; 
public:  
QUEUE() {Rear=NULL; Front=NULL}
void INSERT(); 
void DELETE();
∼QUEUE();
};

Аnswer:

void QUEUE ::INSERT()
{
PASSENGERS * P = new PASSENGERS; 
cout<<"Enter PID"; 
cin>>P->PID; 
cout<<"Enter Name”; 
gets(p->Name);
P->Next = NULL;
if(Rear == NULL)
{
Front = Rear = P;
}
else 
{
Rear->Next = P;
Rear = P;
}
}

Question 4:
Write a function QDELETE( ) in C++ to perform delete operation in a Linked Queue, which contains Passenger number and Passenger name. Consider the following definition of node in the code. All India 2013

struct node 
{
long int Pno; 
char Pname[20]; 
node *Link;
};

Аnswer:

void QDELETE()
{
if(Front == NULL) 
{
cout<<"Queue is empty"; 
exit(0);
}
else
{
node *temp = front; 
cout<<"Passenger Information"; 
cout<<Front->Pno; 
cout<<Front->Pname;
Front=Front->Link; 
delete temp;
}
}

Question 5:
Write a function QINSERT( ) in C++ to perform insert operation on a linked queue, which contains client number and client name. Consider the following definition of NODE in the code of QINSERT ( ). Delhi 2013

struct NODE 
{
long int Cno;    //Client number
char Cname[20];    //Client name
NODE *Next;
};

Аnswer:

void QINSERT()
{
NODE *P = new Node;
cout<<"Enter the Client Number and Name:";
cin>>P- Cno;
gets(P->Cname) ;
P->Next=NULL;
if((front ~ NULL)&&(rear == NULL))
{
front=rear=P;
}
else
{
rear->Next = P; 
rear = P;
}
}

Question 6:
Given the necessary declaration of linked implemented Queue containing players information (as defined in the following definition of Node). Also, write a user defined function in C++ to delete one Player’s information from the Queue.
Delhi 2013C

struct Node 
{
int PlayerNo; 
char PIayerName[20];
Node *Link;
};

Аnswer:

void Delete_NODE()
{
NODE *P;
if(front == Null)
cout<<”Queue is empty";
else if(front == rear) 
{
P = front;
cout<<"Deleted Node information is"; 
cout<<P->PlayerNo; 
puts(p->PlayerName); 
front = rear = NULL; 
delete P;
}
else
{
P = front;
cout<<"Deleted Node information is"; 
cout<<P->PlayerNo; 
puts(P->PlayerName); 
front = front->Link; 
delete P;
}
}

Question 7:
Write a function in C++ to perform insert operation in a dynamic queue containing DVD’s information (represented with the help of an array of structure DVD). Delhi 2012

struct DVD 
{
long No; 
char title[20];
DVD *Link;
};

Аnswer:

void Insert()
{
DVD *p = new DVD; 
cout<<"Enter the DVD number and Title";
cin<<p->No; 
gets(p->title);
p->Link = NULL; 
if((front — NULL) && (rear == NULL))
{
front - rear = p;
}
else
{
rear->Link = p; 
rear = p;
}
}

Question 8:
Write a function in C++ to perform insert operation in a static circular queue containing book’s information (represented with the help of an array of structure BOOK). All India 2012

struct BOOK  
{ 
long AccNo; //Book account number 
char Title[20]; //Book Title
};

Аnswer:

void circularQueInsert(BOOK B[], int Front, int Rear, int Max)
{
if((Rear=Max-l && Front ==0)||(Front == Rear +1))
{
cout<<"Circular Queue is full"; 
exit(O);
}
else if(Front == -1 && Rear == -1)
{
Front = Rear = 0;
}
else if(Rear = Max -1 && Front >0)
{
Rear = 0;
}
else
Rear = Rear+1; 
cout<<"Enter book account number and title"; 
cin>>B[Rear].AccNo; 
gets(B[Rear].Title);
}

Question 9:
Write a function in C++ to perform insert operation on a dynamically allocated queue containing passenger details as given in the following definition of NODE; Delhi 2011

struct NODE 
{
long Pno; //Passenger Number 
char Pname[20]; //Passenger Name 
NODE *Link;
};

Аnswer:

void Enter()
{
NODE *nptr=new NODE;
nptr->Link = NULL;
cout<<"Enter name and number for new passenger";
gets(nptr->Pname); 
cin>>nptr->Pno; 
if(rear == NULL)
{
front = rear = nptr;
}
else
{
rear->Link = nptr; 
rear = nptr;
}
}

Question 10:
Write a function in C++ to perform delete operation on a dynamically allocated queue containing passenger details as given in the following definition of NODE: All India 2011

struct NODE 
{
long Mno; //Member Number 
char Mname[20]; //Member Name 
NODE *Link;
};

Аnswer:

void remove(NODE *front)
{
NODE *nptr; 
if(front == NULL) 
{
cout<<"Queue is empty";
}
else 
{
nptr = front; 
front = front->Link; 
if(front == NULL) 
rear = NULL; 
delete nptr;
}

Question 11:
Write a complete program in C++ to implement a dynamically allocated queue containing names of cities. All India 2010
Аnswer:

#include<iostream.h>
#include<string.h> 
struct Node 
{
char city[30];
Node *link;
};
class queue 
{
Node *front, *rear; 
public:
queue() {front=rear=NULL;} 
void add_Q();    //add queue
void del_Q();    //delete queue
void show_Q();    //show queue
};
void queue :: add_Q()
{
Node *temp = new Node; 
char ct[30]; 
cout<<"Enter city"; 
gets(ct);
strcpy(temp->city,ct); 
temp->link = NULL; 
if(rear == NULL)
front = rear = temp; 
else
{
rear->link = temp; 
rear = temp;
}
}
void queue :: del_Q()
{
Node *temp; 
char ct[20]; 
if(front == NULL)
{
cout<<”queue is empty";
}
else   
{
temp = front; 
front = front->link; 
strcpy(ct, temp->city); 
cout<<"Deleted values are"<<ct; 
delete temp;
}
if(front == NULL)
rear = front;
}
void queue :: show_Q()
{
Node *temp = front; 
cout<<"The queue elements are"; 
while(temp!=NULL)
{
cout<<"\n"<<temp->city; 
temp = temp->l ink;
}
}
void main()
{
int choice; 
queue QUEUE; 
char opt='Y'; 
do 
{
cout<<"\nMain Menu"; 
cout<<"\nl.Insertion in queue"; 
cout<<"\n2.Deletion from queue"; 
cout<<"\n3.Traversal of queue"; 
cout<<"\n4.Exit from queue"; 
cout<<"\nEnter your choice from above(1,2,3,4)"; 
cin<<choice; 
switch(choice)
{
case 1: 
do 
{
QUEUE.add_Q(); 
cout<<"\ndo you want to add more elements<Y/N>?"; 
cin>>opt;
}
while(toupper(opt)=='Y'); 
break; 
case 2: 
do 
{
QUEUE.del_Q(); 
cout<<"\ndo you want to delete more elements<Y/N>?";
cin>>opt;
}
whi1e(toupper(opt)== 'Y'); 
break; 
case 3:
QUEUE.show_Q(); 
break; 
case 4; 
exit(0);
}
}
while(choice!=4);
}

Question 12:
Write a function QUEINS( ) in C++ to insert an element in a dynamically allocated queue containing nodes of the following given structure: Delhi 2009

struct Node
{
int Pid;     //Product Id
char Pname[20];   //Product Name 
Node *Next; 
};

Аnswer:

void QUEINS(Node *rear, int val, char valid)
{
Node *temp=new Node; 
temp->Pid = val; 
strcpy(temp->Pname,val1); 
temp->Next = NULL; 
if(rear == NULL)
rear = front = temp; 
else
{
rear->Next = temp; 
rear = temp;
}
}

Question 13:
Write a function QUEDEL( ) in C++ to display and delete an element in a dynamically allocated queue containing nodes of the following given structure: All India 2009

struct Node 
{
int Itemno; 
char Itemname[30];
Node *Link;
};

Аnswer:

void QUEDEL(Node *front)
{
Node *temp; 
if(front == NULL)
cout<<"Queue is Empty"; 
else
{
temp = front; 
cout<<"deleted item="; 
cout<<front->Itemno; 
cout<<front->Itemname; 
front = front->Link; 
if(front == NULL) 
rear = NULL; 
delete temp;
}
}

Computer ScienceImportant Questions for Computer ScienceNCERT Solutions

The post Important Questions for Class 12 Computer Science (C++) – Linked List, Stack and Queue appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – Structured Query Language

$
0
0

Important Questions for Class 12 Computer Science (C++) – Structured Query Language

Previous Years Examination Questions
2 Marks Questions

Question 1:
Explain the concept UNION between two tables, with the help of appropriate example. Delhi 2014

6 Marks Questions

Question 2:
Write SQL queries for (i) to (iv) and find outputs for SQL queries (v) to (viii), which are based on the tables.AII India 2017
——————————————1———————————————-
(i) To display all details from the table MEMBER in descending order of ISSUEDATE.
(ii) To display the DCODE and DTITLE of all Folk Type DVDs from the table DVD.
(iii) To display the DTYPE and number of DVDs in each DTYPE from the table DVD.
(iv) To display all NAME and ISSUEDATE of those members from the table MEMBER who have DVDs issued (i.e., ISSUEDATE) in the year 2017.

(v) SELECT MIN (ISSUEDATE) FROM MEMBER;
(vi) SELECT DISTINCT DTYPE FROM DVD;
(vii) SELECT D.DCODE, NAME, DTITLE '
FROM DVD D, MEMBER M WHERE D.DC0DE=M.DCODE;
(viii) SELECT DTITLE FROM DVD
WHERE DTYPE NOT IN ("Folk”, "Classical”);

Question 3:
Write SQL queries for (i) to (iv) and find outputs for SQL queries (v) to (viii), which are based on the tables. All India 2016
——————————————2———————————————-
NOTE

• KM is Kilometres travelled
• NOP is number of passengers travelled in vehicle.

(i) To display CNO, CNAME, TRAVELDATE from the table TRAVEL in descending order of CNO.
(ii) To display the CNAME of all the customers from the table TRAVEL who are traveling by vehicle with code V01 or V02.
(iii) To display the CNO and CNAME of those customers from the table TRAVEL who travelled between ‘2015-12-31’ and ‘2015-05-01’.
(iv) To display all the details from table TRAVEL for the customers, who have travel distance more
than 120 KM in ascending order of NOP.

(v) SELECT COUNT(*), VCODE FROM TRAVEL 
GROUP BY VCODE HAVING C0UNT(*)>1;
(vi) SELECT DISTINCT VCODE FROM TRAVEL;
(vii) SELECT VCODE,CNAME,VEHICLETYPE 
FROM TRAVEL A, VEHICLE B
WHERE A.VC0DE=B.VCODE AND KM<90;
(viii) SELECT CNAME, KM*PERKM
FROM TRAVEL A, VEHICLE B
WHERE A.VC0DE=B.VCODE AND A.VC0DE='V05';

Question 4:
Write SQL queries for (i) to (iv) and find outputs for SQL queries (v) to (viii), which are based on the tables. Delhi 2016
——————————————3———————————————-
NOTE

• PERKM is Freight Charges per kilometre
• VTYPE is Vehicle Type
——————————————4———————————————-
NOTE

• NO is Traveller Number
• KM is Kilometre travelled
• NOP is number of travellers travelled in vehicle
• TDATE is Travel Date

(i) To display NO, NAME, TDATE from the table TRAVEL in descending order of NO.
(ii) To display the NAME of all the travellers from the table TRAVEL who are travelling by vehicle
with code 101 or 102. ‘
(iii) To display the NO and NAME of those travellers from the table TRAVEL who travelled between ’2015-12-31’ and ‘2015-04-01’.
(iv) To display all the details from table TRAVEL for the travellers, who have travelled distance more than 100 KM in ascending order of NOP.

(v) SELECT COUNT(*), CODE FROM TRAVEL 
GROUP BY CODE HAVING C0UNT(*) >1;
(vi) SELECT DISTINCT CODE FROM TRAVEL;
(vii) SELECT CODE,NAME,VTYPE 
FROM TRAVEL A, VEHICLE B 
WHERE A.C0DE=B.C0DE AND KM<90;
(viii) SELECT NAME,KM*PERKM
FROM TRAVEL A, VEHICLE B
WHERE A.C0DE=B.C0DE AND A.C0DE='105' ;

Question 5:
Consider the following DEPT and WORKER tables. Write SQL queries for (i) to (iv) and find outputs for SQL queries (v) to (viii): Delhi 2015
——————————————5———————————————-
NOTE

DOJ refers to Date of Joining and DOB refers to Date of Birth of workers.
(i) To display WNO, NAME,, GENDER from the table WORKER in descending order of WNO.
(ii) To display the NAME of all the FEMALE workers from the table WORKER.
(iii) To display the WNO and NAME of those workers from the table WORKER, who are born between ‘1987-01-01’ and ‘1991-12-01’.
(iv) To count and display MALE workers who have joined after ‘1986-01-01’.

(v) SELECT COUNT(*), DCODE FROM WORKER 
GROUP BY DCODE HAVING C0UNT(*)>1;
(vi) SELECT DISTINCT DEPARTMENT FROM DEPT;
(vii) SELECT NAME, DEPARTMENT, CITY FROM WORKER W, DEPT D 
WHERE W.DC0DE=D.DCODE AND WNO<1003;
(viii) SELECT MAX (DOJ), MIN(DOB) FROM WORKER;

Question 6:
Consider the following DEPT and EMPLOYEE tables. Write SQL queries for (i) to (iv) and find outputs for SQL queries (v) to (viii). All India 2015
——————————————6———————————————-
——————————————7———————————————-
NOTE

DOJ refers to Date of Joining and DOB refers to Date of Birth of employees.
(i) To display ENO, NAME, GENDER from the table EMPLOYEE in ascending order of ENO.
(ii) To display the NAME of all the MALE employees from the table EMPLOYEE.
(iii) To display the ENO and NAME of those employees from the table EMPLOYEE who are born between ‘1987-01-01’ and ‘1991-12-01’.
(iv) To count and display FEMALE employees who have joined after ‘1986-01-01’.

(v) SELECT COUNT (*), DC0DE FROM EMPLOYEE 
GROUP BY DCODE HAVING C0UNT(*)>1;
(vi) SELECT DISTINCT DEPARTMENT FROM DEPT;
(vii) SELECT NAME, DEPARTMENT FROM EMPLOYEE E.DEPT D 
WHERE E.DCODE = D.DCODE AND ENO<1003;
(viii) SELECT MAX(DOJ), MIN(DOB) FROM EMPLOYEE;

Question 7:
Consider the following tables SCHOOL and ADMIN and answer (a) and (b) parts of this question : All India 2014 c
——————————————8———————————————-
(a) Write SQL statements for the following:
(i) To display TEACHERNAME, PERIODS of all teachers whose periods are more than 25.
(ii) To display all the information from the table SCHOOL in descending order of experience.
(iii) To display DESIGNATION without duplicate entries from the table ADMIN.
(iv) To display TEACHERNAME, CODE and corresponding DESIGNATION from tables SCHOOL and ADMIN of Male teachers.
(b) Give the output of the following SQL queries :

(i) SELECT DESIGNATION, COUNT (*) FROM ADMIN GROUP BY DESIGNATION HAVING COUNT (*)<2;
(ii) SELECT MAX (EXPERIENCE) FROM SCHOOL;
(iii) SELECT TEACHERNAME FROM SCHOOL WHERE EXPERIENCE > 12 ORDER BY TEACHERNAME;
(iv) SELECT COUNT (*), GENDER FROM ADMIN GROUP BY GENDER;

Question 8:
Answer the questions (a) and (b) on the basis of the following tables STORE and ITEM. Delhi 2014
——————————————9———————————————-
(a) Write the SQL queries (i) to (iv):
(i) To display IName and Price of all the Items in ascending order of their Price.
(ii) To display SNo and SName of all Store located in CP.
(iii) To display Minimum and Maximum Price of each IName from the table ITEM.
(iv) To display IName, Price of all items and their respective SName where they are available.
(b) Write the output of the following SQL commands (i) to (iv):

(i) SELECT DISTINCT IName FROM ITEM
WHERE Price >=5000;
(ii) SELECT Area, COUNT(*)
FROM STORE GROUP BY Area;
(iii) SELECT COUNT(DISTINCT Area) FROM STORE;
(iv) SELECT IName, Price * 0.05 DISCOUNT FROM ITEM 
WHERE SNo IN (S02, S03);

Question 9:
Answer the questions (a) and (b) on the basis of the following tables SHOPPE and ACCESSORIES. All India 2014
——————————————10———————————————-
(a) Write the SQL queries:
(i) To display Name and Price of all the accessories in ascending order of their Price.
(ii) To display Id and SName of all Shoppe located in Nehru Place.
(iii) To display Minimum and Maximum Price of each Name of accessories.
(iv) To display Name, Price of all accessories and their respective SName where they are available.
(b) Write the output of the following SQL commands:

(i) SELECT DISTINCT Name FROM ACCESSORIES WHERE Price>=5000;
(ii) SELECT Area, C0UNT(*) FROM SHOPPE GROUP BY Area;
(iii) SELECT C0UNT(DISTINCT Area) FROM SHOPPE:
(iv) SELECT Name, Price*0.05 DISCOUNT FROM ACCESSORIES WHERE SNo IN (S02.S03);

Question 10:
Write SQL queries for (a) to (f) and write the outputs for the SQL queries mentioned shown in (i) to (iv) parts on the basis of tables PRODUCTS and SUPPLIERS. All India 2013
——————————————11———————————————-
——————————————12———————————————-
(a) To display the details of all the products in ascending order of product names (i.e. PNAME).
(b) To display product name and price of all those products, whose price is in the range of 10000 and 15000 (both values inclusive).
(c) To display the number of products which are supplied by each supplier, i.e. the expected output should be

501 2
502 2
503 1

(d) To display the price, product name (i.e. PNAME) and quantity (i.e. QTY) of those products which have quantity more than 100.
(e) To display the names of those suppliers, who are either from DELHI or from CHENNAI.
(f) To display the name of the companies and the name of the products in descending order of company names.
(g) Obtain the outputs of the following SQL queries based on the data given in tables PRODUCTS and SUPPLIERS:

(i) SELECT DISTINCT SUPCODE FROM PRODUCTS:
(ii) SELECT MAX(PRICE), MIN(PRICE) FROM PRODUCTS;
(iii) SELECT PRICE * QTY AMOUNT FROM PRODUCTS WHERE PID = 104;
(iv) SELECT PNAME, SNAME FROM PRODUCTS P, SUPPLIERS S 
WHERE P.SUPCODE - S.SUPCODE AND QTY>100;

Question 11:
Write SQL queries for (a) to (f) and write the outputs for the SQL queries mentioned shown in (i) to (iv) parts on the basis of tables ITEMS and TRADERS. Delhi 2013
——————————————13———————————————-
(a) To display the details of all the items in ascending order of item names (i.e. INAME).
(b) To display item name and price of all those items, whose price is in the range of 10000 and 22000 (both values inclusive).
(c) To display the number of items, which are traded by each trader. The expected output of this query should be

T01 2
T02 2
T03 1

(d) To display the price, item name (i.e. INAME) and quantity (i.e. QTY) of those items which have quantity more than 150.
(e) To display the names of those traders, who are either from DELHI or from MUMBAI.
(f) To display the name of the companies and the name of the items in descending order of company names.
(g) Obtain the outputs of the following SQL queries based on the data given in tables ITEMS and TRADERS:

(i) SELECT MAX (PRICE), MIN( PRICE) FROM ITEMS;
(ii) SELECT PRICE * QTY AMOUNT FROM ITEMS WHERE CODE = 1004;
(iii) SELECT DISTINCT TCODE FROM ITEMS;
(iv) SELECT INAME, TNAME FROM ITEMS I, TRADERS T 
WHERE I.TCODE = T.TCODE AND QTY<100;

Question 12:
Write SQL queries for (a) to (f) and write the outputs for the SQL queries mentioned shown in (i) to (iv) parts on the basis of tables APPLICANTS and COURSES. Delhi (C) 2013
——————————————14———————————————-
(a) To display name, fee, gender, joinyear about the applicants, who have joined before 2010.
(b) To display the names of applicants, who are paying fee more than 30000.
(c) To display names of all applicants in ascending order of their joinyear.
(d) To display the year and the total number of applicants joined in each YEAR from the table APPLICANTS.
(e) To display the CJD (i.e. Course ID) and the number of applicants registered in the course from the APPLICANTS table.
(f) To display the applicant’s name with their respective course’s name from the tables APPLICANTS and COURSES.
(g) Give the output of following SQL statements:

(i) SELECT NAME, JO I NY EAR FROM APPLICANTS WHERE GENDER-'F’ and C_ID=’A02';
(ii) SELECT MINIJOINYEAR) FROM APPLICANTS WHERE Gender='M';
(iii) SELECT AVG (FEE) FROM APPLICANTS WHERE C_ID='A01’ OR C_ID='A05’;
(iv) SELECT SUM(FEE), C_ID FROM APPLICATIONS GROUP BY C_ID HAVING C0UNT(*)=2;

Question 13:
Consider the following tables CABHUB and CUSTOMER and answer (a) and (b) parts of this question: Delhi 2012
——————————————15———————————————-
(a) Write SQL commands for the following statements:
(i) To display the names of all the white colored vehicles.
(ii) To display name of vehicle, make and capacity of vehicles in ascending order of theii iting Capacity.
(iii) To display the highest charges at which a vehicle can be hired from CABHUB.
(iv) To display the customer names and the corresponding name of the vehicle hired by them.
(b) Give the output of the following SQL queries :

(i) SELECT COUNT (DISTINCT Make) FROM CABHUB;
(ii) SELECT MAX(Charges), MIN (Charges) FROM CABHUB;
(iii) SELECT COUNT(*), Make FROM CABHUB;
(iv) SELECT VehicleName FROM CABHUB WHERE Capacity = 4;

Question 14:
Consider the following tables CUSTOMER and ONLINESHOP. Write SQL commands for the statements (i) to (iv) and give outputs for SQL queries (v) to (viii). Delhi (C) 2012
——————————————16———————————————-
(i) To display cname, area of fill female customers from CUSTOMER table.
(ii) To display the details of all the customers in ascending order of CNAME within SID.
(iii) To display the total number of customers for each area from CUSTOMER table.
(iv) To display cname and corresponding shop from CUSTOMER table and ONLINESHOP table.

(v) SELECT COUNT(DATE), GENDER FROM CUSTOMER GROUP BY GENDER;
(vi) SELECT C0UNT(*) FROM ONLINESHOP;
(vii) SELECT CNAME FROM CUSTOMER WHERE CNAME LIKE "L%";
(viii) SELECT DISTINCT AREA FROM CUSTOMER;

Question 15:
Consider the following tables CARDEN and CUSTOMER and answer (a) and (b) parts of this question: All India 2012
——————————————17———————————————-
(a) Write SQL commands for the following statements:
(i) To display the name of all the SILVER colored cars.
(ii) To display name of car, make and capacity of cars in descending order of their sitting capacity.
(iii) To display the highest Charges at which a vehicle can be hired from CARDEN.
(iv) To display the customer names and the corresponding name of the cars hired by them,
(b) Give the output of the following SQL queries:

(i) SELECT COUNT (DISTINCT Make) FROM CARDEN:
(ii) SELECT MAX(Charges), MIN (Charges) FROM CARDEN;
(iii) SELECT C0UNT(*), Make FROM CARDEN;
(iv) SELECT CarName FROM CARDEN WHERE Capacity = 4;

Question 16:
Consider the following tables EMPLOYEE and SALGRADE and answer (a) and (b) parts of this question: All Indio 2011
——————————————18———————————————-
(a) Write SQL commands for the following statements:
(i) To display the details of all the EMPLOYEE in descending order of DOJ.
(ii) To display name and desig of those EMPLOYEE, whose sgrade is either S02 or S03.
(iii) To display the content of all the EMPLOYEE table, whose DOJ is in between ‘09-FEB-2006’ and ‘08-AUG-2009’.
(iv) To add a new row in the EMPLOYEE table with the following data:
109, ‘Harish Roy’, ‘HEAD-IT, ‘S02’, ‘09-SEP-2007’, ‘21-APR-1983’.
(b) Give the output of the following SQL queries:

(i) SELECT C0UNT(SGRADE), SGRADE FROM EMPLOYEE GROUP BY SGRADE;
(ii) SELECT MIN (DOB), MAX (DOJ) FROM EMPLOYEE;
(iii) SELECT NAME, SALARY FROM EMPLOYEE E, SALGRADE S 
WHERE E.SGRADE = S.SGRADE AND E.EC0DE<103;
(iv) SELECT SGRADE, SALARY+HRA FROM SALGRADE WHERE SGRADE = ‘S02';

Question 17:
Consider the following tables WORKER and PAYLEVEL and answer (a) and (b) parts of this
question: Delhi 2011
——————————————19———————————————-
——————————————20———————————————-
(a) Write SQL commands for the following statements:
(i) To display the details of all WORKER in descending order of DOB.
(ii) To display name and desig of those WORKER, whose plevel is either P001 or P002.
(iii) To display the content of all the WORKER table, whose DOB is in between ‘19-JAN-1984’ and T8-JAN-1987’.
(iv) To add a new row with the following:
19, ‘Daya Kishore’, ‘Operator’, ‘P003’, ‘19-JUN-2008’, ‘11-JUL-1984’.
(b) Give the output of the following SQL queries:

(i) SELECT COUNTCPLEVEL(). PLEVEL FROM WORKER GROUP BY PLEVEL:
(ii) SELECT MAX (DOB), MIN(DOJ) FROM WORKER;
(iii) SELECT NAME, PAY FROM WORKER W, PAYLEVEL P 
WHERE W.PLEVEL= P.PLEVEL AND W.EC0DE<13;
(iv) SELECT PLEVEL, PAY+ALLOWANCE FROM PAYLEVEL WHERE PLEVEL = ‘POO3’:

Question 18:
Consider the following tables STORE and SUPPLIERS and answer (a) and (b) parts of this question: Delhi 2010
——————————————21———————————————-
(a) Write SQL commands for the following statements:
(i) To display details of sill the items in the STORE table in ascending order of LastBuy.
(ii) To display ItemNo and Item of those items from STORE table whose Rate is more than ? 15.
(iii) To display the details of those items whose supplier code (Scode) is 22 or quantity in store (Qty) is more than 110 from the table STORE.
(iv) To display minimum Rate of items for each supplier individually as per Scode from the table STORE.
(b) Give the output of the following SQL queries:

(i) SELECT COUNT(DISTINCT Scode) FROM STORE;
(ii) SELECT Rate * Qty FROM STORE WHERE ItemNo = 2004;
(iii) SELECT Item, Sname FROM STORE S, SUPPLIERS P 
WHERE S.Scode = P.Scode AND ItemNo = 2006;
(iv) SELECT MAX(LastBuy) FROM STORE;

Question 19:
Consider the following tables STOCK and DEALERS and answer (a) and (b) parts of this question: All India 2010
——————————————22———————————————-
(a) Write SQL commands for the following statements:
(i) To display details of all the items in the STOCK table in ascending order of StockDate.
(ii) To display ItemNo and ItemName of those items from STOCK table whose UnitPrice is more than ? 10.
(iii) To display the details of those items whose dealer code (Dcode) is 102 or quantity in stock (Qty) is more than 100 from the table STOCK.
(iv) To display maximum UnitPrice of items for each dealer individually as per Dcode from the table STOCK.
(b) Give the output of the following SQL queries:

(i) SELECT COUNT(DISTINCT Dcode) FROM STOCK;
(ii) SELECT Qty * UnitPrice FROM STOCK WHERE ItemNo = 5006;
(iii) SELECT ItemName. Dname FROM STOCK S, DEALERS D 
WHERE S.Dcode = D.Dcode AND ItemNo = 5004;
(iv) SELECT MIN(StockDate) FROM STOCK;

Question 20:
Consider the following tables GARMENT and FABRIC. Write SQL commands for the statements (i) to (iv) and give outputs for SQL queries (v) to (viii). Delhi 2009
——————————————23———————————————-
——————————————24———————————————-
(i) To display GCODE and DESCRIPTION of each GARMENT in descending order of GCODE.
(ii) To display the details of all the GARMENT, which have READYDATE in between 08-DEC-07 and 16-JUN-08 (inclusive of both the dates).
(iii) To display the average PRICE of all the GARMENT, which are made up of fabric with FCODE as F03.
(iv) To display fabric wise highest and lowest price of GARMENT from GARMENT table. (Display FCODE of each GARMENT alongwith highest and lowest Price).

(v) SELECT SUM(PRICE) FROM GARMENT WHERE FCODE = 'FO1'; . .
(vi) SELECT DESCRIPTION, TYPE FROM GARMENT, FABRIC
WHERE GARMENT.FCODE = FABRIC.FCODE AND GARMENT.PRICE >=1260;
(vii) SELECT MAX(FCODE) FROM FABRIC;
(viii) SELECT COUNT(DISTINCT PRICE) FROM GARMENT;

Question 21:
Consider the following tables DRESS and MATERIAL. Write SQL commands for the statements (i) to (iv) and give outputs for SQL queries (v) to (viii). All India 2009
——————————————25———————————————-
(i) To display DCODE and DESCRIPTION of each dress in ascending order of DCODE.
(ii) To display the details of all the dresses which have LAUNCHDATE in between 05-DEC-07 and 20- JUN-08 (inclusive of both the dates).
(iii) To display the average PRICE of all the dresses which are made up of material with MCODE as M003.
(iv) To display materialwise highest and lowest price of dresses from DRESS table, (display MCODE of each dress alongwith highest and lowest price).

(v) SELECT SUM(PRICE) FROM DRESS WHERE MCODE = *M001';
(vi) SELECT DESCRIPTION, TYPE FROM DRESS, MATERIAL
WHERE DRESS.DCODE = MATERIAL.MCODE AND DRESS.PRICE >= 1250;
(vii) SELECT MAX (MCODE) FROM MATERIAL;
(viii) SELECT COUNT(DISTINCT PRICE) FROM DRESS;

Question 22:
Consider the following tables STUDENT and STREAM. Write SQL commands for the statements (i) to (iv) and give outputs for SQL queries (v) to (viii). Delhi (C) 2009
——————————————26———————————————-
(i) To display the name of streams in alphabetical order from table STREAM.
(ii) To display the number of students whose POINTS are more than 5.
(iii) To update GRADE to ‘A’ for all those students who are getting more than 8 as POINTS.
(iv) ARTS+MATHS stream is no more available. Make necessary change in table fjTREAM.

(v) SELECT SUM(POINTS) FROM STUDENT WHERE AGE >14; .
(vi) SELECT STRCDE, MAX(POINTS) FROM STUDENT
GROUP BY STRCDE HAVING SCODE BETWEEN 105 AND 130;
(vii) SELECT AVG(AGE) FROM STUDENT WHERE SCODE IN (102,105, 110, 120);
(viii) SELECT COUNT(STRNAME) FROM STREAM WHERE STRNAME LIKE "SCI%";

Computer ScienceImportant Questions for Computer ScienceNCERT Solutions

The post Important Questions for Class 12 Computer Science (C++) – Structured Query Language appeared first on Learn CBSE.


Important Questions for Class 12 Computer Science (C++) – Communication Technologies

$
0
0

Important Questions for Class 12 Computer Science (C++) – Communication Technologies

Previous years Examination Questions
  1 Marks Questions

Question 1:
Give two examples of PAN and LAN type of networks. Delhi 2016
Аnswer:

Two examples of PAN type of networks 3.
are as follows:

  1. Upload the photo from your cell phone to your desktop computer.
  2. Watch movies from an online streaming service to your TV.

Two examples of LAN type of networks
are as follows:

  1. Small office or a Internet cafe.
  2. Two or more computers connected in few distances.

Question 2:
Which protocol helps us to browse through Web pages using Internet browsers? Name any one Internet browser. Delhi 2016
Аnswer:

Protocol → HyperText Transfer Protocol A.
(HTTP)
Internet Browser → Google Chrome

Question 3:
Write two advantages of 4G over 3G Mobile Telecommunication Technologies in terms of speed and services. Delhi 2016
Аnswer:

Two advantages of 4G over 3G mobile telecommunication technologies are as follows:

important-questions-for-class-12-computer-science-c-communication-technologies-(345-1)

Question 4:
Write two characteristics of Web 2.0. Delhi 2016; All India 2016
Аnswer:

Characteristics of Web 2.0 are as follows:

  1. Free classification of information
  2. User as a contributor

Question 5:
What is the basic difference between Trojan Horse and Computer Worm? Delhi 2016; All India 2016
Аnswer:

Computer worms are programs that replicate themselves from system to system without the use of a host file, while Trojan horses are impostor files that claim to be something desirable but, in fact are malicious.

Question 6:
Categorise the following under Client Side and Server Side script category:

  1. VBScript
  2. ASP
  3. JSP
  4. JavaScript
    All India 2016: Delhi 2016

Аnswer:
Client side scripting languages are as follows: JavaScript, VBScript
Server side scripting languages are as follows: ASP, JSP

Question 7:
Differentiate between PAN and LAN types of networks. All India 2016
Аnswer:
PAN network is a computer network organised around an individual person, while LAN network is a privately owned networks within a single building or campus upto a few kilometres in distance.

Question 8:
Which protocol helps us to transfer files to and from a remote computer? All India 2016
Аnswer:

Protocol → File Transfer Protocol ( FTP )

Question 9:
Write two advantages of 3G over 2G Mobile Telecommunication Technologies in terms of speed and services. All India 2016
Аnswer:

Two advantages of 3G over 2G Mobile Telecommunication Technologies are as follows:

  1. The downloading and uploading speeds available in 3G technologies are upto 21 Mbps and 5.7 Mbps respectively while in 2G technologies the downloading and uploading speeds are upto 236 Kbps.
  2. The services like mobile TV, video transfer and GPS systems are the additional features of 3G technology that are not available with 2G technologies.

Question 10:
Illustrate the layout for connecting
5 computers in a bus and a star topology of networks. All India 2015: Delhi 2015
Аnswer:

important-questions-for-class-12-computer-science-c-communication-technologies-(346-1)

Question 11:
What is a spam mail? Delhi 2015
Аnswer:

Spam Mail is flooding on the Internet with many copies of the same meaning, in an attempt to force the message on people who would not otherwise choose to receive it.

Question 12:
Differentiate between FTP and HTTP.  Delhi 2015
or
What is the difference between HTTP and FTP? All India 2013
Аnswer:

FTP is a protocol used to upload files from a workstation to a FTP server or download files from a FTP server to a workstation while, HTTP is a protocol used to transfer files from a Web server onto a browser in order to view a Web page that is on the Internet.

Question 13:
Out of the following, which is the fastest

  1. wired and
  2. wireless medium of communication? Infrared, Coaxial Cable, Ethernet Cable, Microwave, Optical Fiber.
    All India 2015: Delhi 2015

Аnswer:

  1. Wired-Optical Fiber
  2. Wireless-Infrared

Question 14:
What is Worm? How is it removed? Delhi 2015
Аnswer:

A computer worm is a stand alone malware computer program that replicates itself in order to spread to other computers.
Worms can be removed by installing antivirus.

Question 15:
Out of the following, which one comes under cyber crime?

  1. Stealing away a brand new computer from a showroom.
  2. Getting in someone’s social networking account without his consent and posting pictures on his behalf to harass him.
  3. Secretly copying files from’ server of a call center and selling it to the order organisation.
  4. Viewing sites on a internal browser. Delhi 2015

Аnswer:
(ii) Getting in someone’s social networking account without his consent and posting pictures on his behalf to harass him.

Question 16:
What kind of data gets stored in cookies and how is it useful? All India 2015
Аnswer:

Cookies contain random alphanumeric text characters, which are determined by the specific Website that created that cookie. It helps you to access a site faster and more efficiently.

Question 17:
Differentiate between packet switching over message switching. All India 2015
or
Differentiate between packet switching and message switching technique in network communication? Delhi 2011
Аnswer:

In message switching, large storage space is required at each node to buffer the complete message blocks. On the other hand in packet switching, messages are divided into subset of equal length, which are generated in the source node and reassembled to get back the initial complete message in destination node.

Question 18:
What is Trojan Horse? All India 2015
Аnswer:

Trojan Horse It is a type of malware designed to provide unauthorised, remote access to a user’s computer. Trojan horses do not have the ability to replicate themselves. They can lead to viruses being installed on a machine since they allow the computer to be controlled by the trojan creator.

Question 19:
Write one characteristic each for 2G and 3G mobile technologies. Delhi 2014
Аnswer:

Characteristic of 2G mobile technology is that it has introduced data services for mobile, starting with text messaging.
Characteristic of 3G mobile technology is that it is faster than 2G and supports video calling.

Question 20:
What is the difference between video conferencing and chat? Delhi 2014
Аnswer:

Chat generally involves one-to-one communication. On the other hand, video conferencing means more than two persons are involved in a discussion.

Question 21:
Expand the following:

  1. GPRS
  2. CDMA
  3. GSM Delhi 2014: All India 2014

or

Expand the following abbreviation:

  1. GSM
  2. CDMA Delhi 2009

Аnswer:

  1. GPRS General Packet Radio Services.
  2. CDMA Code Division Multiple Access.
  3. GSM Global System for Mobile Communication.

Question 22:
Write two characteristics of Wi-Fi.  All India 2014
Аnswer:

Characteristics of Wi-Fi are as follows:

  1. It is a wireless solution for getting connected to the Internet.
  2. It is handly as well as availably throughout the journey.

Question 23:
What is the difference between E-mail and chat? All India 2014; Delhi 2013C
Аnswer:

In order to chat, you need have an account on the same service as the person you are chatting with.
On the other hand, in case of e-mail, it is not necessary, i.e. you can have an account from any provider and you can establish your own.

Question 24:
Which type of network (out of LAN, PAN and MAN) is formed, when you connect two mobiles using bluetooth to transfer a picture file? Delhi 2014
or
Which type of network (out of LAN, PAN and MAN) is formed, when you connect two mobiles using bluetooth to transfer a video.  All India 2014
Аnswer:

When two mobiles are connected using bluetooth to transfer a picture file, a PAN (Personal Area Network) is created.

Question 25:
Which of the following crime(s) does not come under cybercrime?

  1. Copying some important data from a computer without taking permission from the owner of the data.
  2. Stealing keyboard and mouse from a shop.
  3. Getting into unknown person’s social networking account and start messaging on his behalf. All India 2013

Аnswer:
(ii) Stealing keyboard and mouse from a shop.

Question 26:
What is the difference between domain name and IP address? Delhi 2013
Аnswer:

IP address is an identifier for a computer or device on a TCP/IP network, e.g. 1.160.10.240 could be an IP address. Whereas, a domain name is a name that identifies one or more IP addresses, e.g. the domain name microsoft.com represents about a dozen IP addresses.

Question 27:
Write two advantages of using an optical fibre cable over an Ethernet cable to connect two service stations, which are 190 m away from each other. Delhi 2013
or
Write two advantages of using an optical fibre cable over an Ethernet cable to connect two service stations, which are 190 —> 200 m away from each other.  All India 2013
Аnswer:

Two advantages of using optical fibre cable over an Ethernet cable are as follows:

  1. Low power because signals in optical fibres degrade less, low-power transmitters can be used.
  2. Digital Signals Optical fibres are ideally suited for carrying digital information, which is especially useful in computer networks.

Question 28:
What is the difference between packet switching and circuit switching techniques? All India 2013 (C)
Аnswer:

(i) circuit Switching In this, firstly complete
physical connection between two computers is established. After that data are transmitted from the source computer to the destination computer.
e.g. In telephone call, circuit switching is used.
Packet Switching In this, there is a fixed size of packet and data packets are stored in the main memory.
This improves the access time.

Question 29:
Expand the following abbreviations:
(a) HTTP (b) VoIP
All India 2013
Аnswer:

(a) HTTP: HyperText Transfer Protocol
(b) VoIP: Voice over Internet Protocol

Question 30:
Which of the following crime(s) is/are covered under cybercrime?

  1. Stealing brand new hard disk from a shop.
  2. Getting unknown person’s social networking account and start messaging on his behalf.
  3. Copying some important data from a computer without taking permission from the owner of the data. Delhi 2013

Аnswer:
(ii) Getting into unknown person’s social networking account and start messaging on this behalf.

Question 31:
What out of the following, you will use to have an audio visual chat with an expert sitting in a far away place to fix-up technical issue?

  1. E-mail
  2. VoIP
  3. FTP Delhi: All India 2012

Аnswer:
(ii) VoIP

Question 32:
Name one client side scripting language and one server side scripting language.  Delhi: All India 2012
Аnswer:

Client Side Scripting Language VBScript Server Side Scripting Language ASP

Question 33:
Which out of the following does not come under cyber crime?

  1. Stealing a mouse from someone’s compuer.
  2. Operating someone’s Internet banking account, without his knowledge.
  3. Entering in someone’s computer remotely and copying data, without seeking his permission. All Indio 2012

Аnswer:
(i) Stealing a mouse from someone’s computer.

Question 34:
Write one advantage of star topology of network. Also, illustrate how 5 computers can be connected with each other using star topology of network. All India 2012
Аnswer:

Advantage of Star Topology is as follow:
No disruption to the network when connecting or removing devices.
In star topology 5 computers can be connected with each other using server like as follows:
important-questions-for-class-12-computer-science-c-communication-technologies-(347-1)

Question 35:
Give one suitable example of each URL and domain name. Delhi; All India 2012
Аnswer:

URL http://www.Gabsclasses.com/aboutus Domain name Gabsclasses.com

Question 36:
Which of the following come under cyber crime?

  1. Operating someone’s Internet banking account, without his knowledge.
  2. Stealing a keyboard from someone’s computer.
  3. Working on someone’s computer with his/her permission. All India 2012

Аnswer:
(i) Operating someone’s Internet banking account, without his knowledge.

Question 37:
Write one advantage of bus topology of network. Also, illustrate how four computers can be connected with each other using star topology of network.  Delhi 2012
Аnswer:

Advantage of Bus Topology In bus topology, computers can be connected with each other using a single linear cable.
In star topology, four computers can be connected with each other using server in the following way:
important-questions-for-class-12-computer-science-c-communication-technologies-(347-2)

Question 38:
Differentiate between bus and star topology of networks. Delhi 2011, 2009
Аnswer:

In star topology, nodes are connected to server individually whereas in bus topology all nodes are connected to server along a single length of cable.

Question 39:
What is VoIP? Delhi 2011
Аnswer:

VoIP (Voice over Internet Protocol) is simply the transmission of voice traffic over IP-based networks.

Question 40:
Which of the following will come under cyber crime?

  1. Theft of a brand new sealed pack laptop.
  2. Access to a bank account for getting unauthorised money transaction.
  3. Modification in a company data with unauthorised access.
  4. Photo copying a printed copy. Delhi 2011

Аnswer:
(ii) Access to a bank account for getting unauthorised money transaction.

Question 41:
In networking, what is WAN? How is it different from LAN? All India 2011
or
What is the difference between LAN and WAN? Delhi (C) 2009, All India 2009
Аnswer:

WAN (Wide area network) is a computer network that spans a relatively large geographical area. Typically, a WAN consists of two or more LANs.
LAN is a group of computers and network devices connected together, usually within the same building whereas WAN is not restricted to geographical location, although it might be confined within the bounds of state or country.

Question 42:
Differentiate between XML and HTML.  All India 2011
Аnswer:

XML was designed to describe data and to focus on what data is while HTML was designed to display data and to focus on how data looks. HTML is about displaying information while XML is about describing information.

Question 43:
What is Web 2.0? All India 2011
Аnswer:

Web 2.0 is associated with Web application that facilitates participatory information sharing, interoperability, uses centered dasign and collaboration on the world wide web.

Question 44:
What are cookies? All India 2011
Аnswer:

Cookies are files stored temporarily on WWW browser’s computer which allow the WWW server to store persistent information associated with browsing user.

Question 45:
What is the function of modem? Delhi 2011C
Аnswer:

Function of modem is to convert analog signals into digital signals and vice-versa. It is used to connect Internet.

Question 46:
Name any two components required for networking. Delhi 2011C
Аnswer:

Switch/Hub and Repeaters.

Question 47:
What is repeater? Delhi 2011C
Аnswer:

Repeater is an electronic device, that receives a signal and retransmits it at a higher level so that the signal covers longer distance. It’s required if the distance between source and destination is 90 m or more.

Question 48:
What was the role of ARPANET in the computer network? Delhi; All India 2010
Аnswer:

ARPANET (Advanced Research Projects Agency Network). The goal of this project was to connect computers at different universities and US defence.
ARPANET started with a handful of computer but it expanded rapidly.

Question 49:
Which of the following is not an unit for data transfer rate?

  1. Bps
  2. Abps
  3. Gbps
  4. Kbps Delhi 2010

Аnswer:
(ii) Abps is not unit for data transfer rate.

Question 50:
What is the difference between trojan horse and virus in terms of computers? Delhi 2010
Аnswer:

Unlike viruses, trojan horse do not replicate themselves but they can be just a lot destructive. One of the most insidious type of trojan is a program that claims to rid your computer of viruses but instead introduce viruses onto your computer.

Question 51:
What term we use for a software/ hardware device, which is used to block, unauthorised access while permitting authorised communications. This term is also used for a device or set of devices configured to permit, deny, encrypt, decrypt, or proxy all (in and out) computer traffic between different security domains based upon a set of rules and other criteria. Delhi; All India 2010
Аnswer:

Firewall

Question 52:
Write the full forms of the following:

  1. GNU
  2. XML Delhi 2010

Аnswer:

  1. GNU GNU’S NOT UNIX
  2. XML extensible Markup Language

Question 53:
Which of the following is not an unit for data transfer rate?

  1. Mbps
  2. Kbps
  3. Sbps
  4. Gbps Delhi 2011

Аnswer:
(iii) Sbps

Question 54:
What is the difference between virus and worm in the computer? All India 2010
Аnswer:

The main difference between virus and worm is the method by which they reproduce and spread. A virus is dependent upon a boot sector and the transfer of files between machines to spread, while a worm can run completely independently and spread itself through network connections.

Question 55:
Write the full form of the following:

  1. FTP
  2. FSF All India 2010

Аnswer:

  1. FTP File Transfer Protocol
  2. FSF Free Software Foundation.

Question 56:
Name any two common web browsers. All India 2010
Аnswer:

Google Chrome and Internet Explorer.

Question 57:
What is protocol? Which protocol is used to search information from Internet using an Internet browser? Delhi 2009
Аnswer:

Protocol is a set of rules that two or more computers must follow in order to communicate on network. HTTP (HyperText Transfer protocol) is used for searching information from Internet using Internet browser.

Question 58:
Name two switching techniques used to transfer data between two terminals (computers). Delhi; All India 2009
Аnswer:

Switching techniques used to transfer data between two terminals :

  1. Circuit switching
  2. Packet switching

Question 59 :
Expand the following abbreviations

  1. HTTP
  2. ARPANET All India 2009

Аnswer:

  1. HTTP HyperText Transfer Protocol
  2. ARPANET Advanced Research Projects Agency Network

Question 60:
What is protocol? Which protocol is used to copy a file from/to a remotely server ? All India 2009
Аnswer:

Protocol is a set of rules that two or more computers should follow in order to communicate on network. FTP (File Transfer Protocol) is used to copy a file from/to a remotely located server.

Question 61:
Expand the following terminologies

  1. GSM
  2. WLL Delhi 2009 (C)

Аnswer:

  1. GSM Global System for Mobile Communication,
  2. WLL Wireless Local Loop.

Question 62:
Distinguish between Website and Web browser. Delhi 2009 (c)
Аnswer:

Website is a collection of related Web pages served from a single Web domain while Web browser is a software that is used to access and display the Web pages.

Question 63:
What is firewall? Delhi 2009 (C)
Аnswer:

Firewall is a security system that prevents an unauthorised access to a private network. Firewalls can be implemented in both hardware and software or combination of both.

2 Marks Questions

Question 64:
Differentiate between communication using Optical Fibre and Ethernet Cable in context of wired medium of communication technologies. All India 2017
Аnswer:

Differences between Optical Fibre and Ethernet Cable are as follows :
important-questions-for-class-12-computer-science-c-communication-technologies-(348-1)

Question 65:
Janish Khanna used a pen drive to copy files from his friend’s laptop to his office computer. Soon his computer started abnormal functioning. Sometimes it would restart by itself and sometimes it would stop different applications running on it. Which of the following options out of (i) to (iv), would have caused the malfunctioning of the computer? Justify
the reason for your chosen option: All India 2017

  1. Computer Virus
  2. Spam Mail
  3. Computer Bacteria
  4. Trojan Horse

Аnswer:
(i) Computer virus
Reason Computer virus can spread through external media such as CDs, pen drive etc. It is designed to infect the host program and gain control over the system without the owner’s knowledge.

Question 66:
Ms. Raveena Sen is an IT expert and a freelancer. She recently used her skills to access the Admin password for the network server of Super Dooper Technology Ltd. and provided confidential data of the organisation to its CEO, informing him about the vulnerability of their network security. Out of the following options (i) to (iv), which one most appropriately defines Ms. Sen? All India 2017
Justify the reason for your chosen option:

  1. Hacker
  2. Cracker
  3. Operator
  4. Network Admin

Аnswer:
(ii) Cracker
Reason Crackers are generally responsible for breaking into networks, cracking passwords in websites and programs and generally causing havoc through the Internet.

Question 67:
Write any two differences between twisted pair and coaxial pair cable. All India (C)2014
Аnswer:

Two differences between twisted pair and coaxial pair cable are as follows :
important-questions-for-class-12-computer-science-c-communication-technologies-(348-2)

Question 68:
Give the full form of the following terms :

  1. XML
  2. FLOSS
  3. HTTP
  4. FTP Delhi 2011(c)

Аnswer:

  1. XML extensible Markup Language
  2. FLOSS Free Libre and Open Source Software
  3. HTTP HyperText Transfer Protocol
  4. FTP File Transfer Protocol

4 Marks Questions

Question 69:
Hi Standard Tech Training Ltd. is a Mumbai based organisation which is expanding its office set-up to Chennai. At Chennai office compound, they are planning to have 3 different blocks for Admin, Training and Accounts related activities. Each block has a number of computers, which are required to be connected in a network for communication, data and resource sharing.

As a network consultant, you have to suggest the best network related solutions for them for issues/problems raised by them in (i) to (iv), as per the distances between various blocks/locations and other given parameters.
important-questions-for-class-12-computer-science-c-communication-technologies-(336-1)

  1. Suggest the most appropriate block/location to house the SERVER in the CHENNAI office (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
  2. Suggest the best wired medium and draw the cable layout (Block to Block) to efficiently connect various blocks within the CHENNAI office compound.
  3. Suggest a device/software and its placement that would provide data security for the entire network of the CHENNAI office.
  4. Suggest a device and the protocol that shall be needed to provide wireless Internet access to all smartphone/laptop users in the CHENNAI office. All India 2017

Аnswer:

(i) Training Block is the most appropriate block/location to house the SERVER in the CHENNAI office to get the best and effective connectivity because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(349-1)

(iii) Suggested device is firewall. And it will be placed where all messages are entering or leaving the entire network of the CHENNAI office.
(iv) Device: WiFi card
Protocol: TCP/IP

Question 70:
Uplifting Skills Hub India is a knowledge and skill community which has an aim to uplift the standard of knowledge and skills in the society. It is planning to set-up its training centers in multiple towns and villages pan India with its head offices in the nearest cities. They have created a model of their network with a city, a town and 3 villages as follows. As a network consultant, you have to suggest the best network related solutions for their issues/problems raised in (i) to (iv) keeping in mind the distances between various locations and other given parameters.
important-questions-for-class-12-computer-science-c-communication-technologies-(336-2)
NOTE : In Villages, there are community centers, in which one room has been given as training center to this organisation to install computers.
The organisation has got financial support from the government and top IT companies.

  1. Suggest the most appropriate location of the SERVER in the B_HUB (out of the 4 locations), to get the best and effective connectivity. Justify your answer.
  2. Suggest the best wired medium and draw the cable layout (location to location) to efficiently connect various location within the B_HUB.
  3. Which hardware device will you suggest to connect all the computers within each location of B_HUB?
  4. Which service/protocol will be most helpful to conduct live interactions of Experts from Head Office and people at all locations of B_HUB? Delhi 2016

Аnswer:
(i) B_TOWN is the most appropriate location of the server inside the B_HUB because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(349-2)
Ethernet cable is the best wired medium to connect the various locations within the B HUB.
(iii) Switch
(iv) Telnet

Question 71:
Intelligent Hub India is a knowledge community aimed to uplift the standard of skills and knowledge in the society. It is planning to set-up its training centers in multiple towns and villages pan India with its head offices in the nearest cities.
They have created a model of their network with a city, a town and 3 villages as follows.
As a network consultant, you have to suggest the best network related solutions for their issues/problems raised in (i) to (iv), keeping in mind the distance between various locations and other given parameters.
important-questions-for-class-12-computer-science-c-communication-technologies-(337-1)
NOTE In Villages, there are community centers, in which one room has been given as training center to this organisation to install computers. The organisation has got financial support from the government and top IT companies.

  1. Suggest the most appropriate location of the SERVER in the YHUB (out of the 4 locations), to get the best and effective connectivity. Justify your answer.
  2. Suggest the best wired medium and draw the cable layout (location to location) to efficiently connect various locations within the YHUB.
  3. Which hardware device will you suggest to connect all the computers within each location of YHUB?
  4. Which service/protocol will be most helpful to conduct live interactions of Experts from Head Office and people at YHUB locations? All India 2016

Аnswer:

(i) YTOWN is the most appropriate location of the server inside the YHUB because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(349-3)
Ethernet cable is the best wired medium to connect the various locations within the YHUB.
(iii) Switch
(iv) Telnet

Question 72:
Perfect Edu Services Ltd. is an educational organisation. It is planning to set-up its India campus at Chennai-with its head office at Delhi. The chennai campus has 4 main buildings-ADMIN, ENGINEERING, BUSINESS and MEDIA.
You as a network expert have to suggest the best network related solutions for their problems raised in
(i) to (iv), keeping in mind the distance between the buildings and other given parameters.
important-questions-for-class-12-computer-science-c-communication-technologies-(337-2)

  1. Suggest the most appropriate location of the server inside the CHENNAI campus (oof the 4 buildings), to get the best connectivity for maximum number of computers. Justify your answer.
  2. Suggest and draw the cable layout to efficiently connect various buildings within the CHENNAI campus for connecting the computers.
  3. Which hardware device will you suggest to be procured by the company to be installed to protect and control the Internet uses within the campus?
  4. Which of the following will you suggest to establish the online face-to-face communication between the people in the Admin Office of CHENNAI campus and DELHI Head Office?
    (a) Cable TV
    (b) E-mail
    (c) Video Conferencing
    (d) Text Chat Delhi 2018

Аnswer:

(i) ADMIN is the most appropriate location of the server inside the CHENNAI campus because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(349-4)
(iii) Firewall
(iv) (c) Video Conferencing

Question 73:
Xcelencia Edu Services Ltd. is an educational organisation. It is planning to set-up its India campus at Hyderabad with its head office at Delhi. The Hyderabad campus has 4 main buildings -ADMIN, SCIENCE, BUSINESS and ARTS. You as a network expert have to suggest the best network related solutions for their problems raised in (i) to (iv), keeping in mind the distances between the buildings and other given parameters.
important-questions-for-class-12-computer-science-c-communication-technologies-(338-1)

  1. Suggest the most appropriate location of the server inside the HYDERABAD campus (out of the 4 buildings), to get the best connectivity for maximum number of computers. Justify your answer.
  2. Suggest and draw the cable layout to efficiently connect various buildings within the HYDERABAD campus for connecting the computers.
  3. Which hardware device will you suggest to be procured by the company to be installed to protect and control the Internet uses within the campus?
  4. Which of the following will you suggest to establish the online face-to-face communication between the people in the Admin Office of HYDERABAD campus and DELHI Head Office?
    (a) E-mail
    (b) Text Chat
    (c) Video Conferencing
    (d) Cable TVAII India 2015

Аnswer:

(i) ADMIN is the most appropriate location of the server inside the HYDERABAD campus because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(349-5)
(iii) Firewall
(iv) Videoconferencing

Question 74:
Trine Tech Corporation (TTC) is a professional consultancy company. The company is planning to set-up their new offices in India with its hub at .Hyderabad. As a network adviser, you have to understand their requirement and suggest them the best available solutions. Their queries are mentioned as (i) to (iv) below.
Physical locations of the blocks of TTC
important-questions-for-class-12-computer-science-c-communication-technologies-(338-2)

  1. What will the most appropriate block, where TTC should plan to install their server?
  2. Draw a block to block cable layout to connect all the buildings in the most appropriate manner for efficient
    communication.
  3. What will be the best possible connectivity out of the following, you will suggest to connect the new set-up of offices in Bangalore with its London based office.
    • Satellite Link
    • Infrared
    • Ethernet
  4. Which of the following device will be suggested by you to connect each computer in each of the buildings?
    • Switch
    • Modem
    • Gateway Delhi 2014

Аnswer:

(i) TTC should install its server in Finance Block because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(349-6)
(iii) Satellite Link
(iv) Switch

Question 75:
Tech Up Corporation (TUC) is a professional consultancy company. The company is planning to set-up their new offices in India with its hub at Hyderabad. As a network adviser, you have to understand their requirement and suggest to them the best available solutions. Their queries are mentioned as (i) and (iv) below. You have to understand their requirement and suggest to them the best available solutions. Their queries are mentioned as (i) and (iv) below.
important-questions-for-class-12-computer-science-c-communication-technologies-(339-1)

  1. What will the most appropriate block, where TUC should plan to install their server?
  2. Draw a block to block cable layout to connect all the buildings in the most appropriate manner for efficient communication.
  3. What will be the best possible connectivity out of the following, you will suggest to connect the new set-up of offices in Bangalore with its London based office?
    • Infrared
    • Satellite Link
    • Ethernet Cable
  4. Which of the following devices will be suggested by you to connect each computer in each of the buildings?
    • Gateway
    • Sqwitch
    • Modem All India 2014

Аnswer:

(i) TUC should install its server in Human Resource Block as it is having maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(349-7)
(iii) Satellite Link
(iv)
Swatch

Question 76:
G.R.K International Inc. is planning to connect its Bengaluru Office Setup with its Head Office in Delhi. The Bengaluru Office G.R.K. International Inc. is spread across an area of approx. 1 square kilometres consisting of 3 blocks.
Human Resources, Academics and Administration. You as network expert have to suggest answers to the four queries (i) to (iv) raised by them.
important-questions-for-class-12-computer-science-c-communication-technologies-(339-2)
important-questions-for-class-12-computer-science-c-communication-technologies-(340-1)

  1. Suggest the most suitable block in the Bengaluru Office Setup, to host the server. Give a suitable reason with your suggestion.
  2. Suggest the cable layout among the various blocks within the Bengaluru Office Setup for connecting the blocks.
  3. Suggest a suitable networking device to be installed in each of the blocks essentially required for connecting computers inside the blocks with fast and efficient connectivity.
  4. Suggest the most suitable media to provide secure, fast and reliable data connectivity between Delhi Head Office and the Bengaluru Office Setup. Delhi 2013

Аnswer:
(i) Human Resources, because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(349-8)
(iii) Hub/Switch
(iv) Satellites

Question 77:
Expertia Professional Global (EPG) in an online corporate training provider company for IT related courses. The company is setting up their new campus in Mumbai. You as a network expert have to study the physical locations of various buildings and the number of computers to be installed. In the planning phase, provide the best possible answers for the queries (i) to
(iv) raised by them.
Physical Locations of the buildings of EPG
important-questions-for-class-12-computer-science-c-communication-technologies-(340-2)
important-questions-for-class-12-computer-science-c-communication-technologies-(340-3)

  1. Suggest the most appropriate building, where EPG should plan to install the server.
  2. Suggest the most appropriate building to building cable layout to connect all three buildings for efficient communication.
  3. Which type of network out of the following is formed by connection the computers of these three buildings?
    (a) LAN
    (b) MAN
    (c) WAN
  4. Which wireless channel out of the following should be opted by EPG to connect to students of all over the world?
    (a) Infrared
    (b) Microwave
    (c) Satellite Delhi 2013

Аnswer:

(i) EPG should install the server in the Faculty Studio Building because it has maximum
important-questions-for-class-12-computer-science-c-communication-technologies-(350-1)
(iii) LAN(Local Area Network)
(iv) Satellite

Question 78:
Granuda consultants are setting up a secured network for their office campus at Faridabad for their day-to-day office and Web based activities. They are planning to have connectivity between 3 buildings and the head office situated in Kolkata. Answer the questions (i) to (iv) after going through the building positions in the campus and other details, which are given below:
important-questions-for-class-12-computer-science-c-communication-technologies-(340-4)
important-questions-for-class-12-computer-science-c-communication-technologies-(341-1)

  1. Suggest the most suitable place (i.e. block) to house the server of this organisation. Also, give a reason to justify your suggested location.
  2. Suggest a cable layout of connections between the building inside the campus.
  3. Suggest the placement of the following devices with justification : ,
    (a) Switch (b) Repeater
  4. The organisation is planning to provide a high speed link with its head office situated in the Kolkata using a wired connection. Which of the following cable will be most suitable for this job?
  5. (a) Optical fibre (b) Coaxial cable (c) Ethernet cable All India 2012

Аnswer:
(i) The most suitable place to house the server
in building JAMUNA because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(350-2)
(iii) Switches are needed in every building as they help share bandwidth in every building.
Repeaters may be skipped as per above layout(because distance is less than 100 m) however if building RAVI and building JAMUNA are directly connected, we can place a repeater there as the distance between these two building is more than 100 m.
(iv) Coaxial cable

Question 79:
Workalot consultants are setting up a secured network for their office campus of Gurgaon for their day-to-day office and Web based activities. They are planning to have connectivity between 3 buildings and the head office situated in Mumbai. Answer the questions (i) to (iv) after going through the building positions in the campus and other details, which are given below:
important-questions-for-class-12-computer-science-c-communication-technologies-(341-2)
important-questions-for-class-12-computer-science-c-communication-technologies-(341-3)

  1. Suggest the most suitable place (i.e. building) to house the server of this organisation. Also, give a reason to justify your suggested location.
  2. Suggest a cable layout of connections between the buildings inside the campus.
  3. Suggest the placement of the following devices with justification :
    (a) Switch
    (b) Repeater
  4. The organisation is planning to provide a high speed link with its head office situated in the Mumbai using a wired connection. Which of the following cables will be most suitable for this job?
    (a) Optical fibre
    (b) Coaxial cable
    (c) Ethernet cable Delhi 2012

Аnswer:
(i) Building RED is the suitable place to house the server because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(350-3)
(iii) Switches are needed in every building as they help share bandwidth in every building.
Repeaters may be skipped as per above layout (because distance is less than 100 m) however if building Green and building Red are directly connected, we can place a repeater there as the distance between these two buildings is more than 100 m.
(iv) Coaxial cable

Question 80:
Quick Learn University is setting up its academic blocks at Prayag Nagar and planning to set-up a network. The university has three academic blocks and one human resource centre as shown in the diagram below:
important-questions-for-class-12-computer-science-c-communication-technologies-(341-4)
important-questions-for-class-12-computer-science-c-communication-technologies-(342-1)

  1. Suggest the most suitable place (i.e. block/centre) to install the server of this university with a suitable reason.
  2. Suggest an ideal layout for connecting these block/centre for a wired connectivity.
  3. Which device will you suggest to be placed/installed in each of these blocks/centre to efficiently connect all the computers with in these blocks/centre ?
  4. The university is planning to connect its admission office in the closest big city, which is more than 250 km from university, which type of network out of LAN, MAN or WAN will be formed? Justify your answer. Delhi 2011

Аnswer:
(i) The most suitable place to install the server is HR Centre because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(350-4)
(iii) Switch
(iv) Wan as it is another city.

Question 81:
Great Studies University is setting up its academic schools at Sunder Nagar and planning to set-up a network. The university has three academic schools and one administration centre as shown in the diagram:
important-questions-for-class-12-computer-science-c-communication-technologies-(342-2)
important-questions-for-class-12-computer-science-c-communication-technologies-(342-3)

  1. Suggest the most suitable place (i.e. school/centre) to install the server of this university with a suitable reason.
  2. Suggest an ideal layout for connecting these block/centre for a wired connectivity.
  3. Which device will you suggest to be placed/installed in each of these school/centre to efficiently connect all the computers with in these schools/centre.
  4. The university is planning to connect its admission office in the closest big city, which is more than 350 km from university. Which type of network out of LAN, MAN or WAN will be formed? Justify your answer. All India 2011

Аnswer:
(i) The most suitable place to install the server is Admin Centre because it has maximum number of computers.
important-questions-for-class-12-computer-science-c-communication-technologies-(350-5)
(iii) Switch device
(iv) WAN as it is outside the city.

Question 82:
Learn Together is an educational NGO. It is setting up its new campus at Jabalpur for its Web-based activities. The campus has four compounds as shown in the diagram below:
important-questions-for-class-12-computer-science-c-communication-technologies-(342-4)
important-questions-for-class-12-computer-science-c-communication-technologies-(343-1)

  1. Suggest a cable layout of connections between the compounds.
  2. Suggest the most suitable place (i.e. compound) to house the server for this NGO. Also, provide a suitable reason for your suggestion.
  3. Suggest the placement of the following devices with justification:
    (a) Repeater
    (b) Hub/Switch
  4. The NGO. is planning to connect its international office situated in Mumbai, which out of the following wired communication link, will you suggest for a very high speed connectivity?
    (a) Telephone analog line
    (b) Optical fibre
    (c) Ethernet cable. Delhi 2010

Аnswer:
important-questions-for-class-12-computer-science-c-communication-technologies-(350-6)
(ii) The most suitable place to house the server is Training Compound because it has maximum number of computers. •
(iii) (a) Repeater As per one layout (shown in (i), the repeater can be avoided as all distances between the compounds are <=100m.
(b) Hub/Switch Training building as it is hosting the server.
(iv) Optical fibre.

Question 83:
‘Vidya for All’ is an educational NGO. It is setting up its new campus at Jaipur for its Web-based activities. The campus has four buildings as shown in the diagram below:
important-questions-for-class-12-computer-science-c-communication-technologies-(343-2)
important-questions-for-class-12-computer-science-c-communication-technologies-(343-3)

  1. Suggest a cable layout of connections between the buildings.
  2. Suggest the most suitable place (i.e. building) to house the server for this NGO. Also, provide a suitable reason for your suggestion.
  3. Suggest the placement of the following devices with justification
    (a) Repeater (b) Hub/Switch.
  4. The NGO is planning to connect its international office situated in Delhi. Which out of the following wired communication links, will you suggest for a very high speed connectivity?
    (a) Telephone analog line
    (b) Optical fibre
    (c) Ethernet cable. All India 2010

Аnswer:
important-questions-for-class-12-computer-science-c-communication-technologies-(351-1)
(ii) The most suitable place to house the server for this NGO is Training Building because it has the maximum number of computers.
(iii) (a) Repeater As per one layout (shown in (i)), the repeater can be avoided as all distances between the compounds are <= 100 m.
(b) Hub Switch Training building as it is hosting the server
(iv) Optical fibre

Question 84:
Freshminds University of India is starting its first campus in Ana Nagar of South India with its centre admission office in Kolkata. The university has three major blocks comprising of Office block, Science block and Commerce block is in 5 km area campus. ”
As a network expert, you need to suggest the network plan as per (i) to (iv) to the authorities keeping in mind the distance and other given parameters
important-questions-for-class-12-computer-science-c-communication-technologies-(344-1)

  1. Suggest the authorities, the cable layout amongst various blocks inside university campus for connecting the blocks.
  2. Suggest the most suitable place (i.e. block) to house the server for this university with a suitable reason.
  3. Suggest an efficient device from the following to be installed in each of the block to connect all the computers.
    (a) Modem
    (b) Switch
    (c) Gateway
  4. Suggest the most suitable (very high speed) service to provide data connectivity between admission office located in Kolkata and the campus located in Ana Nagar from the following options:
    • Telephone line
    • Fixedline dial-up connection
    • Coaxial cable network
    • GSM
    • Leased line
    • Satellite connection. Delhi 2010,2009

Аnswer:
important-questions-for-class-12-computer-science-c-communication-technologies-(351-2)
(ii) The most suitable place to house the server is Science Block because it has maximum number of computers.
(iii) Switch is the device to be installed in each of the block to connect all the computers.
(iv) Satellite connection

Question 85:
Eduminds University of India is starting its campus in a small town Parampur of Central India with its centre admission office in Delhi. The university has three major buildings comprising of admin building academic buildings and research building in 5 km area campus. As a network expert, you need to suggest the network plan as per (i) to (iv) to the authorities keeping in mind the distances and other given parameters.
important-questions-for-class-12-computer-science-c-communication-technologies-(344-2)

  1. Suggest the authorities, the cable layout amongst various buildings inside the university campus for connecting the buildings.
  2. Suggest the most suitable place (i.e.building) to house the server of this organisation, with a suitable reason.
  3. Suggest an efficient device for the following to be installed in each of thebuilding to connect all the computers
    (a) Gateway
    (b) Modem 1
    (c) Switch
  4. Suggest the most suitable (very high speed) service to provide data connectivity between admission building located in Delhi and the campus located in Parampur form the following options:
    • Telephone line
    • Fixedline dial-up connection
    • Coaxial cable network
    • GSM
    • Leased line
    • Satellite connection. All India 2009

Аnswer:
important-questions-for-class-12-computer-science-c-communication-technologies-(351-3)
(ii) The most suitable place to house the server is Academic Building because it has maximum number of computers.
(iii) Switch is to be installed in each of building to connect all the computers.
(iv) Satellite connection

Question 86:
Institute of Distance Learning is located in Pune and is planning to go in for networking of four wings for better interaction. The details are shown below:
important-questions-for-class-12-computer-science-c-communication-technologies-(345-1)
important-questions-for-class-12-computer-science-c-communication-technologies-(345-2)

  1. Suggest the type of networking (LAN, MAN, WAN) for connecting Lib Wing to Admin Wing. Justify your answer.
  2. Suggest the most suitable place (i.e. wing) to house the server, with a suitable reason.
  3. Suggest and placement of the following devices with reasons
    (a) Repeater (b) Switch
  4. The Institu 3 is planning to link its study centre situated in Delhi. Suggest an economic way to connect it with reasonably high speed. Justify your answer. Delhi 2009C

Аnswer:

  1. Since, the distance between Lib Wing and Admin Wing is small, so type of networking is small, i.e. LAN.
  2. The most suitable place to house the server is student wing because it has maximum number of computers.
  3. (a) Repeater should be installed between Student wing and Admin wing as distance is more than 60 m.
    (b) Switch should be installed in each wing to connect several computers.
  4. Broadband connection as it is between economical and speedy.

Computer ScienceImportant Questions for Computer ScienceNCERT Solutions

The post Important Questions for Class 12 Computer Science (C++) – Communication Technologies appeared first on Learn CBSE.

Important Questions for Class 12 Computer Science (C++) – Boolean Algebra

$
0
0

Important Questions for Class 12 Computer Science (C++) – Boolean Algebra

Previous Years Examination Questions [TOPIC 1]
1 Mark Questions

Question 1:
Derive a Canonical POS expression for a Boolean function G, represented by the following truth table: All India 2017
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-1
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A1

Question 2:
Derive a canonical POS expression for a Boolean function F, represented by the following truth table: Delhi 2016
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-2
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A2

Question 3:
Derive a canonical SOP expression for a boolean function G, represented by the following truth table: All India 2016
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-3
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A3

Question 4:
Derive a canonical SOP expression for boolean function F, represented by the following truth table: Delhi 2015
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-4
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A4

Question 5:
Derive a canonical POS expression for a boolean function F, represented by the following truth table: All India 2015
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-5
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A5

Question 6:
Convert the following Boolean expression into its equivalent canonical sum of products (SOP) form:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-6
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A6

Question 7:
Write the Sum of Product form of the function F (P,Q,R) for the following truth table representation of F: Delhi 2014
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-7
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-8
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A7

Question 8:
Write the Product of Sum form of the function F(X, Y, Z) for the following truth table representation of F: All India 2014
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-9
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A8
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A9

Question 9:
Write the Product of Sum form of the function G(U, V, W) for the following truth table representation of G: Delhi 2013
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-10
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A10

Question 10:
Write the Product of Sum form of the function G(U,V,W) for the following truth table representation of G: Delhi 2013C
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-11
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A11

Question 11:
Write the Sum of Product form of the function F (A, B, C) for the following truth table representation of F: All India 2013
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-12
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A12

Question 12:
Write the POS form of boolean function G, which is represented in a truth table as follows: Delhi 2012
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-13
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A13

Question 13:
Write the SOP form of boolean function F, which is represented in a truth table as follows: All India 2012
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-14
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A14

Question 14:
Write the POS form of a boolean function F, which is represented in a truth table as follows: Delhi 2011
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-15
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A15

Question 15:
Write the SOP form of a boolean function F, which is represented in a truth table as follows: All India 2011
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-16
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A16
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A17

Question 16:
Write the SOP form of a boolean function F, which is represented in a truth table as follows: Delhi (c) 2011
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-17
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A18

Question 17:
Write the POS form of boolean function H, which is represented in a truth table as follows: Delhi 2010
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-18
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A19

Question 18:
Write the SOP form of boolean function G, which is represented in a truth table as follows: All India 2010
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-19
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A20

Question 19:
Write the POS form of a boolean function H, which is represented in a truth table as follows: Delhi 2009
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-20
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A21

Question 20:
Write the POS form of a boolean function G, which is represented in a truth table as follows: All India 2009
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-21
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A22

2 Marks Questions

Question 21:
State DeMorgan’s Laws of Boolean Algebra and verify them using truth table. All India 2017
Or
State DeMorgan’s laws. Verify one of the DeMorgan’s laws using a truth table Delhi 2013C
Or
State and prove DeMorgan’s laws in boolean algebra. Delhi 2011C,2009C

Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A23
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A24

Question 22:
Draw the Logic Circuit of the following Boolean Expression using only NOR Gates: All india 2017
(A+B). (C+D)
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A25

Question 23:
Verify the following using boolean laws:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-22
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A26

Question 24:
Write the boolean expression for the result of the logic circuit as shown below:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-23
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A27

Question 25:
Verify the following using Boolean Laws:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-24
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A28

Question 26:
Write the boolean expression for the result of the Logic Circuit as shown below:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-25
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A29

Question 27:
Verify the following using boolean laws:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-26
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A30

Question 28:
Draw the logic circuit for the following boolean expression:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-27
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A31

Question 29:
Verify the following using boolean laws.
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-28
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A32

Question 30:
Draw the logic circuit for the following boolean expression:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-29
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A33

Question 31:
State distributive law and verify it using truth table. All India 2014C
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A34

Question 32:
Name the law shown below and verify it using a truth table.
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-30
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A35

Question 33:
Obtain the boolean expression for the logic circuit shown below: Delhi 2014
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-31
Answer:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-A36

Question 34:
Name the law shown below and verify it using a truth table.
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-32
Answer:

——————————————–34——————————————

Question 35:
Obtain the boolean expression for the logic circuit shown below: All India 2014
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-33
Answer:

——————————————–35——————————————

Question 36:
Verify the following using boolean laws
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-34
Answer:

——————————————–36——————————————

Question 37:
Verify the following using boolean laws
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-35
Answer:

——————————————–37——————————————

Question 38:
Obtain the boolean expression for the logic circuit shown below:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-36
Answer:

——————————————–38——————————————

Question 39:
Draw a logic circuit for the following boolean expression.
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-37
Answer:

——————————————–39——————————————

Question 40:
Obtain the boolean expression for the logic circuit shown below:.
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-38
Answer:

——————————————–40——————————————

Question 41:
Verify the following boolean expression using truth table:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-39
Answer:

——————————————–41——————————————

Question 42:
Write the equivalent boolean expression for the following logic circuit:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-40
Answer:

——————————————–42——————————————

Question 43:
Verify the following boolean expression using truth table:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-41
Answer:

——————————————–43——————————————

Question 44:
Write the equivalent boolean expression for the following logic circuit:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-42
Answer:

——————————————–44——————————————

Question 45:
Verify the following boolean expression using truth table:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-43
Answer:

——————————————–45——————————————
——————————————–45-1——————————————

Question 46:
Write the equivalent boolean expression for the following logic circuit:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-44
Answer:

——————————————–46——————————————

Question 47:
Verify the following boolean expression using truth table:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-45
Answer:

——————————————–47——————————————

Question 48:
Write the equivalent boolean expression for the following logic circuit:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-46
Answer:

——————————————–48——————————————

Question 49:
Write the equivalent boolean expression for the following logic circuit:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-47
Answer:

——————————————–49——————————————

Question 50:
Write the equivalent boolean expression for the following logic circuit:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-48
Answer:

——————————————–50——————————————

Question 51:
Verify the following algebraically:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-49
Answer:

——————————————–51——————————————

Question 52:
Verify the following algebraically:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-50
Answer:

——————————————–52——————————————

Question 53:
Write the equivalent boolean expression for the following logic circuit:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-51
Answer:

——————————————–53——————————————

Question 54:
Write the equivalent boolean expression for the following logic circuit:.
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-52
Answer:

——————————————–54——————————————

Question 55:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-53
Answer:

——————————————–55——————————————

Question 56:
Write the equivalent boolean expression for the following logic circuit:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-54
Answer:

——————————————–56——————————————

Question 57:
Important Questions for Class 12 Computer Science (C++) - Boolean Algebra-55
Answer:

——————————————–57——————————————

Question 58:
State and verify absorption law in boolean algebra. All India 2009
Answer:
——————————————–58——————————————

Computer ScienceImportant Questions for Computer ScienceNCERT Solutions

The post Important Questions for Class 12 Computer Science (C++) – Boolean Algebra appeared first on Learn CBSE.

Uttar Pradesh NMMS Class 8 Answer Key, Result, Cut Off

$
0
0

Uttar Pradesh NMMS 2017 – 2018 for Class 8 – Answer Key, Result, Cut Off

Uttar Pradesh NMMS 2017 – 2018

Uttar Pradesh National-Means-cum-Merit Scholarship (NMMS) Examination 2017-18 for the class 8 was held on 05 Nov 2017. Uttar Pradesh NMMS 2018 application form, admit card, exam date, result and other information are given below.

Uttar Pradesh NMMS 2017 Schedule

Event Dates
Last date of Application form 26 Sep 2017
Exam Date 05 Nov 2017 – Stage I

Uttar Pradesh NMMS 2017 Answer Key

Uttar Pradesh NMMS 2017 – 2018 Answer Key is available here.

Click here for answer key.

Uttar Pradesh NMMS 2017 Application Form

Uttar Pradesh NMMS 2017 Application Forms can be downloaded from the official website of Uttar Pradesh Basic Education Board (www.upbasiceducationboard.in).

Uttar Pradesh NMMS 2017 Eligibility to appear in the examination

  • Any regular student of class 8 in academic year 2016-17 can appear provided he/she has secured 55% or more marks in aggregate in class VII relaxable by 5% for SC/ST.
  • The student should be studying in class 8th of Govt. schools.
  • The parental income should be less than Rs. 1,50,000/- per year (Certificate issued by Tehsildar/Mamlatdar).

Uttar Pradesh NMMS 2017 Admit Card

Admit card will be sent to the chief superintendent of the examination centre after allotting the roll numbers. Candidate can collect the admit card from the centre superintendent of the examination centre at least one week before the examination.

The post Uttar Pradesh NMMS Class 8 Answer Key, Result, Cut Off appeared first on Learn CBSE.

Python Programming Fundamentals for Class 11 and 12 – Basics Of Python

$
0
0

Python Programming Fundamentals for Class 11 and 12 – Basics Of Python

The previous chapter has given a brief introduction about Python’s user interface. This chapter will scratch the surface of Python programming and expose the basic elements which a programmer needs to know beforehand.

Variable, identifier and literal
A variable is a storage location that has an associated symbolic name (called “identifier”), which contains some value (can be literal or other data) that can change. An identifier is a name used to identify a variable, function, class, module or other object. Literal is a notation for constant values of some built-in type. Literal can be string, plain integer, long integer, floating point number, imaginary number. For e.g., in the expressions

var1=5
 var2='Tom'

varl and var2 are identifiers, while 5 and ‘ Tom’ are integer and string literals, respectively.
Consider a scenario where a variable is referenced by the identifier a and the variable contains a list. If the same variable is referenced by the identifier b as well, and if an element in the list is changed, the change will be reflected in both identifiers of same variable.

>>> a=[1,2,3]
 >>> b=a
 >>> b
 [1, 2, 3]
 >>> a[1]=10
 >>> a
 [1, 10, 3]
 >>> b
 [1, 10,3]

Now, the above scenario can be modified a bit, where a and b are two different variables.

>>> a=[1, 2, 3]
 >>> b=a[:] # Copying data from a to b.
 >>> b [1, 2, 3]
 >>> a[1]=10
 >>> a
 [1, 10, 3]
 >>> b
 [1, 2, 3]

There are some rules that need to be followed for valid identifier naming:

  • The first character of the identifier must be a letter of the alphabet (uppercase or lowercase) or an underscore
  • The rest of the identifier name can consist of letters (uppercase or lowercase character), underscores (‘_’) or digits (0-9).
  • Identifier names are case-sensitive. For example, myname and myName are not the same.
  • Identifiers can be of unlimited length.

Token
A token is a string of one or more characters that is significant as a group. Consider an expression:

sum=6+2

The tokens in the above expression are given in table 2-1:
Table 2-1: Tokens

Token Token type
sum Identifier
= Assignment operator
6 Integer literal
+ Addition operator
2 Integer literal

The process of converting a sequence of characters into a sequence of tokens is called “lexical analysis”. A program or function that performs lexical analysis is called a lexical analyzer, lexer, or tokenizer. A lexer is generally combined with a parser (beyond the scope of this book), which together analyze the syntax of computer language. Python supports the following categories of tokens: NEWLINE, INDENT, DEDENT, identifiers, keywords, literals, operators, and delimiters.

Keywords
The following identifiers (as shown as output in the following code) are used as reserved words (or “keywords”) of the language, and cannot be used as ordinary identifiers.

>>> import keyword
 >>> for kwd in keyword.kwlist:
 ... print kwd
 ...
 and
 as
 assert
 break
 class
 continue
 def
 del
 elif
 else
 except
 exec
 finally
 for
 from
 global
 if
 import
 in
 is
 lambda
 not
 or
 pass
 print
 raise
 return
 try
 while
 with
 yield

One can also check if an identifier is keyword or not using iskeyword () function.

>>> import keyword
 >>> keyword.iskeyword('hi')
 False
 >>> keyword.iskeyword('print')
 True

Operators and operands
An operator is a symbol (such as +, x, etc.) that represents an operation. An operation is an action or procedure which produces a new value from one or more input values^ called operands. There are two types of operators: unary and binary. Unary operator operates only on one operand, such as negation. On the other hand, binary operator operates on two operands, which includes addition, subtraction, multiplication, division, exponentiation operators etc. Consider an expression 3 + 8, here 3 and 8 are called operands, while V is called operator. The operators can also be categorized into:

  • Arithmetic operators.
  • Comparison (or Relational) operators.
  • Assignment operators.
  • Logical operators.
  • Bitwise operators.
  • Membership operators.
  • Identity operators.

Arithematics operators
Table 2-2 enlists the arithematic operators with a short note on the operators.
Table 2-2: Arithematic operators

Operator Description
+ Addition operator- Add operands on either side of the operator.
Subtraction operator – Subtract right hand operand from left hand operand.
* Multiplication operator – Multiply operands on either side of the operator.
/ Division operator – Divide left hand operand by right hand operand.
% Modulus operator – Divide left hand operand by right hand operand and return remainder.
* * Exponent operator – Perform exponential (power) calculation on operands.
// Floor Division operator – The division of operands where the result is the quotient in which the digits after the decimal point are removed.

The following example illustrates the use of the above discussed operators.

>>> a=20
 >>> b=45.0
 >>> a+b
 65.0
 >>> a-b
 -25.0
 >>> a*b
 900.0
 >>> b/a
 2.25
 >>> b%a
 5.0
 >>> a**b
 3.5184372088832e+58
 >>> b//a
 2.0

Relational operators
A relational operator is an operator that tests some kind of relation between two operands. Table 2-3 enlist the relational operators with description.
Table 2-3: Relational operators

Operator Description
== Check if the values of two operands are equal.
!= Check if the values of two operands are not equal.
<> Check if the value of two operands are not equal (same as != operator).
> Check if the value of left operand is greater than the value of right operand.
< Check if the value of left operand is less than the value of right operand.
>= Check if the value of left operand is greater than or equal to the value of right operand.
<= Check if the value of left operand is less than or equal to the value of right operand.

The following example illustrates the use of the above discussed operators.

>>> a, b=20, 40
 >>> a==b
 False
 >>> a!=b
 True
 >>> a<>b
 True
 >>> a>b
 False
 >>> a>> a>=b
 False
 >>> a<=b 
True

Assignment operators
Assignment operator is an operator which is used to bind or rebind names to values. Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement. An augmented assignment expression like x+=l can be rewritten as x=x+1. Table 2-4 enlist the assignment operators with description.
Table 2-4: Assignment operators

Operator Description
= Assignment operator- Assigns values from right side operand to left side operand.
 += Augmented assignment operator- It adds right side operand to the left side operand and
assign the result to left side operand.
 -= Augmented assignment operator- It subtracts right side operand from the left side operand
and assign the result to left side operand.
*= Augmented assignment operator- It multiplies right side operand with the left side operand
and assign the result to left side operand.
/= Augmented assignment operator- It divides left side operand with the right side operand
and assign the result to left side operand.
%= Augmented assignment operator- It takes modulus using two operands and assign the
result to left side operand.
**= Augmented assignment operator- Performs exponential (power) calculation on operands
and assigns value to the left side operand.
//= Augmented assignment operator- Performs floor division on operators and assigns value to
the left side operand.

The following example illustrates the use of the above discussed operators.

>>> a,b=20,40
 >>> c=a+b
 >>> c
 60
 >>> a,b=2.0,4.5
 >>> c=a+b
 >>> C
 6.5
 >>> c+=a
 >>> c
 8.5
 >>> c-=a
 >>> c
 6.5
 >>> c*=a
 >>> c
 13.0
 >>> c/=a
 >>> c
 6.5
 >>> c%=a
 >>> c
 0.5
 >>> c**=a
 >>> c
 0.25
 >>> c//=a
 >>> c .
 0.0

Bitwise operators
A bitwise operator operates on one or more bit patterns or binary numerals at the level of their individual bits. Table 2-5 enlist the bitwise operators with description.
Table 2-5: Bitwise operators

Operator Description
& Binary AND operator- Copies corresponding binary 1 to the result, if it exists in both operands.
I Binary OR operator- Copies corresponding binary 1 to the result, if it exists in either operand.
^ Binary XOR operator- Copies corresponding binary 1 to the result, if it is set in one operand, but not both.
 ~ Binary ones complement operator- It is unary and has the effect of flipping bits.
<< Binary left shift operator- The left side operand bits are moved to the left side by the number on right side operand.
>> Binary right shift operator- The left side operand bits are moved to the right side by the number on right side operand.

The following example illustrates the use of the above discussed operators.

>>> a,b=60,13
 >>> a&b
 12
 >>> a|b
 61
 >>> a^b
 49
 >>> ~a
 -61
 >>> a<<2 
240 
>>> a>>2
 15

In the above example, the binary representation of variables a and b are 00111100 and 00001101, respectively. The above binary operations example is tabulated in table 2-6.
Table 2-6: Bitwsie operation

Bitwise operation Binary representation Decimal representation
a&b 00001100 12
a | b 00111101 61
a^b 00110001 49
~a 11000011 -61
a<<2 11110000 240
a>>2 00001111 15

Logical operators
Logical operators compare boolean expressions and return a boolean result. Table 2-6 enlist the logical operators with description.
Table 2-7: Logical operators

Operator Description
and Logical AND operator- If both the operands are true (or non-zero), then condition becomes true.
or Logical OR operator- If any of the two operands is true (or non-zero), then condition becomes true.
not Logical NOT operator- The result is reverse of the logical state of its operand. If the operand is true (or non-zero), then condition becomes false.

The following example illustrates the use of the above discussed operators.

> 5>2 and 4<8 
True 
>>> 5>2 or 4>8
True
>>> not(5>2)
False

Membership operators
Membership operator is an operator which test for membership in a sequence, such as string, list, tuple etc. Table 2-7 enlists the membership operators.
Table 2-8: Membership operators

Operator Description
in Evaluate to true, if it find a variable in the specified sequence; otherwise false.
not in Evaluate to true, if it does not find a variable in the specified sequence; otherwise false.

The following example illustrates the use of the above discussed operators.

>>> 5 in [0,5,10,15]
 True
 >>> 6 in [0,5,10,15]
 False
 >>> 5 not in [0,5,10,15]
 False
 >>> 6 not in [0,5,10,15]
 True

Identity operators
Identity operators compare the memory locations of two objects. Table 2-8 provides a list of identity operators including a small explanation.
Table 2-9: Identity operators

Operator Description
is Evaluates to true, if the operands on either side of the operator point to the same object, and false otherwise.
is not Evaluates to false, if the operands on either side of the operator point to the same object, and true otherwise.

The following example illustrates the use of the above discussed operators.

>>> a=b=3.1
 >>> a is b
 True
 >>> id(a)
 30984528
 >>> id(b)
 30984528
 >>> c,d=3.1,3.1
 >>> c is d
 False
 >>> id(c)
 35058472
 >>> id (d)
 30984592
 >>> c is not d
 True
 >>> a is not b
 False

Operator precedence
Operator precedence determines how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. In the expression x=7+3*2, x is assigned 13, not 20, because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7.

Table 2-10 summarizes the operator’s precedence in Python, from lowest precedence to highest precedence (from top to bottom). Operators in the same box have the same precedence.
Table 2-10: Operator precedence

Operator
not, or, and
in, not in
is, is not
=, %, =/, =//, -=, +=, *=, **=
<>, ==, !=
<=, <, >, >=
^, /
&
 >>,<<
+/ –
*, /, %, //
~,+, –
**

Delimiters
Delimiter is a character that separates and organizes items of data. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values. Table 2-11 provides a list of tokens which serves as delimiters in Python.
Table 2-11: Delimiters

Delimiters
( ) [ ] @ { } ,  :  . ; =
+= -= *= /= //= %= &= I= ^= >>= <<= **=

The following example shows how the use of delimeters can affect the result.

>>> 5+6/2 # no delimiter used
 8.0
 >>> (5+6)12 # delimiter used
 5.5

Following are few points that a Python programmer should be aware of:

  • The period (.) can also occur in floating-point and imaginary literals.
  • The simple and augmented assignment operators, serve lexically as delimiters, but also perform operations.
  • ASCII characters “, #, and \ have special meaning as part of other tokens or are otherwise significant to the lexical analyzer.
  • Whitespace is not a token, but serve to delimit tokens.

Line structure
A Python program is divided into a number of logical lines.

Physical and logical lines
A physical line is a sequence of characters terminated by an end-of-line sequence. The end of a logical line is represented by the token NEWLINE. A logical line is ignored (i.e. no NEWLINE token is generated) that contains only spaces, tabs, or a comment. This is called “blank line”. The following code

>>> i=5
 >>> print(5)
 5

is same as:

>>> i=5; print (i)
 5

A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.

Explicit line joining
Two or more physical lines may be joined into logical lines using backslash characters (\), as shown in the following example:

>>>if 1900 < year < 2100 and 1 <= month <= 12 \
 ... and 1 <= day <= 31 and 0 <= hour < 24 \
 ... and 0 <= minute < 60 and 0 <= second < 60:
 . . . print year

A line ending in a backslash cannot carry a comment. Also, backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.

>>> str='This is a \
 ... string example'
 >>> str
 'This is a string example' .

Implicit line joining
Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. For example:

>>> month_names=['Januari','Februari','Maart',
 ... 'AprilMei','Juni',
 ... 'Juli','Augustus','September',
 ... 'Oktober','November','December'] # These are theDutch names for the months of the year

Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings; in that case they cannot carry comments.

>>> str="""This is
 ... a string
 ... example"""
 >>> str
 'This is \na string \nexample'
 >>> str='''This is
 ... a string
 ... example'''
 >>> str
 'This is \na string \nexample'

Comment
A comment starts with a hash character (#) that is not part of a string literal, and terminates at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Also, comments are not executed.

Indentation
Whitespace is important in Python. Actually, whitespace at the beginning of the line is important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements. This means that statements which go together must have the same indentation. Each such set of statements is a block. One thing should be remembered is Jhat wrong indentation can give rise to error (IndentationError exception).

>>> i=10
 >>> print "Value is ",i
 Value is 10
 >>> print "Value is ",i
 File "", line 1
 print "Value is ",i
 IndentationError: unexpected indent

The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens. One can observe that by inserting whitespace in the beginning gave rise to IndentationError exception.
The following example shows non-uniform indentation is not an error.

>>> var=100
 >>> if var!=100:
 ... print 'var does not have value 100'
 ... else:
 print 'var has value 100'
 var has value 100

Need for indentation
In C programming language, there are numerous ways to place the braces for grouping of statements. If a programmer is habitual of reading and writing code that uses one style, he or she will feel at least slightly uneasy when reading (or being required to write) another style. Many coding styles place begin/end brackets on a line by themselves. This makes programs considerably longer and wastes valuable screen space, making it harder to get a good overview of a program.

Guido van Rossum believes that using indentation for grouping is extremely elegant and contributes a lot to the clarity of the typical Python program. Since there are no begin/end brackets, there cannot be a disagreement between grouping perceived by the parser and the human reader. Also, Python is much less prone to coding-style conflicts.

Built-in types
This section describes the standard data types that are built into the interpreter. There are various built-in data types, for e.g., numeric, sequence, mapping, etc., but this book will cover few types. Schematic representation of various built-in types is shown in figure 2-1.
python-programming-fundamentals-for-class-11-and-12-basics-of-python-fig 2.1

Numeric types
There are three distinct numeric types: integer, floating point number, and complex number.

Integer
Integer can be sub-classified into three types:

Plain integer
Plain integer (or simply “integer”) represents integer number in the range -2147483648 through 2147483647. When the result of an operation would fall outside this range, the result is normally returned as a long integer.

>>> a=2147483647
 >>> type(a)
 <type 'int'>
 >>> a=a+1
 >>> type(a)
 <type 'long'>
 >>> a=-2147483648
 >>> type(a)
 <type 'int'>
 >>> a=a-1
 >>> type(a)
 <type 'long'>

The built-in function int(x=0) convert a number or string x to an integer, or return 0, if no arguments are given.

>>> a='57'
 >>> type(a)
 <type 'str'>
 >>> a=int(a)
 >>> a
 57
 >>> type(a)
 <type 'int'>
 >>> a=5.7
 >>> type(a)
 <type 'float'>
 >>> a=int(a)
 >>> a
 5
 >>> type(a)
 <type 'int'>
 >>> int ()
 0

Long integer
This represents integer numbers in virtually unlimited range, subject to available memory. The built-in function long (x=0) convert a string or number to a long integer. If the argument is a string, it must contain a possibly signed number. If no argument is given, OL is returned.

>>> a=5
 >>> type(a)
 <type 'int'>
 >>> a=long(a)
 >>> a
 5L
 >>> type(a)
 <type 'long'>
 >>> long()
 OL
 >>> long(5)
 5L
 >>> long(5.8)
 5L
 >>> long('5')
 5L
 >>> long('-5')
 -5L

Integer literals with an L or 1 suffix yield long integers (L is preferred because 11 looks too much like eleven).

>>> a=10L
 >>> type(a)
 <type 'long'>
 >>> a=101
 >>> type(a)
 <type 'long'>

The following expressions are interesting.

>>> import sys
 >>> a=sys.maxint
 >>> a
 2147483647
 >>> type(a)
 <type ' int'>
 >>> a=a+1
 >>> a
 2147483648L
 >>> type(a)
 <type 'long'>

Boolean
This represents the truth values False and True. The boolean type is a sub-type of plain integer, and boolean values behave like the values 0 and 1. The built-in function bool() convert a value to boolean, using the standard truth testing procedure.

>>> bool()
 False
 >>> a=5
 >>> bool(a)
 True
 >>> bool ( 0)
 False
 >>> bool('hi')
 True
 >>> bool(None)
 False
 >>> bool('')
 False
 >>> bool(False)
 False
 >>> bool("False")
 True
 >>> bool(5>3)
 True

Floating point number
This represents decimal point number. Python supports only double-precision floating point number (occupies 8 bytes of memory) and does not support single-precision floating point number (occupies 4 bytes of memory). The built-in function float () convert a string or a number to floating point number.

>>> a=57
 >>> type (a)
 <type 'int'>
 >>> a=float(a)
 >>> a
 57.0
 >>> type(a)
 <type 'float'>
 >>> a='65'
 >>> type(a)
 <type 'str'>
 >>> a=float(a)
 >>> a
 65.0
 >>> type(a)
 <type 'float’>
 >>> a=le308
 >>> a le+308
 >>> type(a)
 <type 'float’>
 >>> a=1e309
 >>> a
 inf
 >>> type (a)
 <type 'float'>

Complex number
This represents complex numbers having real and imaginary parts. The built-in function complex () is used to convert number or string to complex number.

>>> a=5.3
 >>> a=complex(a)
 >>> a (5.3+0j)
 >>> type(a) ctype 'complex'>
 >>> a=complex()
 >>> a
 0 j
 >>> type(a)
 <type 'complex'>

Appending j or J to a numeric literal yields a complex number.

>>> a=3.4j
 >>> a
 3.4 j
 >>> type(a)
 <type 'complex'>
 >>> a=3.5+4.9j
 >>> type(a)
 <type 'complex'>
 >>> a=3.5+4.9J
 >>> type(a)
 <type 'complex'>

The real and imaginary parts of a complex number z can be retrieved through the attributes z . real and z . imag.

a=3.5+4.9J
 >>> a.real
 3.5
 >>> a.imag
 4.9

Sequence Types
These represent finite ordered sets, usually indexed by non-negative numbers. When the length of a sequence is n, the index set contain the numbers 0, 1, . . ., n-1. Item i of sequence a is selected by a [ i ]. There are seven sequence types: string, Unicode string, list, tuple, bytearray, buffer, and xrange objects.
Sequence can be mutable or immutable. Immutable sequence is a sequence that cannot be changed after it is created. If immutable sequence object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change. Mutable sequence is a sequence that can be changed after it is created. There are two intrinsic mutable sequence types: list and byte array.

Iterable is an object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like diet and file etc. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map (), …). When an iterable object is passed as an argument to the built-in function iter (), it returns an iterator for the object. An iterator is an object representing a stream of data; repeated calls to the iterator’s next () method return successive items in the stream. When no more data are available, Stoplteration exception is raised instead.
Some of the sequence types are discussed below:

String
It is a sequence type such that its value can be characters, symbols, or numbers. Please note that string is immutable.

>>> a='Python' : 2.7'
 >>> type(a)
 <type 'str'>
 >>> a[2] = 'S '
 Traceback (most recent call last):
 File "", line 1, in
 TypeError: 'str' object does not support item assignment

The built-in function str (object=’ ‘ ) return a string containing a nicely printable representation of an object. For strings, this returns the string itself. If no argument is given, an empty string is returned.

>>> a=57.3
 >>> type(a)
 <type 'float'>
 >>> a=str(a)
 >>> a
 '57.3'
 >>> type(a)
 <type 'str'>

Tuple
Tuple is comma-separated sequence of arbitrary Python objects enclosed in parenthesis (round brackets). Please note that tuple is immutable. Tuple is discussed in detail in chapter 4.

>>> a= (1,2,3,4)
 >>> type(a)
 <type 'tuple’>
 'a', 'b', 'c')

List
List is comma-separated sequence of arbitrary Python objects enclosed in square brackets. Please note that list is mutable. More information on list is provided in chapter 4.

>>> a=[1,2,3,4]
 >>> type(a)
 <type 'list' >

Set types
These represent unordered, finite set of unique objects. As such, it cannot be indexed by any subscript, however they can be iterated over. Common uses of set are fast membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. There are two set types:

Set
This represents a mutable set. It is created by the built-in function set(), and can be modified afterward by several methods, such as add(), remove () etc. More information on set is given in chapter 4.

>>> set1=set() # A new empty set
 >>> set1.add("cat") # Add a single member
 >>> set1.update(["dog","mouse"]) # Add several members
 >>> set1.remove("mouse") # Remove member
 >>> set1
 set(['dog', 'cat'])
 >>> set2=set(["dog","mouse"])
 >>> print set1&set2 # Intersection
 set(['dog'])
 >>> print setl|set2 # Union
 set(['mouse', 'dog', 'cat'])

The set ( [ iterable ] ) return a new set object, optionally with elements taken from iterable.

Frozenset
This represents an immutable set. It is created by built-in function frozenset (). As a frozenset is immutable, it can be used again as an element of another set, or as dictionary key.

>>> frozenset() frozenset([])
 >>> frozenset('aeiou')
 frozenset(['a', 'i', 'e', 'u', 'o'])
 >>> frozenset([0, 0, 0, 44, 0, 44, 18]) .
 frozenset([0, 18, 44])

The frozenset ( [iterable] ) return return a new frozenset object, optionally with elements taken from iterable.

Mapping Types
This represents a container object that support arbitrary key lookups. The notation a [k] select the value indexed by key k from the mapping a; this can be used in expressions and as the target of assignments or del statements. The built-in function len () returns the number of items in a mapping. Currently, there is a single mapping type:

Dictionary
A dictionary is a mutable collection of unordered values accessed by key rather than by index. In dictionary, arbitrary keys are mapped to values. More information is provided in chapter 4.

>>> dictl={"john":34,"mike":56}
 >>> diet1["michael"]=42
 >>> dictl
 {'mike': 56, 'john': 34, 'michael': 42}
 >>> dictl["mike"]
 56

None
This signifies the absence of a value in a situation, e.g., it is returned from a function that does not explicitly return anything. Its truth value is False.
Some other built-in types such as function, method, class, class instance, file, module etc. are discussed in later chapters.

Integer function
The following function operates on integer (plain and long).
int.bit_length()
Return the number of bits necessary to represent an integer (plain or long) in binary, excluding the sign and leading zeros.

>>>n=-3 7
 >>> bin(n) # bin() convert integer number to a binary string
 >>> n.bit_length()
 6
 >>> n=2**31
 >>> n
 2147483648L
 >>> bin(n)
 'Obi0000000000000000000000000000000'
 >>> n.bit_length()
 32

Float functions
Some of the functions for floating point number are discussed below.
float.as_integer_ratio()
Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator.

>>> (-0.25).as_integer_ratio()
 (-1, 4)

float.is_integer()
Return True if the float instance is finite with integral value, otherwise it return False.

>>> (-2.0).is_integer()
 True
 >>> (3.2) .is_integer()
 False

String
Python can manipulate string, which can be expressed in several ways. String literals can be enclosed in matching single quotes (.’) or double quotes (“); e.g. ‘hello’, “hello” etc. They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple- quoted strings), e.g. ‘ ‘ ‘hello’ ‘ ‘, “””hello”””. A string is enclosed in double quotes if the string contains a single quote (and no double quotes), else it is enclosed in single quotes.

>>> "doesnt"
 ’doesnt1
 >>> "doesn't"
 "doesn't"
 >>> '"Yes," he said.'
 '"Yes," he said.'

The above statements can also be written in some other interesting way using escape sequences.

>>> "doesn\'t" t
 "doesn't"
 >>> '\"Yes,\" he said.'
 '"Yes," he said.'

Escape sequences are character combinations that comprises of a backslash (\) followed by some character, that has special meaning, such as newline, backslash itself, or the quote character. They are called escape sequences because the backslash causes an escape from the normal way characters are interpreted by the compiler/interpreter. The print statement produces a more readable output for such input strings. Table 2-12 mentions some of the escape sequences.
Table 2-12: Escape sequence

Escape sequence Meaning
\n Newline.
\t Horizontal tab.
\v Vertical tab.
\\ Backslash (\).
\’ Single quote (‘).
\” Double quote (“).

String literal may optionally be prefixed with a letter r or R , such string is called raw string, and there is no escaping of character by backslash.

>>> str='This is \n a string'
 >>> print str
 This is a string
 >>> str=r'This is \n a string'
 >>> print str
 This is \n a string

Specifically, a raw string cannot end in a single backslash.

>>> str=r'\'
 File "", line 1
 str=r '\'
 SyntaxError: EOL while scanning string literal

Triple quotes are used to specify multi-line string. One can use single quotes and double quotes freely within the triple quotes.

>>> line="""This is
 ... a triple
 ... quotes example"""
 >>> line
 'This is\na triple\nquotes example'
 >>> print line *'
 This is a triple quotes example

Unicode strings are not discussed in this book, but just for the information that a prefix of ‘ u’ or ‘ U’ makes the string a Unicode string.
The string module contains a number of useful constants and functions for string based operations. Also, for string functions based on regular expressions, refer re module. Both string and re modules are discussed later in this chapter.

String operations
Some of the string operations supported by Python are discussed below.

Concatenation
Strings can be concatenated using + operator.

>>> word='Python'+' Program'
 >>> word 'Python Program'

Two string literals next to each other are automatically concatenated; this only works with two literals, not with arbitrary string expressions.

>>> 'Python' ' Program'
 'Python Program'
 >>> wordl='Python'
 >>> word2='Program'
 >>> wordl word2
 File "", line 1 wordl word2
 SyntaxError: invalid syntax

Repetition
Strings can be repeated with * operator.

>>> word='Help '
 >>> word*3
 'Help Help Help '
 >>> 3*word
 'Help Help Help '

Membership operation
As discussed previously, membership operators in and not in are used to test for membership in a sequence.

>>> word= ' Python '
 >>> 'th' in word
 True
 >>> 'T' not in word
 True

Slicing operation
String can be indexed, the first character of a string has sub-script (index) as 0. There is no separate character type; a character is simply a string of size one. A sub-string can be specified with the slice notation.

>>> word='Python'
 >>> word[2]
 ' t'
 >>> word [0:2]
 'Py'

String slicing can be in form of steps, the operation s [ i : j : k ] slices the string s from i to j with step k.

>>> word[1:6:2]
 ' yhn'

Slice indices have useful defaults, an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word[:2]
 'Py'
 >>> word[2:]
 'thon'

As mentioned earlier, string is immutable, however, creating a new string with the combined content is easy and efficient.

>>> word[0]='J'
 Traceback (most recent call last):
 File "", line 1, in
 TypeError: 'str' object does not support item assignment
 >>> 'J'+word[1:]
 'Jython'

If upper bound is greater than length of string, then it is replaced by the string size; an upper bound smaller than the lower bound returns an empty string.

>>> word[2:50]
 'thon'
 >>> word [4:1]
 ' '

Indices can be negative numbers, which indicates counting from the right hand side.

>>> word[-l]
 'n'
 >>> word[-2]
 ' o'
 >>> word[-3:]
 ' hon'
 >>>. word [ : -3 ]
 'Pyt'
 >>> word[-0] # -0 is same as 0
 'p.

Out of range negative slice indices are truncated, but single element (non-slice) index raises IndexError exception.

>>> word[-100:]
 'Python'
 >>> word[-100]
 Traceback (most recent call last):
 File "", line 1, in
 IndexError: string index out of range

String formatting
String objects has an interesting built-in operator called modulo operator (%). This is also known as the “string formatting” or “interpolation operator”. Given format%values (where format is a string object), the % conversion specifications in format are replaced with zero or more elements of values. The % character marks the start of the conversion specifier. If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (a dictionary). If dictionary is provided, then the mapping key is provided in parenthesis.

>>> '%s Python is a programming language.' % 'Python'
 'Python Python is a programming language.'
 >>> '%s Python is a programming language.' % ('Python')
 'Python Python is a programming language.'
 >>>
 >>> '%s has %d quote types.' % ('Python',2)
 'Python has 2 quote types.'
 >>> '%s has %03d quote types.' % ('Python',2)
 'Python has 002 quote types.'
 >>> '%(language)s has %(number)03d quote types.' % \
 ... {"language":"Python","number":2}
 'Python has 002 quote types.'

In the above example, 03 consists of two components:

  • 0 is a conversion flag i.e. the conversion will be zero padded for numeric values.
  • 3 is minimum field width (optional).

Table 2-13 shows some of the conversion types.
Table 2-13: Conversion types

Conversion Meaning
D Signed integer decimal.
I Signed integer decimal.
E Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
F Floating point decimal format.
F Floating point decimal format.
g Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
G Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
S String.

Precision (optional) is given as a dot (.) followed by the precision number. While using conversion type f, F, e, or E, the precision determines the number of digits after the decimal point, and it defaults to 6.

>>>"Today's stock price :%f" % 50
 "Today's stock price: 50.00000
 >>> "Today's stock price :%F" % 50
 "Today's stock price: 50.000000
 >>>
 >>> "Today's stock price :%f" % 50.4625
 "Today's stock price: 50.462500"
 >>> "Today's stock price :%F" % 50.4625
 "Today's stock price: 50.462520"
 >>>
 >>> "Today's stock price :%.2f" % 50.46251987624312359
 "Today's stock price: 50.46
 >>> "Today's stock price :%.2F" % 50.46251987624312359
 "Today's stock price: 50.46
 >>>
 >>> "Today's stock price: %e" % 50.46251987624312359
 "Today's stock price: 5.046252e+01"
 >>> "Today's stock price: %E" % 50.46251987624312359
 "Today's stock price: 50.046252E+01"
 >>>
 >>> "Today's stock price: %.3e" % 50.46251987624312359
 "Today's stock price: 5. 046e+01"
 >>> "Today's stock price: %.3E" % 50.46251987624312359
 "Today's stock price: 5. 046E+01"

While using conversion type g or G, the precision determines the number of significant digits before and after the decimal point, and it defaults to 6.

>>> "Today's stock price: %g" % 50.46251987624312359
 "Today's stock price: 50.4625"
 >>> "Today's stock price: %G" % 50.46251987624312359 -
 "Today's stock price: 50.4625"
 >>>
 >>> "Today's stock price: %g" % 0.0000005046251987624312359
 "Today's stock price: 5.04625e-07"
 >>> "Today's stock price: %G" % 0.0000005046251987624312359
 "Today's stock price: 5.04625E-07"

String constants
Some constants defined in string module are as follows:

string.ascii_lowercase
It returns string containing lowercase letters ‘ abcdefghi jklmnopqrstuvwxyz ‘.

>>> import string
 >>> string.ascii_lowercase
 'abcdefghijklmnopqrstuvwxyz'

string. ascii__uppercase
It return string containing uppercase letters ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ ‘.

>> string.ascii_uppercase 
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.ascii_letters
It returns string containing concatenation of the ascii_lowercase and ascii_uppercase constants.

>>> string.ascii_letters
 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.digits
It returns the string containing digits ‘ 0123456789 ‘.

>> string.digits 
' 0123456789'

string.hexdigits
It returns the string containing hexadecimal characters ‘ 0123 456 78 9abcdef ABCDEF ‘.

>>> string.hexdigits
 '0123456789abcdefABCDEF'

string.octdigits
It returns the string containing octal characters ‘01234567’.

>>> string.octdigits
 '01234567'

string.punctuation
It returns the string of ASCII characters which are considered punctuation characters.

>>> string. punctuation 
' ! "#$%&V ()* + ,-./: ;<=>?@ [\\] A_' { |

string.whitespace
It returns the string containing all characters that are considered whitespace like space, tab, vertical tab etc.

>>> string.whitespace
 '\t\n\x0b\x0c\r '

string.printable
It returns the string of characters which are considered printable. This is a combination of digits, letters, punctuation, and whitespace.

>>> string.printable
 '01234567 8 9abcdefghij klmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%& V()*+,-./:;<=>?©[\\]A_'{I\t\n\r\x0b\x0c’

String methods
Below are listed some of the string methods which supports both strings and Unicode objects. Alternatively, some of these string operations can also be accomplished using functions of string module.
str.isalnum()
Return True, if all characters in the string are alphanumeric, otherwise False is returned.

>>> str="this2009"
 >>> str.isalnum()
 True
 >>> str="this is string example....wow!!!"
 >>> str.isalnum()
 False

str.isalpha()
Return True, if all characters in the string are alphabetic, otherwise False is returned.

>>> str="this"
 >>> str.isalpha()
 True
 >>> str="this is string example .... wow!!!"
 >>> str.isalpha() ,
 False

striisdigit()
Return True, if all characters in the string are digits, otherwise False is returned.

>>> str="this2009
 >>> str.isdigit()
 False
 >>> str="2009"
 >>> str.isdigit()
 True

str.isspace()
Return True, if there are only whitespace characters in the string, otherwise False is returned.

>>> str=" "
 >>> str.isspace ()
 True
 >>> str="This is string example .... wow!!!"
 >>> str.isspace ()
 False

str.islower()
Return True, if all cased characters in the string are in lowercase and there is at least one cased character, False otherwise.

>>> str="THIS is string example....wow!!!"
 >>> str.islower()
 False
 >>> str="this is string example .... wow!!!"
 >>> str.islower()
 True
 >>> str="this2009"
 >>> str.islower()
 True
 >>> str="2009"
 >>> str.islower()
 False

str.lower()
Return a string with all the cased characters converted to lowercase.

>>> str="THIS IS STRING EXAMPLE .... WOW!!!"
 >>> str.lower()
 'this is string example....wow!!!'

The above can be imitated using string module’s function string. lower (s), where s is a string.

>>> import string
 >>> str="THIS IS STRING EXAMPLE .... WOW!!!" -
 >>> string.lower(str)
 'this is string example....wow!!!'

str.isupper ()
Return True, if all cased characters in the string are uppercase and there is at least one cased character, otherwise False is returned.

>>> str="THIS IS STRING EXAMPLE .... WOW!!!"
 >>> str.isupper()
 True
 >>> str="THIS is string example .... wow!!!"
 >>> str.isupper ()
 False

str.upper ()
Return a string with all the cased characters converted to uppercase. Note that str . upper () . isupper () might be False, if string contains uncased characters.

>>> str="this is string example .... wow!!!"
 >>> str.upper()
 'THIS IS STRING EXAMPLE....WOW!!!'
 >>> str.upper () .isupper()
 True
 >>> str="012340"
 >>> str.upper()
 ' 012340'
 >>> str.upper().isupper()
 False

The above can be imitated using string module’s function string. upper (s), where s is a string.

>>> str="this is string example .... wow!!!"
 >>> string.upper(str)
 'THIS IS STRING EXAMPLE....WOW!!!'
 >>> string.upper(str).isupper() t
 True .
 >>> str="012340"
 >>> string.upper(str)
 '012340'
 >>> string.upper(str).isupper()
 False

str.capitalize()
Return a string with its first character capitalized and the rest lower cased.

>>> str="this Is stRing example .... wow!!!" -
 >>> str.capitalize()
 'This is string example....wow!!!'

The above can be imitated using string module’s function string. capitalize (word), where word is a string.

>>> str="this Is stRing example....wow!!!"
 >>> string.capitalize(str)
 'This is string example....wow!!!'

str.istitle ()
Return True, if the string is title cased, otherwise False is returned.

>>> str="This Is String Example ... Wow!!!"
 >>> str.istitle ()
 True
 >>> str="This is string example .... wow!!!"
 >>> str.istitle()
 False

str.title ()
Return a title cased version of the string, where words start with an uppercase character and the remaining characters are lowercase. It will return unexpected result in cases where words have apostrophe etc.

>>> str="this is string example .... wow!!!"
 >>> str.title()
 'This Is String Example....Wow!!!'
 >>> str="this isn't a float example .... wow!!!"
 >>> str.title ()
 "This Isn'T A Float Example .... Wow!!!"

str.swapcase()
Return a copy of the string with reversed character case.

>>> str="This is string example .... WOW!!! "
 >>> str.swapcase()
 'tHIS IS STRING EXAMPLE ... .wow! !! '

The above can be imitated using string module’s function string. swapcase (s), where s is a string.

>>> str="This is string example .... WOW!!!"
 >>> string.swapcase(str)
 'tHIS IS STRING EXAMPLE....wow!!!' '

str.count(sub[,start[,end]])
Return the number of non-overlapping occurrences of sub-string sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

>>> str="this is string example .... wow!!!"
 >>> sub="i"
 >>> str.count(sub,4,40)
 2
 >>> sub="wow"
 >>> str.count(sub)
 1

The above can be imitated using string module’s function string. count (s, sub [, start [, end] ] ), where s is a string.

>>> str="this is string example .... wow!!!"
 >>> sub="i"
 >>> string.count(str,sub,4,40)
 2
 >>> sub="wow"
 >>> string.count(str,sub)
 1

str.find(sub[,start[,end]])
Return the lowest index in the string where sub-string sub is found, such that sub is contained in the slice s [ start: end]. Optional arguments start and end are interpreted as in slice notation. Return -1, if sub is not found.

>>> str1 = "this is string example .... wow! !!"
 >>> str2="exam"
 >>> str1.find(str2)
 15
 >>> str1.find(str2,10)
 15
 >>> strl.find(str2,40)
 -1

The above can be imitated using string module’s function string, find (s, sub [, start [, end] ] ), where s is a string.

>>> str1="this is string example .... wow!!!"
 >>> str2="exam"
 >>> string.find(str1,str2)
 15
 >>> string.find(strl,str2,10)
 15
 >>> string.find(strl,str2,40)
 -1

The find () method should be used only if there is a requirement to know the position of sub. To check if sub is a sub-string or not, use the in operator:

>>> 'Py' in 'Python'
 True

str.rfind(sub[,start[, end]])
Return the highest index in the string where sub-string sub is found, such that sub is contained within s [start: end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

>>> str1="this is really a string example....wow!!!"
 >>> str2="is"
 >>> str1.rfind(str2)
 5
 >>> str1.rfind(str2,0,10)
 5
 >>> strl.rfind(str2,10,20)
 -1

The above can be imitated using string module’s function string. rf ind (s, sub [, start [, end] ] ), where s is a string.

>>> str1 = "this is really a string example.... wow!!!"
 >>> str2="is"
 >>> string.rfind(str1,str2)
 5
 >>> string.rfind(str1,str2,0,10)
 5
 >>> string.rfind(str1,str2,10,0)
 -1

str.index(sub[,start[,end]])
Like find (), but raise ValueError when the sub-string is not found.

>>> str1="this is string example....wow!!!"
 >>> str2="exam"
 >>> str1.index(str2)
 15
 >>> str1.index(str2,10) .
 15
 >>> str1.index(str2,40)
 Traceback (most recent call last):
 File "<pyshell#38>", line 1, in str1.index(str2, 40)
 ValueError: substring not found

The above can be imitated using string module’s function string. index (s, sub [, start i [, end] ] ), where s is a string.

>>> strl = "this is string example .... wow!!!"
 >>> str2 = "exam"
 >>> string.index(strl,str2)
 15
 >>> string.index(strl,str2,10)
 15
 >>> string.index(strl,str2,40)
 Traceback (most recent call last):
 File "", line 1, in
 File "C:\Python27\lib\string.py", line 328, in index
 return s.index(*args)
 ValueError: substring not found

str.rindex(sub[,start[,end]])
Like rf ind (), but raises ValueError when the sub-string sub is not found.

>>> strl="this is string example....wow!!!"
 >>> str2="is"
 >>> strl.rindex(str2)
 5
 >>> str1.rindex(str2,10,20)
 Traceback (most recent call last):
 File "", line 1, in
 ValueError: substring not found

The above can be imitated using string module’s function string. rf ind (s, sub [, start [, end] ] ), where s is a string.

>>> strl = "this is string example .... wow!!!"
 >>> str2="is"
 >>> string.rindex(strl,str2)
 5
 >>> string.rindex(strl,str2,10,20)
 Traceback (most recent call last):
 File "", line 1, in
 File "C:\Python27\lib\string.py", line 337, in rindex return s.rindex(*args)
 ValueError: substring not found

str.startswith(prefix[,start[,end]])
Return True, if string start with the prefix, otherwise return False. The prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

>>> str="this is string example .... wow!!!" .
 >>> str.startswith(1 this 1)
 True
 >>> str.startswith('is',2)
 True
 >>> str.startswith('this',10,17)
 False
 >>> pfx=('the','where' ,'thi')
 >>> str.startswith(pfx)
 True

str.endswith(suffix[,start[,end]])
Return True, if the string ends with the specified suffix, otherwise return False. The suffix can also be a tuple of suffixes to look for. The test starts from the index mentioned by optional argument start. The comparison is stopped indicated by optional argument end.

>>> str="this is string example .... wow!!!"
 >>> suffix="wow!!!"
 >>> str.endswith(suffix)
 True
 >>> suf f ix= ( "tot! ! ! " , "wow !!.!")
 >>> str.endswith(suffix)
 True
 >>> str.endswith(suffix,20)
 True •
 >>> suffix="is"
 >>> str.endswith(suffix,2,4)
 True
 >>> str.endswith(suffix,2,6)
 False
 >>> str . endswith ( ( ' hey ' , ' bye w!.!!.'):)
 True

str.join(iterable)
Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string str providing this method.

>>> str="-"
 >>> seq=("a" , "b" , "c" ) s
 >>> str.join(seq) ,
 'a-b-c'
 »> seq= [ "a" , "b" , "c" ]
 >>> str.join(seq)
 'a-b-c'

The above can be imitated using string module’s function string, join (words [, sep] ), where words is a list or tuple of strings, while default value for sep is a single space character.

>>> str="-"
 >>> seq=("a","b","c") -
 >>> string.join(seq,str)
 'a-b-c'
 »> seq= [ "a" , "b" , "c" ]
 >>> string.join(seq,str)
 'a-b-c'

str.replace(old,new [,count])
Return a string with all occurrences of sub-string old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

>>> str="this is string example.... wow!! ! this is really string"
 >>> str.replace("is ","was")
 'thwas was string example.... wow!! ! thwas was really string'
 >>> str="this is string example....wow!!! this is really string"
 >>> str.replace("is","was",3)
 'thwas was string example....wow!!! thwas is really string'

The above can be imitated using string module’s function string, replace (s, old, new [, maxreplace ] ), where s is a string and maxreplace is same as count (discussed above).

>>> str="this is string example.... wow!! ! this is really string"
 >>> string.replace(str,"is","was")
 'thwas was string example.... wow!! ! thwas was really string'
 >>> str="this is string example.... wow!! ! this is really string"
 >>> string.replace(str,"is","was", 3)
 'thwas was string example.... wow!! ! thwas is really string'

str.center(width[,fillchar])
Return centered string of length width. Padding is done using optional argument f illchar (default is a space).

>>> str="this is string example .... wow!!!"
 >>> str.center(40,'a')
 'aaaathis is string example....wow!!!aaaa'
 >>> str="this is string example .... wow!!!"
 >>> str.center(40)
 ' this is string example....wow!!! '

The above can be imitated using string module’s function stping. center (s, width [, f illchar ] ), where s is a string.

>>> str="this is string example....wow!!!"
 >>> string.center(str,40,'a')
 'aaaathis is string example....wow!!!aaaa'
 >>> str="this is string example .... wow!!!"
 >>> string.center(str,40)
 ' this is string example....wow!!!'

str.ljust(width),fillchar])
Return the string left justified in a string of length width. Padding is done using the optional argument fillchar (default is a space). The original string is returned if width is less than or equal to
len(str).

>>> str="this is string example .... wow!!!"
 >>> str.1 just(50, 10 ' )
 'this is string example ... .wow! !!000000000000000000'
 >>> str="this is string example .... wow!!!"
 >>> str.1just(50)
 'this is string example....wow!!! '
 >>> str="this is string example .... wow!!!"
 >>> str.1just(10)
 'this is string example....wow!!!'

The above can be imitated using string module’s function string. 1 just (s, width [, f illchar ] ), where s is a string.

>>> str="this is string example....wow!!!"
 >>> string.1just(str,50, ’ 0 ' )
 'this is string example ....wow!!!000000000000000000'
 >>> str="this is string example....wow!!!"
 >>> string.1just(str,50)
 'this is string example....wow!!! '

str.rjust(width[,fillchar])
Return the right justified string of length width. Padding is done using the optional argument fillchar (default is a space). The original string is returned if width is less than or equal to len ( str).

>>> str="this is string example .... wow!!!"
 >>> str.rjust(50,'0')
 'OOOOOOOOOOOOOOOOOOthis is string example....wow!!!'
 >>> str="this is string example....wow!!!"
 >>> str.rjust (10, '0 ' )
 'this is string example....wow!!!'

The above can be imitated using string module’s function string.r just (s, width [, fillchar]), where s is a string.

>>> str="this is string example .... wow!!!"
 >>> string.rjust(str,50,' 0')
 '000000000000000000this is string example....wow!!!'
 >>> str="this is string example .... wow!!!"
 >>> string.rjust(str,10,'0')
 'this is string example....wow!!!'

str.zfill(width)
Return a string of length width, having leading zeros. The original string is returned, if width is less than or equal to len (str).

>>> str="this is string example .... wow!!!"
 >>> str.zfill ( 40)
 'OOOOOOOOthis is string example....wow!!!'
 >>> str . zf ill ( 45)
 'OOOOOOOOOOOOOthis is string example....wow!!!'

The above can be imitated using string module’s function string. zfill (s, width), where s is a string.

>>> str="this is string example....wow!!!"
 >>> string.zfill(str,40)
 'OOOOOOOOthis is string example....wow!!!'
 >>> string.zfill(str,45)
 'OOOOOOOOOOOOOthis is string example....wow!!!' str.strip([chars])

Return a string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str="OOOOOOOthis is string example... .wow! !!0000000"
 >>> str.strip ('0')
 'this is string example....wow!!!'

The above can be imitated using string module’s function string . strip ( s [, chars ] ), where s is a string.

>>> str="OOOOOOOthis is string example .... wow!!!0000000"
 >>> string.strip(str,'0')
 'this is string example....wow!!!'

str.lstrip([chars])
Return a string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" this is string example. . . .wow! ! ! "
 >>> str.lstrip()
 'this is string example....wow!!! '
 >>> str="88888888this is string example .... wow!!!8888888"
 >>> str.lstrip('8')
 'this is string example ....wow! !! 8888888'

The above can be imitated using string module’s function string. lstrip (s [, chars ]), where s is a string.

>>> str=" this is string example....wow!!! " .
 >>>string.lstrip(str)
 'this is string example....wow!!! '
 >>> str="88888888this is string example .... wow!!!8888888"
 >>> string.lstrip(str,'8')
 'this is string example ....wow! !! 8888888 '

str.rstrip([chars])
Return a string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" this is string example....wow!!! "
 >>> str.rstrip()
 ' this is string example....wow!!!'
 >>> str="88888888this is string example .... wow!!!8888888"
 >>> str.rstrip('8')
 '88888888this is string example .... wow!!! '

The above can be imitated using string module’s function string. rstrip (s [, chars ]), where s is a string.

>>> str=" this is string example....wow!!! "
 >>> string.rstrip(str)
 ' this is string example....wow!!!'
 >>> str="88888888this is string example .... wow!!!8888888"
 >>> string.rstrip(str,'8')
 '88888888this is string example....wow!!!'

str.partition(sep)
Split the string at the first occurrence of sep, and return a tuple containing the part before the separator, the separator itself, and the part after the separator.

>>> str=" this is string example .... wow!! ! "
 >>> str.partition('s')
 (' thi', 's', ' is string example .... wow!! ! ')

str.rpartition(sep)
Split the string at the last occurrence of sep, and return a tuple containing the part before the separator, the separator itself, and the part after the separator.

>>> str=" this is string example....wow!!! "
 >>> str.rpartition('s')
 (' this is ', 's', 'tring example.... wow!! ! ')

str.split([sep[,maxsplit]])
Return a list of the words from the string using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then all possible splits are made. If sep is not specified or None, any whitespace string is a separator.

>>> str="Linel-abcdef \nLine2-abc \nLine4-abcd"
 >>> str.split()
 ['Linel-abcdef', 'Line2-abc', 'Line4-abcd']
 >>> str.split(' ',1)
 ['Linel-abcdef', '\nLine2-abc \nLine4-abcd']

The above can be imitated using string module’s function string. split (s [, sep [, maxsplit ] ] ), where s is a string.

>>> str="Linel-abcdef \nLine2-abc \nLine4-abcd"
 >>> string.split(str)
 ['Linel-abcdef', 'Line2-abc', 'Line4-abcd']
 >>> string.split(str,' ',1)
 ['Linel-abcdef', '\nLine2-abc \nLine4-abcd']

str.rsplit([sep[,maxsplit]])
Return a list of the words from the string using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit () behaves like split () which is described in detail below.

>>> str=" this is string example....wow!!! "
 >>> str.rsplit()
 ['this', 'is', 'string', 'example .... wow!!!']
 >>> str.rsplit('s') '
 [' thi', ' i', ' ', 'tring example.... wow!! ! ']

The above can be imitated using string module’s function string. rsplit (s [, sep [, maxsplit] ] ), where s is a string.

>>> str=" this is string example .... wow!! !
 >>> string.rsplit(str)
 ['this', 'is', 'string', 'example .... wow!!!']
 >>> string.rsplit(str,'s')
 [' thi', ' i', ' ', 'tring example.... wow!! !

str.splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given.

>>> str="Linel-a b c d e f\nLine2- a b c\n\nLine4- abed"
 >>> str.splitlines()
 ['Linel-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
 >>> str.splitlines(0)
 ['Linel-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
 >>> str.splitlines(False)
 ['Linel-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d'] .
 >>> str.splitlines(1)
 ['Linel-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
 >>> str.splitlines(True)
 ['Linel-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']

str.translate(table[,deletechars])
Return a string having all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.
The maketransO function (discussed later in this section) from the string module is used to create a translation table. For string objects, set the table argument to None for translations that only delete characters.

>>> str='this is string example....wow!!!'
 >>> tab=string.maketrans('e','E')
 >>> str.translate(tab)
 'this is string ExamplE....wow!!!'
 >>> str.translate(tab,'ir')
 'ths s stng ExamplE....wow!!!'
 >>> str.translate(None,'ir')
 'ths s stng example....wow!!!'

The above can be imitated using string module’s function string. translate (s, table [, deletechars ] ), where s is a string.

>>> str='this is string example....wow!!!'
 >>> tab=string.maketrans('e','E')
 >>> string.translate(str,tab)
 'this is string ExamplE....wow!!!'
 >>> string.translate(str,tab,'ir')
 'ths s stng ExamplE....wow!!!'
 >>> string.translate(str,None,'ir')
 'ths s stng example....wow!!!'

The following functions are there in string module, but are not available as string methods.

string. capwords (s [, sep] )
Split the argument s into words using str. split (), then capitalize each word using str . capitalize (), and join the capitalized words using str . join (). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise, sep is used to split and join the words.

>>> str=" this is string example.... wow!!! >>> string.capwords(str)
 'This Is String Example.... Wow!!!'
 >>> string.capwords(str,' ')
 ' This Is String Example.... Wow!!! '
 >>> string.capwords(str,'s')
 ' this is sTring example.... wow!!! '

string.maketrans(from, to)
Return a translation table suitable for passing to translate (), that will map each character in from into the character at the same position in to, from and to must have the same length.

>>> str='this is string example....wow!!!'
 >>> tab=string.maketrans('t!' ,'T.')
 >>> string.translate(str,tab)
 'This is sTring example....wow...'
 >>> string.translate(str,tab,'ir')
 'Ths s sTng example....wow...'
 >>> string.transiate(str,None,'ir')
 'ths s stng example....wow!!!'

Regular expression module
Regular expression (also called RE, or regex, or regex pattern) is a specialized approach in Python, using which programmer can specify rules for the set of possible strings that needs to be matched; this set might contain english sentences, e-mail addresses, or anything. REs can also be used to modify a string or to split it apart in various ways.

Meta characters
Most letters and characters will simply match themselves. For example, the regular expression test will match the string test exactly. There are exceptions to this rule; some characters are special “meta characters”, and do not match themselves. Instead, they signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. Some of the meta characters are discussed below:
Table 2-14: Meta characters

Meta character Description Example
[] Used to match a set of characters. [time]
The regular expression would match any of the characters t, i, m or e.
[a-z]
The regular expression would match only lowercase characters.
^ A Used to complement a set of characters. [^time]
The regular expression would match any other characters than t, /’, m or e.
$ Used to match the end of string only. time$
The regular expression would match time in ontime, but will not match time in timetable.
* Used to specify that the previous character can be matched zero or more times. tim *e
The regular expression would match strings like timme, tie and so on.
+ Used to specify that the previous character can be matched one or more times. tim+e
The regular expression would match strings like timme, timmme, time and so on.
? Used to specify that the previous character can be matched either once or zero times. tim ?e
The regular expression would only match strings like time or tie.
{} The curly brackets accept two integer values. The first value specifies the minimum number of occurrences and second value specifies the maximum of occurrences. tim{1,4}e
The regular expression would match only strings time, timme, timmme or timmmme.

Regular expression module functions
Some of the methods of re module as discussed below:

re.compile(pattern)
The function compile a regular expression pattern into a regular expression object, which can be used for matching using its match () and search () methods, discussed below.

>>> import re
 >>> p=re.compile('tim*e')

re.match(pattern,string)
If zero or more characters at the beginning of string match the regular expression pattern, match () return a corresponding MatchObject instance. The function returns None, if the string does not match the pattern.

re.group()
The function return the string matched by the RE.

>>> m=re.match('tim*e','timme pass time')
 >>> m.group()
 'timme'

The above patch of code can also be written as:

>>> p=re.compile('tim*e')
 >>> m=p.match('timme pass timme')
 >>> m.group()
 'timme'

re.search(pattern,string)
The function scans through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. The function returns None, if no position in the string matches the pattern.

>>> m=re.search('tim*eno passtimmmeee1)
 >>> m.group()
 'timmme'

The above patch of code can also be written as:

>>> p=re.compile('tim*e')
 >>> m=p.search('no passtimmmeee')
 >>> m.group()
 'timmme'

re.start()
The function returns the starting position of the match.

re.end()
The function returns the end position of the match.

re.span()
The function returns a tuple containing the (start, end) indexes of the match.

>>> m=re.search('tim*e','no passtimmmeee')
 >>> m.start()
 7
 >>> m.end()
 13
 >>> m.span()
 (7, 13)

The above patch of code can also be written as:

>>> p=re.compile('tim*e')
 >>> m=p.search('no passtimmmeee')
 >>> m.start()
 7
 >>> m.end()
 13
 >>> m.span()
 (7, 13)

re.findall(pattern,string)
The function returns all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.

>>> m=re.findall('tim*e','timeee break no pass timmmeee')
 >>> m
 ['time', 'timmme']

The above patch of code can also be written as:

>>> p=re.compile('tim*e')
 >>> m=p.findall('timeee break no pass timmmeee')
 >>> m
 ['time', 'timmme']

re.finditer(pattern,string)
The function returns an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found.

>>> m=re.finditer('tim*etimeee break no pass timmmeee')
 >>> for match in m:
 ... print match.group()
 ... print match.span()
 time
 (0, 4)
 timmme
 (21, 27)

The above patch of code can also be written as:

>>> p=re.compile('tim*e')
 >>> m=p.finditer('timeee break no pass timmmeee')
 >>> for match in m:
 ... print match.group()
 ... print match.span()
 time (0, 4) timmme (21, 27)

Error
An error (or software bug) is a fault in a computer program that produces incorrect or unexpected result, or causes it to behave in unintended ways. Mostly bug arise from mistakes and errors made by people in either a program’s source code or its design. Usually, errors are classified as: syntax error, run-time error and logical error.

Syntax error
Syntax error refers to an error in the syntax of tokens and/or sequence of tokens that is intended to be written in a particular programming language. For compiled languages, syntax errors occur strictly at compile-time. A program will not compile until all syntax errors are corrected. For interpreted languages, however, not all syntax errors can be reliably detected until run-time.

>>> prin 'Hi'
 SyntaxError: invalid syntax
 >>> print "Hi'
 SyntaxError: EOL while scanning string literal

Run-time error
Run-time error is an error which can be detected during the execution of a program. The code appears to be correct (it has no syntax errors), but it will not execute. For example, if a programmer has written a correct code to open a file using open () function, and if the file is corrupted, the application cannot carry out the execution of open () function, and it stops running.

Logical error
Logical error (or semantic error) is a bug in a program that causes it to operate incorrectly, but not terminate abnormally. A logical error produces unintended or undesired output or other behavior, although it may not immediately be recognized. Logic error occurs both in compiled and interpreted languages. Unlike a program with a syntax error, a program with a logical error is a valid program in the language, though it does not behave as intended. The only clue to the existence of logic errors is the production of wrong solutions. For example, if a program calculates average of variables a and b, instead of writing the expression c= (a+b) /2, one can write c=a+b/2, which is a logical error.

>>> print a+b/2
 6.5
 >>> print (a+b)/2
 5.0

Python Programming FundamentalsComputer Science

The post Python Programming Fundamentals for Class 11 and 12 – Basics Of Python appeared first on Learn CBSE.

Uttarakhand Board Previous Year Question Papers

$
0
0

Uttarakhand Board Previous Year Question Papers for Class 10 & Class 12

Uttarakhand Board Previous Year Question Papers are given below for Class 10 and Class 12. UK board Question Paper are very helpful for Board exam preparation. UK Board Class XII Question Paper contains the marking scheme. Students must refer this page to score high marks in the upcoming exams. These question papers also help student to know the weak areas where he / she need work a bit harder.

Uttarakhand Board Previous Year Question Papers for Class 10

  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Accountancy
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Agriculture Science
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Business
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-English
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Hindi
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Hindustan Music
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Home Science
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Information Technology
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Mathematics
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Painting
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Punjabi
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Sanskrit
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Science
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Social Science
  • Uttarakhand-Board-Class-10-Previous-Year-Question-Paper-Urdu

Uttarakhand Board Previous Year Question Papers for Class 12

 

The post Uttarakhand Board Previous Year Question Papers appeared first on Learn CBSE.

Viewing all 9450 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>