Equipping the Modern Audio-Video Forensic Laboratory
Establishing or increasing the capability of a modern forensic audio-video laboratory draws on diverse disciplines including physics, electrical and electronic engineering, computer science, analog and digital theory, acoustics, digital signal analysis, digital imaging, and other related fields. These disciplines require a wide variety of electronic equipment to enable a forensic examiner to conduct reliable examinations. This paper is directed toward established laboratories that have limited audio-video capability but may be required to increase audio-video forensic support.
The following factors should be considered when establishing or increasing the capability of a modern audio/video forensic laboratory:
- Identifying potential employees
- Requiring a lengthy apprenticeship or equivalent experience of personnel in certain audio and video analyses fields
- Obtaining specialized training in such areas as digital signal analysis, recording theory, sound measurement, and video imaging
- Seeking support and guidance from other established laboratories
- Equipping the laboratory to play back and record in numerous analog and digital audio and video formats, and then providing the capability to improve voice intelligibility, compare voices, identify non-voice signals, authenticate recordings, enhance video images, and conduct other related analyses
- Procuring professional audio, video, enhancement, signal analysis, imaging, and other related equipment
- Identifying physical space for the laboratory
Audio-Video Examinations
Modern audio-video forensic laboratories are capable of analyzing analog or digital audio-video recordings to support criminal investigations, governmental intelligence, civil litigation, personnel and administrative matters, and other related issues. Some laboratories conduct a wide range of examinations on audio and video recordings, whereas others provide only duplication and a few other commonly requested analyses.
The eight most commonly conducted audio-video examinations are listed below, with the level of complexity from lowest to highest:
- Playback and duplication: The capability to play back recordings and provide high-quality, readily useable duplicates on standard formats. A fully equipped laboratory can work with most audio-video formats as well as specialized recordings (e.g., miniature law enforcement formats, 911 logging recordings, time-lapse video).
- Repair: The capability to repair torn or stretched tapes in standard audio-video analog and digital formats
- Audio enhancement: The capability to improve the voice intelligibility of recordings and to prepare enhanced copies of audio recordings and the audio information on video formats
- Voice identification: The capability to compare unknown recorded voices to known voice exemplars by identifying similar and dissimilar characteristics
- Video image duplication and enhancement: The capability to duplicate or improve video recordings
- Signal analysis: The capability to quantify, identify, and compare non-voice signals to determine origin and characteristics (i.e., telephone signaling, gunshot sounds)
- Authenticity: The capability to resolve the authenticity of audio-video recordings by determining originality, continuity, and integrity
- Digital data analysis and retrieval: The capability to extract and analyze digital audio-video recordings on commercial and proprietary recording devices
Figure 1 An Audio Workstation. Click to enlarge image. | Figure 2 A Magnetic Imaging Workstation. Click to enlarge image. |
Equipment and Costs
The equipment requirements for the eight audio-video forensic examinations are listed below. The phase numbers represent the most basic through the more sophisticated equipment requirements. The equipment costs reflect the prices at the time of publication and do not include personnel, training, and laboratory space.
Phase I: Basic Playback, Duplication, and Repair
Equipment: To allow high-quality playback and standard-format duplication of audio and video recordings, a laboratory should have the following equipment (Koenig 1987; Luther and Inglis 1999; Pohlmann 2000; Watkinson 2001; Watkinson 2000):
- Standard professional audiocassette decks with heavy-duty transports, a +10 percent or greater speed adjustment around each standard speed, a three-head design, Dolby-noise-reduction systems (B, C, and S), and real-time counters. Useful additions include set speeds of 15/16, 17/8, and 3¾ inches per second (ips), a continuous playback speed adjustment from at least 15/32 to 3¾ ips, and a headphone jack with its own volume control.
- Professional audio microcassette playback decks optimized for forensic applications, including continuous playback speeds of 0.7 to 2.4 centimeters per second, accurate metering, headphone volume controls, and professional-quality transport and electronic systems. Laboratory personnel normally do not make audio microcassette copies due to their inherently lower quality.
- Specialized audio playback systems including open-reel, minicassette, miniature on-the-body, NT digital, and other analog and digital devices with playback speed, track configuration, and other features that match the type of recordings expected to be received in the laboratory. Playback of selected recordings may require specialized devices and/or software available only to law enforcement agencies.
- Video recorders/playback units with formats ranging from analog U-Matic to the latest digital configurations, including VHS, VHS-C, SVHS, 8mm, Hi8, time-lapse, 6mm digital, and 8mm digital. High-quality or professional decks ensure the best possible playback and/or recording. In video playback, emphasis must be placed on the need for each head (field) to precisely follow its respective track. This may require procuring a number of video playback units of similar type in order to optimize the output results. A professional analog or digital format or a semiprofessional format (i.e., SVHS) unit should be available when interim copies are needed to minimize inherent losses in video duplication.
- A professional digital time-base corrector to remedy timing errors for the variety of video formats expected in the laboratory and to capture and hold separate fields and frames in its memory
- A video monitor to accurately display the full bandwidth and resolution of the highest quality format that will be played back in the laboratory. A hand-held screen degausser should also be available to ensure long-term color purity.
- Equipment racks of the correct width for the equipment, usually 19 inches. They should include professional-quality accessories including patch bays, spacer panels, and wire runs.
- Tables for workspace and equipment that are sturdy and at least 30 by 60 inches in size to allow ample work and equipment space. Avoid folding tables, except for temporary use.
- High-quality wiring, connectors, and adapters to manage all required equipment connections
- Tape repair supplies including appropriate splicing blocks, edit-tabs, razor blades, small knives to cut open housings, nonmagnetic-leader tape, tape-cleaning solvent, and miniature, non-magnetized tool kits
- Ferrofluid solution with particle sizes in the 0.2 to 1.5 micron range. Smaller particle sizes cannot consistently be removed from analog tapes.
- A ten-power loupe to check for a tape’s track configuration and azimuth alignment, after application of the ferrofluid solution
- Well-padded, heavy-duty, professional-quality headphones that completely seal around the ears. Cheaper consumer headphones can be sonically equal to the professional models, but they usually do not hold up to the heavy-duty use in the laboratory.
- Blank high-quality audio and video recordable media for preparing copies
- Accurate test recordings for calibration of playback and recording equipment
Phase II: Audio Enhancement
Equipment: To allow meaningful improvements in the voice intelligibility of recorded audio information, an audio-video laboratory should have the following equipment (Bellanger 2001; Davis 2002; Koenig 1988):
- A digital-adaptive enhancement processor that allows the operator to access and implement a number of different filter algorithms, including one- and two-channel adaptive, bandpass, comb, notch, spectral inverse, parametric, and graphic equalizer. The digital-adaptive enhancement processor should also permit the use of compression and limiting functions. The best configurations are hardware implementations with software control, because purely software programs may not implement complex filters in real-time, and the audio signals are susceptible to corruption when the computer is doing other operations simultaneously. All of these filtering systems should contain high-quality 16-bit, or greater, analog-to-digital and digital-to-analog converters, at least two input channels, and a range of sampling rates to at least 32 kHz.
- A separate compressor/limiter with at least two channels, adjustable and automatic compression ratios, attack-release times, and gain reduction of at least 40 dB
- A spectrum analyzer that provides a detailed visual representation of the audio signal. The unit should be a fast-Fourier transform design (not a real-time analyzer) with single-channel capability. If the laboratory also conducts signal analysis and/or authenticity examinations, a dual-channel or larger unit would be needed. The fast-Fourier transform device should have 16-bit or greater resolution, frequency display ranges adjustable from at least 0-100 Hz up to 0-20 kHz, a variable number of averages, and at least 800 lines of resolution on any frequency range. A zoom capability can also be a useful feature for some applications (Bracewell 2000).
- A modern computer system that can be used for a number of applications including controlling the digital enhancement devices and running other appropriate software.
- A computer printer that provides hard copies of fast-Fourier transform plots, filter settings of the digital enhancement devices, and other applicable information.
- Non-real-time software programs for precise, non-linear time and amplitude processing of audio recordings. Some of the functions applicable to the forensic field include pitch shifting for general or localized correction of playback speed, amplitude adjustments, and normalization. These software programs also allow redactions of specific portions of a recording to be performed with more ease and accuracy.
Equipment: Present laboratory spectrographic and/or computer voice comparison systems do not produce conclusive results, but meaningful findings are possible with careful analysis of speech samples collected under forensic conditions. The minimum requirements include the following equipment (IAI Voice Identification and Acoustic Analysis Subcommittee 1991; Committee on Evaluation of Sound Spectrograms, National Research Council, National Academy of Sciences 1979; Tosi 1979; Koenig 1993; Koenig 1986):
- An analog sound spectrograph that produces excellent voice spectrograms, especially under noisy recording conditions. It is being quickly replaced with specialized spectrographic software.
- Specialized spectrogram software that produces digitally calculated spectrograms that have been optimized for the speech and forensic communities. This software should be user-friendly and allow the operator to control all the important time and frequency characteristics of the graphic representation.
- Specialized forensic voice identification algorithms that are presently being developed (Nakasone and Beck 2001; Reynolds et al. 2000). When fully developed, this specialized, computer-based software will allow automated and/or operator-assisted voice comparisons between different voice samples.
- Editing software that allows two or more recorded voice samples to be selectively isolated and combined into a new recording.
- A headphone-switching box that allows the rapid toggling between two input signals containing separate voice samples for aural comparison.
Phase IV: Video Image Duplication and Enhancement
Equipment: To allow the most accurate duplication and enhancement of video recordings, an audio-video forensic laboratory should have the following equipment (Blitzer and Jacobia 2002; Bovik 2000; Russ 2002; Russ 2001):
- A video-capture device that accurately captures the entire resolution of a single field/frame and continuous video for any analog format expected in the laboratory. Inputs should include at least composite and S-Video.
- A high-speed computer system with a fast processor, a large monitor, sufficient random access memory, an input for digital video (i.e., FireWire), and extensive hard-drive storage to handle the video applications of the laboratory. Some manufacturers provide computer equipment that has already been optimized for this task.
- Color and black-and-white computer and video printers that provide hard-copy images from video evidence. Like other components in the system, the printers should have sufficient resolution to reproduce the entire captured and/or enhanced fields/frames.
- Software programs for continuous video and still video enhancement, with appropriate algorithms to sharpen, enlarge, enhance, edit, and correct visual details
Equipment: This phase includes signal analysis of audio signals and authenticity analyses of audio and video formats. The minimum requirements include the following equipment (Bellamy 2000; Bolt et al. 1974; Hodges 2001; Koenig 1990; Koenig et al. 1998; Rappaport 1996; Reeve 1995; Reeve 1992):
- The Phase IV computer system
- Professional video monitors that include pulse-cross and under-scan modes, component and composite inputs, and at least 600 lines of horizontal resolution. They should be able to fully reproduce all anticipated digital formats up to the highest level resolution. Multiple monitors may be needed to manage all of the analog and digital recordings.
- A dual-channel spectrum analyzer of the fast-Fourier transform design, not a real-time analyzer. The required features include zoom, two-channel comparison algorithms, and long-term averaging.
- A macro-photographic or digital camera system that allows the production of accurate pictures of the tape surface, ranging from 0.0125 up to 2 inches in width. If a digital camera is used, it should have a resolution of at least 2000 by 2000 pixels.
- A high-quality laboratory computer sound card that has a 16-bit or higher resolution, sample rates to at least 44.1 kHz, two or more input and output channels, and low-noise and distortion characteristics.
- Signal analysis software with the capability to perform waveform, narrow-band spectrum, spectrographic, and other analyses on .wav, as well as on other computer-formatted audio files. It should allow aural review of selected portions of the displayed data, permit high-quality printouts of the various analyses, and have the capability to display multiple windows on the screen with time correlation between the various displays.
- Professional audio and video digital recorders that permit the duplication of original evidence without any loss of visual or aural information
Phase VI: Digital Data Analysis and Retrieval
Equipment: This phase involves the transfer, analysis, and retrieval (when necessary) of digital data contained on the various audio and video recorders used in the investigative field. Digital forensic recordings may exist on a variety of media types including tape (DAT, NT-2, DDS), optical (CD-R/RW, DVD-R/+R/-RW/+RW/RAM), magneto-optical (MiniDisc), and random access (FLASH memory chips, hard drives). These recordings may have been recorded in a standard format or on proprietary recorders that require specialized hardware and/or software to play back and analyze the recorded data. Most of the equipment needed for this phase was discussed in Phases I through V; however, there are a few additional requirements include the following items:
- Software that allows the user to view the digital data down to the bit level. The proprietary recorders may require additional hardware and/or advanced software that often are available only to law enforcement agencies.
- A removable, writable digital medium that has sufficient storage capability to archive large data files that exist on higher-capacity formats and on solid-state body recorders.
Laboratory Space Considerations
The laboratory should be configured or constructed to decrease outside noise and vibration, dampen laboratory equipment sounds, and minimize radio-frequency interference and magnetic fields. Equipment should be optimally arranged for sufficient appropriate workspace including separate electrical circuits, proper lighting, and secure and adequate storage (Berger et al. 2000; Harris 1991; Salter 1998).
- The following strategies should be implemented to decrease outside noise and vibration:
- Eliminate as much of the outside noise as possible by locating the laboratory away from noisy outdoor environments like train tracks, airports, playgrounds, and busy streets.
- Increase the distance between building noise and the laboratory by avoiding shipping docks, cafeterias, or machine shops. Distancing the laboratory may mean moving the laboratory space to a quieter location in the same building or to a different building. If laboratory relocation is not possible, noise relocation may be an option. For example, request that most of the dock shipments be loaded or unloaded as far as possible from the laboratory or arrange with the cafeteria so that the lunch tables and the noisiest equipment are farthest from the common wall with the laboratory. Machine shop noise can be reduced by placing sound-absorbing materials around the equipment and installing soundproofing material on the walls and ceiling.
- The laboratory walls can be isolated and soundproofed. However, building new walls inside the present laboratory, isolating the new walls from the old outside walls, and treating the space between the two walls reduces laboratory space, increases construction costs, and creates temporary noise and dust.
- Decrease the noise generated in the laboratory by purchasing equipment and computers with low-noise fans. Place noisy equipment in soundproof isolation compartments. Whenever possible, avoid fluorescent lighting to prevent the audible buzz the lighting produces and the low-level noise it can induce in certain electronic equipment. Limit the speed of the heating and air conditioning fans, and correct noisy air vents.
- Minimize radio-frequency interference by locating laboratories away from commercial radio and TV transmitting stations or police and other radio-transmitter towers. Some equipment is more susceptible to outside fields than others, so place that equipment in different locations in the laboratory or at different heights in the racks. Placing the laboratory space below ground usually minimizes radio-frequency problems. Interference from the building’s electrical wiring can often be removed with specialized AC power filters. Large transformers or loudspeakers with large magnets should not be placed near any audio or video evidence. A portable gauss meter can determine if there are problematic magnetic fields in the area. To avoid electrical spikes and other irregularities, the laboratory should have dedicated electrical circuits.
- Equipment may be placed on tables, but sturdy equipment racks are preferred. Racks allow higher density with better cooling, provide better protection, facilitate wiring and rapid changes in connections, are moveable, and look professional.
- The workspace should be flexible enough to handle reorganization. Floor space should be planned to accommodate current and future equipment. The aisles should allow easy access for bulky evidence, large equipment, and equipment repair. There should be sufficient table space to visually examine, mark, and lay out evidence. The workspace should have sufficient lighting, preferably incandescent track lighting.
- A separate, secured area containing a safe or safe file for evidence storage should be available with controlled entry and an alarm. The storage area should be free of magnetic fields and be temperature- and humidity-controlled.
XXX . V OUT BUREAU ; The Electronic Digital Computer
Binary Arithmetic, Logic and Memory Among Basic Elements in Its Functioning
Lord Byron had a flair for poetry and for life, but Lady Byron (the "Princess of Parallelograms") and their only child — Ada Augusta, Countess of Lovelace appear to have been more intrigued by mathematics. In fact, Lady Lovelace (1815-52) blazed a trail of her own in the arts of computer analysts and programming.
She was fascinated by the mathematician Charles Babbage, visited him frequently and avidly as he explained his plan for an automatic mathematical machine called the Analytical Engine. And she left behind, in detailed notes appended to her translation of an article in French on Babbage’s plan, a brilliant description of a machine that "weaves algebraic patterns just as the Jacquard-loom weaves flowers and leaves."
This mathematical machine of counting wheels, gears and cranks was never completed despite fund-raising schemes such as an abortive plan by Babbage and Lady Lovelace to develop a surefire system for betting on the horses. But what was once called "Babbage's Folly" turned out to be a really smashing idea.
Babbage (1792-1871), who grew grumpy with age and disappointment, was a mathematical professor at Cambridge in the eighteen-thirties. He had a piercing and restless mind, a biting tongue, a visceral distaste for organ grinders, an "inveterate habit of contriving tools" and side interests in such matters as actuarial tables, economic systems analysis, the pulse beats of animals and colored lights for the ballet.
This many-splendored genius built a model of a small Difference Engine that elevated polynomials by the method of taking differences among numbers. He was involved in a project—never finished—to build a bigger Difference Engine when he conceived the grand design for an even more elegant counting-wheel machine, the Analytical Engine.
It was to have a "store" to hold information to be processed, a "mill" to work on the data and a "control" to provide automatic operation. The control was to be the kind of punchcards introduced in 1801 by the French inventor Joseph Marie Jacquard for automatic loom weaving.
Machine calculation is at least as old as the abacus, but the history of modern calculators dates to the 17th century, when Napier, Pascal and Leibnitz all built computing devices. Pascal's calculator is particularly important as the prototype of mechanical calculators now being used.
It remained for Babbage to advance concepts immediately recognizable as having a direct relationship to the way present day digital computers operate. In Babbage's time, however, the technology for carrying out his ideas simply did not exist.
More than a hundred years elapsed before the first machine resembling the Analytical Engine was built. This mechanical computer, conceived by Howard H. Aiken of Harvard, was completed with the collaboration of the International Business Machines Corporation in 1944.
Two years later came the first electronic digital computer—ENIAC (Electronic Numerical Integrator and Calculator)—designed by J. Presper Eckert and John Mauchly of the University of Pennsylvania.
Many men have played pivotal roles in the evolution of technologies important to computer science. Among them are the following:
George Boole (1815-1864), a British mathematician who developed the concepts of symbolic logic.
Norbert Wiener (1894-1964) of the Massachusetts Institute of Technology, whose Cybernetics systematized concepts of control and communications.
Alan M. Turing (1912-54), a British mathematician who formulated a definition of automatic machines, worked out a mathematical model of an elementary "universal computer and proved theoretically that it could be programmed to do any calculation that could be done by any automatic machine.
John von Neumann (1903-57), a Hungarian mathematician who came to the United States where he developed the concept of the stored program for digital computers.
Claude E. Shannon, now aged 50, of M.I.T, who defined the application of symbolic logic to electrical switching and is even better known for his basic work in information theory.
The stored-program concept involves the storage of both commands and data in a dynamic memory system in which the commands as well as the data can be processed arithmetically. This gives the digital computer a high degree of flexibility that makes it distinct from Babbage’s image of the Analytical Engine.
Babbage's machine program was based on instructions punched into sets of cards. He even conceived of a method of conditional transfer. In such a transfer, a designated result of a calculation, but one unknown in advance, would—in turning out to be, say, a negative instead of a positive number—cause the machine to select an alternate set of cards for a different preplanned set of actions.
Profound Impact
Modern punchcards are often used to feed instructions to the present-day computer. This machine also handles conditional operations as part of its control capabilities. But no card-changing is required. As the computer automatically checks off the instructions to it in sequence, it can modify the commands as well as the substantive contents stored in its memory.
This is possible because both the commands and the data are represented by numbers, and the computer can manipulate numbers generally. For example, if three numbers—16, 1 and 17—are all stored in the memory, with 16 calling for one set of actions and 17 for another set of actions, the computer can shift from one set to the other whenever it is told to add a 1 to the 16.
During the last two decades the digital computer has become a primary element in a great ferment of interrelated change that is transforming the world in which we live and the way we live in it. Scientific and technological advances, marked by intensified research and a narrowing of the time between discovery and application, are having a profound impact on the works of man.
The computer has not only been an important aid in the research, but it also has been used as a workhorse device in processing large floods of data produced by an expanding and more intricate economy. Furthermore, the computer has been integrated more and more into the dynamic operational aspects of this economy and its various institutions.
In business, for example, the computer has become an essential tool in management planning and control activities. There is a continuous requirement for improved techniques as well as more efficient methods to deal with the growing amounts of paperwork demanded by a society that is increasingly preoccupied with reports, analyses, records and detailed documentation.
Aside from its applications in science, industry and business, the electronic digital computer is now being used widely in government, in medicine, in education, in transportation and communications, in the arts—and the list of its specific uses is growing steadily. What is this modern electronic Analytical Engine? How does it work?
Coded Information
Whether it is solving a differential equation on the motion of charged particles or keeping track of a nuts-and-bolts inventory, the digital computer functions fundamentally as a numerical transformer of coded information. It takes sets of numbers, processes them as directed and provides another number or set of numbers as a result.
A modern digital computer is composed of elements that provide five essential functional capabilities: input, memory, arithmetic-logic, control and output. An ordinary adding machine also has some of these capabilities. But the computer is very different.
Among the characteristics that make it different are the flexibility with which it can be adapted generally to logical operations, the blinding speed with which it can execute instructions that are stored within its memory, and its built-in capacity to carry out these instructions in sequence automatically and to alter them according to a prescribed plan.
Despite its size and complexity, a computer achieves its results by doing a relatively few basic things. It can add two numbers, multiply them, subtract one from the other or divide one by the other. It also can move or rearrange numbers and, among other things, compare two values and then take some pre-determined action in accordance with what it finds.
These computer talents, bestowed by man, provide a means of solving multiple problems that can be broken down by man in terms of the factor, "if so, then . . ." As an example, take the case of a company that must send one of its employes to France quickly. The personnel director is asked to supply the names of candidates who are single, under 35 and able to speak French.
A logical flow chart could be worked out for this set of conditions and personnel cards fed into a computer for sorting-out on the basis of the conditions.
Elementary as the above procedure is, the same type of logical approach is used in getting a computer to perform a wide variety of calculations, including, for example, Social Security deductions in the processing of payrolls.
Aside from its affinity for logic, the computer obeys with amazing speed. Extra-fast computers can now execute about 10 million steps a second. By way of imperfect but still impressive comparison, each of the myriad neurons of the nervous system handles about 200 switching operations a second.
For all its transistor chips, magnetic cores, printed circuits, wires, lights and buttons, the computer must be told what to do and how. Once a properly functioning modern computer gets its instructions in the form of a properly detailed "program," it controls itself automatically so that it responds accurately and at the right time in the step-by-step sequence required to solve a given problem.
It makes decisions by command and not, as humans often do, by instinct. If the data put into the machine are wrong, the machine will give the wrong answer.
Computer operation begins with the "software," that is, the detailed program needed to instruct the machine.
Developing the software is a very expensive enterprise and frequently more troublesome than designing the actual "hardware"—the computer itself. As an illustration of what the software may involve, it is often necessary to specify 60,000 instructions or more for a large centralized inventory-control system.
Software development calls for a thorough analysis and systematic dissection of a given problem, the preparation of the kind of flow-chart plan shown above to conform with the machine’s capacities and the translation of the required steps into a language that the machine understands. It also involves, finally, the debugging of the program to test its correctness in a wide variety of situations.
For an understanding of what is required of the machine to solve a problem, consider the matter of controlling the quantitative level of a particular set of items in a manufacturer’s inventory.
Inventory control is a complex and varied procedure, but the key questions can be formulated in mathematical equations where numerical quantities are substituted to describe an inventory situation as it actually exists. Some means must be available, then, to get these numerical quantities into the computer.
This requires an input facility that converts any symbols used outside the machine (numerical, alphabetical or otherwise) into the proper internal code used by the machine to represent those symbols. Generally, the internal machine code is based on the two numerical elements 0 and 1.
In the decimal-number system, each symbol from 0 through 9 is called a digit. As we move one place from right to left in this system, we are multiplying by a factor of 10. In the 0- and -1 system—described as binary—each symbol—0 or 1—is called a "bit," which is a contractor of the words "binary" and "digit." As we move one place from right to left in this system, we are multiplying by a factor of 2.
The 0's and 1's of binary notation represent the information processed by the computer, but they do not appear to the machine in that form. They are embodied in the ups and downs of electrical pulses and the settings of electronic switches inside the machine.
For an understanding of pulse-formation and pulse sequences, it may be helpful to consider an elementary circuit consisting of a battery (say, a 6-volt type), a light bulb and a spring-loaded hand key, all connected, with the operator alternately pressing down on the key and releasing it.
When the key is down, the battery voltage turns on the light with a 6-volt pulse. When the key is released, the lamp voltage becomes 0 and the light goes off. When the key is pressed again, there is another 6-volt pulse and the lamp lights again.
If the hand on the key were steady and the sequence rhythmical, the pulses would occur regularly and distributed evenly along an imaginary base line whose length represented time. The width of the space occupied by each pulse would depend on the beat, or frequency.
Since the pulses given off by our pulse-producer are either 6 volts or 0, we could call the 6-volt level of each pulse a 1 and the level at which there is no voltage a 0. In effect, then, we can use pulses as the conveyors of information.
Such pulses can be used to code decimal numbers, alphabetic letters, words, punctuation marks or designs arranged in machine-readable patterns. But more sophisticated means than a simple hand key are used for the computer’s input facility. Some advanced inputs involve the scanning of a printed page, the conversion of a limited vocabulary of spoken words and the use of "light pens" to detect information on a television-like cathode-ray tube.
So far as our inventory equation is concerned, the information pertaining to it may be inserted in the computer by any of a variety of input devices. One possible device is actually a key-driven machine—a typewriter whose keys are connected to electronic networks that convert information into pulse sequences corresponding to notations on the pressed keys.
Such terminal devices may be operated at remote points.
Other input means are provided by punched cards and punched tape, with metal brushes or photoelectric cells sensing the holes and closing an electric circuit each time a hole is sensed. Use is also made of magnetic tape, disks, drums and ink, with the information being represented by different patterns of magnetized spots.
Look at one of your bank checks. The chances are you will find some numerals at the bottom. They are printed with magnetic ink for purposes of data processing.
But getting back to the inventory problem. Once the information pertaining to it is fed into the machine, the data must be lodged somewhere and preserved so that they do not disappear. For example, when a computer is "told" how many inventory items are on hand, it must "remember" that fact—and other facts associated with the problem.
Storing such information is the function of the computer "memory."
Small packages consisting of ferromagnetic cores are widely used as the computer’s main memory. Magnetic tape, disks and rotating drums are used as auxiliary memories. On such auxiliary devices, information is recorded and retrieved from their surface by "read-write" heads similar to those used for the recording and playback functions on an ordinary tape recorder.
A core, whose dimensions are measured in thousandths of an inch, is a tiny doughnut-shaped object pressed from a mixture of ferric oxide powder and other materials and then baked in an oven.
Millions of cores are used for very large computer memories. They are strung, or "sewn," into a wire mesh. Then other wires are passed through them in three planes so that appropriate pulses can cause each core to absorb ("read") or release ("write") information bits.
Electric current is sent through the wires to magnetize a core. The core’s magnetic direction, counterclockwise in this case, is determined by the direction of the current. Even if the current is removed, the core remains magnetized in the same direction.
It stays magnetized in this way until reversal of the applied current causes it to change state. The two states can be used to represent 0 or 1, plus or minus, yes or no, on or off.
With so many cores strung together, how is a particular core selected for storing a bit? Two wires run through each core at right angles to each other. Only half the current required to magnetize a core is sent through each wire.
Consequently, only that core receiving full magnetization current from the two wires is selected.
When a core is required to release information, a "read" current is applied to it. This causes a change in its state, and the change induces a pulse in the sense wire that amounts to a message from the memory to another part of the computer.
For rotating drums, the read-write heads contain coils of fine wire wound around tiny magnetic elements. A 30-channel drum used for storage in a data-processing system, with seven formation tracks for each channel.
Means have now been described for getting information into the computer and storing it. Since problems like inventory control are based on equations, however, the computer must at least have the arithmetic capability of adding, subtracting, multiplying and dividing.
In manipulating numerical data inside the computer, it is necessary to shift bits of information or hold while parts of the machine analyze the data. Sometimes it is also necessary to compare two numbers to see if they are equal, or to see if one is larger than the other, or if it is 0, and so on.
Indeed, many modern computers provide more than a hundred capabilities such as these, each one of which is built into the hardware.
The computational requirements are handled by the computer’s arithmetic-logic unit. Its physical parts include various registers, comparators, adders, and other "logic circuits."
A register is a device that receives information, holds it—usually temporarily—and then releases it as directed by the step-by-step instructions programmed into the computer. Magnetic cores or "flip-flops" are frequently used to form a register.
A flip-flop is an electronic switch. It usually consists of two transistors arranged so that incoming pulses cause them to switch states alternately. One flips on when the other flops off, with the latter releasing a pulse in the process. Thus, multiple flip-flops can be connected to form a register in which binary counting is accomplished by means, of pulse triggers.
Stable two-state electronic devices like the flip-flop are admirably suited for processing the 0 and 1 elements of the binary-number system. This, in fact, helps to explain why the binary-number system is commonly used in computers.
Like decimal numbers, binary numbers obey all the rules of arithmetic and can therefore be added, subtracted, multiplied and divided. Addition is the primary arithmetic process carried out in the computer's arithmetic-logic unit.
All of the operations can be carried out either by addition or variants of addition.
For example, multiplication can be done by repeated addition. Subtraction can be accomplished by complementing one number, adding it to another and then adding an extra 1. And division can be achieved by repeated subtraction.
In the decimal system, the complement of a number can be obtained by subtracting that number from a series of 9’s and adding 1 to the result. The complement of 88, for example, is 12.
In the binary system, the complement of a number is obtained by subtracting that number from a series of 1's and then adding the extra 1. This, however, is equivalent to changing all 0's to 1's and all 1's to 0's and then adding 1.
Consequently, in a computer, it is easy to provide simple circuitry to complement a number by inverting it and, in this way, carry out subtraction by means of addition. Basic operations in the binary system, similar to those carried out in the decimal system.
ANSWER THE SAME
Logical operations in the computer’s arithmetic unit, as well as in other units of the machine, can be represented in an algebra of logic named after the 19th-century English mathematician George Boole.
In Boolean representation, the multiplication sign (x) means AND while the plus sign (+) means OR. A bar over any symbol means NOT. An affirmative statement like A can therefore be expressed negatively as Ā (NOT A).
If a switch is regarded as being in state A when it is closed, then it is in a state of Ā (NOT A) when it is open. If another switch is in series with the first switch and its two states are similarly considered to be B for closed and NOT B for open, then we must have both an A and B for the entire circuit to be completed.
When the A and B conditions are met the result may be called "true" or 1. Thus, for the two switches in series, the completed circuit may be described, by the simple Boolean equation: A x B. Alternatively, AB) = 1 (the x meaning AND).
Use of the Boolean notation may be illustrated in the design of the familiar upstairs-downstairs light arrangement in which a hall lamp can be turned on or off from either location. The four conditions implicit in the problem may be represented in logic diagrams or, even more effectively, in a "truth table."
In handling the logic required to process a problem like inventory control, the computer is obviously dealing with more complicated matters than the hall lamp arrangement. But the logic used in mapping the circuitry for the computer’s arithmetic unit is similar, particularly with regard to the important internal connectors known as "gates.”
A gate is a logic element that produces an output signal only when a specified set of conditions is met. If the conditions are met, the gate will pass information pulses; if not, it will block the flow.
There are three basic types of gates: the OR, which passes data when the appropriate signal is present at any of its inputs; the AND, which passes data only when the same appropriate signals are present at all inputs; and the NOT, which turns a 1-signal into a 0-signal, and vice versa.
Gates are package elements in computers. Instead of drawing such circuits repeatedly, computer designers rely on symbols to depict them.
The utility of such symbols is demonstrated below for two kinds of computer activity: the transfer of an information bit from one register to another and the addition of two numbers by a half-adder. The half-adder is called that because it can deal only with two numbers to be added and not with a "carry" from a previous stage.
For the data bit to be transferred from FF-A (Flip-Flop A) to FF-B above, there must be two appropriate signals of the same kind at the two inputs of the AND-gate. One such signal (a 1' in this case) is already provided by the condition of FF-A. But the second signal is not present until a 1-pulse is applied over the transfer line.
When the second signal appears over the line in the form of a 1-pulse, the two inputs of the AND-gate are both properly primed and the bit stored in FF-A is duplicated in FF-B. Thus, in effect, the bit has been transferred.
In the half-adder shown, notice that the addition of 1 and 1 in binary arithmetic must produce a sum of 0 and a carry of 1. The circuit accomplishes this. Incidentally, two half-adders can be combined to form a full adder capable of handling a carry from a previous stage as well as two new numbers to be added.
Arithmetic units can be operated serially, with one pulse following the other in a single-file sequence, or in parallel, with the pulses stacked one over the other. Parallel operation is the faster method because more can be made to happen in a given time interval.
We already have discussed three facilities basic to the processing of our inventory data — input, storage and arithmetic-logic. But we still have not processed the data. Nor, for that matter, have we established the traffic pattern needed to avert chaos in the computer.
As indicated earlier, the machine must operate in a step-by-step fashion. Thus, it must be told when to add (or subtract, etc.), when to transfer information from the memory to the arithmetic unit, when to store it back into memory, where to look for the next instruction, and so on.
Supervision of these functions is the work of the control unit, the computer’s built-in traffic cop. It regulates the internal operations of each unit and the relations between them by means of electrical timing pulses that open and shut connecting gates in the required sequence.
All operations in the computer take place in fixed time intervals measured by sections of a continuous train of pulses. These basic pulses are sometimes provided by timing marks on a rotating drum, but more frequently they are generated by a free-running electronic oscillator called the "clock."
The clock-beat sets the fundamental machine rhythm and synchronizes the auxiliary generators inside the computer. In a way, the clock is like a spinning wheel of fortune to which has been affixed a tab that touches an outer ring of tabs in sequence as the wheel revolves. If a signal is present at an outer tab when the wheel tab gets there, the appropriate gate is opened.
Each time-interval represents a cycle during which the computer carries out part of its duties. One machine operation can be set up for the computer during an instruction cycle (I-time), for example, and then processed during an execution cycle (E-time).
Now that the control unit has been "added," we have a machine to process information and problems like inventory control. But we still have to get the results out of the computer. The results, stored in the memory after processing, are extracted in the form of pulses and emerge as output "readouts" on devices that look similar to the input devices mentioned earlier.
Among the output systems used are punched cards, magnetic tape, magnetic disks and paper tape. The great demand, however, is for a printed readout. Thus, a great variety of printers is being used for the output requirement.
A recent surge of application development has created a need for other output forms, including graphic displays on cathode-ray tubes, signals for many kinds of control devices and even voice reproduction.
All the parts making up the computer, however, are interconnected by wires, printed circuits and gates through which pulse information flows as directed by instructions given to the computer.
These instructions, or program, determine the circuits that will be called upon to solve a problem, the interactions between them and the sequence in which the various machine elements will be called into play.
All modern digital computers can be used to help program themselves. But man is the ultimate controller. The computer stands mute until the instructions that man has written are fed into the machine and the right buttons pressed.
Happily, the programmer — or the computer operator for that matter — does not have to know all about the electronic circuitry inside the computer. On the other hand, the programmer must know the organization of the machine, the kind of statements he can use in communicating with it and how to write these statements sequentially to get the computer to solve the problem he wants solved.
The language used to communicate with the computer is called the "source language."
Each source language has its vocabulary, its syntax and its repertoire of permissible instructions. An asterisk (*) may mean multiply, a "verb" (operation command) may have to precede a "noun" (data location) and parentheses may have to be related to symbols in specified ways to achieve desired results.
Use of Source Languages
Source languages are usually designated by acronyms. Among those in wide use are ALGOL (Algorithmic Language), COBOL (Common Business Oriented Language) and FORTRAN (Formula Translator). A statement in these languages is much less formidable than it would have to be if it were written directly in the code used by the computer hardware.
For example, the instruction DISTANCE = RATE * TIME means simply: make distance equal rate multiplied by time.
Obviously, before a computer can deal with such an instruction, there must be some way to convert the source-language statement into the appropriate series of machine-language instructions. The translation is accomplished by a computer program (set of instructions) previously written and stored in the machine’s memory.
This type of program is called a "compiler." A given source language is associated with a particular compiler.
The memory may be regarded as consisting of a vast set of "mailbox"-type slots. Each slot has a designation number called an "address" and each is large enough to hold a stipulated number of digits. (We will be dealing below with decimal digits, which are, in fact, the way numbers are represented in the programmer’s written instructions.)
Let us assume, for simplicity's sake, that there are 1,000 memory "mailboxes," or slots, with addresses ranging from No. 0 through No. 999. Assume further that we are going to use five digits in each program instruction to represent both the operation to be carried out by the computer and the addresses of the slots.
Since three digits are required for the address numbers, two are left to represent the type of operation we want the computer to carry out. Thus, under the above circumstances, a typical instruction would be based on a five-digit number broken down into two parts.
Bear in mind that the "noun" part of the above instruction refers to the address number and not to the numbers stored as data at that address. Actually, in designating the address as part of his instruction, the programmer is really interested in the information available at that address.
Getting back to inventories again, let us take the case of a warehouse where we want to keep track of 50 categories of items that are being stocked—with the number of items in each category having a maximum quantity that can be expressed in five digits. At the end of each day we want to know how many items we have left in each category.
For each category, this involves adding new receipts to the quantity originally on hand and subtracting from the sum the day’s total withdrawals. Thus, we have a set of three data numbers for 50 categories, making it necessary to use 150 "mailboxes" with five-digit capacities in the computer’s memory to store these five-digit parcels of information.
Beginning with the first category, we could place the "starting amount" of items on hand at Address No. 100, the amount of new receipts at Address No. 200, and the total daily withdrawals at Address No. 300. Arithmetically, we must add the information content of Address No. 100 to the content of Address No. 200 and subtract from the total the content of Address No. 300.
With this accomplished, we would like to keep current by putting the result back at Address No. 100.
For the "verb" part of the instructions, let us designate the number 16 for add only, 17 for reset-to-0 and add, 20 for subtract, 07 for store, 30 for transfer and 50 for print. The simplified program instructions, then, could read as follows:
Instructions | Meaning |
---|---|
17 100 | Reset to 0 and add the content of Address No. 100 (amount of items on hand) into the accumulator register. |
16 200 | Add to the above quantity (items on hand) the new receipts, which will be found at Address No. 200. |
20 300 | Subtract total daily withdrawals. |
07 100 | Store result at Address No. 100. |
Each of the instructions to the left above is a five-digit number and the five-digit capacity of any memory slot can store it. The instruction-number groups could be loaded into the "mailboxes" at addresses beginning at, say, No. 900. Hence we have the following addresses for the above instructions:
Addresses | Instructions |
---|---|
900 | 17 100 |
901 | 16 200 |
902 | 20 300 |
903 | 07 100 |
Once the machine is told—by the setting of switches on the computer console—to start executing instructions beginning at Address No. 900, it will do so in sequence, searching Address No. 901 for its next instruction and No. 902 for the one after that, and so on, unless it is told to do otherwise.
If we want the machine to print out the answer after completing the instruction at Address No. 903, we can put the next instruction in No. 904 as follows:
Address | Instruction | Meaning |
---|---|---|
904 | 50 100 | Print content of No.100 |
Now that one set of items has been processed, we want the computer to go on and do the same job automatically for the 49 other categories of items in the warehouse. After the first category comes the second, so we might be tempted to put an instruction at Address No. 905 telling the computer to go back to Address No. 900 for its next instruction and start the cycle over again for the second category.
Since 30 means transfer, this instruction would read:
Address | Instruction | Meaning |
---|---|---|
905 | 30 900 | Go back to 900 and start over |
But it would be best not to give such an instruction.
For in going back to 900 and proceeding as before to Nos. 901, 902 and 903, the computer would merely be repeating the processing of information concerning the first-category information stored at Address Nos. 100, 200 and 300.
Let us suppose that the second-category information is actually stored at Address Nos. 101, 201 and 301.
Thus, the information stored at 900, 901, 902 and 903 must be changed so the instructions will apply to the contents of Address Nos. 101, 201 and 301. This can be accomplished because of the important fact that the instructions themselves are numbers and are therefore modifiable arithmetically.
To modify the instruction at Address No. 900, all we have to do is add a 1 to it, and make it read 17 101 instead of 17 100. The same must be done for the instructions stored at Address Nos. 901, 902 and 903.
Consequently, we store a five-digit 1—00001—at some memory address, say Address No. 400.
Then, forgetting about our last instruction for Address No. 905, we write a new one to be inserted in that "mailbox" and place further instructions at succeeding addresses for the purpose of adding the 00001 to the original instructions at Address Nos. 900 through 903.
The add-1 procedure continues until the 50 categories of items have been processed and readouts printed for each category. After the 50th category is processed, the machine would come to a halt if the instructions contained such a command.
As we have dealt with the warehouse inventory problem above, the rather simple arithmetic requirements already have produced a more complex and longer set of instructions than might originally have been imagined. Additional instructions would actually be required to define the format of the printed output, including matters related to margins, column headings, dates, page numbering, and so on.
But take heart.
Remember that the computer itself has the built-in logical power, when properly programmed in a sound source language, to allow us to communicate with it in a language more like our own—whether it be English or the languages of science, engineering, mathematics or business.
When a source language is used, each source-language statement causes the compiler program for the language to generate sequences of machine-language instructions like those given for the warehouse inventory problem. It is in this fashion that the computer helps us program our problems.
All this and other even more impressive feats being performed by the modern Analytical Engine are wondrous to behold. But a comment by Lady Lovelace in the eighteen-forties about Babbage's machine still holds true of the present-day digital computer:
"The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform."
ELECTRONICS ENGINEER PASS OUT BUREAU ; Digital Computer
a computer that transforms quantities expressed in the form of sets of digits—that is, in the form of numbers. The simplest transformations of numbers are the arithmetic operations of addition and subtraction, which have been known since antiquity. Arithmetic operations, however, are only a special case of the transformation of numbers given in digital form, and in a modern digital computer they constitute only a small part of the set of operations that the machine can perform on numbers.
The first device for simple computations was the abacus, which was used to carry out the arithmetic operations of addition and subtraction (seeCOMPUTER TECHNOLOGY). In ancient times paper (or its equivalent) and writing instruments were rare, and the abacus freed man from the need to remember the addition table and to write down intermediate results of computations.
An important advance in the development of calculating devices was the invention by B. Pascal of an adding machine in 1641 or, according to some sources, 1643. Pascal’s machine consisted of a train of number wheels, each of which corresponded to a decimal place. Each number wheel was divided into ten sectors, which corresponded to the digits 0 to 9. Addition was performed by turning the wheel the appropriate number of sectors. The use of a rotating wheel to perform addition and subtraction had been proposed before Pascal by, for example, Professor W. Schickard of the University of Tübingen in 1623. Pascal’s machine, however, provided for automatic carrying: when a wheel made a complete rotation, the wheel for the next higher decimal place turned one unit. The machine thus reflected ordinary addition of decimal numbers, wherein tens formed by the addition of units are carried to the tens decimal place, hundreds formed by the addition of tens are carried to the hundreds decimal place, and so on. Pascal’s provision for carrying made possible the addition of multidigit numbers without human intervention in the work of the mechanism. His principle was made use of for almost three hundred years—from the mid-17th to the early 20th century—in the construction of hand-operated adding machines and electrically driven keyboard computers.
The first calculating machines performed such elementary operations as addition, subtraction, carrying to the next higher place in addition, borrowing from the next higher place in subtraction, and shift of the carriage (by hand or, in electric machines, automatically). Multiplication and division were done by successive addition and subtraction, respectively. The functions of man and machine in the performance of computations were divided in the following manner: the machine did the arithmetic operations on numbers; the operator directed the course of the computational process, entered numbers in the machine, recorded intermediate and final results, and looked up in tables the values of various functions involved in the computations. With such a distribution of roles, increases in the speed at which the machine performed the arithmetic operations produced insignificant increases in the overall speed at which computations were carried out, since the procedures for which the operator was responsible constituted the larger part of the computational process. Therefore, although electric calculating machines could in principle perform up to 1,000 arithmetic operations per hour, in practice not more than 1,000 operations could be done in an eight-hour workday.
A step forward in the development of digital calculating machines was the invention of punch-card equipment. In punch-card calculating machines all “human” functions, except the finding of values of functions in tables, were essentially entrusted to the machine. An additional exception was the entry of data into the machine: the input data had to be recorded on punch cards. This operation was done by a person separately on a special device. The prepared punch cards were placed in the machine, which read the data contained on them and performed the necessary computational operations without human intervention. The intermediate results of computations were recorded in memory registers, and the final results were printed on paper or were entered on punch cards, from which a special device copied them on paper. Control of the computational process, that is, the programming of the machine, was handled through plugboard wiring. Thus, punch-card machines contained in embryonic form all the most important elements of an automatic digital computer, whose operation does not require human participation after the necessary preparation for the performance of the computations is completed.
Punch-card calculating machines had an arithmetic unit; a memory (in the form of decks of cards and registers for storing intermediate results); an input device, which read the data on the punch cards; and an output device. Their speed was limited, since they performed arithmetic operations in much the same way as adding machines—that is, through mechanical movements. The most serious bottleneck in punch-card machines, however, was the problem of control of the computational process. Since such control, that is, the specification of the sequence of elementary operations, was effected by using wires to connect different terminals on the plugboard in the appropriate way, only simple sequences of computational operations could be programmed. Because the operations could be repeated many times, punch-card machines were used particularly widely in cases where the solution of a problem reduced to the repetition of simple sets of operations, for example, in bookkeeping and in simple problems of statistical analysis (tabulating machines). The most complicated problems solved on punch-card machines were ordinary second-order linear differential equations.
By the 1970’s punch-card machines had been in virtually every case supplanted by the more efficient and versatile electronic digital computers. The historical importance of punch-card machines was that they provided experience in the processing of information by machine and made possible an understanding of the prerequisites for the construction of automatic digital computers.
Regardless of their physical structure, digital computers that operate automatically must be able to perform operations, including arithmetic operations, on quantities (“words”) given in digital form, and they must be able to store both the results of the computations and the input information, which consists of the input data and the program describing the computational algorithm to be used. Other functional capabilities required of such computers are control of the computational process—that is, automatic adjustment of the machine to carry out each successive operation mandated by the program—and “communication” with the operator—that is, acceptance from him of the input information and presentation to him of the computational results he needs. The functions of the computer are usually carried out by corresponding units (Figure 1), although a partial combination of functions in a single unit is sometimes encountered. In any case, an automatic digital computer must perform all functions listed.
Every digital computer has “digital elements” with a finite number of stable states; the number of such states must be equal to the base of the number system used in the given machine. For example, in mechanical desk calculators, such as adding machines, these elements are the number wheels, which may take ten definite positions, in accordance with the decimal number system. Since electronic digital elements are most easily constructed with two stable states, the binary number system, which has only the two digits 0 and 1, is preferred in electronic digital computers.
The adoption of the binary number system facilitated the representation of numbers and considerably simplified the performance of operations on them. For example, the digital element of an adder must in this case have the property of changing to the opposite state whenever it receives the signal 1, which corresponds to the addition of 1 ; if the digital element is already in the 1 state, the change in its state must be accompanied by the sending of a 1 signal to the adder’s digital element for the next higher place. The operation of multiplication reduces to the multiple addition of the multiplicand and to shifts, and division reduces to subtraction and shifts.
Logical operations are also considerably simplified in the binary system. Any complex computational algorithm usually contains a variety of instructions, involving, for example, branching of the computational process, repetition of computational procedures, and the placement of various conditions on the accuracy of the computations. The machine must “understand” these instructions and must “make decisions” regarding their timely execution. Such actions of the machine are not arithmetic; rather, they are used for logical analysis of situations. One of the most common machine procedures is to perform a certain step—that is, to execute a certain program instruction—if a certain situation exists and to transfer to the execution of some other instruction if the situation does not exist. Because electronic digital computers can perform both arithmetic and logical operations, their capabilities go far beyond their direct purpose of arithmetic calculations, and they can be regarded as general-purpose transformers of discrete data. Since continuous data can practically always be approximated by discrete data, modern electronic computers can be said to be general-purpose transformers of data of any type.
The first truly electronic digital computer was the Electronic Numerical Integrator and Calculator (ENIAC), which was completed in 1945 and went into operation in 1946 in the USA. The construction of the first electronic digital computers did not require the invention of new elements, since such elements were already used in automatic control systems and, in particular, in radar installations. It was necessary merely to adapt the existing elements for use in a digital computer. The digital element of the first electronic machines was a flip-flop composed of two triodes. As a result of the use of such a digital element, the first electronic digital computer contained a large number of electron tubes and had a low reliability. Nevertheless, the ENIAC marked the beginning of the history of electronic digital computers. The ENIAC showed that it was in principle possible to construct an automatic digital computer that operated according to a predetermined program; some technological improvements were all that was required. The appearance of the ENIAC gave rise to energetic work in many countries on the development of reliable electronic digital elements and the design of efficient structures for digital computers.
The period of basic research in the history of digital computers ended by the early 1950’s with the development of the typical first-generation digital computer. In such a computer the digital element of the main memory was a ring-shaped ferrite core, with a rectangular hysteresis loop, having two stable states of residual magnetization. The basic element of the control unit and the arithmetic unit was a flip-flop made from electron tubes. The reliability of first-generation digital computers was substantially higher than that of the first digital computers. This increase in reliability was due not only to the replacement of the flip-flops in the memory of the computer with ferrite cores but also to a number of technological advances.
Since for purely engineering reasons it was not possible to construct a large-capacity ferrite memory unit with a high access speed, the digital computer used, and has used up to the present day, not only ferrite core memory units but also relatively slow-access peripheral, or auxiliary, memory units based on magnetic tapes, magnetic disks, and magnetic drums. The capacity of such units is limited, generally speaking, only by the amount of space they occupy.
The continuously growing complexity of the problems solved with digital computers required that the machines be made more complex and that the number of electronic elements be increased. These needs meant an increase in the size and power consumption of electron-tube machines. Despite engineering improvements, the electron tube remained the most unreliable element of the first-generation digital computer and slowed the further development of digital computer equipment.
In the mid-1950’s electron tubes were supplanted by semiconductor devices—that is, by diodes and transistors. Since the life of a semiconductor device is considerably longer than that of electron tubes, the adoption of the new basic elements substantially increased the reliability of digital computers and considerably reduced the size of the machines. The introduction of semiconductor digital elements marked the beginning of the second generation of electronic digital computers.
The evolution of computers has been accompanied by an increase in their speed. The speed of first-generation machines grew from several hundred operations per second to several tens of thousands of operations per second. The first transistorized machines had a speed of the order of 5,000 operations per second. Much higher speeds were subsequently obtained. For example, the CDC 7600 computer developed in the USA could perform 10–15 million operations per second.
Because of the way in which the computational process was organized in first-generation digital computers, however, further increases in the speed of such machines produced virtually no increase in productivity. A program was read into the computer for the solution of certain problems, and a new problem could not be introduced until the completion of the final solution and the output of the results of the computations. Every computational process, however, involves not only such fast operations as arithmetic operations and certain logical operations but also slow operations performed by mechanical devices—for example, the introduction of the input information into the machine, the printing of the results of the computations, and the transfer of information from the auxiliary memory to the main memory. As the speed of computers grew, the slow operations occupied an increasingly large part of the overall operating time of the machine. While the slow operations were carried out, the fast units of the machine, for example, the arithmetic unit, were idle. Thus, improvements affecting only the electronic elements did not result in significant increases in the productivity of digital computers.
The 1960’s consequently saw a fundamental change in the structure of digital computers. Machines were constructed in which the various units were capable of working independently of one another according to different programs. This advance permitted the machine to handle several jobs simultaneously (seeMULTIPROGRAMMING). For example, while a slow operation, which may last several seconds, is being performed, the arithmetic unit has time to solve not one but several problems. The most efficient modern digital computers can handle several dozen tasks at the same time. The work of the digital computer and the formation of the job stream are controlled by a special program known as the operating system. Multiprogramming operation does not increase the speed at which a specific problem is solved but substantially raises the overall productivity of the computer.
The next stage in the development of multiprogramming operation was the construction of shared-access computers (seeCOMPUTER NETWORK). The input of jobs to such a machine need not be from a single input device; there may be many such devices, and they need not be located in the same place as the computer. Each user of the machine has his own terminal, which includes an input device and an output device. The terminal may be at a considerable distance from the computer. Jobs are transmitted from the terminals along communication lines, usually telephone lines, to the computer, which determines their order, that is, the time at which they are to be executed. The results of the computer’s work are sent back along the communication lines to the user’s terminal, whose output device may be a printer or a display unit (seeDATA DISPLAY).
The development of multiprogramming led to the creation of systems that joined together several shared-access digital computers having different levels of productivity. Such a system could serve tens or hundreds of users located in different cities and even in different countries. For digital computers to be used in this way, their functional capabilities had to be expanded, and, consequently, their structure had to be made more complex. Semiconductor elements no longer satisfied the requirements of digital computer development regarding size, energy consumption, cost, and reliability.
Second-generation digital computers were succeeded in the 1960’s by third-generation machines, which used integrated circuitry. The elementary building blocks of second-generation computers were constructed from individual components (such as diodes, transistors, capacitors, and resistors), which were connected through soldering. Although these building blocks were considerably smaller than the banks of electron tubes used in first-generation machines, their dimensions were substantial, reaching tens and even hundreds of cubic centimeters. Moreover, the soldering points were sources of frequent failure. The introduction of integrated circuitry permitted an increase in complexity of the building blocks of the digital computer without an increase in size. The first integrated circuits (IC) replaced a single block of a second-generation digital computer. The subsequent large-scale integrated circuits (LSI circuits) replaced several dozen integrated circuits. The packing density of microcircuitry has continued to grow.
Machines constructed with large-scale integrated circuits are sometimes classified as fourth-generation digital computers. Such a classification is not well-founded, since there is no clear boundary between small-scale and medium-scale integrated circuits, between medium-scale and large-scale integrated circuits, or between large-scale and ultralarge-scale integrated circuits. A considerably more important factor in the development of electronic digital computers has been the nature of the basic elements of the main memory. Instead of the ferrite core memory units of first-, second-, and third-generation computers, fourth-generation computers use as memory elements semiconductor devices fabricated by a technology similar to that for integrated circuits. Small-capacity models of such a memory were constructed and used in the early 1970’s as ultrahigh-access memory. The mid-1970’s saw a tendency to combine a semiconductor main memory with slower supplementary ferrite memory units.
The 1970’s were characterized by a polarization in digital computer technology. On the one hand, the use of shared-access computer systems led to the development of superpowerful machines with a speed of the order of several tens of millions of operations per second and with a large main memory. On the other hand, small machines known as minicomputers were developed for individual use, for the control of industrial processes, and for the processing of experimental data in research laboratories; these machines included table models and were of medium speed. Minicomputers can be connected through communication lines with powerful shared-access computer systems and thus can be used as terminals. The prefix “mini-” refers primarily to the size of the machine; the productivity of minicomputers is often greater than that of the most powerful first-generation machines. Since minicomputers can meet most of the needs of the individual user, and since complex jobs can be handled better by shared-access computer systems, the production of medium-capacity digital computers has dropped.
In the late 1960’s and early 1970’s superpowerful multiprocessors were developed. In such a machine several processors operate simultaneously, that is, in parallel. The advantage of multiprocessing systems for the simultaneous execution of multiple jobs is obvious. The presence in one computer system of several processors also permits, in principle, the execution of a single job to be broken up, since any real computational algorithm contains a number of branches that may be executed independently of one another. Multiprocessing thus considerably reduces the time required for the execution of a job. Multiprocessing systems using large-scale integrated circuitry should evidently be classified as fourth-generation machines.
Digital computers are finding increasing application in a variety of areas of human activity. In addition to the performance of complicated scientific and engineering calculations, their uses in the late 1970’s included the automated design and the automatic control of industrial processes, transportation systems, and complex experimental apparatus. Digital computers were used to perform economic computations in economic-statistical analysis, the compilation of demographic statistics, the construction of plans, operations research, bookkeeping, and inventory control. Other important uses included mathematical modeling in the “descriptive” sciences—for example, biology, medicine, geology, and sociology—and information storage for ready reference in science and technology, in traffic-control systems, and in libraries.
Digital computer
A device that processes numerical information; more generally, any device that manipulates symbolic information according to specified computational procedures. The term digital computer—or simply, computer—embraces calculators, computer workstations, control computers (controllers) for applications such as domestic appliances and industrial processes, data-processing systems, microcomputers, microcontrollers, multiprocessors, parallel computers, personal computers, network servers, and supercomputers. See Digital control, Microcomputer, Programmable controllers, Supercomputer
A digital computer is an electronic computing machine that uses the binary digits (bits) 0 and 1 to represent all forms of information internally in digital form. Every computer has a set of instructions that define the basic functions it can perform. Sequences of these instructions constitute machine-language programs that can be stored in the computer and used to tailor it to an essentially unlimited number of specialized applications. Calculators are small computers specialized for mathematical computations. General-purpose computers range from pocket-sized personal digital assistants (notepad computers), to medium-sized desktop computers (personal computers and workstations), to large, powerful computers that are shared by many users via a computer network. The vast majority of digital computers now in use are inexpensive, special-purpose microcontrollers that are embedded, often invisibly, in such devices as toys, consumer electronic equipment, and automobiles. See Bit, Computer programming, Embedded systems
The main data-processing elements of a computer reside in a small number of electronic integrated circuits (ICs) that form a microprocessor or central processing unit (CPU). Electronic technology allows a basic instruction such as “add two numbers” to be executed many millions of times per second. Other electronic devices are used for program and data storage (memory circuits) and for communication with external devices and human users (input-output circuits). Nonelectronic (magnetic, optical, and mechanical) devices also appear in computers. They are used to construct input-output devices such as keyboards, monitors (video screens), secondary memories, printers, sensors, and mechanical actuators.
Information is stored and processed by computers in fixed-sized units called words. Common word sizes are 8, 16, 32, and 64 bits. Four-bit words can be used to encode the first 16 integers. By increasing the word size, the number of different items that can be represented and their precision can be made as large as desired. A common word size in personal computers is 32 bits, which allows 232 = 4,294,967,296 distinct numbers to be represented.
Computer words can represent many different forms of information, not just numbers. For example, 8-bit words called characters or bytes are used to encode text symbols (the 10 decimal digits, the 52 upper- and lowercase letters of the English alphabet, and punctuation marks). A widely used code of this type is ASCII (American Standard Code for Information Interchange). Visual information can be reduced to black and white dots (pixels) corresponding to 0's and 1's. Audio information can be digitized by mapping a small element of sound into a binary word; for example, a compact disk (CD) uses several million 16-bit words to store an audio recording. Logical quantities encountered in reasoning or decision making can be captured by associating 1 with true and 0 with false. Hence, most forms of information are readily reduced to a common, numberlike binary format suitable for processing by computer.
Logic components
The operation of a digital computer can be viewed at various levels of abstraction, which are characterized by components of different complexity. These levels range from the low, transistor level seen by an electronic circuit designer to the high, system level seen by a computer user. A useful intermediate level is the logic level, where the basic components process individual bits. By using other basic components called gates, logic circuits can be constructed to perform many useful operations. See Logic circuitsSystem organization
An accumulator is a digital system that constitutes a simple processor capable of executing a few instructions. By introducing more data-processing circuits and registers, as well as control circuits for a larger set of instructions, a practical, general-purpose processor can be constructed. Such a processor forms the “brain” of every computer, and is referred to as its central processing unit. A CPU implemented on a single integrated-circuit chip is called a microprocessor.A typical computer program is too large to store in the CPU, so another component called the main memory is used to store a program's instructions and associated data while they are being executed (Fig. 1). Main memory consists of high-speed integrated circuits designed to allow storage and retrieval of information one word at a time. All words in main memory can be accessed with equal ease; hence this is also called a random-access memory (RAM).
A computer program is processed by loading it into main memory and then transferring its instructions and data one word (or a few words) at a time to the CPU for processing. Hence, there is a continual flow of instructions and data words between the CPU and its main memory. As millions of words must be transferred per second, a high-speed communication link is needed between the CPU and main memory. The system bus (Fig. 1) fills this role.
A computer has input-output (I/O) control circuits and buses to connect it to external input-output devices (also called peripherals). Typical input-output devices are a keyboard, which is an input device, and a printer, which is an output device. Because most computers need more storage space than main memory can supply, they also employ secondary memory units which form part of the computer's input-output subsystem. Common secondary memory devices are hard disk drives, flexible (floppy) disk drives, and magnetic tape units. Compared to main memory, secondary memories employ storage media (magnetic disks and tapes) that have higher capacity and lower cost. However, secondary memories are also significantly slower than main memory. See Computer peripheral devices, Computer storage technology
No explicit instructions are needed for input-output operations if input-output devices share with main memory the available memory addresses. This is known as memory-mapped input-output, and allows load and store instructions to be used to transfer data between the CPU and input-output devices. In general, a computer's instruction set should include a selection of instructions of the following three types: (1) Data-transfer instructions that move data unchanged between the CPU, main memory, and input-output devices. (2) Data-processing instructions that perform numerical operations such as add, subtract, multiply, and divide, as well as nonnumerical (logical) operations, such as not , and , exclusive-or , and shift . (3) Program-control instructions that can change the order in which instructions are executed, for example branch, branch-on-zero, call procedure, and return from procedure.
The instruction unit (I unit) of a CPU (Fig. 2), also called the program control unit, is responsible for fetching instructions from main memory, using the program counter as the instruction address register. The opcode of a newly fetched instruction I is placed in the instruction register. The opcode is then decoded to determine the sequence of actions required to execute I. These may include the loading or storing of data assigned to main memory, in which case the I unit computes all needed addresses and issues all needed control signals to the CPU and the system bus. Data are processed in the CPU's execution unit (E unit), also called the datapath, which contains a set of registers used for temporary storage of data operands, and an arithmetic logic unit (ALU), which contains the main data-processing circuits.
Performance measures
A simple indicator of a CPU's performance is the frequency f of its central timing signal (clock), measured in millions of clock signals issued per second or megahertz (MHz). The clock frequency depends on the integrated-circuit technology used; frequencies of several hundred megahertz are achievable with current technology. Each clock signal triggers execution of a basic instruction such as a fixed-point addition; hence, the time required to execute such an instruction (the clock cycle time) is 1/f microseconds. Complex instructions like multiplication or operations on floating-point numbers require several clock cycles to complete their execution. Another measure of CPU performance is the (average) instruction execution rate, measured in millions of instructions per second (MIPS).Instruction execution time is strongly affected by the time to move instructions or data between the CPU and main memory. The time required by the CPU to access a word in main memory is typically about five times longer than the CPU's clock cycle time. This disparity in speed has existed since the earliest computers despite efforts to develop memory circuits that would be fast enough to keep up with the fastest CPUs. Maximum performance requires the CPU to be supplied with a steady flow of instructions that need to be executed. This flow is disrupted by branch instructions, which account for 20% or more of the instructions in a typical program.
To deal with the foregoing issues, various performance-enhancing features have been incorporated into the design of computers. The communication bottleneck between the CPU and main memory is reduced by means of a cache, which is a special memory unit inserted between the two units. The cache is smaller than main memory but can be accessed more rapidly, and is often placed on the same integrated-circuit chip as the CPU. Its effect is to reduce the average time required by the CPU to send information to or receive information from the memory subsystem. Special logic circuits support the complex flow of information among main memory, the cache, and the registers of the CPU. However, the cache is largely invisible to the programs being executed.
The instruction execution rate can be increased by executing several instructions concurrently. One approach is to employ several E units that are tailored to different instruction types. Examples are an integer unit designed to execute fixed-point instructions and a floating-point unit designed for floating-point instructions. The CPU can then execute a fixed-point instruction and a floating-point instruction at the same time. Processors that execute several instructions in parallel in this way are called superscalar. See Concurrent processing
Another speedup technique called pipelining allows several instructions to be processed simultaneously in special circuits called pipelines. Execution of an instruction is broken into several consecutive steps, each of which can be assigned to a separate stage of the pipeline. This makes it possible for an n-stage E unit to overlap the execution of up to n different instructions. A pipeline processing circuit resembles an assembly line on which many products are in various stages of manufacture at the same time. The ability of a CPU to execute several instructions at the same time by using multiple or pipelined E units is highly dependent on the availability of instructions of the right type at the right time in the program being executed. A useful measure of the performance of a CPU that employs internal parallelism is the average number of clock cycles per instruction (CPI) needed to execute a representative set of programs.
CISCs and RISCs
A software implementation of a complex operation like multiply is slower than the corresponding hardware implementation. Consequently, as advances in IC technology lowered the cost of hardware circuits, instruction sets tended to increase in size and complexity. By the mid-1980s, many microprocessors had instructions of several hundred different types, characterized by diverse formats, memory addressing modes, and execution times. The heterogeneous instruction sets of these complex instruction set computers (CISCs) have some disadvantages. Complex instructions require more processing circuits, which tend to make CISCs large and expensive. Moreover, the decoding and execution of complex instruction can slow down the processing of simple instructions.To address the defects of CISCs, a new class of fast computers referred to as reduced instruction set computers (RISCs) was introduced. RISCs are characterized by fast, efficient—but not necessarily small—instruction sets. The following features are common to most RISCs: (1) All instructions are of fixed length and have just a few opcode formats and addressing modes. (2) The only instructions that address memory are load and store instructions; all other instructions require their operands to be placed in CPU registers. (3) The fetching and processing of most instructions is overlapped in pipelined fashion.
digital computer
A computer that accepts and processes data that has been converted into binary numbers. Most computers are digital. Contrast with analog computerXXX . VX0 OUT BUREAU ; MICROELECTRONICS
Novices in electronics usually think that the microcontroller is the same as the microprocessor. That's not true. They differ from each other in many ways. The first and most important difference in favour of the microcontroller is its functionality. In order for the microprocessor to be used, other components, first of all memory, must be added to it. Even though it is considered a powerful computing machine, it is not capable of establishing direct communication with the peripherals. Instead, specialized circuits must be used for this purpose. This is how it was in the beginning and remains the same today.
ALL THE MICROCONTROLLER IS CAPABLE OF
Microcontrollers are very popular nowadays. Just pay attention to the example below and you will understand the reasons for their great success. It won't take up much of your time, just a couple of minutes. Around ten years ago, the process of designing an electronic device controlling an elevator in a multistory building was extremely difficult, even for a team of experts. Have you ever thought of what requirements an ordinary elevator has to meet? How to deal with situation when two or more people call the same elevator at the same time? Which call has the priority? How to handle the security questions? Loss of electricity? Operation failure? Misuse? After solving these basic questions, a tough process of designing an appropriate electronics using a large number of special-purpose chips comes next. Depending on the device complexity, such process can take weeks, even months. Then it's time to make a printed circuit board and assemble device. A huge device! It is another long-lasting and trying work. Finally, when your device is finished and tested many times, the crucial moment comes. The moment when you take a deep breath and switch the power supply on. The party is over at this point as electronic devices almost never start to operate immediately. Get ready for many sleepless nights, corrections, improvements... and don't forget, we are still talking about running an ordinary elevator. When your device finally works perfectly and everybody is satisfied and you get paid for the work you have done, other constructing companies will become interested in your work. Of course, if you are lucky, another day will bring you a locking offer from a new investor. A new building has four stories more. You know what it is all about? You think you can control destiny? You are going to make a universal device which can be used in buildings of 4 to 40 stories, a masterpiece of electronics? Even if you manage to make such an electronic jewel, your investor will wait in front of your door asking for a camera in the elevator. Or for relaxing music in case of elevator failure. Or for a two-door elevator. Anyway, Murphy's law is inexorable and you will certainly not be able to make advantage of all the effort you have made. Unfortunately, everything said so far is true. This is what 'handling electronics' really means. No, no, wait, let us correct ourselves, this is how it was until the first microcontrollers were designed - small, powerful and cheap devices. Since the moment their programming stopped being a science, everything went in another direction... Electronics capable of controlling a small submarine, a crane or an elevator are now built into one single chip. Microcontrollers offer a wide range of applications, but only a few of them are normally used. It's up to you to decide what you want from the microcontroller and dump a program accordingly containing appropriate instructions into it. Prior to turning the device on, its operation should be tested by simulation. If everything works fine, build the microcontroller into your device. If you ever need to change, improve or upgrade the program, just do it. Until when? Until you feel satisfied. That's all.GO REVERSE LAPTOP
Before businesses recycle old laptops, here are some things that could be removed and salvaged for future use. Do You Know What’s on the Inside of Your Laptop? Take a Look from the Inside of a Laptop Sent for E-Recycling—and the Parts You Could Still Keep, or Get for Upgrading or Building Your Own. Laptops are created from an interesting collection of parts, many of which can be reused when the laptop itself has become outdated and is headed for the land of e-recycling. To keep hazardous materials out of landfills these devices must be properly dismantled and parts sorted for e-recycling.Depending on the age and life of device, some material may be worth holding on to as a backup for other machines?
Here is a look inside a laptop, and some of the parts that might be worth keeping—or buying to build your own.
The Battery
Most laptop batteries are unique to one model and can be expensive to replace. If your battery still has some life to it, you may be able to reuse it within your organization. If not, or you’re not sure if it’s good, don’t remove it, keep it on your device for recycling.
Power Supply
Since the power supply connector changes with almost every model, you won’t likely need an old power supply again once that laptop is broken or recycled, but someone else with the same model computer, may want it. If the power supply is broken or not useable, you could keep the power cable. It may fit into another power supply or device. If not, this accessory can be recycled, too.
RAM
Memory sticks (RAM) are usually easy to remove. A large variety of RAM exists with differences in storage capacity (gigabytes), clock speed (MHz), and shape (DDR2, DDR3). Since memory technology changes infrequently, you might have other devices that can use the old laptop’s RAM.
Hard Drive
An old hard drive is removable and can be used to store non-essential data, for example movies or music. However, hard drives store important data, and often times corporations or organizations will want these units completely destroyed, or wiped clean of it’s data. If that’s the case organizations can remove these for destruction.
CMOS Battery
This little coin-shaped battery sits on the motherboard and powers low-level system functions while the laptop is turned off. These batteries are used on all computer motherboards and in many other devices and are worth keeping. Store it in a cool, dark, and dry place.
Display
The display screen is one of the most valuable parts of your laptop, provided it’s still in a nice condition. It’s also one of the parts that can be tough to remove. Be extra careful when removing or shipping it, it’s extremely fragile.
CPU (Central Processing Unit)
In terms of value, your laptop’s CPU is up there with the display. It’s more of a tricky part to remove, generally you must remove the passive cooling system first that sits on top of it. Be careful when disassembling the cooling system and removing the CPU. Try not to touch the CPU’s pins, but instead hold the unit around the edges.
Other Parts
There are many more parts that you might be able to extract and play with, including the keyboard, touchpad, webcam, card reader, WIFI card, SD memory card reader or fingerprint reader.
Leftovers
Other parts will be left over that you cannot re-use or sell. These may include the additional batteries, power supply, display, the motherboard, or the plastic casing of the entire laptop. Please don’t simply trash what’s left of your laptop. If you do disassemble a laptop and remove any of the above assets, whatever is left of it still contains valuable resources that can be recovered in a recycling process.
As a caution, don’t begin to take apart your laptop just because it no longer turns on. Either you or someone more experienced in computer repair should first try to troubleshoot the problem. It may turn out that your computer still has years of life left in it. And, when recycling, as with any electronic, if you start to remove the parts and pieces your dive is considered scrap instead of a whole unit.
Building Your Own
You can get laptop adaptors, Wi-Fi cards, docking stations, optical drives, keyboards, memory and other materials to replace or build your own system. These parts are usually available for a discounted from resellers and some electronic recyclers.
Southeastern Data has a store where you can find such items. You can get old, new and hard to find computer and electronic parts to build, replace or upgrade your computers and electronics, and even recycle your non-working and older parts. Each week you have access to different types of computers and electronics—parts and whole units—since their inventory constantly changes. A computer part or electronic that may not be there one week, could show up the next.
To save money, and find that computer parts and components such as: extra memory, Wi-Fi card and other material, it’s best to stop by their online store weekly. You can even buy full working laptops, networking gear and a wide range of electronics devices.
Here is some of the inventory I found available this week for Laptops in the Southeastern Data online store:
What is a computer?
A computer is an electronic device that manipulates information, or data. It has the ability to store, retrieve, and process data. You may already know that you can use a computer to type documents, send email, play games, and browse the Web. You can also use it to edit or create spreadsheets, presentations, and even videos.
Watch the video below to learn about different types of computers.
Hardware vs. software
Before we talk about different types of computers, let's talk about two things all computers have in common: hardware and software.- Hardware is any part of your computer that has a physical structure, such as the keyboard or mouse. It also includes all of the computer's internal parts, which you can see in the image below.
- Software is any set of instructions that tells the hardware what to do and how to do it. Examples of software include web browsers, games, and word processors. Below, you can see an image of Microsoft PowerPoint, which is used to create presentations.
Everything you do on your computer will rely on both hardware and software. For example, right now you may be viewing this lesson in a web browser (software) and using your mouse (hardware) to click from page to page. As you learn about different types of computers, ask yourself about the differences in their hardware. As you progress through this tutorial, you'll see that different types of computers also often use different types of software.
What are the different types of computers?
When most people hear the word computer, they think of a personal computer such as a desktop or laptop. However, computers come in many shapes and sizes, and they perform many different functions in our daily lives. When you withdraw cash from an ATM, scan groceries at the store, or use a calculator, you're using a type of computer.Desktop computers
Laptop computers
Tablet computers
Servers
Other types of computers
Many of today's electronics are basically specialized computers, though we don't always think of them that way. Here are a few common examples.- Smartphones: Many cell phones can do a lot of things computers can do, including browsing the Internet and playing games. They are often called smartphones.
- Wearables: Wearable technology is a general term for a group of devices—including fitness trackers and smartwatches—that are designed to be worn throughout the day. These devices are often called wearables for short.
- Game consoles: A game console is a specialized type of computer that is used for playing video games on your TV.
- TVs: Many TVs now include applications—or apps—that let you access various types of online content. For example, you can stream video from the Internet directly onto your TV.
PCs and Macs
Personal computers come in two main styles: PC and Mac. Both are fully functional, but they have a different look and feel, and many people prefer one or the other.PCs
Macs
Introduction
The basic parts of a desktop computer are the computer case, monitor, keyboard, mouse, and power cord. Each part plays an important role whenever you use a computer.
Watch the video below to learn about the basic parts of a desktop computer.
Computer case
Computer cases come in different shapes and sizes. A desktop case lies flat on a desk, and the monitor usually sits on top of it. A tower case is tall and sits next to the monitor or on the floor. All-in-one computers come with the internal components built into the monitor, which eliminates the need for a separate case.
Monitor
Newer monitors usually have LCD (liquid crystal display) or LED (light-emitting diode) displays. These can be made very thin, and they are often called flat-panel displays. Older monitors use CRT (cathode ray tube) displays. CRT monitors are much larger and heavier, and they take up more desk space.
Keyboard
The keyboard is one of the main ways to communicate with a computer. There are many different types of keyboards, but most are very similar and allow you to accomplish the same basic tasks.
Click the buttons in the interactive below to learn about the different parts of the keyboard.
edit hotspotsedit hotspotsedit hotspots
If you want to learn how to type or improve your touch-typing skills, check out our free Typing Tutorial.
Mouse
There are two main mouse types: optical and mechanical. The optical mouse uses an electronic eye to detect movement and is easier to clean. The mechanical mouse uses a rolling ball to detect movement and requires regular cleaning to work properly.
To learn the basics of using a mouse, check out our interactive Mouse Tutorial.
Mouse alternatives
There are other devices that can do the same thing as a mouse. Many people find them easier to use, and they also require less desk space than a traditional mouse. The most common mouse alternatives are below.- Trackball: A trackball has a ball that can rotate freely. Instead of moving the device like a mouse, you can roll the ball with your thumb to move the pointer.
- Touchpad: A touchpad—also called a trackpad—is a touch-sensitive pad that lets you control the pointer by making a drawing motion with your finger. Touchpads are common on laptop computers.
Introduction
Take a look at the front and back of your computer case and count the number of buttons, ports, and slots you see. Now look at your monitor and count any you find there. You probably counted at least 10, and maybe a lot more.Each computer is different, so the buttons, ports, and sockets will vary from computer to computer. However, there are certain ones you can expect to find on most desktop computers. Learning how these ports are used will help whenever you need to connect something to your computer, like a new printer, keyboard, or mouse.
Watch the video below to learn about the buttons, ports, and slots on a desktop computer.
Front of a computer case
Click the buttons in the interactive below to become familiar with the front of a computer.
edit hotspotsedit hotspots
Back of a computer case
The back of a computer case has connection ports that are made to fit specific devices. The placement will vary from computer to computer, and many companies have their own special connectors for specific devices. Some of the ports may be color coded to help you determine which port is used with a particular device.Other types of ports
There are many other types of ports, such as FireWire, Thunderbolt, and HDMI. If your computer has ports you don't recognize, you should consult your manual for more information.
Now you try it! Practice connecting the cables with the interactive game below.
Peripherals you can use with your computer
The most basic computer setup usually includes the computer case, monitor, keyboard, and mouse, but you can plug many different types of devices into the extra ports on your computer. These devices are called peripherals. Let's take a look at some of the most common ones.- Printers: A printer is used to print documents, photos, and anything else that appears on your screen. There are many types of printers, including inkjet, laser, and photo printers. There are even all-in-one printers, which can also scan and copy documents.
- Scanners: A scanner allows you to copy a physical image or document and save it to your computer as a digital (computer-readable) image. Many scanners are included as part of an all-in-one printer, although you can also buy a separate flatbed or handheld scanner.
- Speakers/headphones: Speakers and headphones are output devices, which means they send information from the computer to the user—in this case, they allow you to hear sound and music. Depending on the model, they may connect to the audio port or the USB port. Some monitors also have built-in speakers.
- Microphones: A microphone is a type of input device, or a device that receives information from a user. You can connect a microphone to record sound or talk with someone else over the Internet. Many laptop computers come with built-in microphones.
- Web cameras: A web camera—or webcam—is a type of input device that can record videos and take pictures. It can also transmit video over the Internet in real time, which allows for video chat or video conferencing with someone else. Many webcams also include a microphone for this reason.
- Game controllers and joysticks: A game controller is used to control computer games. There are many other types of controllers you can use, including joysticks, although you can also use your mouse and keyboard to control most games.
- Digital cameras: A digital camera lets you capture pictures and videos in a digital format. By connecting the camera to your computer's USB port, you can transfer the images from the camera to the computer.
- Mobile phones, MP3 players, tablet computers, and other devices: Whenever you buy an electronic device, such as a mobile phone or MP3 player, check to see if it comes with a USB cable. If it does, this means you can most likely connect it to your computer.
Inside a computer
Have you ever looked inside a computer case, or seen pictures of the inside of one? The small parts may look complicated, but the inside of a computer case isn't really all that mysterious. This lesson will help you master some of the basic terminology and understand a bit more about what goes on inside a computer.
Watch the video below to learn about what's inside a desktop computer.
Motherboard
CPU/processor
The central processing unit (CPU), also called a processor, is located inside the computer case on the motherboard. It is sometimes called the brain of the computer, and its job is to carry out commands. Whenever you press a key, click the mouse, or start an application, you're sending instructions to the CPU.
The CPU is usually a two-inch ceramic square with a silicon chip located inside. The chip is usually about the size of a thumbnail. The CPU fits into the motherboard's CPU socket, which is covered by the heat sink, an object that absorbs heat from the CPU.
A processor's speed is measured in megahertz (MHz), or millions of instructions per second; and gigahertz (GHz), or billions of instructions per second. A faster processor can execute instructions more quickly. However, the actual speed of the computer depends on the speed of many different components—not just the processor.
RAM (random access memory)
This short-term memory disappears when the computer is turned off. If you're working on a document, spreadsheet, or other type of file, you'll need to save it to avoid losing it. When you save a file, the data is written to the hard drive, which acts as long-term storage.
RAM is measured in megabytes (MB) or gigabytes (GB). The more RAM you have, the more things your computer can do at the same time. If you don't have enough RAM, you may notice that your computer is sluggish when you have several programs open. Because of this, many people add extra RAM to their computers to improve performance.
Hard drive
When you run a program or open a file, the computer copies some of the data from the hard drive onto the RAM. When you save a file, the data is copied back to the hard drive. The faster the hard drive, the faster your computer can start up and load programs.
Power supply unit
If you decide to open the computer case and take a look, make sure to unplug the computer first. Before touching the inside of the computer, you should touch a grounded metal object—or a metal part of the computer casing—to discharge any static buildup. Static electricity can be transmitted through the computer circuits, which can seriously damage your machine.
Expansion cards
Most computers have expansion slots on the motherboard that allow you to add various types of expansion cards. These are sometimes called PCI (peripheral component interconnect) cards. You may never need to add any PCI cards because most motherboards have built-in video, sound, network, and other capabilities.However, if you want to boost the performance of your computer or update the capabilities of an older computer, you can always add one or more cards. Below are some of the most common types of expansion cards.
Video card
Sound card
The sound card—also called an audio card—is responsible for what you hear in the speakers or headphones. Most motherboards have integrated sound, but you can upgrade to a dedicated sound card for higher-quality sound.Network card
Bluetooth card (or adapter)
What is a laptop computer?
A laptop is a personal computer that can be easily moved and used in a variety of locations. Most laptops are designed to have all of the functionality of a desktop computer, which means they can generally run the same software and open the same types of files. However, laptops also tend to be more expensive than comparable desktop computers.
Watch the video below to learn about laptop computers.
How is a laptop different from a desktop?
Because laptops are designed for portability, there are some important differences between them and desktop computers. A laptop has an all-in-one design, with a built-in monitor, keyboard, touchpad (which replaces the mouse), and speakers. This means it is fully functional, even when no peripherals are connected. A laptop is also quicker to set up, and there are fewer cables to get in the way.You'll also have to the option to connect a regular mouse, larger monitor, and other peripherals. This basically turns your laptop into a desktop computer, with one main difference: You can easily disconnect the peripherals and take the laptop with you wherever you go.
Here are the main differences you can expect with a laptop.
- Touchpad: A touchpad—also called a trackpad—is a touch-sensitive pad that lets you control the pointer by making a drawing motion with your finger.
- Battery: Every laptop has a battery, which allows you to use the laptop when it's not plugged in. Whenever you plug in the laptop, the battery recharges. Another benefit of having a battery is that it can provide backup power to the laptop if the power goes out.
- AC adapter: A laptop usually has a specialized power cable called an AC adapter, which is designed to be used with that specific type of laptop.
- Ports: Most laptops have the same types of ports found on desktop computers (such as USB), although they usually have fewer ports to save space. However, some ports may be different, and you may need an adapter in order to use them.
- Price: Generally speaking, laptops tend to be more expensive than a desktop computer with the same internal components. While you may find that some basic laptops cost less than desktop computers, these are usually much less powerful machines.
What is a mobile device?
A mobile device is a general term for any type of handheld computer. These devices are designed to be extremely portable, and they can often fit in your hand. Some mobile devices—like tablets, e-readers, and smartphones—are powerful enough to do many of the same things you can do with a desktop or laptop computer.Tablet computers
Like laptops, tablet computers are designed to be portable. However, they provide a different computing experience. The most obvious difference is that tablet computers don't have keyboards or touchpads. Instead, the entire screen is touch-sensitive, allowing you to type on a virtual keyboard and use your finger as a mouse pointer.E-readers
E-book readers—also called e-readers—are similar to tablet computers, except they are mainly designed for reading e-books (digital, downloadable books). Notable examples include the Amazon Kindle, Barnes & Noble Nook, and Kobo. Most e-readers use an e-ink display, which is easier to read than a traditional computer display. You can even read in bright sunlight, just like if you were reading a regular book.
You don't need an e-reader to read e-books. They can also be read on tablets, smartphones, laptops, and desktops.
Smartphones
A smartphone is a more powerful version of a traditional cell phone. In addition to the same basic features—phone calls, voicemail, text messaging—smartphones can connect to the Internet over Wi-Fi or a cellular network (which requires purchasing a monthly data plan). This means you can use a smartphone for the same things you would normally do on a computer, such as checking your email, browsing the Web, or shopping online.What is an operating system?
An operating system is the most important software that runs on a computer. It manages the computer's memory and processes, as well as all of its software and hardware. It also allows you to communicate with the computer without knowing how to speak the computer's language. Without an operating system, a computer is useless.
Watch the video below to learn more about operating systems.
The operating system's job
Your computer's operating system (OS) manages all of the software and hardware on the computer. Most of the time, there are several different computer programs running at the same time, and they all need to access your computer's central processing unit (CPU), memory, and storage. The operating system coordinates all of this to make sure each program gets what it needs.Types of operating systems
Operating systems usually come pre-loaded on any computer you buy. Most people use the operating system that comes with their computer, but it's possible to upgrade or even change operating systems. The three most common operating systems for personal computers are Microsoft Windows, Mac OS X, and Linux.Modern operating systems use a graphical user interface, or GUI (pronounced gooey). A GUI lets you use your mouse to click icons, buttons, and menus, and everything is clearly displayed on the screen using a combination of graphics and text.
Microsoft Windows
Microsoft created the Windows operating system in the mid-1980s. Over the years, there have been many different versions of Windows, but the most recent ones are Windows 10 (released in 2015), Windows 8 (2012), Windows 7 (2009), and Windows Vista (2007). Windows comes pre-loaded on most new PCs, which helps to make it the most popular operating system in the world.
Check out our tutorials on Windows Basics and specific Windows versions for more information.
Mac OS X
Mac OS is a line of operating systems created by Apple. It comes preloaded on all new Macintosh computers, or Macs. All of the recent versions are known as OS X (pronounced O-S Ten), and the specific versions include El Capitan (released in 2015), Yosemite (2014), Mavericks (2013), Mountain Lion (2012), and Lion (2011).According to StatCounter Global Stats, Mac OS X users account for less than 10% of global operating systems—much lower than the percentage of Windows users (more than 80%). One reason for this is that Apple computers tend to be more expensive. However, many people do prefer the look and feel of Mac OS X over Windows.
Linux
Linux (pronounced LINN-ux) is a family of open-source operating systems, which means they can be modified and distributed by anyone around the world. This is different from proprietary software like Windows, which can only be modified by the company that owns it. The advantages of Linux are that it is free, and there are many different distributions—or versions—you can choose from.According to StatCounter Global Stats, Linux users account for less than 2% of global operating systems. However, most servers run Linux because it's relatively easy to customize.
To learn more about different distributions of Linux, visit the Ubuntu, Linux Mint, and Fedora websites, or refer to our Linux Mint Resources. For a more comprehensive list, you can visit MakeUseOf's list of The Best Linux Distributions.
Operating systems for mobile devices
The operating systems we've been talking about so far were designed to run on desktop and laptop computers. Mobile devices such as phones, tablet computers, and MP3 players are different from desktop and laptop computers, so they run operating systems that are designed specifically for mobile devices. Examples of mobile operating systems include Apple iOS and Google Android. In the screenshot below, you can see iOS running on an iPad.What is an application?
You may have heard people talking about using a program, an application, or an app. But what exactly does that mean? Simply put, an app is a type of software that allows you to perform specific tasks. Applications for desktop or laptop computers are sometimes called desktop applications, while those for mobile devices are called mobile apps.When you open an application, it runs inside the operating system until you close it. Most of the time, you will have more than one application open at the same time, which is known as multi-tasking.
Watch the video below to learn more about applications.
App is a common term for an application, especially for simple applications that can be downloaded inexpensively or even for free. Many apps are also available for mobile devices and even some TVs.
Desktop applications
There are countless desktop applications, and they fall into several categories. Some are more full featured (like Microsoft Word), while others may only do one or two things (like a clock or calendar app). Below are just a few types of applications you might use.- Word processors: A word processor allows you to write a letter, design a flyer, and create many other types of documents. The most well-known word processor is Microsoft Word.
- Web browsers: A web browser is the tool you use to access the Internet. Most computers come with a web browser pre-installed, but you can also download a different one if you prefer. Examples of browsers include Internet Explorer, Mozilla Firefox, Google Chrome, and Safari.
- Media players: If you want to listen to MP3s or watch movies you've downloaded, you'll need to use a media player. Windows Media Player and iTunes are popular media players.
- Games: There are many types of games you can play on your computer. They range from card games like Solitaire to action games like Halo. Many action games require a lot of computing power, so they may not work unless you have a newer computer.
Mobile apps
Desktop and laptop computers aren't the only devices that can run applications. You can also download apps for mobile devices like smartphones and tablets. Here are a few examples of mobile apps.- Gmail: You can use the Gmail app to easily view and send emails from your mobile device. It's available for Android and iOS devices.
- Instagram: You can use Instagram to quickly share photos with your friends and family. It's available for Android and iOS.
- Duolingo: With a combination of quizzes, games, and other activities, this app can help you learn new languages. It's available for Android and iOS.
Installing new applications
Every computer and mobile device will come with some applications already built in, such as a web browser and media player. However, you can also purchase and install new apps to add more functionalitySetting up a computer
So you have a new computer and you're ready to set it up. This may seem like an overwhelming and complicated task, but it's actually a lot easier than you might think! Most computers are set up in a similar way, so it doesn't matter what brand of computer you have.If you're setting up a new computer that's still in the box, you'll probably find a how-to guide that includes step-by-step details. Even if it didn't include instructions, you can still set up the computer in a few easy steps. We'll take you through the different steps needed to set up a typical computer.
Setting up a laptop computer
If you have a laptop, setup should be easy: Just open it and press the power button. If the battery isn't charged, you'll need to plug in the AC adapter. You can continue using the laptop while it charges.Setting up a desktop computer
Step 1
Unpack the monitor and computer case from the box. Remove any plastic covering or protective tape. Place the monitor and computer case on a desk or work area.Step 2
Locate the monitor cable. There are several types of monitor cables, so the one for your computer may not look like the one in the image below.Step 3
Connect one end of the cable to the monitor port on the back of the computer case and the other end to the monitor. If you're using a VGA cable like the one in the picture below, you'll want to tighten the screws on the monitor cable to secure it.
Many computer cables will only fit a specific way. If the cable doesn't fit, don't force it or you might damage the connectors. Make sure the plug aligns with the port, then connect it.
To figure out which cables belong in which ports, try our Connecting Cables interactive.
Step 4
Unpack the keyboard and determine whether it uses a USB (rectangular) connector or a PS/2 (round) connector. If it uses a USB connector, plug it into any of the USB ports on the back of the computer. If it uses a PS/2 connector, plug it into the purple keyboard port on the back of the computer.Step 5
Unpack the mouse and determine whether it uses a USB or PS/2 connector. If it uses a USB connector, plug it into any of the USB ports on the back of the computer. If it uses a PS/2 connector, plug it into the green mouse port on the back of the computer.
If your keyboard has a USB port, you can connect your mouse to the keyboard instead of connecting it directly to your computer.
If you have a wireless mouse or keyboard, you may need to connect a Bluetooth dongle (USB adapter) to your computer. However, many computers have built-in Bluetooth, so an adapter may not be necessary.
Step 6
If you have external speakers or headphones, you can connect them to your computer's audio port (either on the front or back of the computer case). Many computers have color-coded ports. Speakers or headphones connect to the green port, and microphones connect to the pink port. The blue port is the line in, which can be used with other types of devices.Step 7
Locate the two power supply cables that came with your computer. Plug the first power supply cable into the back of the computer case and then into a surge protector. Then, using the other cable, connect the monitor to the surge protector.
You can also use an uninterruptable power supply (UPS), which acts as a surge protector and provides temporary power if there is a power outage.
Step 8
Finally, plug the surge protector into a wall outlet. You may also need to turn on the surge protector if it has a power switch.
If you don't have a surge protector, you can plug the computer directly into the wall. However, this is not recommended because electrical surges can damage your computer.
Step 9
If you have a printer, scanner, webcam, or other peripherals, you can connect them at this point. Many peripherals are plug and play, which means they will be recognized by your computer as soon as they are plugged in.
Generally, peripherals are optional, and you can add new ones at any time; you don't have to add all peripherals during the initial setup of your computer.
Getting started with your first computer
A computer is more than just another household appliance. The vast amount of information and possibilities can be overwhelming. But you can accomplish a lot with a computer, and using one can be a good experience. Let's walk through getting started with your first computer.
Turning on a computer for the first time can be different from one computer to the next. Your experience could be different from this lesson. It's OK to ask someone for help.
If you're using a desktop computer, you'll need to make sure that the keyboard, mouse, and monitor are plugged into the computer case before you continue. Review our lesson on Setting Up a Computer to learn how.Turning on a computer
The very first step is to turn on the computer. To do this, locate and press the power button. It's in a different place on every computer, but it will have the universal power button symbol (shown below).Once the computer has booted up, it may be ready to use, or it may require you to log in. This means identifying yourself by typing your user name or selecting your profile, then typing your password. If you've never logged in to your computer before, you may need to create an account.
The keyboard and mouse
You interact with a computer mainly by using the keyboard and mouse, or a trackpad on laptops. Learning to use these devices is essential to learning to use a computer. Most people find it comfortable to place the keyboard on the desk directly in front of them and the mouse to one side of the keyboard.
Note that the mouse pointer is also called a cursor, but it is shaped differently. The keyboard cursor is also called the insertion point.
Using a computer
The main screen you'll start from is the desktop. This is sort of like a main menu or a table of contents. From here, you can access the programs and features you need to use your computer.Icons are used to represent the different files, applications, and commands on your computer. An icon is a small image that's intended to give you an idea at a glance of what it represents, like a logo. Double-clicking an icon on the desktop will open that application or file.
Getting to know your computer's OS
Now that you know the absolute basics of using a computer, it's time to learn more about your computer's operating system. We'll be talking about the two most common operating systems in this lesson: Microsoft Windows and Mac OS X.Getting to know the interface
Both PCs and Macs use a graphical user interface (GUI), and they each have their own look and feel. The interactives below will introduce you to the Windows and Mac interfaces.
Click the buttons in the interactive below to learn more about the Windows interface.
edit hotspots
Click the buttons in the interactive below to learn more about the Mac OS X interface.
edit hotspots
If you have difficulty seeing or hearing—or if you have trouble manipulating the mouse or keyboard—there are many settings that can help make your computer easier to use. To learn more, check out our lesson on Using Accessibility Features.
All about your computer's file system
No matter which operating system you use, your computer uses folders to organize all of the different files and applications it contains. Folder icons on your computer are designed to look like file folders full of documents or pictures.
To find out more about file systems on Macs, check out the lesson on Working with Files in our OS X Basics tutorial. To learn more about PC file systems, take a look at the Working with Files lesson in our Windows Basics tutorial.
Opening your computer's file system
Whether you're using a PC or a Mac, the file system icon will be in the bottom-left part of the screen. On a PC, the File Explorer icon looks like a folder, as in the image below.Basic navigation
Whether you're using Windows Explorer or Finder, basic navigation will work the same way. If you see the file you want, you can double-click it with your mouse. Otherwise, you can use the Navigation pane on the left side of the window to select a different location.Deleting files
OS X and Windows use a Trash can—or Recycle Bin—to prevent you from accidentally deleting files. When you delete a file, it is moved to the Trash can. If you change your mind, you can move the file back to its original location.Opening files and applications
Each application on your computer has a group of file types—or formats—it is able to open. When you double-click a file, your computer will automatically use the correct application to open it. In our example, we're opening a Microsoft Word document (Chicago Trip Details), which will open in Microsoft Word.- To open an application in Windows, click the Start button, then select the desired application. If you don't see the one you want, you can click All Programs/All Apps to see a full list, or simply type the name of the application on your keyboard to search for it. In the example below, we're opening Internet Explorer.
- To open an application on a Mac, click the application's icon on the Dock. If you don't see the one you want, click the Spotlight icon in the top-right corner of the screen, then type the name of the application on your keyboard to search for it. In the example below, we're opening Safari.
Adjusting your computer's settings
When you start using a new computer, you may want to begin by adjusting the computer's settings. Adjusting your settings can range from simple tasks such as changing your desktop background to more advanced tasks like adjusting your security or keyboard settings.- In Windows 10, click the Start button, then select Settings.
- In Windows 8.1 and earlier, click the Start button, then locate and select the Control Panel. Check out the Adjusting Your Settings lesson in our Windows Basics tutorial to learn more about the Control Panel.
- On a Mac, click the Apple icon, then select System Preferences. Check out our Adjusting Your Settings lesson in our OS X Basics tutorial to learn more about System Preferences.
Shutting down your computer
When you're done using your computer, it's important to shut it down properly.- To shut down Windows, click the Start button, then select Shut down (in some versions, this may say Turn Off Computer or look like the power symbol).
- To shut down a Mac, click the Apple icon, then select Shut Down.
How do I connect to the Internet?
Once you've set up your computer, you may want to purchase home Internet access so you can send and receive email, browse the Web, stream videos, and more. You may even want to set up a home wireless network, commonly known as Wi-Fi, so you can connect multiple devices to the Internet at the same time.
XXX . VX00 OUT BUREAU ; COMPUTER PROGRAMMING ON ELECTRONIC SYSTEM
Computer programming is the act of writing computer programs, which are a sequence of instructions written using a Computer Programming Language to perform a specified task by the computer. Computer Programming is fun and easy to learn provided you adopt a proper approach. This tutorial attempts to cover the basics of computer programming using a simple and practical approach for the benefit of novice learners.
Audience
This tutorial has been prepared for the beginners who are willing to learn computer programming but they are unable to learn it due to lack of proper guidance. We are confident that after completing this tutorial, you will be at a level where you can code in C Programming language and will have a basic understanding of Java and Python programming languages as well from where you can continue further.If you are completely new to Computer Programming, then we recommend you to read this tutorial twice or even thrice. First reading will not give you much idea, but during your second reading, you will start grasping most of the concepts and you will enjoy writing computer programs.
Prerequisites
We do not expect much from you as prerequisites, however, we assume that you have some amount of exposure to computers and its peripherals like keyboard, mouse, screen, printer, etc.Introduction to Computer Program
Before getting into computer programming, let us first understand computer programs and what they do.
A computer program is a sequence of instructions written using a Computer Programming Language to perform a specified task by the computer.
The two important terms that we have used in the above definition are −- Sequence of instructions
- Computer Programming Language
You will use Human Language to tell the way to go to KFC, something as follows −
First go straight, after half kilometer, take left from the red light and then drive around one kilometer and you will find KFC at the right.Here, you have used English Language to give several steps to be taken to reach KFC. If they are followed in the following sequence, then you will reach KFC −
1. Go straight 2. Drive half kilometer 3. Take left 4. Drive around one kilometer 5. Search for KFC at your right sideNow, try to map the situation with a computer program. The above sequence of instructions is actually a Human Program written in English Language, which instructs on how to reach KFC from a given starting point. This same sequence could have been given in Spanish, Hindi, Arabic, or any other human language, provided the person seeking direction knows any of these languages.
Now, let's go back and try to understand a computer program, which is a sequence of instructions written in a Computer Language to perform a specified task by the computer. Following is a simple program written in Python programming Language −
print "Hello, World!"The above computer program instructs the computer to print "Hello, World!" on the computer screen.
- A computer program is also called a computer software, which can range from two lines to millions of lines of instructions.
- Computer program instructions are also called program source code and computer programming is also called program coding.
- A computer without a computer program is just a dump box; it is programs that make computers active.
Introduction to Computer Programming
If you understood what a computer program is, then we will say: the act of writing computer programs is called computer programming.As we mentioned earlier, there are hundreds of programming languages, which can be used to write computer programs and following are a few of them −
- Java
- C
- C++
- Python
- PHP
- Perl
- Ruby
Uses of Computer Programs
Today computer programs are being used in almost every field, household, agriculture, medical, entertainment, defense, communication, etc. Listed below are a few applications of computer programs −- MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are examples of computer programs.
- Computer programs are being used to develop graphics and special effects in movie making.
- Computer programs are being used to perform Ultrasounds, X-Rays, and other medical examinations.
- Computer programs are being used in our mobile phones for SMS, Chat, and voice communication.
Computer Programmer
Someone who can write computer programs or in other words, someone who can do computer programming is called a Computer Programmer.Based on computer programming language expertise, we can name a computer programmers as follows −
- C Programmer
- C++ Programmer
- Java Programmer
- Python Programmer
- PHP Programmer
- Perl Programmer
- Ruby Programmer
Algorithm
From programming point of view, an algorithm is a step-by-step procedure to resolve any problem. An algorithm is an effective method expressed as a finite set of well-defined instructions.Thus, a computer programmer lists down all the steps required to resolve a problem before writing the actual code. Following is a simple example of an algorithm to find out the largest number from a given list of numbers −
1. Get a list of numbers L1, L2, L3....LN 2. Assume L1 is the largest, Largest = L1 3. Take next number Li from the list and do the following 4. If Largest is less than Li 5. Largest = Li 6. If Li is last number from the list then 7. Print value stored in Largest and come out 8. Else repeat same process starting from step 3The above algorithm has been written in a crude way to help beginners understand the concept. You will come across more standardized ways of writing computer algorithms as you move on to advanced levels of computer programming.
We assume you are well aware of English Language, which is a well-known Human Interface Language. English has a predefined grammar, which needs to be followed to write English statements in a correct way. Likewise, most of the Human Interface Languages (Hindi, English, Spanish, French, etc.) are made of several elements like verbs, nouns, adjectives, adverbs, propositions, and conjunctions, etc.
Similar to Human Interface Languages, Computer Programming Languages are also made of several elements. We will take you through the basics of those elements and make you comfortable to use them in various programming languages. These basic elements include −
- Programming Environment
- Basic Syntax
- Data Types
- Variables
- Keywords
- Basic Operators
- Decision Making
- Loops
- Numbers
- Characters
- Arrays
- Strings
- Functions
- File I/O
This tutorial has been designed to give you an idea about the following most popular programming languages −
- C Programming
- Java Programming
- Python Programming
Though Environment Setup is not an element of any Programming Language, it is the first step to be followed before setting on to write a program.
When we say Environment Setup, it simply implies a base on top of which we can do our programming. Thus, we need to have the required software setup, i.e., installation on our PC which will be used to write computer programs, compile, and execute them. For example, if you need to browse Internet, then you need the following setup on your machine −
- A working Internet connection to connect to the Internet
- A Web browser such as Internet Explorer, Chrome, Safari, etc.
Similarly, you will need the following setup to start with programming using any programming language.
- A text editor to create computer programs.
- A compiler to compile the programs into binary format.
- An interpreter to execute the programs directly.
Text Editor
A text editor is a software that is used to write computer programs. Your Windows machine must have a Notepad, which can be used to type programs. You can launch it by following these steps −Start Icon → All Programs → Accessories → Notepad → Mouse Click on NotepadIt will launch Notepad with the following window −
You can use this software to type your computer program and save it in a file at any location. You can download and install other good editors like Notepad++, which is freely available.
If you are a Mac user, then you will have TextEdit or you can install some other commercial editor like BBEdit to start with.
Compiler?
You write your computer program using your favorite programming language and save it in a text file called the program file.Now let us try to get a little more detail on how the computer understands a program written by you using a programming language. Actually, the computer cannot understand your program directly given in the text format, so we need to convert this program in a binary format, which can be understood by the computer.
The conversion from text program to binary file is done by another software called Compiler and this process of conversion from text formatted program to binary format file is called program compilation. Finally, you can execute binary file to perform the programmed task.
We are not going into the details of a compiler and the different phases of compilation.
The following flow diagram gives an illustration of the process −
So, if you are going to write your program in any such language, which needs compilation like C, C++, Java and Pascal, etc., then you will need to install their compilers before you start programming.
Interpreter
We just discussed about compilers and the compilation process. Compilers are required in case you are going to write your program in a programming language that needs to be compiled into binary format before its execution.There are other programming languages such as Python, PHP, and Perl, which do not need any compilation into binary format, rather an interpreter can be used to read such programs line by line and execute them directly without any further conversion.
So, if you are going to write your programs in PHP, Python, Perl, Ruby, etc., then you will need to install their interpreters before you start programming.
Online Compilation
If you are not able to set up any editor, compiler, or interpreter on your machine, then tutorialspoint.com provides a facility to compile and run almost all the programs online with an ease of a single click.So do not worry and let's proceed further to have a thrilling experience to become a computer programmer in simple and easy steps.
Let’s start with a little coding, which will really make you a computer programmer. We are going to write a single-line computer program to write Hello, World! on your screen. Let’s see how it can be written using different programming languages.
Hello World Program in C
Try the following example using our online compiler option available at www.compileonline.com.For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler.
Try to change the content inside printf(), i.e., type anything in place of Hello World! and then check its result. It just prints whatever you keep inside the two double quotes.
Live Demo
#include <stdio.h> int main() { /* printf() function to write Hello, World! */ printf( "Hello, World!" ); }which produces the following result −
Hello, World!This little Hello World program will help us understand various basic concepts related to C Programming.
Program Entry Point
For now, just forget about the #include <stdio.h> statement, but keep a note that you have to put this statement at the top of a C program.Every C program starts with main(), which is called the main function, and then it is followed by a left curly brace. The rest of the program instruction is written in between and finally a right curly brace ends the program.
The coding part inside these two curly braces is called the program body. The left curly brace can be in the same line as main(){ or in the next line like it has been mentioned in the above program.
Functions
Functions are small units of programs and they are used to carry out a specific task. For example, the above program makes use of two functions: main() and printf(). Here, the function main() provides the entry point for the program execution and the other function printf() is being used to print an information on the computer screen.You can write your own functions which we will see in a separate chapter, but C programming itself provides various built-in functions like main(), printf(), etc., which we can use in our programs based on our requirement.
Some of the programming languages use the word sub-routine instead of function, but their functionality is more or less the same.
Comments
A C program can have statements enclosed inside /*.....*/. Such statements are called comments and these comments are used to make the programs user friendly and easy to understand. The good thing about comments is that they are completely ignored by compilers and interpreters. So you can use whatever language you want to write your comments.Whitespaces
When we write a program using any programming language, we use various printable characters to prepare programming statements. These printable characters are a, b, c,......z, A, B, C,.....Z, 1, 2, 3,...... 0, !, @, #, $, %, ^, &, *, (, ), -, _, +, =, \, |, {, }, [, ], :, ;, <, >, ?, /, \, ~. `. ", '. Hope I'm not missing any printable characters from your keyboard.Apart from these characters, there are some characters which we use very frequently but they are invisible in your program and these characters are spaces, tabs (\t), new lines(\n). These characters are called whitespaces.
These three important whitespace characters are common in all the programming languages and they remain invisible in your text document −
Whitespace | Explanation | Representation |
---|---|---|
New Line | To create a new line | \n |
Tab | To create a tab. | \t |
Space | To create a space. | empty space |
Live Demo
#include <stdio.h> int main() { /* printf() function to write Hello, World! */ printf( "Hello, World!" ); }which produces the following result −
Hello, World!If we make all these whitespace characters visible, then the above program will look like this and you will not be able to compile it −
#include <stdio.h>\n \n int main()\n { \n \t/* printf() function to write Hello, World! */ \n \tprintf(\t"Hello, World!"\t);\n \n }\n
Semicolons
Every individual statement in a C Program must be ended with a semicolon (;), for example, if you want to write "Hello, World!" twice, then it will be written as follows −Live Demo
#include <stdio.h> int main() { /* printf() function to write Hello, World! */ printf( "Hello, World!\n" ); printf( "Hello, World!" ); }This program will produce the following result −
Hello, World! Hello, World!Here, we are using a new line character \n in the first printf() function to create a new line. Let us see what happens if we do not use this new line character −
Live Demo
#include <stdio.h> int main() { /* printf() function to write Hello, World! */ printf( "Hello, World!" ); printf( "Hello, World!" ); }This program will produce the following result −
Hello, World! Hello, World!We will learn identifiers and keywords in next few chapters.
Program Explanation
Let us understand how the above C program works. First of all, the above program is converted into a binary format using C compiler. So let’s put this code in test.c file and compile it as follows −$gcc test.c -o demoIf there is any grammatical error (Syntax errors in computer terminologies), then we fix it before converting it into binary format. If everything goes fine, then it produces a binary file called demo. Finally, we execute the produced binary demo as follows −
$./demowhich produces the following result −
Hello, World!Here, when we execute the binary a.out file, the computer enters inside the program starting from main() and encounters a printf() statement. Keep a note that the line inside /*....*/ is a comment and it is filtered at the time of compilation. So printf() function instructs the computer to print the given line at the computer screen. Finally, it encounters a right curly brace which indicates the end of main() function and exits the program.
Syntax Error
If you do not follow the rules defined by the programing language, then at the time of compilation, you will get syntax errors and the program will not be compiled. From syntax point of view, even a single dot or comma or a single semicolon matters and you should take care of such small syntax as well. In the following example, we have skipped a semicolon, let's try to compile the program −Live Demo
#include <stdio.h> main() { printf("Hello, World!") }This program will produce the following result −
main.c: In function 'main': main.c:7:1: error: expected ';' before '}' token } ^So the bottom-line is that if you are not following proper syntax defined by the programming language in your program, then you will get syntax errors. Before attempting another compilation, you will need to fix them and then proceed.
Hello World Program in Java
Following is the equivalent program written in Java. This program will also produce the same result Hello, World!.Live Demo
public class HelloWorld { public static void main(String []args) { /* println() function to write Hello, World! */ System.out.println("Hello, World!"); } }which produces the following result −
Hello, World!
Hello World Program in Python
Following is the equivalent program written in Python. This program will also produce the same result Hello, World!.Live Demo
# print function to write Hello, World! */ print "Hello, World!"which produces the following result −
Hello, World!Hope you noted that for C and Java examples, first we are compiling the programs and then executing the produced binaries, but in Python program, we are directly executing it. As we explained in the previous chapter, Python is an interpreted language and it does not need an intermediate step called compilation.
Python does not require a semicolon (;) to terminate a statement, rather a new line always means termination of the statement.
Let's discuss about a very simple but very important concept available in almost all the programming languages which is called data types. As its name indicates, a data type represents a type of the data which you can process using your computer program. It can be numeric, alphanumeric, decimal, etc.
Let’s keep Computer Programming aside for a while and take an easy example of adding two whole numbers 10 & 20, which can be done simply as follows −
10 + 20Let's take another problem where we want to add two decimal numbers 10.50 & 20.50, which will be written as follows −
10.50 + 20.50The two examples are straightforward. Now let's take another example where we want to record student information in a notebook. Here we would like to record the following information −
Name: Class: Section: Age: Sex:Now, let's put one student record as per the given requirement −
Name: Zara Ali Class: 6th Section: J Age: 13 Sex: FThe first example dealt with whole numbers, the second example added two decimal numbers, whereas the third example is dealing with a mix of different data. Let's put it as follows −
- Student name "Zara Ali" is a sequence of characters which is also called a string.
- Student class "6th" has been represented by a mix of whole number and a string of two characters. Such a mix is called alphanumeric.
- Student section has been represented by a single character which is 'J'.
- Student age has been represented by a whole number which is 13.
- Student sex has been represented by a single character which is 'F'.
Similarly, when we write a computer program to process different types of data, we need to specify its type clearly; otherwise the computer does not understand how different operations can be performed on that given data. Different programming languages use different keywords to specify different data types. For example, C and Java programming languages use int to specify integer data, whereas char specifies a character data type.
Subsequent chapters will show you how to use different data types in different situations. For now, let's check the important data types available in C, Java, and Python and the keywords we will use to specify those data types.
C and Java Data Types
C and Java support almost the same set of data types, though Java supports additional data types. For now, we are taking a few common data types supported by both the programming languages −Type | Keyword | Value range which can be represented by this data type |
---|---|---|
Character | char | -128 to 127 or 0 to 255 |
Number | int | -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 |
Small Number | short | -32,768 to 32,767 |
Long Number | long | -2,147,483,648 to 2,147,483,647 |
Decimal Number | float | 1.2E-38 to 3.4E+38 till 6 decimal places |
Python Data Types
Python has five standard data types but this programming language does not make use of any keyword to specify a particular data type, rather Python is intelligent enough to understand a given data type automatically.- Numbers
- String
- List
- Tuple
- Dictionary
Variables are the names you give to computer memory locations which are used to store values in a computer program.
For example, assume you want to store two values 10 and 20 in your program and at a later stage, you want to use these two values. Let's see how you will do it. Here are the following three simple steps −
- Create variables with appropriate names.
- Store your values in those two variables.
- Retrieve and use the stored values from the variables.
Creating variables
Creating variables is also called declaring variables in C programming. Different programming languages have different ways of creating variables inside a program. For example, C programming has the following simple way of creating variables −#include <stdio.h> int main() { int a; int b; }The above program creates two variables to reserve two memory locations with names a and b. We created these variables using int keyword to specify variable data type which means we want to store integer values in these two variables. Similarly, you can create variables to store long, float, char or any other data type. For example −
/* variable to store long value */ long a; /* variable to store float value */ float b;You can create variables of similar type by putting them in a single line but separated by comma as follows −
#include <stdio.h> int main() { int a, b; }Listed below are the key points about variables that you need to keep in mind −
- A variable name can hold a single type of value. For example, if variable a has been defined int type, then it can store only integer.
- C programming language requires a variable creation, i.e., declaration before its usage in your program. You cannot use a variable name in your program without creating it, though programming language like Python allows you to use a variable name without creating it.
- You can use a variable name only once inside your program. For example, if a variable a has been defined to store an integer value, then you cannot define a again to store any other type of value.
- There are programming languages like Python, PHP, Perl, etc., which do not want you to specify data type at the time of creating variables. So you can store integer, float, or long without specifying their data type.
- You can give any name to a variable like age, sex, salary, year1990 or anything else you like to give, but most of the programming languages allow to use only limited characters in their variables names. For now, we will suggest to use only a....z, A....Z, 0....9 in your variable names and start their names using alphabets only instead of digits.
- Almost none of the programming languages allow to start their variable names with a digit, so 1990year will not be a valid variable name whereas year1990 or ye1990ar are valid variable names.
Store Values in Variables
You have seen how we created variables in the previous section. Now, let's store some values in those variables −#include <stdio.h> int main() { int a; int b; a = 10; b = 20; }The above program has two additional statements where we are storing 10 in variable a and 20 is being stored in variable b. Almost all the programming languages have similar way of storing values in variable where we keep variable name in the left hand side of an equal sign = and whatever value we want to store in the variable, we keep that value in the right hand side.
Now, we have completed two steps, first we created two variables and then we stored required values in those variables. Now variable a has value 10 and variable b has value 20. In other words we can say, when above program is executed, the memory location named a will hold 10 and memory location b will hold 20.
Access stored values in variables
If we do not use the stored values in the variables, then there is no point in creating variables and storing values in them. We know that the above program has two variables a and b and they store the values 10 and 20, respectively. So let's try to print the values stored in these two variables. Following is a C program, which prints the values stored in its variables −Live Demo
#include <stdio.h> int main() { int a; int b; a = 10; b = 20; printf( "Value of a = %d\n", a ); printf( "Value of b = %d\n", b ); }When the above program is executed, it produces the following result −
Value of a = 10 Value of b = 20You must have seen printf() function in the previous chapter where we had used it to print "Hello, World!". This time, we are using it to print the values of variables. We are making use of %d, which will be replaced with the values of the given variable in printf() statements. We can print both the values using a single printf() statement as follows −
Live Demo
#include <stdio.h> int main() { int a; int b; a = 10; b = 20; printf( "Value of a = %d and value of b = %d\n", a, b ); }When the above program is executed, it produces the following result −
Value of a = 10 and value of b = 20If you want to use float variable in C programming, then you will have to use %f instead of %d, and if you want to print a character value, then you will have to use %c. Similarly, different data types can be printed using different % and characters.
Variables in Java
Following is the equivalent program written in Java programming language. This program will create two variables a and b and very similar to C programming, it will assign 10 and 20 in these variables and finally print the values of the two variables in two ways −Live Demo
public class DemoJava { public static void main(String []args) { int a; int b; a = 10; b = 20; System.out.println("Value of a = " + a); System.out.println("Value of b = " + b); System.out.println("Value of a = " + a + " and value of b = " + b); } }When the above program is executed, it produces the following result −
Value of a = 10 Value of b = 20 Value of a = 10 and value of b = 20
Variables in Python
Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables.Python does not want you to specify the data type at the time of variable creation and there is no need to create variables in advance.
Live Demo
a = 10 b = 20 print "Value of a = ", a print "Value of b = ", b print "Value of a = ", a, " and value of b = ", bWhen the above program is executed, it produces the following result −
Value of a = 10 Value of b = 20 Value of a = 10 and value of b = 20You can use the following syntax in C and Java programming to declare variables and assign values at the same time −
Live Demo
#include <stdio.h> int main() { int a = 10; int b = 20; printf( "Value of a = %d and value of b = %d\n", a, b ); }When the above program is executed, it produces the following result −
Value of a = 10 and value of b = 20
So far, we have covered two important concepts called variables and their data types. We discussed how to use int, long, and float to specify different data types. We also learnt how to name the variables to store different values.
Though this chapter is not required separately because reserved keywords are a part of basic programming syntax, we kept it separate to explain it right after data types and variables to make it easy to understand.
Like int, long, and float, there are many other keywords supported by C programming language which we will use for different purpose. Different programming languages provide different set of reserved keywords, but there is one important & common rule in all the programming languages that we cannot use a reserved keyword to name our variables, which means we cannot name our variable like int or float rather these keywords can only be used to specify a variable data type.
For example, if you will try to use any reserved keyword for the purpose of variable name, then you will get a syntax error.
Live Demo
#include <stdio.h> int main() { int float; float = 10; printf( "Value of float = %d\n", float); }When you compile the above program, it produces the following error −
main.c: In function 'main': main.c:5:8: error: two or more data types in declaration specifiers int float; ......Let's now give a proper name to our integer variable, then the above program should compile and execute successfully −
Live Demo
#include <stdio.h> int main() { int count; count = 10; printf( "Value of count = %d\n", count); }
C Programming Reserved Keywords
Here is a table having almost all the keywords supported by C Programming language −auto | else | long | switch |
break | enum | register | typedef |
case | extern | return | union |
char | float | short | unsigned |
const | for | signed | void |
continue | goto | sizeof | volatile |
default | if | static | while |
do | int | struct | _Packed |
double |
Java Programming Reserved Keywords
Here is a table having almost all the keywords supported by Java Programming language −abstract | assert | boolean | break |
byte | case | catch | char |
class | const | continue | default |
do | double | else | enum |
extends | final | finally | float |
for | goto | if | implements |
import | instanceof | int | interface |
long | native | new | package |
private | protected | public | return |
short | static | strictfp | super |
switch | synchronized | this | throw |
throws | transient | try | void |
volatile | while |
Python Programming Reserved Keywords
Here is a table having almost all the keywords supported by Python Programming language −and | exec | not |
assert | finally | or |
break | for | pass |
class | from | |
continue | global | raise |
def | if | return |
del | import | try |
elif | in | while |
else | is | with |
except | lambda | yield |
An operator in a programming language is a symbol that tells the compiler or interpreter to perform specific mathematical, relational or logical operation and produce final result. This chapter will explain the concept of operators and it will take you through the important arithmetic and relational operators available in C, Java, and Python.
Arithmetic Operators
Computer programs are widely used for mathematical calculations. We can write a computer program which can do simple calculation like adding two numbers (2 + 3) and we can also write a program, which can solve a complex equation like P(x) = x4 + 7x3 - 5x + 9. If you have been even a poor student, you must be aware that in first expression 2 and 3 are operands and + is an operator. Similar concepts exist in Computer Programming.Take a look at the following two examples −
2 + 3 P(x) = x4 + 7x3 - 5x + 9.These two statements are called arithmetic expressions in a programming language and plus, minus used in these expressions are called arithmetic operators and the values used in these expressions like 2, 3 and x, etc., are called operands. In their simplest form, such expressions produce numerical results.
Similarly, a programming language provides various arithmetic operators. The following table lists down a few of the important arithmetic operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −
Operator | Description | Example |
---|---|---|
+ | Adds two operands | A + B will give 30 |
- | Subtracts second operand from the first | A - B will give -10 |
* | Multiplies both operands | A * B will give 200 |
/ | Divides numerator by de-numerator | B / A will give 2 |
% | This gives remainder of an integer division | B % A will give 0 |
Live Demo
#include <stdio.h> int main() { int a, b, c; a = 10; b = 20; c = a + b; printf( "Value of c = %d\n", c); c = a - b; printf( "Value of c = %d\n", c); c = a * b; printf( "Value of c = %d\n", c); c = b / a; printf( "Value of c = %d\n", c); c = b % a; printf( "Value of c = %d\n", c); }When the above program is executed, it produces the following result −
Value of c = 30 Value of c = -10 Value of c = 200 Value of c = 2 Value of c = 0
Relational Operators
Consider a situation where we create two variables and assign them some values as follows −A = 20 B = 10Here, it is obvious that variable A is greater than B in values. So, we need the help of some symbols to write such expressions which are called relational expressions. If we use C programming language, then it will be written as follows −
(A > B)Here, we used a symbol > and it is called a relational operator and in their simplest form, they produce Boolean results which means the result will be either true or false. Similarly, a programming language provides various relational operators. The following table lists down a few of the important relational operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −
Operator | Description | Example |
---|---|---|
== | Checks if the values of two operands are equal or not, if yes then condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (A <= B) is true. |
Live Demo
#include <stdio.h> int main() { int a, b; a = 10; b = 20; /* Here we check whether a is equal to 10 or not */ if( a == 10 ) { /* if a is equal to 10 then this body will be executed */ printf( "a is equal to 10\n"); } /* Here we check whether b is equal to 10 or not */ if( b == 10 ) { /* if b is equal to 10 then this body will be executed */ printf( "b is equal to 10\n"); } /* Here we check if a is less b than or not */ if( a < b ) { /* if a is less than b then this body will be executed */ printf( "a is less than b\n"); } /* Here we check whether a and b are not equal */ if( a != b ) { /* if a is not equal to b then this body will be executed */ printf( "a is not equal to b\n"); } }When the above program is executed, it produces the following result −
a is equal to 10 a is less than b a is not equal to b
Logical Operators
Logical operators are very important in any programming language and they help us take decisions based on certain conditions. Suppose we want to combine the result of two conditions, then logical AND and OR logical operators help us in producing the final result.The following table shows all the logical operators supported by the C language. Assume variable A holds 1 and variable B holds 0, then −
Operator | Description | Example |
---|---|---|
&& | Called Logical AND operator. If both the operands are non-zero, then condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | !(A && B) is true. |
Live Demo
#include <stdio.h> int main() { int a = 1; int b = 0; if ( a && b ) { printf("This will never print because condition is false\n" ); } if ( a || b ) { printf("This will be printed print because condition is true\n" ); } if ( !(a && b) ) { printf("This will be printed print because condition is true\n" ); } }When you compile and execute the above program, it produces the following result −
This will be printed print because condition is true This will be printed print because condition is true
Operators in Java
Following is the equivalent program written in Java. C programming and Java provide almost identical set of operators and conditional statements. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators −You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
Live Demo
public class DemoJava { public static void main(String []args) { int a, b, c; a = 10; b = 20; c = a + b; System.out.println("Value of c = " + c ); c = a - b; System.out.println("Value of c = " + c ); c = a * b; System.out.println("Value of c = " + c ); c = b / a; System.out.println("Value of c = " + c ); c = b % a; System.out.println("Value of c = " + c ); if( a == 10 ) { System.out.println("a is equal to 10" ); } } }When the above program is executed, it produces the following result −
Value of c = 30 Value of c = -10 Value of c = 200 Value of c = 2 Value of c = 0 a is equal to 10
Operators in Python
Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables. Fortunately, C programming and Python programming languages provide almost identical set of operators. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators.You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
Live Demo
a = 10 b = 20 c = a + b print "Value of c = ", c c = a - b print "Value of c = ", c c = a * b print "Value of c = ", c c = a / b print "Value of c = ", c c = a % b print "Value of c = ", c if( a == 10 ): print "a is equal to 10"When the above program is executed, it produces the following result −
Value of c = 30 Value of c = -10 Value of c = 200 Value of c = 0 Value of c = 10 a is equal to 10
Decision making is critical to computer programming. There will be many situations when you will be given two or more options and you will have to select an option based on the given conditions. For example, we want to print a remark about a student based on his secured marks. Following is the situation −
Assume given marks are x for a student: If given marks are more than 95, then Student is brilliant If given marks are less than 30, then Student is poor If given marks are less than 95 and more than 30, then Student is averageNow, the question is how to write a programming code to handle such situations. Almost all the programming languages provide conditional statements that work based on the following flow diagram −
Let's write a C program with the help of if conditional statements to convert the above given situation into a programming code −
Live Demo
#include <stdio.h> int main() { int x = 45; if( x > 95) { printf( "Student is brilliant\n"); } if( x < 30) { printf( "Student is poor\n"); } if( x < 95 && x > 30 ) { printf( "Student is average\n"); } }When the above program is executed, it produces the following result −
Student is averageThe above program uses if conditional statements. Here, the first if statement checks whether the given condition i.e., variable x is greater than 95 or not and if it finds the condition is true, then the conditional body is entered to execute the given statements. Here we have only one printf() statement to print a remark about the student.
Similarly, the second if statement works. Finally, the third if statement is executed, here we have the following two conditions −
- First condition is x > 95
- Second condition is x < 30
This tutorial will give you a basic idea on various forms of if statements and an introduction to switch statements available in C programming language. Different programming languages provide different types of decision-making statements, but the basic concept remains the same as explained in this tutorial.
if...else statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. The syntax of an if...else statement in C programming language is −if(boolean_expression) { /* Statement(s) will execute if the boolean expression is true */ } else { /* Statement(s) will execute if the boolean expression is false */ }The above syntax can be represented in the form of a flow diagram as shown below −
An if...else statement is useful when we have to take a decision out of two options. For example, if a student secures more marks than 95, then the student is brilliant, otherwise no such situation can be coded, as follows −
Live Demo
#include <stdio.h> int main() { int x = 45; if( x > 95) { printf( "Student is brilliant\n"); } else { printf( "Student is not brilliant\n"); } }When the above program is executed, it produces the following result −
Student is not brilliant
if...elseif...else statement
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions.While using if, else if, else statements, there are a few points to keep in mind −
- An if can have zero or one else's and it must come after an else if.
- An if can have zero to many else…if's and they must come before the else.
- Once an else…if succeeds, none of the remaining else…if's or else's will be tested.
if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ } else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */ } else { /* Executes when the none of the above condition is true */ }Now with the help of if...elseif...else statement, the very first program can be coded as follows −
Live Demo
#include <stdio.h> int main() { int x = 45; if( x > 95) { printf( "Student is brilliant\n"); } else if( x < 30) { printf( "Student is poor\n"); } else if( x < 95 && x > 30 ) { printf( "Student is average\n"); } }When the above program is executed, it produces the following result −
Student is average
The Switch Statement
A switch statement is an alternative of if statements which allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. It has the following syntax −switch(expression){ case ONE : statement(s); break; case TWO: statement(s); break; ...... default : statement(s); }The expression used in a switch statement must give an integer value, which will be compared for equality with different cases given. Wherever an expression value matches with a case value, the body of that case will be executed and finally, the switch will be terminated using a break statement. If no break statements are provided, then the computer continues executing other statements available below to the matched case. If none of the cases matches, then the default case body is executed.
The above syntax can be represented in the form of a flow diagram as shown below −
Now, let's consider another example where we want to write the equivalent English word for a given number. Then, it can be coded as follows −
Live Demo
#include <stdio.h> int main() { int x = 2; switch( x ){ case 1 : printf( "One\n"); break; case 2 : printf( "Two\n"); break; case 3 : printf( "Three\n"); break; case 4 : printf( "Four\n"); break; default : printf( "None of the above...\n"); } }When the above program is executed, it produces the following result −
Two
Decisions in Java
Following is the equivalent program written in Java which too supports if, if...else, if...elseif...else, and switch statements.You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
Live Demo
public class DemoJava { public static void main(String []args) { int x = 45; if( x > 95) { System.out.println( "Student is brilliant"); } else if( x < 30) { System.out.println( "Student is poor"); } else if( x < 95 && x > 30 ) { System.out.println( "Student is average"); } } }When the above program is executed, it produces the following result −
Student is average
Decisions in Python
Following is the equivalent program written in Python. Python provides if, if...else, if...elif...else, and switch statements. Here, you must note that Python does not make use of curly braces for conditional body, instead it simply identifies the body of the block using indentation of the statements.You can try to execute the following program to see the output −
Live Demo
x = 45 if x > 95: print "Student is brilliant" elif x < 30: print "Student is poor" elif x < 95 and x > 30: print "Student is average" print "The end"When the above program is executed, it produces the following result −
Student is average The end
Let's consider a situation when you want to print Hello, World! five times. Here is a simple C program to do the same −
Live Demo
#include <stdio.h> int main() { printf( "Hello, World!\n"); printf( "Hello, World!\n"); printf( "Hello, World!\n"); printf( "Hello, World!\n"); printf( "Hello, World!\n"); }When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!It was simple, but again, let's consider another situation when you want to write Hello, World! a thousand times. We can certainly not write printf() statements a thousand times. Almost all the programming languages provide a concept called loop, which helps in executing one or more statements up to a desired number of times. All high-level programming languages provide various forms of loops, which can be used to execute one or more statements repeatedly.
Let's write the above C program with the help of a while loop and later, we will discuss how this loop works
Live Demo
#include <stdio.h> int main() { int i = 0; while ( i < 5 ) { printf( "Hello, World!\n"); i = i + 1; } }When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!The above program makes use of a while loop, which is being used to execute a set of programming statements enclosed within {....}. Here, the computer first checks whether the given condition, i.e., variable "a" is less than 5 or not and if it finds the condition is true, then the loop body is entered to execute the given statements. Here, we have the following two statements in the loop body −
- First statement is printf() function, which prints Hello World!
- Second statement is i = i + 1, which is used to increase the value of variable i
To conclude, a loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −
This tutorial has been designed to present programming's basic concepts to non-programmers, so let's discuss the two most important loops available in C programming language. Once you are clear about these two loops, then you can pick-up C programming tutorial or a reference book and check other loops available in C and the way they work.
The while Loop
A while loop available in C Programming language has the following syntax −while ( condition ) { /*....while loop body ....*/ }The above code can be represented in the form of a flow diagram as shown below −
The following important points are to be noted about a while loop −
- A while loop starts with a keyword while followed by a condition enclosed in ( ).
- Further to the while() statement, you will have the body of the loop enclosed in curly braces {...}.
- A while loop body can have one or more lines of source code to be executed repeatedly.
- If the body of a while loop has just one line, then its optional to use curly braces {...}.
- A while loop keeps executing its body till a given condition holds true. As soon as the condition becomes false, the while loop comes out and continues executing from the immediate next statement after the while loop body.
- A condition is usually a relational statement, which is evaluated to either true or false. A value equal to zero is treated as false and any non-zero value works like true.
The do...while Loop
A while loop checks a given condition before it executes any statements given in the body part. C programming provides another form of loop, called do...while that allows to execute a loop body before checking a given condition. It has the following syntax −do { /*....do...while loop body ....*/ } while ( condition );The above code can be represented in the form of a flow diagram as shown below −
If you will write the above example using do...while loop, then Hello, World will produce the same result −
Live Demo
#include <stdio.h> int main() { int i = 0; do { printf( "Hello, World!\n"); i = i + 1; } while ( i < 5 ); }When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!
The break statement
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. The syntax for a break statement in C is as follows −break;A break statement can be represented in the form of a flow diagram as shown below −
Following is a variant of the above program, but it will come out after printing Hello World! only three times −
Live Demo
#include <stdio.h> int main() { int i = 0; do { printf( "Hello, World!\n"); i = i + 1; if( i == 3 ) { break; } } while ( i < 5 ); }When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World!
The continue statement
The continue statement in C programming language works somewhat like the break statement. Instead of forcing termination, continue forces the next iteration of the loop to take place, skipping any code in between. The syntax for a continue statement in C is as follows −continue;A continue statement can be represented in the form of a flow diagram as shown below −
Following is a variant of the above program, but it will skip printing when the variable has a value equal to 3 −
Live Demo
#include <stdio.h> int main() { int i = 0; do { if( i == 3 ) { i = i + 1; continue; } printf( "Hello, World!\n"); i = i + 1; } while ( i < 5 ); }When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World! Hello, World!
Loops in Java
Following is the equivalent program written in Java that too supports while and do...while loops. The following program prints Hello, World! five times as we did in the case of C Programming −You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
Live Demo
public class DemoJava { public static void main(String []args) { int i = 0; while ( i < 5 ) { System.out.println("Hello, World!"); i = i + 1; } } }The break and continue statements in Java programming work quite the same way as they work in C programming.
Loops in Python
Following is the equivalent program written in Python. Python too supports while and do...while loops. The following program prints Hello, World! five times as we did in case of C Programming. Here you must note that Python does not make use of curly braces for the loop body, instead it simply identifies the body of the loop using indentation of the statements.You can try to execute the following program to see the output. To show the difference, we have used one more print statement, which will be executed when the loop will be over.
Live Demo
i = 0 while (i < 5): print "Hello, World!" i = i + 1 print "Loop ends"When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Loop endsThe break and continue statements in Python work quite the same way as they do in C programming.
Every programming language provides support for manipulating different types of numbers such as simple whole integers and floating point numbers. C, Java, and Python categorize these numbers in several categories based on their nature.
Let's go back and check the data types chapter, where we listed down the core data types related to numbers −
Type | Keyword | Value range which can be represented by this data type |
---|---|---|
Number | int | -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 |
Small Number | short | -32,768 to 32,767 |
Long Number | long | -2,147,483,648 to 2,147,483,647 |
Decimal Number | float | 1.2E-38 to 3.4E+38 till 6 decimal places |
We have seen various mathematical and logical operations on numbers during a discussion on operators. So we know how to add numbers, subtract numbers, divide numbers, etc.
First let's see how to print various types of numbers available in C programming language −
Live Demo
#include <stdio.h> int main() { short s; int i; long l; float f; double d; s = 10; i = 1000; l = 1000000; f = 230.47; d = 30949.374; printf( "s: %d\n", s); printf( "i: %d\n", i); printf( "l: %ld\n", l); printf( "f: %.3f\n", f); printf( "d: %.3f\n", d); }Rest of the coding is very obvious, but we used %.3f to print float and double, which indicates the number of digits after the decimal to be printed. When the above program is executed, it produces the following result −
s: 10 i: 1000 l: 1000000 f: 230.470 d: 30949.374
Math Operations on Numbers
The following table lists down various useful built-in mathematical functions available in C programming language which can be used for various important mathematical calculations.For example, if you want to calculate the square root of a number, for example, 2304, then you have a built-in function available to calculate the square root.
Sr.No. | Function & Purpose |
---|---|
1 | double cos(double); This function takes an angle (as a double) and returns the cosine. |
2 | double sin(double); This function takes an angle (as a double) and returns the sine. |
3 | double tan(double); This function takes an angle (as a double) and returns the tangent. |
4 | double log(double); This function takes a number and returns the natural log of that number. |
5 | double pow(double, double); The first is a number you wish to raise and the second is the power you wish to raise it to. |
6 | double hypot(double, double); If you pass this function the length of two sides of a right triangle, it will return the length of the hypotenuse. |
7 | double sqrt(double); You pass this function a number and it returns its square root. |
8 | int abs(int); This function returns the absolute value of an integer that is passed to it. |
9 | double fabs(double); This function returns the absolute value of any decimal number passed to it. |
10 | double floor(double); Finds the integer which is less than or equal to the argument passed to it. |
Live Demo
#include <stdio.h> #include <math.h> int main() { short s; int i; long l; float f; double d; printf( "sin(s): %f\n", sin(10)); printf( "abs(i): %f\n", abs(1000)); printf( "floor(f): %f\n", floor(230.47)); printf( "sqrt(l): %f\n", sqrt(1000000)); printf( "pow(d, 2): %f\n", pow(2.374, 2)); }When the above program is executed, it produces the following result −
sin(s): -0.544021 abs(i): -0.544021 floor(f): 230.000000 sqrt(l): 1000.000000 pow(d, 2): 5.635876Besides the above usage, you will use numbers in loop counting, flag representation, true or false values in C programming.
Numbers in Java
Following is the equivalent program written in Java. Java provides almost all the numeric data types available in C programming.You can try to execute the following program to see the output, which is identical to the result generated by the above C example.
Live Demo
public class DemoJava { public static void main(String []args) { short s; int i; long l; float f; double d; s = 10; i = 1000; l = 1000000L; f = 230.47f; d = 30949.374; System.out.format( "s: %d\n", s); System.out.format( "i: %d\n", i); System.out.format( "l: %d\n", l); System.out.format( "f: %f\n", f); System.out.format( "d: %f\n", d); } }When the above program is executed, it produces the following result −
s: 10 i: 1000 l: 1000000 f: 230.470001 d: 30949.374000Java also provides a full range of built-in functions for mathematical calculation and you can use them in the same way as you did in C programming.
Numbers in Python
Python is a little different from C and Java; it categorizes numbers in int, long, float and complex. Here are some examples of numbers in Python −int | long | float | complex |
---|---|---|---|
10 | 51924361L | 0.0 | 3.14j |
100 | -0x19323L | 15.20 | 45.j |
-786 | 0122L | -21.9 | 9.322e-36j |
080 | 0xDEFABCECBDAECBFBAEl | 32.3+e18 | .876j |
-0490 | 535633629843L | -90. | -.6545+0J |
-0x260 | -052318172735L | -32.54e100 | 3e+26J |
0x69 | -4721885298529L | 70.2-E12 | 4.53e-7j |
Live Demo
s = 10 i = 1000 l = 1000000 f = 230.47 d = 30949.374 print "s: ", s print "i: ", i print "l: ", l print "f: ", f print "d: ", dWhen the above program is executed, it produces the following result −
s: 10 i: 1000 l: 1000000 f: 230.47 d: 30949.374Python also provides a full range of built-in functions for mathematical calculations and you can use them in the same way you have used them in C programming.
If it was easy to work with numbers in computer programming, it would be even easier to work with characters. Characters are simple alphabets like a, b, c, d...., A, B, C, D,....., but with an exception. In computer programming, any single digit number like 0, 1, 2,....and special characters like $, %, +, -.... etc., are also treated as characters and to assign them in a character type variable, you simply need to put them inside single quotes. For example, the following statement defines a character type variable ch and we assign a value 'a' to it −
char ch = 'a';Here, ch is a variable of character type which can hold a character of the implementation's character set and 'a' is called a character literal or a character constant. Not only a, b, c,.... but when any number like 1, 2, 3.... or any special character like !, @, #, #, $,.... is kept inside single quotes, then they will be treated as a character literal and can be assigned to a variable of character type, so the following is a valid statement −
char ch = '1';A character data type consumes 8 bits of memory which means you can store anything in a character whose ASCII value lies in between -127 to 127, so it can hold any of the 256 different values. A character data type can store any of the characters available on your keyboard including special characters like !, @, #, #, $, %, ^, &, *, (, ), _, +, {, }, etc.
Note that you can keep only a single alphabet or a single digit number inside single quotes and more than one alphabets or digits are not allowed inside single quotes. So the following statements are invalid in C programming −
char ch1 = 'ab'; char ch2 = '10';Given below is a simple example, which shows how to define, assign, and print characters in C Programming language −
Live Demo
#include <stdio.h> int main() { char ch1; char ch2; char ch3; char ch4; ch1 = 'a'; ch2 = '1'; ch3 = '$'; ch4 = '+'; printf( "ch1: %c\n", ch1); printf( "ch2: %c\n", ch2); printf( "ch3: %c\n", ch3); printf( "ch4: %c\n", ch4); }Here, we used %c to print a character data type. When the above program is executed, it produces the following result −
ch1: a ch2: 1 ch3: $ ch4: +
Escape Sequences
Many programming languages support a concept called Escape Sequence. When a character is preceded by a backslash (\), it is called an escape sequence and it has a special meaning to the compiler. For example, \n in the following statement is a valid character and it is called a new line character −char ch = '\n';Here, character n has been preceded by a backslash (\), it has special meaning which is a new line but keep in mind that backslash (\) has special meaning with a few characters only. The following statement will not convey any meaning in C programming and it will be assumed as an invalid statement −
char ch = '\1';The following table lists the escape sequences available in C programming language −
Escape Sequence | Description |
---|---|
\t | Inserts a tab in the text at this point. |
\b | Inserts a backspace in the text at this point. |
\n | Inserts a newline in the text at this point. |
\r | Inserts a carriage return in the text at this point. |
\f | Inserts a form feed in the text at this point. |
\' | Inserts a single quote character in the text at this point. |
\" | Inserts a double quote character in the text at this point. |
\\ | Inserts a backslash character in the text at this point. |
Live Demo
#include <stdio.h> int main() { char ch1; char ch2; char ch3; char ch4; ch1 = '\t'; ch2 = '\n'; printf( "Test for tabspace %c and a newline %c will start here", ch1, ch2); }When the above program is executed, it produces the following result −
Test for tabspace and a newline will start here
Characters in Java
Following is the equivalent program written in Java. Java handles character data types much in the same way as we have seen in C programming. However, Java provides additional support for character manipulation.You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
Live Demo
public class DemoJava { public static void main(String []args) { char ch1; char ch2; char ch3; char ch4; ch1 = 'a'; ch2 = '1'; ch3 = '$'; ch4 = '+'; System.out.format( "ch1: %c\n", ch1); System.out.format( "ch2: %c\n", ch2); System.out.format( "ch3: %c\n", ch3); System.out.format( "ch4: %c\n", ch4); } }When the above program is executed, it produces the following result −
ch1: a ch2: 1 ch3: $ ch4: +Java also supports escape sequence in the same way you have used them in C programming.
Characters in Python
Python does not support any character data type but all the characters are treated as string, which is a sequence of characters. We will study strings in a separate chapter. You do not need to have any special arrangement while using a single character in Python.Following is the equivalent program written in Python −
Live Demo
ch1 = 'a'; ch2 = '1'; ch3 = '$'; ch4 = '+'; print "ch1: ", ch1 print "ch2: ", ch2 print "ch3: ", ch3 print "ch4: ", ch4When the above program is executed, it produces the following result −
ch1: a ch2: 1 ch3: $ ch4: +Python supports escape sequences in the same way as you have used them in C programming.
Consider a situation where we need to store five integer numbers. If we use programming's simple variable and data type concepts, then we need five variables of int data type and the program will be as follows −
Live Demo
#include <stdio.h> int main() { int number1; int number2; int number3; int number4; int number5; number1 = 10; number2 = 20; number3 = 30; number4 = 40; number5 = 50; printf( "number1: %d\n", number1); printf( "number2: %d\n", number2); printf( "number3: %d\n", number3); printf( "number4: %d\n", number4); printf( "number5: %d\n", number5); }It was simple, because we had to store just five integer numbers. Now let's assume we have to store 5000 integer numbers. Are we going to use 5000 variables?
To handle such situations, almost all the programming languages provide a concept called array. An array is a data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number1, number2, ..., number99, you just declare one array variable number of integer type and use number1[0], number1[1], and ..., number1[99] to represent individual variables. Here, 0, 1, 2, .....99 are index associated with var variable and they are being used to represent individual elements available in the array.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Create Arrays
To create an array variable in C, a programmer specifies the type of the elements and the number of elements to be stored in that array. Given below is a simple syntax to create an array in C programming −type arrayName [ arraySize ];This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, now to declare a 10-element array called number of type int, use this statement −
int number[10];Here, number is a variable array, which is sufficient to hold up to 10 integer numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −int number[5] = {10, 20, 30, 40, 50};The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −
int number[] = {10, 20, 30, 40, 50};You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −
number[4] = 50;The above statement assigns element number 5th in the array with a value of 50. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be the total size of the array minus 1. The following image shows the pictorial representation of the array we discussed above −
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −int var = number[9];The above statement will take the 10th element from the array and assign the value to var variable. The following example uses all the above-mentioned three concepts viz. creation, assignment, and accessing arrays −
Live Demo
#include <stdio.h> int main () { int number[10]; /* number is an array of 10 integers */ int i = 0; /* Initialize elements of array n to 0 */ while( i < 10 ) { /* Set element at location i to i + 100 */ number[ i ] = i + 100; i = i + 1; } /* Output each array element's value */ i = 0; while( i < 10 ) { printf("number[%d] = %d\n", i, number[i] ); i = i + 1; } return 0; }When the above code is compiled and executed, it produces the following result −
number[0] = 100 number[1] = 101 number[2] = 102 number[3] = 103 number[4] = 104 number[5] = 105 number[6] = 106 number[7] = 107 number[8] = 108 number[9] = 109
Arrays in Java
Following is the equivalent program written in Java. Java supports arrays, but there is a little difference in the way they are created in Java using the new operator.You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
Live Demo
public class DemoJava { public static void main(String []args) { int[] number = new int[10]; int i = 0; while( i < 10 ) { number[ i ] = i + 100; i = i + 1; } i = 0; while( i < 10 ) { System.out.format( "number[%d] = %d\n", i, number[i] ); i = i + 1; } } }When the above program is executed, it produces the following result −
number[0] = 100 number[1] = 101 number[2] = 102 number[3] = 103 number[4] = 104 number[5] = 105 number[6] = 106 number[7] = 107 number[8] = 108 number[9] = 109
Arrays (Lists) in Python
Python does not have a concept of Array, instead Python provides another data structure called list, which provides similar functionality as arrays in any other language.Following is the equivalent program written in Python −
Live Demo
# Following defines an empty list. number = [] i = 0 while i < 10: # Appending elements in the list number.append(i + 100) i = i + 1 i = 0 while i < 10: # Accessing elements from the list print "number[", i, "] = ", number[ i ] i = i + 1When the above program is executed, it produces the following result −
number[ 0 ] = 100 number[ 1 ] = 101 number[ 2 ] = 102 number[ 3 ] = 103 number[ 4 ] = 104 number[ 5 ] = 105 number[ 6 ] = 106 number[ 7 ] = 107 number[ 8 ] = 108 number[ 9 ] = 109
During our discussion about characters, we learnt that character data type deals with a single character and you can assign any character from your keyboard to a character type variable.
Now, let's move a little bit ahead and consider a situation where we need to store more than one character in a variable. We have seen that C programming does not allow to store more than one character in a character type variable. So the following statements are invalid in C programming and produce syntax errors −
char ch1 = 'ab'; char ch2 = '10';We have also seen how to use the concept of arrays to store more than one value of similar data type in a variable. Here is the syntax to store and print five numbers in an array of int type −
Live Demo
#include <stdio.h> main() { int number[5] = {10, 20, 30, 40, 50}; int i = 0; while( i < 5 ) { printf("number[%d] = %d\n", i, number[i] ); i = i + 1; } }When the above code is compiled and executed, it produces the following result −
number[0] = 10 number[1] = 20 number[2] = 30 number[3] = 40 number[4] = 50Now, let's define an array of five characters in the same way as we did for numbers and try to print them −
Live Demo
#include <stdio.h> main() { char ch[5] = {'H', 'e', 'l', 'l', 'o'}; int i = 0; while( i < 5 ) { printf("ch[%d] = %c\n", i, ch[i] ); i = i + 1; } }Here, we used %c to print character value. When the above code is compiled and executed, it produces the following result −
ch[0] = H ch[1] = e ch[2] = l ch[3] = l ch[4] = oIf you are done with the above example, then I think you understood how strings work in C programming, because strings in C are represented as arrays of characters. C programming simplified the assignment and printing of strings. Let's check the same example once again with a simplified syntax −
Live Demo
#include <stdio.h> main() { char ch[5] = "Hello"; int i = 0; /* Print as a complete string */ printf("String = %s\n", ch); /* Print character by character */ while( i < 5 ) { printf("ch[%d] = %c\n", i, ch[i] ); i = i + 1; } }Here, we used %s to print the full string value using array name ch, which is actually the beginning of the memory address holding ch variable as shown below −
Although it's not visible from the above examples, a C program internally assigns null character '\0' as the last character of every string. It indicates the end of the string and it means if you want to store a 5 character string in an array, then you must define an array size of 6 as a good practice, though C does not complain about it.
If the above code is compiled and executed, it produces the following result −
String = Hello ch[0] = H ch[1] = e ch[2] = l ch[3] = l ch[4] = o
Basic String Concepts
Based on the above discussion, we can conclude the following important points about strings in C programming language −- Strings in C are represented as arrays of characters.
- We can constitute a string in C programming by assigning character by character into an array of characters.
- We can constitute a string in C programming by assigning a complete string enclosed in double quote.
- We can print a string character by character using an array subscript or a complete string by using an array name without subscript.
- The last character of every string is a null character, i.e., ‘\0’.
- Most of the programming languages provide built-in functions to manipulate strings, i.e., you can concatenate strings, you can search from a string, you can extract sub-strings from a string, etc. For more, you can check our detailed tutorial on C programming or any other programming language.
Strings in Java
Though you can use character arrays to store strings, but Java is an advanced programming language and its designers tried to provide additional functionality. Java provides strings as a built-in data type like any other data type. It means you can define strings directly instead of defining them as array of characters.Following is the equivalent program written in Java. Java makes use of the new operator to create string variables as shown in the following program.
You can try to execute the following program to see the output −
Live Demo
public class DemoJava { public static void main(String []args) { String str = new String("Hello"); System.out.println( "String = " + str ); } }When the above program is executed, it produces the following result −
String = Hello
Strings in Python
Creating strings in Python is as simple as assigning a string into a Python variable using single or double quotes.Given below is a simple program that creates two strings and prints them using print() function −
Live Demo
var1 = 'Hello World!' var2 = "Python Programming" print "var1 = ", var1 print "var2 = ", var2When the above program is executed, it produces the following result −
var1 = Hello World! var2 = Python ProgrammingPython does not support character type; these are treated as strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. Take a look at the following code segment −
Live Demo
var1 = 'Hello World!' var2 = "Python Programming" print "var1[0]: ", var1[0] print "var2[1:5]: ", var2[1:5]When the above code is executed, it produces the following result −
var1[0]: H var2[1:5]: ytho
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. You have already seen various functions like printf() and main(). These are called built-in functions provided by the language itself, but we can write our own functions as well and this tutorial will teach you how to write and use those functions in C programming language.
Good thing about functions is that they are famous with several names. Different programming languages name them differently, for example, functions, methods, sub-routines, procedures, etc. If you come across any such terminology, then just imagine about the same concept, which we are going to discuss in this tutorial.
Let's start with a program where we will define two arrays of numbers and then from each array, we will find the biggest number. Given below are the steps to find out the maximum number from a given set of numbers −
1. Get a list of numbers L1, L2, L3....LN 2. Assume L1 is the largest, Set max = L1 3. Take next number Li from the list and do the following 4. If max is less than Li 5. Set max = Li 6. If Li is last number from the list then 7. Print value stored in max and come out 8. Else prepeat same process starting from step 3Let's translate the above program in C programming language −
Live Demo
#include <stdio.h> int main() { int set1[5] = {10, 20, 30, 40, 50}; int set2[5] = {101, 201, 301, 401, 501}; int i, max; /* Process first set of numbers available in set1[] */ max = set1[0]; i = 1; while( i < 5 ) { if( max < set1[i] ) { max = set1[i]; } i = i + 1; } printf("Max in first set = %d\n", max ); /* Now process second set of numbers available in set2[] */ max = set2[0]; i = 1; while( i < 5 ) { if( max < set2[i] ) { max = set2[i]; } i = i + 1; } printf("Max in second set = %d\n", max ); }When the above code is compiled and executed, it produces the following result −
Max in first set = 50 Max in second set = 501If you are clear about the above example, then it will become easy to understand why we need a function. In the above example, there are only two sets of numbers, set1 and set2, but consider a situation where we have 10 or more similar sets of numbers to find out the maximum numbers from each set. In such a situation, we will have to repeat, processing 10 or more times and ultimately, the program will become too large with repeated code. To handle such situation, we write our functions where we try to keep the source code which will be used again and again in our programming.
Now, let's see how to define a function in C programming language and then in the subsequent sections, we will explain how to use them.
Defining a Function
The general form of a function definition in C programming language is as follows −return_type function_name( parameter list ) { body of the function return [expression]; }A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −
- Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
- Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.
- Parameter List − A parameter is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
- Function Body − The function body contains a collection of statements that defines what the function does.
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform a defined task.Now, let's write the above example with the help of a function −
Live Demo
#include <stdio.h> int getMax( int set[] ) { int i, max; max = set[0]; i = 1; while( i < 5 ) { if( max < set[i] ) { max = set[i]; } i = i + 1; } return max; } main() { int set1[5] = {10, 20, 30, 40, 50}; int set2[5] = {101, 201, 301, 401, 501}; int max; /* Process first set of numbers available in set1[] */ max = getMax(set1); printf("Max in first set = %d\n", max ); /* Now process second set of numbers available in set2[] */ max = getMax(set2); printf("Max in second set = %d\n", max ); }When the above code is compiled and executed, it produces the following result −
Max in first set = 50 Max in second set = 501
Functions in Java
If you are clear about functions in C programming, then it is easy to understand them in Java as well. Java programming names them as methods, but the rest of the concepts remain more or less same.Following is the equivalent program written in Java. You can try to execute it to see the output −
Live Demo
public class DemoJava { public static void main(String []args) { int[] set1 = {10, 20, 30, 40, 50}; int[] set2 = {101, 201, 301, 401, 501}; int max; /* Process first set of numbers available in set1[] */ max = getMax(set1); System.out.format("Max in first set = %d\n", max ); /* Now process second set of numbers available in set2[] */ max = getMax(set2); System.out.format("Max in second set = %d\n", max ); } public static int getMax( int set[] ) { int i, max; max = set[0]; i = 1; while( i < 5 ) { if( max < set[i] ) { max = set[i]; } i = i + 1; } return max; } }When the above program is executed, it produces the following result −
Max in first set = 50 Max in second set = 501
Functions in Python
Once again, if you know the concept of functions in C and Java programming, then Python is not much different. Given below is the basic syntax of defining a function in Python −def function_name( parameter list ): body of the function return [expression]Using this syntax of function in Python, the above example can be written as follows −
Live Demo
def getMax( set ): max = set[0] i = 1 while( i < 5 ): if( max < set[i] ): max = set[i] i = i + 1 return max set1 = [10, 20, 30, 40, 50] set2 = [101, 201, 301, 401, 501] # Process first set of numbers available in set1[] max = getMax(set1) print "Max in first set = ", max # Now process second set of numbers available in set2[] max = getMax(set2) print "Max in second set = ", maxWhen the above code is executed, it produces the following result −
Max in first set = 50 Max in second set = 501
Computer Files
A computer file is used to store data in digital format like plain text, image data, or any other content. Computer files can be organized inside different directories. Files are used to keep digital data, whereas directories are used to keep files.Computer files can be considered as the digital counterpart of paper documents. While programming, you keep your source code in text files with different extensions, for example, C programming files end with the extension .c, Java programming files with .java, and Python files with .py.
File Input/Output
Usually, you create files using text editors such as notepad, MS Word, MS Excel or MS Powerpoint, etc. However, many times, we need to create files using computer programs as well. We can modify an existing file using a computer program.File input means data that is written into a file and file output means data that is read from a file. Actually, input and output terms are more related to screen input and output. When we display a result on the screen, it is called output. Similarly, if we provide some input to our program from the command prompt, then it is called input.
For now, it is enough to remember that writing into a file is file input and reading something from a file is file output.
File Operation Modes
Before we start working with any file using a computer program, either we need to create a new file if it does not exist or open an already existing file. In either case, we can open a file in the following modes −- Read-Only Mode − If you are going to just read an existing file and you do not want to write any further content in the file, then you will open the file in read-only mode. Almost all the programming languages provide syntax to open files in read-only mode.
- Write-Only Mode − If you are going to write into either an existing file or a newly created file but you do not want to read any written content from that file, then you will open the file in write-only mode. All the programming languages provide syntax to open files in write-only mode.
- Read & Write Mode − If you are going to read as well as write into the same file, then you will open file in read & write mode.
- Append Mode − When you open a file for writing, it allows you to start writing from the beginning of the file; however it will overwrite existing content, if any. Suppose we don’t want to overwrite any existing content, then we open the file in append mode. Append mode is ultimately a write mode, which allows content to be appended at the end of the file. Almost all the programming languages provide syntax to open files in append mode.
Opening Files
You can use the fopen() function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Here is the prototype, i.e., signature of this function call −FILE *fopen( const char * filename, const char * mode );Here, filename is string literal, which you will use to name your file and access mode can have one of the following values −
Sr.No | Mode & Description |
---|---|
1 | r Opens an existing text file for reading purpose. |
2 | w Opens a text file for writing. If it does not exist, then a new file is created. Here, your program will start writing content from the beginning of the file. |
3 | a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here, your program will start appending content in the existing file content. |
4 | r+ Opens a text file for reading and writing both. |
5 | w+ Opens a text file for both reading and writing. It first truncates the file to zero length, if it exists; otherwise creates the file if it does not exist. |
6 | a+ Opens a text file for both reading and writing. It creates a file, if it does not exist. The reading will start from the beginning, but writing can only be appended. |
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −int fclose( FILE *fp );The fclose( ) function returns zero on success, or EOF, special character, if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see a few of them in the next section.
Writing a File
Given below is the simplest function to write individual characters to a stream −int fputc( int c, FILE *fp );The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success, otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −
int fputs( const char *s, FILE *fp );The function fputs() writes the string s into the file referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can also use the function int fprintf(FILE *fp,const char *format, ...) to write a string into a file. Try the following example −
#include <stdio.h> int main() { FILE *fp; fp = fopen("/tmp/test.txt", "w+"); fprintf(fp, "This is testing for fprintf...\n"); fputs("This is testing for fputs...\n", fp); fclose(fp); }When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.
Reading a File
Given below is the simplest function to read a text file character by character −int fgetc( FILE * fp );The fgetc() function reads a character from the input file referenced by fp. The return value is the character read; or in case of any error, it returns EOF. The following function allows you to read a string from a stream −
char *fgets( char *buf, int n, FILE *fp );The function fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h> main() { FILE *fp; char buff[255]; fp = fopen("/tmp/test.txt", "r"); fscanf(fp, "%s", buff); printf("1 : %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("2: %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("3: %s\n", buff ); fclose(fp); }When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −
1 : This 2 : is testing for fprintf... 3 : This is testing for fputs...Let's analyze what happened here. First, the fscanf() method reads This because after that, it encountered a space. The second call is for fgets(), which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely.
File I/O in Java
Java provides even richer set of functions to handle File I/O. For more on this topic, we suggest you to check our Java Tutorials.Here, we will see a simple Java program, which is equivalent to the C program explained above. This program will open a text file, write a few text lines into it, and close the file. Finally, the same file is opened and then read from an already created file. You can try to execute the following program to see the output −
import java.io.*; public class DemoJava { public static void main(String []args) throws IOException { File file = new File("/tmp/java.txt"); // Create a File file.createNewFile(); // Creates a FileWriter Object using file object FileWriter writer = new FileWriter(file); // Writes the content to the file writer.write("This is testing for Java write...\n"); writer.write("This is second line...\n"); // Flush the memory and close the file writer.flush(); writer.close(); // Creates a FileReader Object FileReader reader = new FileReader(file); char [] a = new char[100]; // Read file content in the array reader.read(a); System.out.println( a ); // Close the file reader.close(); } }When the above program is executed, it produces the following result −
This is testing for Java write... This is second line...
File I/O in Python
The following program shows the same functionality to open a new file, write some content into it, and finally, read the same file −# Create a new file fo = open("/tmp/python.txt", "w") # Writes the content to the file fo.write( "This is testing for Python write...\n"); fo.write( "This is second line...\n"); # Close the file fo.close() # Open existing file fo = open("/tmp/python.txt", "r") # Read file content in a variable str = fo.read(100); print str # Close opened file fo.close()When the above code is executed, it produces the following result −
This is testing for Python write... This is second line...
We appreciate your patience for going through this tutorial. We have tried to keep it concise but as this subject contains several topics, we have shown a few examples in detail.
If you have not understood any of the concepts, then we recommend to go through the tutorial once again and once you are comfortable with the concepts explained in this tutorial, you can proceed further.
There are many other subjects related to computer programming which we did not cover intentionally to avoid any confusion, but we are sure those concepts will not be difficult for you to understand as long as you make yourself comfortable with the concepts explained in this tutorial.
At tutorialspoint, we have put lots of effort to prepare comprehensive tutorials on C, Java, and Python programming languages and we strongly recommend you to start either of them, after having completed this tutorial.
Introduction to Computer Program
Before getting into computer programming, let us first understand computer programs and what they do.
A computer program is a sequence of instructions written using a Computer Programming Language to perform a specified task by the computer.
The two important terms that we have used in the above definition are −- Sequence of instructions
- Computer Programming Language
You will use Human Language to tell the way to go to KFC, something as follows −
First go straight, after half kilometer, take left from the red light and then drive around one kilometer and you will find KFC at the right.Here, you have used English Language to give several steps to be taken to reach KFC. If they are followed in the following sequence, then you will reach KFC −
1. Go straight 2. Drive half kilometer 3. Take left 4. Drive around one kilometer 5. Search for KFC at your right sideNow, try to map the situation with a computer program. The above sequence of instructions is actually a Human Program written in English Language, which instructs on how to reach KFC from a given starting point. This same sequence could have been given in Spanish, Hindi, Arabic, or any other human language, provided the person seeking direction knows any of these languages.
Now, let's go back and try to understand a computer program, which is a sequence of instructions written in a Computer Language to perform a specified task by the computer. Following is a simple program written in Python programming Language −
print "Hello, World!"The above computer program instructs the computer to print "Hello, World!" on the computer screen.
- A computer program is also called a computer software, which can range from two lines to millions of lines of instructions.
- Computer program instructions are also called program source code and computer programming is also called program coding.
- A computer without a computer program is just a dump box; it is programs that make computers active.
Introduction to Computer Programming
If you understood what a computer program is, then we will say: the act of writing computer programs is called computer programming.As we mentioned earlier, there are hundreds of programming languages, which can be used to write computer programs and following are a few of them −
- Java
- C
- C++
- Python
- PHP
- Perl
- Ruby
Uses of Computer Programs
Today computer programs are being used in almost every field, household, agriculture, medical, entertainment, defense, communication, etc. Listed below are a few applications of computer programs −- MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are examples of computer programs.
- Computer programs are being used to develop graphics and special effects in movie making.
- Computer programs are being used to perform Ultrasounds, X-Rays, and other medical examinations.
- Computer programs are being used in our mobile phones for SMS, Chat, and voice communication.
Computer Programmer
Someone who can write computer programs or in other words, someone who can do computer programming is called a Computer Programmer.Based on computer programming language expertise, we can name a computer programmers as follows −
- C Programmer
- C++ Programmer
- Java Programmer
- Python Programmer
- PHP Programmer
- Perl Programmer
- Ruby Programmer
Algorithm
From programming point of view, an algorithm is a step-by-step procedure to resolve any problem. An algorithm is an effective method expressed as a finite set of well-defined instructions.Thus, a computer programmer lists down all the steps required to resolve a problem before writing the actual code. Following is a simple example of an algorithm to find out the largest number from a given list of numbers −
1. Get a list of numbers L1, L2, L3....LN 2. Assume L1 is the largest, Largest = L1 3. Take next number Li from the list and do the following 4. If Largest is less than Li 5. Largest = Li 6. If Li is last number from the list then 7. Print value stored in Largest and come out 8. Else repeat same process starting from step 3The above algorithm has been written in a crude way to help beginners understand the concept. You will come across more standardized ways of writing computer algorithms as you move on to advanced levels of computer programming.
Computer Programming - Basics
We assume you are well aware of English Language, which is a well-known Human Interface Language. English has a predefined grammar, which needs to be followed to write English statements in a correct way. Likewise, most of the Human Interface Languages (Hindi, English, Spanish, French, etc.) are made of several elements like verbs, nouns, adjectives, adverbs, propositions, and conjunctions, etc.Similar to Human Interface Languages, Computer Programming Languages are also made of several elements. We will take you through the basics of those elements and make you comfortable to use them in various programming languages. These basic elements include −
- Programming Environment
- Basic Syntax
- Data Types
- Variables
- Keywords
- Basic Operators
- Decision Making
- Loops
- Numbers
- Characters
- Arrays
- Strings
- Functions
- File I/O
This tutorial has been designed to give you an idea about the following most popular programming languages −
- C Programming
- Java Programming
- Python Programming
Computer Programming - Environment
Though Environment Setup is not an element of any Programming Language, it is the first step to be followed before setting on to write a program.When we say Environment Setup, it simply implies a base on top of which we can do our programming. Thus, we need to have the required software setup, i.e., installation on our PC which will be used to write computer programs, compile, and execute them. For example, if you need to browse Internet, then you need the following setup on your machine −
- A working Internet connection to connect to the Internet
- A Web browser such as Internet Explorer, Chrome, Safari, etc.
Similarly, you will need the following setup to start with programming using any programming language.
- A text editor to create computer programs.
- A compiler to compile the programs into binary format.
- An interpreter to execute the programs directly.
Text Editor
A text editor is a software that is used to write computer programs. Your Windows machine must have a Notepad, which can be used to type programs. You can launch it by following these steps −Start Icon → All Programs → Accessories → Notepad → Mouse Click on NotepadIt will launch Notepad with the following window −
You can use this software to type your computer program and save it in a file at any location. You can download and install other good editors like Notepad++, which is freely available.
If you are a Mac user, then you will have TextEdit or you can install some other commercial editor like BBEdit to start with.
Compiler?
You write your computer program using your favorite programming language and save it in a text file called the program file.Now let us try to get a little more detail on how the computer understands a program written by you using a programming language. Actually, the computer cannot understand your program directly given in the text format, so we need to convert this program in a binary format, which can be understood by the computer.
The conversion from text program to binary file is done by another software called Compiler and this process of conversion from text formatted program to binary format file is called program compilation. Finally, you can execute binary file to perform the programmed task.
We are not going into the details of a compiler and the different phases of compilation.
The following flow diagram gives an illustration of the process −
So, if you are going to write your program in any such language, which needs compilation like C, C++, Java and Pascal, etc., then you will need to install their compilers before you start programming.
Interpreter
We just discussed about compilers and the compilation process. Compilers are required in case you are going to write your program in a programming language that needs to be compiled into binary format before its execution.There are other programming languages such as Python, PHP, and Perl, which do not need any compilation into binary format, rather an interpreter can be used to read such programs line by line and execute them directly without any further conversion.
So, if you are going to write your programs in PHP, Python, Perl, Ruby, etc., then you will need to install their interpreters before you start programming.
Online Compilation
If you are not able to set up any editor, compiler, or interpreter on your machine, then tutorialspoint.com provides a facility to compile and run almost all the programs online with an ease of a single click.So do not worry and let's proceed further to have a thrilling experience to become a computer programmer in simple and easy steps.
Computer Programming - Basic Syntax
Let’s start with a little coding, which will really make you a computer programmer. We are going to write a single-line computer program to write Hello, World! on your screen. Let’s see how it can be written using different programming languages.Hello World Program in C
Try the following example using our online compiler option available at www.compileonline.com.For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler.
Try to change the content inside printf(), i.e., type anything in place of Hello World! and then check its result. It just prints whatever you keep inside the two double quotes.
Live Demo
#include <stdio.h> int main() { /* printf() function to write Hello, World! */ printf( "Hello, World!" ); }which produces the following result −
Hello, World!This little Hello World program will help us understand various basic concepts related to C Programming.
Program Entry Point
For now, just forget about the #include <stdio.h> statement, but keep a note that you have to put this statement at the top of a C program.Every C program starts with main(), which is called the main function, and then it is followed by a left curly brace. The rest of the program instruction is written in between and finally a right curly brace ends the program.
The coding part inside these two curly braces is called the program body. The left curly brace can be in the same line as main(){ or in the next line like it has been mentioned in the above program.
Functions
Functions are small units of programs and they are used to carry out a specific task. For example, the above program makes use of two functions: main() and printf(). Here, the function main() provides the entry point for the program execution and the other function printf() is being used to print an information on the computer screen.You can write your own functions which we will see in a separate chapter, but C programming itself provides various built-in functions like main(), printf(), etc., which we can use in our programs based on our requirement.
Some of the programming languages use the word sub-routine instead of function, but their functionality is more or less the same.
Comments
A C program can have statements enclosed inside /*.....*/. Such statements are called comments and these comments are used to make the programs user friendly and easy to understand. The good thing about comments is that they are completely ignored by compilers and interpreters. So you can use whatever language you want to write your comments.Whitespaces
When we write a program using any programming language, we use various printable characters to prepare programming statements. These printable characters are a, b, c,......z, A, B, C,.....Z, 1, 2, 3,...... 0, !, @, #, $, %, ^, &, *, (, ), -, _, +, =, \, |, {, }, [, ], :, ;, <, >, ?, /, \, ~. `. ", '. Hope I'm not missing any printable characters from your keyboard.Apart from these characters, there are some characters which we use very frequently but they are invisible in your program and these characters are spaces, tabs (\t), new lines(\n). These characters are called whitespaces.
These three important whitespace characters are common in all the programming languages and they remain invisible in your text document −
Whitespace | Explanation | Representation |
---|---|---|
New Line | To create a new line | \n |
Tab | To create a tab. | \t |
Space | To create a space. | empty space |
Live Demo
#include <stdio.h> int main() { /* printf() function to write Hello, World! */ printf( "Hello, World!" ); }which produces the following result −
Hello, World!If we make all these whitespace characters visible, then the above program will look like this and you will not be able to compile it −
#include <stdio.h>\n \n int main()\n { \n \t/* printf() function to write Hello, World! */ \n \tprintf(\t"Hello, World!"\t);\n \n }\n
Semicolons
Every individual statement in a C Program must be ended with a semicolon (;), for example, if you want to write "Hello, World!" twice, then it will be written as follows −Live Demo
#include <stdio.h> int main() { /* printf() function to write Hello, World! */ printf( "Hello, World!\n" ); printf( "Hello, World!" ); }This program will produce the following result −
Hello, World! Hello, World!Here, we are using a new line character \n in the first printf() function to create a new line. Let us see what happens if we do not use this new line character −
Live Demo
#include <stdio.h> int main() { /* printf() function to write Hello, World! */ printf( "Hello, World!" ); printf( "Hello, World!" ); }This program will produce the following result −
Hello, World! Hello, World!We will learn identifiers and keywords in next few chapters.
Program Explanation
Let us understand how the above C program works. First of all, the above program is converted into a binary format using C compiler. So let’s put this code in test.c file and compile it as follows −$gcc test.c -o demoIf there is any grammatical error (Syntax errors in computer terminologies), then we fix it before converting it into binary format. If everything goes fine, then it produces a binary file called demo. Finally, we execute the produced binary demo as follows −
$./demowhich produces the following result −
Hello, World!Here, when we execute the binary a.out file, the computer enters inside the program starting from main() and encounters a printf() statement. Keep a note that the line inside /*....*/ is a comment and it is filtered at the time of compilation. So printf() function instructs the computer to print the given line at the computer screen. Finally, it encounters a right curly brace which indicates the end of main() function and exits the program.
Syntax Error
If you do not follow the rules defined by the programing language, then at the time of compilation, you will get syntax errors and the program will not be compiled. From syntax point of view, even a single dot or comma or a single semicolon matters and you should take care of such small syntax as well. In the following example, we have skipped a semicolon, let's try to compile the program −Live Demo
#include <stdio.h> main() { printf("Hello, World!") }This program will produce the following result −
main.c: In function 'main': main.c:7:1: error: expected ';' before '}' token } ^So the bottom-line is that if you are not following proper syntax defined by the programming language in your program, then you will get syntax errors. Before attempting another compilation, you will need to fix them and then proceed.
Hello World Program in Java
Following is the equivalent program written in Java. This program will also produce the same result Hello, World!.Live Demo
public class HelloWorld { public static void main(String []args) { /* println() function to write Hello, World! */ System.out.println("Hello, World!"); } }which produces the following result −
Hello, World!
Hello World Program in Python
Following is the equivalent program written in Python. This program will also produce the same result Hello, World!.Live Demo
# print function to write Hello, World! */ print "Hello, World!"which produces the following result −
Hello, World!Hope you noted that for C and Java examples, first we are compiling the programs and then executing the produced binaries, but in Python program, we are directly executing it. As we explained in the previous chapter, Python is an interpreted language and it does not need an intermediate step called compilation.
Python does not require a semicolon (;) to terminate a statement, rather a new line always means termination of the statement.
Computer Programming - Data Types
Let's discuss about a very simple but very important concept available in almost all the programming languages which is called data types. As its name indicates, a data type represents a type of the data which you can process using your computer program. It can be numeric, alphanumeric, decimal, etc.Let’s keep Computer Programming aside for a while and take an easy example of adding two whole numbers 10 & 20, which can be done simply as follows −
10 + 20Let's take another problem where we want to add two decimal numbers 10.50 & 20.50, which will be written as follows −
10.50 + 20.50The two examples are straightforward. Now let's take another example where we want to record student information in a notebook. Here we would like to record the following information −
Name: Class: Section: Age: Sex:Now, let's put one student record as per the given requirement −
Name: Zara Ali Class: 6th Section: J Age: 13 Sex: FThe first example dealt with whole numbers, the second example added two decimal numbers, whereas the third example is dealing with a mix of different data. Let's put it as follows −
- Student name "Zara Ali" is a sequence of characters which is also called a string.
- Student class "6th" has been represented by a mix of whole number and a string of two characters. Such a mix is called alphanumeric.
- Student section has been represented by a single character which is 'J'.
- Student age has been represented by a whole number which is 13.
- Student sex has been represented by a single character which is 'F'.
Similarly, when we write a computer program to process different types of data, we need to specify its type clearly; otherwise the computer does not understand how different operations can be performed on that given data. Different programming languages use different keywords to specify different data types. For example, C and Java programming languages use int to specify integer data, whereas char specifies a character data type.
Subsequent chapters will show you how to use different data types in different situations. For now, let's check the important data types available in C, Java, and Python and the keywords we will use to specify those data types.
C and Java Data Types
C and Java support almost the same set of data types, though Java supports additional data types. For now, we are taking a few common data types supported by both the programming languages −Type | Keyword | Value range which can be represented by this data type |
---|---|---|
Character | char | -128 to 127 or 0 to 255 |
Number | int | -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 |
Small Number | short | -32,768 to 32,767 |
Long Number | long | -2,147,483,648 to 2,147,483,647 |
Decimal Number | float | 1.2E-38 to 3.4E+38 till 6 decimal places |
Python Data Types
Python has five standard data types but this programming language does not make use of any keyword to specify a particular data type, rather Python is intelligent enough to understand a given data type automatically.- Numbers
- String
- List
- Tuple
- Dictionary
Computer Programming - Variables
Variables are the names you give to computer memory locations which are used to store values in a computer program.For example, assume you want to store two values 10 and 20 in your program and at a later stage, you want to use these two values. Let's see how you will do it. Here are the following three simple steps −
- Create variables with appropriate names.
- Store your values in those two variables.
- Retrieve and use the stored values from the variables.
Creating variables
Creating variables is also called declaring variables in C programming. Different programming languages have different ways of creating variables inside a program. For example, C programming has the following simple way of creating variables −#include <stdio.h> int main() { int a; int b; }The above program creates two variables to reserve two memory locations with names a and b. We created these variables using int keyword to specify variable data type which means we want to store integer values in these two variables. Similarly, you can create variables to store long, float, char or any other data type. For example −
/* variable to store long value */ long a; /* variable to store float value */ float b;You can create variables of similar type by putting them in a single line but separated by comma as follows −
#include <stdio.h> int main() { int a, b; }Listed below are the key points about variables that you need to keep in mind −
- A variable name can hold a single type of value. For example, if variable a has been defined int type, then it can store only integer.
- C programming language requires a variable creation, i.e., declaration before its usage in your program. You cannot use a variable name in your program without creating it, though programming language like Python allows you to use a variable name without creating it.
- You can use a variable name only once inside your program. For example, if a variable a has been defined to store an integer value, then you cannot define a again to store any other type of value.
- There are programming languages like Python, PHP, Perl, etc., which do not want you to specify data type at the time of creating variables. So you can store integer, float, or long without specifying their data type.
- You can give any name to a variable like age, sex, salary, year1990 or anything else you like to give, but most of the programming languages allow to use only limited characters in their variables names. For now, we will suggest to use only a....z, A....Z, 0....9 in your variable names and start their names using alphabets only instead of digits.
- Almost none of the programming languages allow to start their variable names with a digit, so 1990year will not be a valid variable name whereas year1990 or ye1990ar are valid variable names.
Store Values in Variables
You have seen how we created variables in the previous section. Now, let's store some values in those variables −#include <stdio.h> int main() { int a; int b; a = 10; b = 20; }The above program has two additional statements where we are storing 10 in variable a and 20 is being stored in variable b. Almost all the programming languages have similar way of storing values in variable where we keep variable name in the left hand side of an equal sign = and whatever value we want to store in the variable, we keep that value in the right hand side.
Now, we have completed two steps, first we created two variables and then we stored required values in those variables. Now variable a has value 10 and variable b has value 20. In other words we can say, when above program is executed, the memory location named a will hold 10 and memory location b will hold 20.
Access stored values in variables
If we do not use the stored values in the variables, then there is no point in creating variables and storing values in them. We know that the above program has two variables a and b and they store the values 10 and 20, respectively. So let's try to print the values stored in these two variables. Following is a C program, which prints the values stored in its variables −Live Demo
#include <stdio.h> int main() { int a; int b; a = 10; b = 20; printf( "Value of a = %d\n", a ); printf( "Value of b = %d\n", b ); }When the above program is executed, it produces the following result −
Value of a = 10 Value of b = 20You must have seen printf() function in the previous chapter where we had used it to print "Hello, World!". This time, we are using it to print the values of variables. We are making use of %d, which will be replaced with the values of the given variable in printf() statements. We can print both the values using a single printf() statement as follows −
Live Demo
#include <stdio.h> int main() { int a; int b; a = 10; b = 20; printf( "Value of a = %d and value of b = %d\n", a, b ); }When the above program is executed, it produces the following result −
Value of a = 10 and value of b = 20If you want to use float variable in C programming, then you will have to use %f instead of %d, and if you want to print a character value, then you will have to use %c. Similarly, different data types can be printed using different % and characters.
Variables in Java
Following is the equivalent program written in Java programming language. This program will create two variables a and b and very similar to C programming, it will assign 10 and 20 in these variables and finally print the values of the two variables in two ways −Live Demo
public class DemoJava { public static void main(String []args) { int a; int b; a = 10; b = 20; System.out.println("Value of a = " + a); System.out.println("Value of b = " + b); System.out.println("Value of a = " + a + " and value of b = " + b); } }When the above program is executed, it produces the following result −
Value of a = 10 Value of b = 20 Value of a = 10 and value of b = 20
Variables in Python
Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables.Python does not want you to specify the data type at the time of variable creation and there is no need to create variables in advance.
Live Demo
a = 10 b = 20 print "Value of a = ", a print "Value of b = ", b print "Value of a = ", a, " and value of b = ", bWhen the above program is executed, it produces the following result −
Value of a = 10 Value of b = 20 Value of a = 10 and value of b = 20You can use the following syntax in C and Java programming to declare variables and assign values at the same time −
Live Demo
#include <stdio.h> int main() { int a = 10; int b = 20; printf( "Value of a = %d and value of b = %d\n", a, b ); }When the above program is executed, it produces the following result −
Value of a = 10 and value of b = 20
Computer Programming - Keywords
So far, we have covered two important concepts called variables and their data types. We discussed how to use int, long, and float to specify different data types. We also learnt how to name the variables to store different values.Though this chapter is not required separately because reserved keywords are a part of basic programming syntax, we kept it separate to explain it right after data types and variables to make it easy to understand.
Like int, long, and float, there are many other keywords supported by C programming language which we will use for different purpose. Different programming languages provide different set of reserved keywords, but there is one important & common rule in all the programming languages that we cannot use a reserved keyword to name our variables, which means we cannot name our variable like int or float rather these keywords can only be used to specify a variable data type.
For example, if you will try to use any reserved keyword for the purpose of variable name, then you will get a syntax error.
Live Demo
#include <stdio.h> int main() { int float; float = 10; printf( "Value of float = %d\n", float); }When you compile the above program, it produces the following error −
main.c: In function 'main': main.c:5:8: error: two or more data types in declaration specifiers int float; ......Let's now give a proper name to our integer variable, then the above program should compile and execute successfully −
Live Demo
#include <stdio.h> int main() { int count; count = 10; printf( "Value of count = %d\n", count); }
C Programming Reserved Keywords
Here is a table having almost all the keywords supported by C Programming language −auto | else | long | switch |
break | enum | register | typedef |
case | extern | return | union |
char | float | short | unsigned |
const | for | signed | void |
continue | goto | sizeof | volatile |
default | if | static | while |
do | int | struct | _Packed |
double |
Java Programming Reserved Keywords
Here is a table having almost all the keywords supported by Java Programming language −abstract | assert | boolean | break |
byte | case | catch | char |
class | const | continue | default |
do | double | else | enum |
extends | final | finally | float |
for | goto | if | implements |
import | instanceof | int | interface |
long | native | new | package |
private | protected | public | return |
short | static | strictfp | super |
switch | synchronized | this | throw |
throws | transient | try | void |
volatile | while |
Python Programming Reserved Keywords
Here is a table having almost all the keywords supported by Python Programming language −and | exec | not |
assert | finally | or |
break | for | pass |
class | from | |
continue | global | raise |
def | if | return |
del | import | try |
elif | in | while |
else | is | with |
except | lambda | yield |
Computer Programming - Operators
An operator in a programming language is a symbol that tells the compiler or interpreter to perform specific mathematical, relational or logical operation and produce final result. This chapter will explain the concept of operators and it will take you through the important arithmetic and relational operators available in C, Java, and Python.Arithmetic Operators
Computer programs are widely used for mathematical calculations. We can write a computer program which can do simple calculation like adding two numbers (2 + 3) and we can also write a program, which can solve a complex equation like P(x) = x4 + 7x3 - 5x + 9. If you have been even a poor student, you must be aware that in first expression 2 and 3 are operands and + is an operator. Similar concepts exist in Computer Programming.Take a look at the following two examples −
2 + 3 P(x) = x4 + 7x3 - 5x + 9.These two statements are called arithmetic expressions in a programming language and plus, minus used in these expressions are called arithmetic operators and the values used in these expressions like 2, 3 and x, etc., are called operands. In their simplest form, such expressions produce numerical results.
Similarly, a programming language provides various arithmetic operators. The following table lists down a few of the important arithmetic operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −
Operator | Description | Example |
---|---|---|
+ | Adds two operands | A + B will give 30 |
- | Subtracts second operand from the first | A - B will give -10 |
* | Multiplies both operands | A * B will give 200 |
/ | Divides numerator by de-numerator | B / A will give 2 |
% | This gives remainder of an integer division | B % A will give 0 |
Live Demo
#include <stdio.h> int main() { int a, b, c; a = 10; b = 20; c = a + b; printf( "Value of c = %d\n", c); c = a - b; printf( "Value of c = %d\n", c); c = a * b; printf( "Value of c = %d\n", c); c = b / a; printf( "Value of c = %d\n", c); c = b % a; printf( "Value of c = %d\n", c); }When the above program is executed, it produces the following result −
Value of c = 30 Value of c = -10 Value of c = 200 Value of c = 2 Value of c = 0
Relational Operators
Consider a situation where we create two variables and assign them some values as follows −A = 20 B = 10Here, it is obvious that variable A is greater than B in values. So, we need the help of some symbols to write such expressions which are called relational expressions. If we use C programming language, then it will be written as follows −
(A > B)Here, we used a symbol > and it is called a relational operator and in their simplest form, they produce Boolean results which means the result will be either true or false. Similarly, a programming language provides various relational operators. The following table lists down a few of the important relational operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −
Operator | Description | Example |
---|---|---|
== | Checks if the values of two operands are equal or not, if yes then condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (A <= B) is true. |
Live Demo
#include <stdio.h> int main() { int a, b; a = 10; b = 20; /* Here we check whether a is equal to 10 or not */ if( a == 10 ) { /* if a is equal to 10 then this body will be executed */ printf( "a is equal to 10\n"); } /* Here we check whether b is equal to 10 or not */ if( b == 10 ) { /* if b is equal to 10 then this body will be executed */ printf( "b is equal to 10\n"); } /* Here we check if a is less b than or not */ if( a < b ) { /* if a is less than b then this body will be executed */ printf( "a is less than b\n"); } /* Here we check whether a and b are not equal */ if( a != b ) { /* if a is not equal to b then this body will be executed */ printf( "a is not equal to b\n"); } }When the above program is executed, it produces the following result −
a is equal to 10 a is less than b a is not equal to b
Logical Operators
Logical operators are very important in any programming language and they help us take decisions based on certain conditions. Suppose we want to combine the result of two conditions, then logical AND and OR logical operators help us in producing the final result.The following table shows all the logical operators supported by the C language. Assume variable A holds 1 and variable B holds 0, then −
Operator | Description | Example |
---|---|---|
&& | Called Logical AND operator. If both the operands are non-zero, then condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | !(A && B) is true. |
Live Demo
#include <stdio.h> int main() { int a = 1; int b = 0; if ( a && b ) { printf("This will never print because condition is false\n" ); } if ( a || b ) { printf("This will be printed print because condition is true\n" ); } if ( !(a && b) ) { printf("This will be printed print because condition is true\n" ); } }When you compile and execute the above program, it produces the following result −
This will be printed print because condition is true This will be printed print because condition is true
Operators in Java
Following is the equivalent program written in Java. C programming and Java provide almost identical set of operators and conditional statements. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators −You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
Live Demo
public class DemoJava { public static void main(String []args) { int a, b, c; a = 10; b = 20; c = a + b; System.out.println("Value of c = " + c ); c = a - b; System.out.println("Value of c = " + c ); c = a * b; System.out.println("Value of c = " + c ); c = b / a; System.out.println("Value of c = " + c ); c = b % a; System.out.println("Value of c = " + c ); if( a == 10 ) { System.out.println("a is equal to 10" ); } } }When the above program is executed, it produces the following result −
Value of c = 30 Value of c = -10 Value of c = 200 Value of c = 2 Value of c = 0 a is equal to 10
Operators in Python
Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables. Fortunately, C programming and Python programming languages provide almost identical set of operators. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators.You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
Live Demo
a = 10 b = 20 c = a + b print "Value of c = ", c c = a - b print "Value of c = ", c c = a * b print "Value of c = ", c c = a / b print "Value of c = ", c c = a % b print "Value of c = ", c if( a == 10 ): print "a is equal to 10"When the above program is executed, it produces the following result −
Value of c = 30 Value of c = -10 Value of c = 200 Value of c = 0 Value of c = 10 a is equal to 10
Decision Statements
Decision making is critical to computer programming. There will be many situations when you will be given two or more options and you will have to select an option based on the given conditions. For example, we want to print a remark about a student based on his secured marks. Following is the situation −Assume given marks are x for a student: If given marks are more than 95, then Student is brilliant If given marks are less than 30, then Student is poor If given marks are less than 95 and more than 30, then Student is averageNow, the question is how to write a programming code to handle such situations. Almost all the programming languages provide conditional statements that work based on the following flow diagram −
Let's write a C program with the help of if conditional statements to convert the above given situation into a programming code −
Live Demo
#include <stdio.h> int main() { int x = 45; if( x > 95) { printf( "Student is brilliant\n"); } if( x < 30) { printf( "Student is poor\n"); } if( x < 95 && x > 30 ) { printf( "Student is average\n"); } }When the above program is executed, it produces the following result −
Student is averageThe above program uses if conditional statements. Here, the first if statement checks whether the given condition i.e., variable x is greater than 95 or not and if it finds the condition is true, then the conditional body is entered to execute the given statements. Here we have only one printf() statement to print a remark about the student.
Similarly, the second if statement works. Finally, the third if statement is executed, here we have the following two conditions −
- First condition is x > 95
- Second condition is x < 30
This tutorial will give you a basic idea on various forms of if statements and an introduction to switch statements available in C programming language. Different programming languages provide different types of decision-making statements, but the basic concept remains the same as explained in this tutorial.
if...else statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. The syntax of an if...else statement in C programming language is −if(boolean_expression) { /* Statement(s) will execute if the boolean expression is true */ } else { /* Statement(s) will execute if the boolean expression is false */ }The above syntax can be represented in the form of a flow diagram as shown below −
An if...else statement is useful when we have to take a decision out of two options. For example, if a student secures more marks than 95, then the student is brilliant, otherwise no such situation can be coded, as follows −
Live Demo
#include <stdio.h> int main() { int x = 45; if( x > 95) { printf( "Student is brilliant\n"); } else { printf( "Student is not brilliant\n"); } }When the above program is executed, it produces the following result −
Student is not brilliant
if...elseif...else statement
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions.While using if, else if, else statements, there are a few points to keep in mind −
- An if can have zero or one else's and it must come after an else if.
- An if can have zero to many else…if's and they must come before the else.
- Once an else…if succeeds, none of the remaining else…if's or else's will be tested.
if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ } else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */ } else { /* Executes when the none of the above condition is true */ }Now with the help of if...elseif...else statement, the very first program can be coded as follows −
Live Demo
#include <stdio.h> int main() { int x = 45; if( x > 95) { printf( "Student is brilliant\n"); } else if( x < 30) { printf( "Student is poor\n"); } else if( x < 95 && x > 30 ) { printf( "Student is average\n"); } }When the above program is executed, it produces the following result −
Student is average
The Switch Statement
A switch statement is an alternative of if statements which allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. It has the following syntax −switch(expression){ case ONE : statement(s); break; case TWO: statement(s); break; ...... default : statement(s); }The expression used in a switch statement must give an integer value, which will be compared for equality with different cases given. Wherever an expression value matches with a case value, the body of that case will be executed and finally, the switch will be terminated using a break statement. If no break statements are provided, then the computer continues executing other statements available below to the matched case. If none of the cases matches, then the default case body is executed.
The above syntax can be represented in the form of a flow diagram as shown below −
Now, let's consider another example where we want to write the equivalent English word for a given number. Then, it can be coded as follows −
Live Demo
#include <stdio.h> int main() { int x = 2; switch( x ){ case 1 : printf( "One\n"); break; case 2 : printf( "Two\n"); break; case 3 : printf( "Three\n"); break; case 4 : printf( "Four\n"); break; default : printf( "None of the above...\n"); } }When the above program is executed, it produces the following result −
Two
Decisions in Java
Following is the equivalent program written in Java which too supports if, if...else, if...elseif...else, and switch statements.You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
Live Demo
public class DemoJava { public static void main(String []args) { int x = 45; if( x > 95) { System.out.println( "Student is brilliant"); } else if( x < 30) { System.out.println( "Student is poor"); } else if( x < 95 && x > 30 ) { System.out.println( "Student is average"); } } }When the above program is executed, it produces the following result −
Student is average
Decisions in Python
Following is the equivalent program written in Python. Python provides if, if...else, if...elif...else, and switch statements. Here, you must note that Python does not make use of curly braces for conditional body, instead it simply identifies the body of the block using indentation of the statements.You can try to execute the following program to see the output −
Live Demo
x = 45 if x > 95: print "Student is brilliant" elif x < 30: print "Student is poor" elif x < 95 and x > 30: print "Student is average" print "The end"When the above program is executed, it produces the following result −
Student is average The end
Computer Programming - Loops
Let's consider a situation when you want to print Hello, World! five times. Here is a simple C program to do the same −Live Demo
#include <stdio.h> int main() { printf( "Hello, World!\n"); printf( "Hello, World!\n"); printf( "Hello, World!\n"); printf( "Hello, World!\n"); printf( "Hello, World!\n"); }When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!It was simple, but again, let's consider another situation when you want to write Hello, World! a thousand times. We can certainly not write printf() statements a thousand times. Almost all the programming languages provide a concept called loop, which helps in executing one or more statements up to a desired number of times. All high-level programming languages provide various forms of loops, which can be used to execute one or more statements repeatedly.
Let's write the above C program with the help of a while loop and later, we will discuss how this loop works
Live Demo
#include <stdio.h> int main() { int i = 0; while ( i < 5 ) { printf( "Hello, World!\n"); i = i + 1; } }When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!The above program makes use of a while loop, which is being used to execute a set of programming statements enclosed within {....}. Here, the computer first checks whether the given condition, i.e., variable "a" is less than 5 or not and if it finds the condition is true, then the loop body is entered to execute the given statements. Here, we have the following two statements in the loop body −
- First statement is printf() function, which prints Hello World!
- Second statement is i = i + 1, which is used to increase the value of variable i
To conclude, a loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −
This tutorial has been designed to present programming's basic concepts to non-programmers, so let's discuss the two most important loops available in C programming language. Once you are clear about these two loops, then you can pick-up C programming tutorial or a reference book and check other loops available in C and the way they work.
The while Loop
A while loop available in C Programming language has the following syntax −while ( condition ) { /*....while loop body ....*/ }The above code can be represented in the form of a flow diagram as shown below −
The following important points are to be noted about a while loop −
- A while loop starts with a keyword while followed by a condition enclosed in ( ).
- Further to the while() statement, you will have the body of the loop enclosed in curly braces {...}.
- A while loop body can have one or more lines of source code to be executed repeatedly.
- If the body of a while loop has just one line, then its optional to use curly braces {...}.
- A while loop keeps executing its body till a given condition holds true. As soon as the condition becomes false, the while loop comes out and continues executing from the immediate next statement after the while loop body.
- A condition is usually a relational statement, which is evaluated to either true or false. A value equal to zero is treated as false and any non-zero value works like true.
The do...while Loop
A while loop checks a given condition before it executes any statements given in the body part. C programming provides another form of loop, called do...while that allows to execute a loop body before checking a given condition. It has the following syntax −do { /*....do...while loop body ....*/ } while ( condition );The above code can be represented in the form of a flow diagram as shown below −
If you will write the above example using do...while loop, then Hello, World will produce the same result −
Live Demo
#include <stdio.h> int main() { int i = 0; do { printf( "Hello, World!\n"); i = i + 1; } while ( i < 5 ); }When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!
The break statement
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. The syntax for a break statement in C is as follows −break;A break statement can be represented in the form of a flow diagram as shown below −
Following is a variant of the above program, but it will come out after printing Hello World! only three times −
Live Demo
#include <stdio.h> int main() { int i = 0; do { printf( "Hello, World!\n"); i = i + 1; if( i == 3 ) { break; } } while ( i < 5 ); }When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World!
The continue statement
The continue statement in C programming language works somewhat like the break statement. Instead of forcing termination, continue forces the next iteration of the loop to take place, skipping any code in between. The syntax for a continue statement in C is as follows −continue;A continue statement can be represented in the form of a flow diagram as shown below −
Following is a variant of the above program, but it will skip printing when the variable has a value equal to 3 −
Live Demo
#include <stdio.h> int main() { int i = 0; do { if( i == 3 ) { i = i + 1; continue; } printf( "Hello, World!\n"); i = i + 1; } while ( i < 5 ); }When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World! Hello, World!
Loops in Java
Following is the equivalent program written in Java that too supports while and do...while loops. The following program prints Hello, World! five times as we did in the case of C Programming −You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
Live Demo
public class DemoJava { public static void main(String []args) { int i = 0; while ( i < 5 ) { System.out.println("Hello, World!"); i = i + 1; } } }The break and continue statements in Java programming work quite the same way as they work in C programming.
Loops in Python
Following is the equivalent program written in Python. Python too supports while and do...while loops. The following program prints Hello, World! five times as we did in case of C Programming. Here you must note that Python does not make use of curly braces for the loop body, instead it simply identifies the body of the loop using indentation of the statements.You can try to execute the following program to see the output. To show the difference, we have used one more print statement, which will be executed when the loop will be over.
Live Demo
i = 0 while (i < 5): print "Hello, World!" i = i + 1 print "Loop ends"When the above program is executed, it produces the following result −
Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Loop endsThe break and continue statements in Python work quite the same way as they do in C programming.
Computer Programming - Numbers
Every programming language provides support for manipulating different types of numbers such as simple whole integers and floating point numbers. C, Java, and Python categorize these numbers in several categories based on their nature.Let's go back and check the data types chapter, where we listed down the core data types related to numbers −
Type | Keyword | Value range which can be represented by this data type |
---|---|---|
Number | int | -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 |
Small Number | short | -32,768 to 32,767 |
Long Number | long | -2,147,483,648 to 2,147,483,647 |
Decimal Number | float | 1.2E-38 to 3.4E+38 till 6 decimal places |
We have seen various mathematical and logical operations on numbers during a discussion on operators. So we know how to add numbers, subtract numbers, divide numbers, etc.
First let's see how to print various types of numbers available in C programming language −
Live Demo
#include <stdio.h> int main() { short s; int i; long l; float f; double d; s = 10; i = 1000; l = 1000000; f = 230.47; d = 30949.374; printf( "s: %d\n", s); printf( "i: %d\n", i); printf( "l: %ld\n", l); printf( "f: %.3f\n", f); printf( "d: %.3f\n", d); }Rest of the coding is very obvious, but we used %.3f to print float and double, which indicates the number of digits after the decimal to be printed. When the above program is executed, it produces the following result −
s: 10 i: 1000 l: 1000000 f: 230.470 d: 30949.374
Math Operations on Numbers
The following table lists down various useful built-in mathematical functions available in C programming language which can be used for various important mathematical calculations.For example, if you want to calculate the square root of a number, for example, 2304, then you have a built-in function available to calculate the square root.
Sr.No. | Function & Purpose |
---|---|
1 | double cos(double); This function takes an angle (as a double) and returns the cosine. |
2 | double sin(double); This function takes an angle (as a double) and returns the sine. |
3 | double tan(double); This function takes an angle (as a double) and returns the tangent. |
4 | double log(double); This function takes a number and returns the natural log of that number. |
5 | double pow(double, double); The first is a number you wish to raise and the second is the power you wish to raise it to. |
6 | double hypot(double, double); If you pass this function the length of two sides of a right triangle, it will return the length of the hypotenuse. |
7 | double sqrt(double); You pass this function a number and it returns its square root. |
8 | int abs(int); This function returns the absolute value of an integer that is passed to it. |
9 | double fabs(double); This function returns the absolute value of any decimal number passed to it. |
10 | double floor(double); Finds the integer which is less than or equal to the argument passed to it. |
Live Demo
#include <stdio.h> #include <math.h> int main() { short s; int i; long l; float f; double d; printf( "sin(s): %f\n", sin(10)); printf( "abs(i): %f\n", abs(1000)); printf( "floor(f): %f\n", floor(230.47)); printf( "sqrt(l): %f\n", sqrt(1000000)); printf( "pow(d, 2): %f\n", pow(2.374, 2)); }When the above program is executed, it produces the following result −
sin(s): -0.544021 abs(i): -0.544021 floor(f): 230.000000 sqrt(l): 1000.000000 pow(d, 2): 5.635876Besides the above usage, you will use numbers in loop counting, flag representation, true or false values in C programming.
Numbers in Java
Following is the equivalent program written in Java. Java provides almost all the numeric data types available in C programming.You can try to execute the following program to see the output, which is identical to the result generated by the above C example.
Live Demo
public class DemoJava { public static void main(String []args) { short s; int i; long l; float f; double d; s = 10; i = 1000; l = 1000000L; f = 230.47f; d = 30949.374; System.out.format( "s: %d\n", s); System.out.format( "i: %d\n", i); System.out.format( "l: %d\n", l); System.out.format( "f: %f\n", f); System.out.format( "d: %f\n", d); } }When the above program is executed, it produces the following result −
s: 10 i: 1000 l: 1000000 f: 230.470001 d: 30949.374000Java also provides a full range of built-in functions for mathematical calculation and you can use them in the same way as you did in C programming.
Numbers in Python
Python is a little different from C and Java; it categorizes numbers in int, long, float and complex. Here are some examples of numbers in Python −int | long | float | complex |
---|---|---|---|
10 | 51924361L | 0.0 | 3.14j |
100 | -0x19323L | 15.20 | 45.j |
-786 | 0122L | -21.9 | 9.322e-36j |
080 | 0xDEFABCECBDAECBFBAEl | 32.3+e18 | .876j |
-0490 | 535633629843L | -90. | -.6545+0J |
-0x260 | -052318172735L | -32.54e100 | 3e+26J |
0x69 | -4721885298529L | 70.2-E12 | 4.53e-7j |
Live Demo
s = 10 i = 1000 l = 1000000 f = 230.47 d = 30949.374 print "s: ", s print "i: ", i print "l: ", l print "f: ", f print "d: ", dWhen the above program is executed, it produces the following result −
s: 10 i: 1000 l: 1000000 f: 230.47 d: 30949.374Python also provides a full range of built-in functions for mathematical calculations and you can use them in the same way you have used them in C programming.
Computer Programming - Characters
If it was easy to work with numbers in computer programming, it would be even easier to work with characters. Characters are simple alphabets like a, b, c, d...., A, B, C, D,....., but with an exception. In computer programming, any single digit number like 0, 1, 2,....and special characters like $, %, +, -.... etc., are also treated as characters and to assign them in a character type variable, you simply need to put them inside single quotes. For example, the following statement defines a character type variable ch and we assign a value 'a' to it −char ch = 'a';Here, ch is a variable of character type which can hold a character of the implementation's character set and 'a' is called a character literal or a character constant. Not only a, b, c,.... but when any number like 1, 2, 3.... or any special character like !, @, #, #, $,.... is kept inside single quotes, then they will be treated as a character literal and can be assigned to a variable of character type, so the following is a valid statement −
char ch = '1';A character data type consumes 8 bits of memory which means you can store anything in a character whose ASCII value lies in between -127 to 127, so it can hold any of the 256 different values. A character data type can store any of the characters available on your keyboard including special characters like !, @, #, #, $, %, ^, &, *, (, ), _, +, {, }, etc.
Note that you can keep only a single alphabet or a single digit number inside single quotes and more than one alphabets or digits are not allowed inside single quotes. So the following statements are invalid in C programming −
char ch1 = 'ab'; char ch2 = '10';Given below is a simple example, which shows how to define, assign, and print characters in C Programming language −
Live Demo
#include <stdio.h> int main() { char ch1; char ch2; char ch3; char ch4; ch1 = 'a'; ch2 = '1'; ch3 = '$'; ch4 = '+'; printf( "ch1: %c\n", ch1); printf( "ch2: %c\n", ch2); printf( "ch3: %c\n", ch3); printf( "ch4: %c\n", ch4); }Here, we used %c to print a character data type. When the above program is executed, it produces the following result −
ch1: a ch2: 1 ch3: $ ch4: +
Escape Sequences
Many programming languages support a concept called Escape Sequence. When a character is preceded by a backslash (\), it is called an escape sequence and it has a special meaning to the compiler. For example, \n in the following statement is a valid character and it is called a new line character −char ch = '\n';Here, character n has been preceded by a backslash (\), it has special meaning which is a new line but keep in mind that backslash (\) has special meaning with a few characters only. The following statement will not convey any meaning in C programming and it will be assumed as an invalid statement −
char ch = '\1';The following table lists the escape sequences available in C programming language −
Escape Sequence | Description |
---|---|
\t | Inserts a tab in the text at this point. |
\b | Inserts a backspace in the text at this point. |
\n | Inserts a newline in the text at this point. |
\r | Inserts a carriage return in the text at this point. |
\f | Inserts a form feed in the text at this point. |
\' | Inserts a single quote character in the text at this point. |
\" | Inserts a double quote character in the text at this point. |
\\ | Inserts a backslash character in the text at this point. |
Live Demo
#include <stdio.h> int main() { char ch1; char ch2; char ch3; char ch4; ch1 = '\t'; ch2 = '\n'; printf( "Test for tabspace %c and a newline %c will start here", ch1, ch2); }When the above program is executed, it produces the following result −
Test for tabspace and a newline will start here
Characters in Java
Following is the equivalent program written in Java. Java handles character data types much in the same way as we have seen in C programming. However, Java provides additional support for character manipulation.You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
Live Demo
public class DemoJava { public static void main(String []args) { char ch1; char ch2; char ch3; char ch4; ch1 = 'a'; ch2 = '1'; ch3 = '$'; ch4 = '+'; System.out.format( "ch1: %c\n", ch1); System.out.format( "ch2: %c\n", ch2); System.out.format( "ch3: %c\n", ch3); System.out.format( "ch4: %c\n", ch4); } }When the above program is executed, it produces the following result −
ch1: a ch2: 1 ch3: $ ch4: +Java also supports escape sequence in the same way you have used them in C programming.
Characters in Python
Python does not support any character data type but all the characters are treated as string, which is a sequence of characters. We will study strings in a separate chapter. You do not need to have any special arrangement while using a single character in Python.Following is the equivalent program written in Python −
Live Demo
ch1 = 'a'; ch2 = '1'; ch3 = '$'; ch4 = '+'; print "ch1: ", ch1 print "ch2: ", ch2 print "ch3: ", ch3 print "ch4: ", ch4When the above program is executed, it produces the following result −
ch1: a ch2: 1 ch3: $ ch4: +Python supports escape sequences in the same way as you have used them in C programming.
Computer Programming - Arrays
Consider a situation where we need to store five integer numbers. If we use programming's simple variable and data type concepts, then we need five variables of int data type and the program will be as follows −Live Demo
#include <stdio.h> int main() { int number1; int number2; int number3; int number4; int number5; number1 = 10; number2 = 20; number3 = 30; number4 = 40; number5 = 50; printf( "number1: %d\n", number1); printf( "number2: %d\n", number2); printf( "number3: %d\n", number3); printf( "number4: %d\n", number4); printf( "number5: %d\n", number5); }It was simple, because we had to store just five integer numbers. Now let's assume we have to store 5000 integer numbers. Are we going to use 5000 variables?
To handle such situations, almost all the programming languages provide a concept called array. An array is a data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number1, number2, ..., number99, you just declare one array variable number of integer type and use number1[0], number1[1], and ..., number1[99] to represent individual variables. Here, 0, 1, 2, .....99 are index associated with var variable and they are being used to represent individual elements available in the array.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Create Arrays
To create an array variable in C, a programmer specifies the type of the elements and the number of elements to be stored in that array. Given below is a simple syntax to create an array in C programming −type arrayName [ arraySize ];This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, now to declare a 10-element array called number of type int, use this statement −
int number[10];Here, number is a variable array, which is sufficient to hold up to 10 integer numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −int number[5] = {10, 20, 30, 40, 50};The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −
int number[] = {10, 20, 30, 40, 50};You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −
number[4] = 50;The above statement assigns element number 5th in the array with a value of 50. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be the total size of the array minus 1. The following image shows the pictorial representation of the array we discussed above −
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −int var = number[9];The above statement will take the 10th element from the array and assign the value to var variable. The following example uses all the above-mentioned three concepts viz. creation, assignment, and accessing arrays −
Live Demo
#include <stdio.h> int main () { int number[10]; /* number is an array of 10 integers */ int i = 0; /* Initialize elements of array n to 0 */ while( i < 10 ) { /* Set element at location i to i + 100 */ number[ i ] = i + 100; i = i + 1; } /* Output each array element's value */ i = 0; while( i < 10 ) { printf("number[%d] = %d\n", i, number[i] ); i = i + 1; } return 0; }When the above code is compiled and executed, it produces the following result −
number[0] = 100 number[1] = 101 number[2] = 102 number[3] = 103 number[4] = 104 number[5] = 105 number[6] = 106 number[7] = 107 number[8] = 108 number[9] = 109
Arrays in Java
Following is the equivalent program written in Java. Java supports arrays, but there is a little difference in the way they are created in Java using the new operator.You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
Live Demo
public class DemoJava { public static void main(String []args) { int[] number = new int[10]; int i = 0; while( i < 10 ) { number[ i ] = i + 100; i = i + 1; } i = 0; while( i < 10 ) { System.out.format( "number[%d] = %d\n", i, number[i] ); i = i + 1; } } }When the above program is executed, it produces the following result −
number[0] = 100 number[1] = 101 number[2] = 102 number[3] = 103 number[4] = 104 number[5] = 105 number[6] = 106 number[7] = 107 number[8] = 108 number[9] = 109
Arrays (Lists) in Python
Python does not have a concept of Array, instead Python provides another data structure called list, which provides similar functionality as arrays in any other language.Following is the equivalent program written in Python −
Live Demo
# Following defines an empty list. number = [] i = 0 while i < 10: # Appending elements in the list number.append(i + 100) i = i + 1 i = 0 while i < 10: # Accessing elements from the list print "number[", i, "] = ", number[ i ] i = i + 1When the above program is executed, it produces the following result −
number[ 0 ] = 100 number[ 1 ] = 101 number[ 2 ] = 102 number[ 3 ] = 103 number[ 4 ] = 104 number[ 5 ] = 105 number[ 6 ] = 106 number[ 7 ] = 107 number[ 8 ] = 108 number[ 9 ] = 109
Computer Programming - Strings
During our discussion about characters, we learnt that character data type deals with a single character and you can assign any character from your keyboard to a character type variable.Now, let's move a little bit ahead and consider a situation where we need to store more than one character in a variable. We have seen that C programming does not allow to store more than one character in a character type variable. So the following statements are invalid in C programming and produce syntax errors −
char ch1 = 'ab'; char ch2 = '10';We have also seen how to use the concept of arrays to store more than one value of similar data type in a variable. Here is the syntax to store and print five numbers in an array of int type −
Live Demo
#include <stdio.h> main() { int number[5] = {10, 20, 30, 40, 50}; int i = 0; while( i < 5 ) { printf("number[%d] = %d\n", i, number[i] ); i = i + 1; } }When the above code is compiled and executed, it produces the following result −
number[0] = 10 number[1] = 20 number[2] = 30 number[3] = 40 number[4] = 50Now, let's define an array of five characters in the same way as we did for numbers and try to print them −
Live Demo
#include <stdio.h> main() { char ch[5] = {'H', 'e', 'l', 'l', 'o'}; int i = 0; while( i < 5 ) { printf("ch[%d] = %c\n", i, ch[i] ); i = i + 1; } }Here, we used %c to print character value. When the above code is compiled and executed, it produces the following result −
ch[0] = H ch[1] = e ch[2] = l ch[3] = l ch[4] = oIf you are done with the above example, then I think you understood how strings work in C programming, because strings in C are represented as arrays of characters. C programming simplified the assignment and printing of strings. Let's check the same example once again with a simplified syntax −
Live Demo
#include <stdio.h> main() { char ch[5] = "Hello"; int i = 0; /* Print as a complete string */ printf("String = %s\n", ch); /* Print character by character */ while( i < 5 ) { printf("ch[%d] = %c\n", i, ch[i] ); i = i + 1; } }Here, we used %s to print the full string value using array name ch, which is actually the beginning of the memory address holding ch variable as shown below −
Although it's not visible from the above examples, a C program internally assigns null character '\0' as the last character of every string. It indicates the end of the string and it means if you want to store a 5 character string in an array, then you must define an array size of 6 as a good practice, though C does not complain about it.
If the above code is compiled and executed, it produces the following result −
String = Hello ch[0] = H ch[1] = e ch[2] = l ch[3] = l ch[4] = o
Basic String Concepts
Based on the above discussion, we can conclude the following important points about strings in C programming language −- Strings in C are represented as arrays of characters.
- We can constitute a string in C programming by assigning character by character into an array of characters.
- We can constitute a string in C programming by assigning a complete string enclosed in double quote.
- We can print a string character by character using an array subscript or a complete string by using an array name without subscript.
- The last character of every string is a null character, i.e., ‘\0’.
- Most of the programming languages provide built-in functions to manipulate strings, i.e., you can concatenate strings, you can search from a string, you can extract sub-strings from a string, etc. For more, you can check our detailed tutorial on C programming or any other programming language.
Strings in Java
Though you can use character arrays to store strings, but Java is an advanced programming language and its designers tried to provide additional functionality. Java provides strings as a built-in data type like any other data type. It means you can define strings directly instead of defining them as array of characters.Following is the equivalent program written in Java. Java makes use of the new operator to create string variables as shown in the following program.
You can try to execute the following program to see the output −
Live Demo
public class DemoJava { public static void main(String []args) { String str = new String("Hello"); System.out.println( "String = " + str ); } }When the above program is executed, it produces the following result −
String = Hello
Strings in Python
Creating strings in Python is as simple as assigning a string into a Python variable using single or double quotes.Given below is a simple program that creates two strings and prints them using print() function −
Live Demo
var1 = 'Hello World!' var2 = "Python Programming" print "var1 = ", var1 print "var2 = ", var2When the above program is executed, it produces the following result −
var1 = Hello World! var2 = Python ProgrammingPython does not support character type; these are treated as strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. Take a look at the following code segment −
Live Demo
var1 = 'Hello World!' var2 = "Python Programming" print "var1[0]: ", var1[0] print "var2[1:5]: ", var2[1:5]When the above code is executed, it produces the following result −
var1[0]: H var2[1:5]: ytho
Computer Programming - Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. You have already seen various functions like printf() and main(). These are called built-in functions provided by the language itself, but we can write our own functions as well and this tutorial will teach you how to write and use those functions in C programming language.Good thing about functions is that they are famous with several names. Different programming languages name them differently, for example, functions, methods, sub-routines, procedures, etc. If you come across any such terminology, then just imagine about the same concept, which we are going to discuss in this tutorial.
Let's start with a program where we will define two arrays of numbers and then from each array, we will find the biggest number. Given below are the steps to find out the maximum number from a given set of numbers −
1. Get a list of numbers L1, L2, L3....LN 2. Assume L1 is the largest, Set max = L1 3. Take next number Li from the list and do the following 4. If max is less than Li 5. Set max = Li 6. If Li is last number from the list then 7. Print value stored in max and come out 8. Else prepeat same process starting from step 3Let's translate the above program in C programming language −
Live Demo
#include <stdio.h> int main() { int set1[5] = {10, 20, 30, 40, 50}; int set2[5] = {101, 201, 301, 401, 501}; int i, max; /* Process first set of numbers available in set1[] */ max = set1[0]; i = 1; while( i < 5 ) { if( max < set1[i] ) { max = set1[i]; } i = i + 1; } printf("Max in first set = %d\n", max ); /* Now process second set of numbers available in set2[] */ max = set2[0]; i = 1; while( i < 5 ) { if( max < set2[i] ) { max = set2[i]; } i = i + 1; } printf("Max in second set = %d\n", max ); }When the above code is compiled and executed, it produces the following result −
Max in first set = 50 Max in second set = 501If you are clear about the above example, then it will become easy to understand why we need a function. In the above example, there are only two sets of numbers, set1 and set2, but consider a situation where we have 10 or more similar sets of numbers to find out the maximum numbers from each set. In such a situation, we will have to repeat, processing 10 or more times and ultimately, the program will become too large with repeated code. To handle such situation, we write our functions where we try to keep the source code which will be used again and again in our programming.
Now, let's see how to define a function in C programming language and then in the subsequent sections, we will explain how to use them.
Defining a Function
The general form of a function definition in C programming language is as follows −return_type function_name( parameter list ) { body of the function return [expression]; }A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −
- Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
- Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.
- Parameter List − A parameter is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
- Function Body − The function body contains a collection of statements that defines what the function does.
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform a defined task.Now, let's write the above example with the help of a function −
Live Demo
#include <stdio.h> int getMax( int set[] ) { int i, max; max = set[0]; i = 1; while( i < 5 ) { if( max < set[i] ) { max = set[i]; } i = i + 1; } return max; } main() { int set1[5] = {10, 20, 30, 40, 50}; int set2[5] = {101, 201, 301, 401, 501}; int max; /* Process first set of numbers available in set1[] */ max = getMax(set1); printf("Max in first set = %d\n", max ); /* Now process second set of numbers available in set2[] */ max = getMax(set2); printf("Max in second set = %d\n", max ); }When the above code is compiled and executed, it produces the following result −
Max in first set = 50 Max in second set = 501
Functions in Java
If you are clear about functions in C programming, then it is easy to understand them in Java as well. Java programming names them as methods, but the rest of the concepts remain more or less same.Following is the equivalent program written in Java. You can try to execute it to see the output −
Live Demo
public class DemoJava { public static void main(String []args) { int[] set1 = {10, 20, 30, 40, 50}; int[] set2 = {101, 201, 301, 401, 501}; int max; /* Process first set of numbers available in set1[] */ max = getMax(set1); System.out.format("Max in first set = %d\n", max ); /* Now process second set of numbers available in set2[] */ max = getMax(set2); System.out.format("Max in second set = %d\n", max ); } public static int getMax( int set[] ) { int i, max; max = set[0]; i = 1; while( i < 5 ) { if( max < set[i] ) { max = set[i]; } i = i + 1; } return max; } }When the above program is executed, it produces the following result −
Max in first set = 50 Max in second set = 501
Functions in Python
Once again, if you know the concept of functions in C and Java programming, then Python is not much different. Given below is the basic syntax of defining a function in Python −def function_name( parameter list ): body of the function return [expression]Using this syntax of function in Python, the above example can be written as follows −
Live Demo
def getMax( set ): max = set[0] i = 1 while( i < 5 ): if( max < set[i] ): max = set[i] i = i + 1 return max set1 = [10, 20, 30, 40, 50] set2 = [101, 201, 301, 401, 501] # Process first set of numbers available in set1[] max = getMax(set1) print "Max in first set = ", max # Now process second set of numbers available in set2[] max = getMax(set2) print "Max in second set = ", maxWhen the above code is executed, it produces the following result −
Max in first set = 50 Max in second set = 501
Computer Programming - File I/O
Computer Files
A computer file is used to store data in digital format like plain text, image data, or any other content. Computer files can be organized inside different directories. Files are used to keep digital data, whereas directories are used to keep files.Computer files can be considered as the digital counterpart of paper documents. While programming, you keep your source code in text files with different extensions, for example, C programming files end with the extension .c, Java programming files with .java, and Python files with .py.
File Input/Output
Usually, you create files using text editors such as notepad, MS Word, MS Excel or MS Powerpoint, etc. However, many times, we need to create files using computer programs as well. We can modify an existing file using a computer program.File input means data that is written into a file and file output means data that is read from a file. Actually, input and output terms are more related to screen input and output. When we display a result on the screen, it is called output. Similarly, if we provide some input to our program from the command prompt, then it is called input.
For now, it is enough to remember that writing into a file is file input and reading something from a file is file output.
File Operation Modes
Before we start working with any file using a computer program, either we need to create a new file if it does not exist or open an already existing file. In either case, we can open a file in the following modes −- Read-Only Mode − If you are going to just read an existing file and you do not want to write any further content in the file, then you will open the file in read-only mode. Almost all the programming languages provide syntax to open files in read-only mode.
- Write-Only Mode − If you are going to write into either an existing file or a newly created file but you do not want to read any written content from that file, then you will open the file in write-only mode. All the programming languages provide syntax to open files in write-only mode.
- Read & Write Mode − If you are going to read as well as write into the same file, then you will open file in read & write mode.
- Append Mode − When you open a file for writing, it allows you to start writing from the beginning of the file; however it will overwrite existing content, if any. Suppose we don’t want to overwrite any existing content, then we open the file in append mode. Append mode is ultimately a write mode, which allows content to be appended at the end of the file. Almost all the programming languages provide syntax to open files in append mode.
Opening Files
You can use the fopen() function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Here is the prototype, i.e., signature of this function call −FILE *fopen( const char * filename, const char * mode );Here, filename is string literal, which you will use to name your file and access mode can have one of the following values −
Sr.No | Mode & Description |
---|---|
1 | r Opens an existing text file for reading purpose. |
2 | w Opens a text file for writing. If it does not exist, then a new file is created. Here, your program will start writing content from the beginning of the file. |
3 | a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here, your program will start appending content in the existing file content. |
4 | r+ Opens a text file for reading and writing both. |
5 | w+ Opens a text file for both reading and writing. It first truncates the file to zero length, if it exists; otherwise creates the file if it does not exist. |
6 | a+ Opens a text file for both reading and writing. It creates a file, if it does not exist. The reading will start from the beginning, but writing can only be appended. |
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −int fclose( FILE *fp );The fclose( ) function returns zero on success, or EOF, special character, if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see a few of them in the next section.
Writing a File
Given below is the simplest function to write individual characters to a stream −int fputc( int c, FILE *fp );The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success, otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −
int fputs( const char *s, FILE *fp );The function fputs() writes the string s into the file referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can also use the function int fprintf(FILE *fp,const char *format, ...) to write a string into a file. Try the following example −
#include <stdio.h> int main() { FILE *fp; fp = fopen("/tmp/test.txt", "w+"); fprintf(fp, "This is testing for fprintf...\n"); fputs("This is testing for fputs...\n", fp); fclose(fp); }When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.
Reading a File
Given below is the simplest function to read a text file character by character −int fgetc( FILE * fp );The fgetc() function reads a character from the input file referenced by fp. The return value is the character read; or in case of any error, it returns EOF. The following function allows you to read a string from a stream −
char *fgets( char *buf, int n, FILE *fp );The function fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h> main() { FILE *fp; char buff[255]; fp = fopen("/tmp/test.txt", "r"); fscanf(fp, "%s", buff); printf("1 : %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("2: %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("3: %s\n", buff ); fclose(fp); }When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −
1 : This 2 : is testing for fprintf... 3 : This is testing for fputs...Let's analyze what happened here. First, the fscanf() method reads This because after that, it encountered a space. The second call is for fgets(), which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely.
File I/O in Java
Java provides even richer set of functions to handle File I/O. For more on this topic, we suggest you to check our Java Tutorials.Here, we will see a simple Java program, which is equivalent to the C program explained above. This program will open a text file, write a few text lines into it, and close the file. Finally, the same file is opened and then read from an already created file. You can try to execute the following program to see the output −
import java.io.*; public class DemoJava { public static void main(String []args) throws IOException { File file = new File("/tmp/java.txt"); // Create a File file.createNewFile(); // Creates a FileWriter Object using file object FileWriter writer = new FileWriter(file); // Writes the content to the file writer.write("This is testing for Java write...\n"); writer.write("This is second line...\n"); // Flush the memory and close the file writer.flush(); writer.close(); // Creates a FileReader Object FileReader reader = new FileReader(file); char [] a = new char[100]; // Read file content in the array reader.read(a); System.out.println( a ); // Close the file reader.close(); } }When the above program is executed, it produces the following result −
This is testing for Java write... This is second line...
File I/O in Python
The following program shows the same functionality to open a new file, write some content into it, and finally, read the same file −# Create a new file fo = open("/tmp/python.txt", "w") # Writes the content to the file fo.write( "This is testing for Python write...\n"); fo.write( "This is second line...\n"); # Close the file fo.close() # Open existing file fo = open("/tmp/python.txt", "r") # Read file content in a variable str = fo.read(100); print str # Close opened file fo.close()When the above code is executed, it produces the following result −
This is testing for Python write... This is second line...
Computer Programming - Summary
We appreciate your patience for going through this tutorial. We have tried to keep it concise but as this subject contains several topics, we have shown a few examples in detail.If you have not understood any of the concepts, then we recommend to go through the tutorial once again and once you are comfortable with the concepts explained in this tutorial, you can proceed further.
There are many other subjects related to computer programming which we did not cover intentionally to avoid any confusion, but we are sure those concepts will not be difficult for you to understand as long as you make yourself comfortable with the concepts explained in this tutorial.
At tutorialspoint, we have put lots of effort to prepare comprehensive tutorials on C, Java, and Python programming languages and we strongly recommend you to start either of them, after having completed this tutorial.
Computer programming is the act of writing computer programs, which are a sequence of instructions written using a Computer Programming Language to perform a specified task by the computer. Computer Programming is fun and easy to learn provided you adopt a proper approach. This tutorial attempts to cover the basics of computer programming using a simple and practical approach for the benefit of novice learners
Computers aren't very smart. Sure, they can do a lot of math or help you search the Internet. But, if you asked a computer to vacuum the house for you, could it do it? If you asked a computer to draw a picture of a bird for you, would it? A computer would have no idea about what you're saying
Hello Admin,
BalasHapusBuilding up or expanding the ability of a cutting edge criminological sound video research facility draws on different orders including material science, electrical and electronic designing, software engineering, simple and computerized hypothesis, acoustics, advanced sign examination, computerized imaging, and other related fields.
Regards,
Thanks
RITU
سسس
BalasHapusمتجر خاص بتصميم تطبيقات الحاسب بالسعودية
BalasHapusخدماتنا
Great information on computer languages , keep posting more Software Testing Training in Pune
BalasHapusExcellent computer language information; please continue to post.
BalasHapusPython Training Institute in KPHB