Principles of Programming using C - 23ESCS11 Module 1 Notes PDF

Summary

These notes provide a basic introduction to C programming, including fundamental concepts like bits, bytes, words, and the relationships between them. The notes also cover introductions to computers. Good introduction to important C programming concepts.

Full Transcript

Principles of Programming using C – 23ESCS11 Module – 1 Affiliated to VTU Dayananda Sagar Academy of Technology & Approved by AICTE Management...

Principles of Programming using C – 23ESCS11 Module – 1 Affiliated to VTU Dayananda Sagar Academy of Technology & Approved by AICTE Management Accredited by NAAC with A+ Grade (Autonomous Institute under VTU) 6 Programs Accredited by NBA (CSE, ISE, ECE, EEE, MECH, CV) DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING NOTES SUBJECT: Principles of Programming using C SUBJECT CODE: 23ESCS11 SEMESTER: I/II Sem PREPARED BY SRIDEVI G M DEPARTMENT OF ISE, DSATM Sridevi G M, Department of ISE, DSATM Page |1 Principles of Programming using C – 23ESCS11 Module – 1 BASIC INFORMATION Bits, Bytes and Words Bit: The bit is smallest value which can be stored in computer. The bit is also called as binary digit. The bit can hold binary value either 0 or 1. Nibble: The nibble is a collection of four bits. Byte: The byte is a collection of eight bits. The byte is the standard unit of measurement of computer memory data storage and transmission speed. The relationships between these units are expressed in the following manner: Unit Equivalent to Remarks 1 kilobyte (KB) 1024 bytes Space used by 10 lines of text. I megabyte (MB) 1024 kilobytes Memory of the earliest PCs 1 gigabyte (GB) 1024 megabytes Storage capacity of a CD-ROM 1 terabyte (TB) 1024 gigabytes Capacity of today's hard disks. 1 petabyte (PB) 1024 terabytes Space used for rendering of film Avatar Words: Even though computer memory is measured in bytes (rather mega- or gigabytes), the CPU handles memory data in larger units, called words, where a word is usually an even multiple of bytes (two bytes, four bytes, etc.). This number is purely based on processor architecture. Most machine instructions are one word in size, and because a CPU register must be able to hold an instruction, it too is one word wide. Module I INTRODUCTION TO C 1.1 WHAT IS A COMPUTER? A computer, in simple terms, can be defined as an electronic device that is designed to accept data, perform the required mathematical and logical operations at high speed, and output the result. The processing is fast, accurate and consistent, and is generally achieved without significant human intervention. 1.2 CHARACTERISTICS OF COMPUTERS A computer is an electronic device that performs a function based on a given set of instructions known as a program. A computer accepts data, processes it, and produces information. Here, data refers to some raw fact or figure, and information implies the processed data. The important characteristics of a computer (refer to Figure 1.1) are discussed in the following text. Sridevi G M, Department of ISE, DSATM Page |2 Principles of Programming using C – 23ESCS11 Module – 1 Fig. 1.1 Characteristics of a Computer Speed Computers can perform millions of operations per second, which means that data that may otherwise take many hours to process is output as information in the blink of an eye. The speed of computers is usually given in nanoseconds and picoseconds, where 1 nanosecond = 1 × 10 −9 seconds and 1 picosecond = 1 × 10 −12 seconds. Accuracy A computer is a very fast, reliable, and robust electronic device. It always gives accurate results, provided the correct data and set of instructions are input to it. Hence, in the event of an error, it is the user who has fed the incorrect data/program is responsible. This clearly means that the output generated by a computer depends on the given instructions and input data. If the input data is wrong, then the output will also be erroneous. In computer terminology, this is known as garbage-in, garbage-out (GIGO). Automation Besides being very fast and accurate, computers are automatable devices that can perform a task without any user intervention. The user just needs to assign the task to the computer, after which it automatically controls different devices attached to it and executes the program instructions. Diligence Unlike humans, computers never get tired of a repetitive task. It can continually work for hours without creating errors. Even if a large number of executions need to be executed, each and every execution requires the same duration, and is executed with the same accuracy. Versatile Versatility is the quality of being flexible. Today, computers are used in our daily life in different fi elds. For example, they are used as personal computers (PCs) for home use, for business-oriented tasks, weather forecasting, space exploration, teaching, railways, banking, medicine, and so on, indicating that computers can perform different tasks simultaneously. On the PC that you use at home, you may play a game, compose and send e-mails, listen to music, Sridevi G M, Department of ISE, DSATM Page |3 Principles of Programming using C – 23ESCS11 Module – 1 etc. Therefore, computers are versatile devices as they can perform multiple tasks of different nature at the same time. Memory Similar to humans, computers also have memory. Just the way we cannot store everything in our memory and need secondary media, such as a notebook, to record certain important things, computers also have internal or primary memory (storage space) as well as external or secondary memory. While the internal memory of computers is very expensive and limited in size, the secondary storage is cheaper and of bigger capacity. No IQ Although the trend today is to make computers intelligent by inducing artificial intelligence (AI) in them, they still do not have any decision-making abilities of their own. They need guidance to perform various tasks. Economical Today, computers are considered as short term investments for achieving long-term gains. Using computers also reduces manpower requirements and leads to an elegant and efficient way of performing various tasks. Hence, computers save time, energy, and money. When compared to other systems, computers can do more work in lesser time. 1.3 STORED PROGRAM CONCEPT All digital computers are based on the principle of stored program concept, which was introduced by Sir John von Neumann in the late 1940s. The following are the key characteristic features of this concept: Before any data is processed, instructions are read into memory. Instructions are stored in the computer’s memory for execution. Instructions are stored in binary form (using binary numbers—only 0s and 1s). Processing starts with the fi rst instruction in the program, which is copied into a control unit circuit. The control unit executes the instructions. Instructions written by the users are performed sequentially until there is a break in the current flow. Input/Output and processing operations are performed simultaneously. While data is being read/written, the central processing unit (CPU) executes another program in the memory that is ready for execution. Types of Stored Program Computers 1. Shared memory for instructions and data Sridevi G M, Department of ISE, DSATM Page |4 Principles of Programming using C – 23ESCS11 Module – 1 2. Separate memory for instructions and data 1.4 GENERATION OF COMPUTERS Five of generations of computer is listed in (Table 1.1). The computer of each generation is faster, smaller and me powerful than its counterpart of the preceding generation. Consequently, advances in hardware have also resulted in the development of powerful and user-friendly programming language. Table 1.1 Computer Generations (Hardware) Generation. Based on Other Features First Vacuum tubes Magnetic drums for memory Magnetic cores, disks, punched cards and Second Transistors printouts Third Integrated circuits Keyboard, monitor and operating system (ICs) Fourth Microprocessors Networking ULSI Nano Fifth Mainly unclear technology Vacuum Tubes: The First Generation Computers of this generation (like the Colossus and ENIAC) used thousands of vacuum tubes for computation. Memory requirements were met by magnetic drums (forerunner of today's hard disk). Because of the size of vacuum tubes, first generation computers took up a lot of space. They also consumed enormous amounts of power and generated a lot of heat. In spite of housing these computers in air-conditioned enclosures, frequent breakdowns were common. The ENIAC used 18,000 vacuum tubes, occupied 1800 sq. ft. of room space and consumed 180KW of power, Machines of this generation were prohibitively expensive to buy and maintain. First-generation computers were programmed using a first-generation language- machine language. Sridevi G M, Department of ISE, DSATM Page |5 Principles of Programming using C – 23ESCS11 Module – 1 Program input was provided by punched cards and output was obtained on paper. First-generation computers were only used for scientific work and were not deployed commercially. Transistors: The Second Generation The transistors replaced vacuum tubes in second-generation computers which became available in the 1950s. Compared to vacuum tubes, transistors were faster, smaller and consumed less power smaller magnetic cores also replaced the first-generation magnetic drums. Even though transistor generated less heat, second-generation computers still needed air- conditioning. The input-output mechanism however remained largely unchanged. Second-generation computers were programmed using a symbolic or assembly language. The computers also implemented the stored program concept which allowed both program and data to reside in memory. Higher level languages like COBOL language for most applications and FORTRAN also began to make their appearance. Integrated Circuits: The Third Generation Computer speed and efficiency got a sharp boost with the development of the integrated circuit. By virtue of miniaturization, computers consequently got smaller, cheaper and energy efficient. For these reasons, they could be seen in several medium-sized organizations. This generation adopted a keyboard and monitor to interact with the user. Memory capacity increased substantially, and the magnetic hard disk was used for secondary storage. Third-generation computers also had an operating system, which is a special program meant to control the resources of the computer. By virtue of a feature known as time sharing, the computer could run programs invoked by multiple users. The existing programming languages were supplemented by BASIC, C, C++ and Java. The Microprocessor: The Fourth Generation The integration of components went several steps ahead. Using LSI (Large Scale Integration) and VLSI (Very Large Scale Integration) technology, it is now possible to have the entire CPU, its associated memory and input/output control circuitry on a single chip. Intel introduced the 4004 microprocessor in 1971 and improvement in the usual parameters (like speed, heat generation, size, etc.) continues at a frenetic pace to this day. Sridevi G M, Department of ISE, DSATM Page |6 Principles of Programming using C – 23ESCS11 Module – 1 Microprocessors have invaded our homes to drive desktops, laptops, smartphones, microwave ovens and washing machines. Laptops and smartphones offer gigabytes (GB) of memory compared to a few megabytes (MB) that were available in the early days of this generation. Operating systems have moved from the rudimentary MSDOS to a mouse based Graphical User Interface (GUI) like Windows. More advanced systems like Linux are now available for desktops and laptops, and a variant of it (Android) powers most of our smartphones. There have been other sweeping changes in this generation. Laptops and smartphones offer Fourth generation languages (4GLs), which resemble natural languages, have also come into being. This generation has also made a rapid strides in networking technology, sharing of information, became possible by connecting computers in a network using TCP/IP technology. Artificial Intelligence: The Fifth Generation The fifth generation represents a vision of the computers of the future. The conventional parameters of computing (speed, size, energy consumption, VLSI to UL.SI, etc.) would continue to improve path-breaking changes in the way we use computers are also expected. Fifth-generation systems should be capable of producing human-like behavior. These systems expected to interact with users in natural language and learn from experience. Speech recognition and speech output should also be possible with these systems. Computer speeds need to make an exponential jump, a feat that would be possible using quantum computers. Google’s D-Wave 2X quantum computer is 100 million times faster than today's machines. Computers must be able to perform parallel processing so that multiple processors concurrently handle different aspects of a problem. Neural networks and expert systems have to be developed. These applications would be able to make decisions and advise humans by analysing data using human-like intelligence but without using the services of an expert. Other possibly disruptive technologies-like molecular computing that could take miniaturization to molecular levels. 1.5 CLASSIFICATION OF COMPUTERS The computers can also be categorized by their size. The size of a computer is often an indirect indicator of its capabilities and the application domains where they are employed. Sridevi G M, Department of ISE, DSATM Page |7 Principles of Programming using C – 23ESCS11 Module – 1 The following categories are in order of descending size. Supercomputers These are huge machines having the most powerful and fastest processors. A supercomputer uses multiple CPUs for parallel data processing. Speeds are measured in Hop (floating point operations per second). The fastest supercomputer (the Tianhe-2) operates at a speed of 34 peta flops. (1 peta = 1000 tera = 1,000,000 giga). Supercomputers can handle multiple users but that’s not its unique feature. Supercomputers are too powerful to be used for transaction processing. Used for weather forecasting, analysis of geological data, nuclear simulation and space exploration. They are also used to solve complex scientific problems Supercomputers have enormous storage, with huge amounts of power and generate a lot of heat. Because of their exorbitant cost, they are mainly used by government agencies Mainframes These are multi-user machines that can support hundreds or thousands of users using the feature of time sharing supported by systems like Linux. Users interact with this system using a terminal and keyboard, which is akin to the way we use PCs. Mainframes can concurrently run multiple programs even with a single CPU. The processor speed in a mainframe is measured in mip (million instructions per second). Mainframes are generally used to handle data and applications related to the organization as whole. The mainframes are employed to handle online transactions (stock exchange transactions, for instance). The capability to handle large amounts of data makes the mainframe suitable for use in government, banks and financial institutions, and large corporations. Note: Sridevi G M, Department of ISE, DSATM Page |8 Principles of Programming using C – 23ESCS11 Module – 1 The supercomputer is employed to run one program as fast as possible. The mainframe is meant to serve a large number of users. Minicomputers Minicomputers or midrange computers as they can be considered as downsized mainframes since they have the essential features of mainframes. Minicomputers can serve hundreds of users and are small enough to partially occupy a room. But they are not affordable enough to be used in the home. The minicomputer, which Digital Equipment Corporation (DEC) introduced in the 1970s, is thus rightly positioned between a mainframe and a micro-computer. Minicomputers are used in smaller organizations or a department of large one captive machines of turnkey equipment running specialized software. Microcomputers The microcomputer or personal computer (PC) introduced by Apple and later endorsed by IBM. This computer is a single-user machine powered by a single microprocessor; Today's PCs are very powerful machines having gigabytes of memory and a terabyte or two of disk storage. They are used both in the standalone mode (at home) and in a network (in office). A microcomputer takes the form of a desktop, notebook (laptop) or a netbook (smaller Laptop). Even though a PC has a single CPU, high-end PCs support microprocessors comes with multiple cores like the Intel Core i5 and i7 etc. Each core can be considered with some approximation processor by itself. PCs today are powered by three types of operating systems Windows, Mac OS and Linux. Businesses and individuals use the PC for word processing, spread sheet handling and desktop publishing; PCs also support Internet browsing software like Firefox and Google Chrome. All PCs are multimedia ready, they can handle images, audio and video files the PC is also an entertainment device. A variant of the microcomputer is the workstation which essentially is a microcomputer with a more powerful processor, high resolution terminal and high quality graphic capabilities (like CAD/CAM). Smartphones and Embedded Computers The relentless drive toward miniaturization has led to the emergence of two types of devices 1. Smartphones: The smartphone is a general-purpose computer that sis also capable of making phone calls. Sridevi G M, Department of ISE, DSATM Page |9 Principles of Programming using C – 23ESCS11 Module – 1 The smartphone has a powerful processor, usually with multiple cores like the quad- core Snapdragon 820). It also supports gigabytes of main memory but doesn't have a hard disk for secondary storage. This requirement is met by flash memory (1.10.4). Smartphones today run well-developed operating system (Android or iOS), and can run a wide range of application (popular called “apps”). 2. Embedded computers: The embedded computer is a small computer-like that is part of a larger system. Embedded computers (also called microcontrollers) arrived before smartphones. These are very small circuits containing CPU, non-volatile memory and input and output handling facilities. They are embedded into many of the machines that we ears, washing machines, MP3 players and cameras. The processor here in a single modifiable program stored in memories embedded computers can't match the capabilities of a smartphone. 1.6 APPLICATIONS OF COMPUTERS Word Processing software enables users to read and write documents. Users can add images, tables and graphs. It has automatic correction of spelling mistakes and copy-paste features. Internet is a network of networks that connects computers all over the world and provides access to an enormous amount of information. E-mail, Chat software and video conferencing tools Digital video or audio composition and editing is simpler with computers. Desktop publishing enables users to create page layouts for entire books Government Simulation Traffic Control Geology Legal System Astronomy Retail Weather Forecasting Sports Education Music Online Banking Movies Industry and Engineering Travel and Tourism Robots Business and Industry Decision Support Systems Hospitals Expert Systems Sridevi G M, Department of ISE, DSATM P a g e | 10 Principles of Programming using C – 23ESCS11 Module – 1 1.7 BASIC ORGANIZATION OF A COMPUTER A computer is an electronic device that performs five major operations: Accepting data or instructions (input) Storing data Processing data Displaying results (output) Controlling and coordinating all operations inside a computer In this section, we will discuss all these functions and see how one unit of a computer interacts with another to perform these operations. Figure 1.11 shows the interaction between the different units of a computer system. Input This is the process of entering data and instructions (also known as programs ) into the computer system. The data and instructions can be entered by using different input devices such as keyboard, mouse, scanner, and trackball. Note that computers understand binary language, which consists of only two symbols (0 and 1), so it is the responsibility of the input devices to convert the input data into binary codes. Storage: Storage is the process of saving data and instructions permanently in the computer so that they can be used for processing. The computer storage space not only stores the data and programs that operate on that data but also stores the intermediate results and the final results of processing. A computer has two types of storage areas: Primary storage Primary storage, also known as the main memory , is the storage area that is directly accessible by the CPU at very high speeds. It is used to store the data and parts of programs, the intermediate results of processing, and the recently generated results of jobs that are currently being worked on by the computer. Primary storage space is very expensive and therefore limited in capacity. Another drawback of main memory is that it is volatile in nature; that is, as soon as the computer is switched off, the information stored gets erased. Hence, it cannot be used as a permanent storage of useful data and programs for future use. An example of primary storage is random access memory (RAM). Sridevi G M, Department of ISE, DSATM P a g e | 11 Principles of Programming using C – 23ESCS11 Module – 1 Secondary storage Also known as auxiliary memory, this memory is just the opposite of primary memory. It overcomes all the drawbacks of the primary storage area. It is cheaper, non-volatile, and used to permanently store data and programs of those jobs that are not being currently executed by the CPU. Secondary memory supplements the limited storage capacity of the primary memory. An example is the magnetic disk used to store data, such as C and D drives, for future use. Output Output is the process of giving the result of data processing to the outside world (external to the computer system). The results are given through output devices such as monitor, and printer. Since the computer accepts data only in binary form and the result of processing is also in binary form, the result cannot be directly given to the user. The output devices, therefore, convert the results available in binary codes into a human-readable language before displaying it to the user. Control The control unit (CU) is the central nervous system of the entire computer system. It manages and controls all the components of the computer system. It is the CU that decides the manner in which instructions will be executed and operations performed. It takes care of the step-by-step processing of all operations that are performed in the computer. Note that the CPU is a combination of the arithmetic logic unit (ALU) and the CU. The CPU is better known as the brain of the computer system because the entire processing of data is done in the ALU, and the CU activates and monitors the operations of other units (such as input, output, and storage) of the computer system. Processing The process of performing operations on the data as per the instructions specifi ed by the user (program) is called processing. Data and instructions are taken from the primary memory and transferred to the ALU, which performs all sorts of calculations. The intermediate results of processing may be stored in the main memory, as they might be required again. When the processing completes, the fi nal result is then transferred to the main memory. Hence, the data may move from main memory to the ALU multiple times before the processing is over. LAB SESSION - INSIDE THE COMPUTER Sridevi G M, Department of ISE, DSATM P a g e | 12 Principles of Programming using C – 23ESCS11 Module – 1 The following are some of the major parts of the computer: CPU The CPU is the brain of the computer. It performs all calculations and controls the devices connected to the computer system. The faster the CPU, the quicker programs can process the instructions. RAM A fast CPU is of no use if the computer does not have sufficient RAM. As discussed earlier, RAM is the computer’s memory which stores information used by applications that are currently being executed by the CPU. More memory means more applications can be executed at the same time without degrading the system’s performance. Hard disk drive (HDD) The HDD of the computer is the secondary memory of the computer system where information is stored permanently. All types of data, documents, and programs are stored on the hard disk. The larger the hard disk, the more the amount of data that can be stored on the drive. Though the size of the HDD does not affect the speed of execution of the program, it does affect the speed at which the user can access his/ her files. Video card The video card is a board that plugs into the motherboard of the computer and generates images for display. Many video cards these days have their own RAM and processor to enhance the speed of the graphics display. Many computers come with an in-built video chip. In such a computer, a separate video card is used only if the computer has to be used for high-end multimedia work or to play video games. Sound card As with video cards, sound cards are expansion boards that are used to enable a computer to manipulate sound. For example, sound cards allow the users to plug in speakers and a microphone. Some sound cards also provide the jacks for hooking your computer up to a common stereo. Modem A modem (modulator–demodulator) is a device that enables the computer to use a telephone line to communicate and connect to the Internet. Network card A network card is used to connect the computer either to other computers or to the Internet (in case you are using a fast Internet connection such as cable or DSL). Fans There are one or more fans inside the computer to keep the air moving and the computer cool. Cables There are multiple wires inside the computer that are fl at, ribbon-like cables. They are used to provide power and communication to the various parts inside the computer. Sridevi G M, Department of ISE, DSATM P a g e | 13 Principles of Programming using C – 23ESCS11 Module – 1 INPUT AND OUTPUT DEVICES 2.1 INPUT DEVICES An input device is used to feed data and instructions into the computer 1. Keyboard Typing Keys Numeric Keys Function Keys Control Keys Keyboard Inside a Keyboard 2. Pointing Devices  Mouse  Point, Click, Drag, Scroll  Mechanical Mouse, Optical Mouse, Cordless Mouse  Trackball  Touchpad Mechanical Mouse Optical Mouse Cordless Mouse Trackball Trackpad Sridevi G M, Department of ISE, DSATM P a g e | 14 Principles of Programming using C – 23ESCS11 Module – 1 3. Handheld Devices Joystick Stylus Touchscreen Joystick Stylus Touchscreen 4. Optical Devices Barcode Reader Image Scanner Optical Character Recognition Optical Mark Recognition Magnetic Ink Character Reader Sridevi G M, Department of ISE, DSATM P a g e | 15 Principles of Programming using C – 23ESCS11 Module – 1 Barcode Reader Image Scanner Optical Character Recognition Optical Mark Recognition Magnetic Ink Character Reader 5. Audio visual Input Devices Audio Devices Video Input Devices Microphone Web camera Digital camera 2.2 OUTPUT DEVICES 1. Soft Copy Devices Monitor-CRT Monitor, LCD, Plasma Monitor Projector- LCD, Digital Light Display(DLP) projector Speakers Sridevi G M, Department of ISE, DSATM P a g e | 16 Principles of Programming using C – 23ESCS11 Module – 1 CRT Monitor Working of a CRT Monitor LCD Monitor Working of LCD Monitor Plasma Monitor Working of Plasma Monitor Sridevi G M, Department of ISE, DSATM P a g e | 17 Principles of Programming using C – 23ESCS11 Module – 1 LCD Projector DLP Projector Speakers Headphones Headset 2. Hard Copy Devices Printer Sridevi G M, Department of ISE, DSATM P a g e | 18 Principles of Programming using C – 23ESCS11 Module – 1 Dot Matrix Printer Daisy Wheel Printer Line Printer Band Printer Inkjet Printer Laser Printer Sridevi G M, Department of ISE, DSATM P a g e | 19 Principles of Programming using C – 23ESCS11 Module – 1 Plotter a. Drum Plotter b. flatbed plotter Sridevi G M, Department of ISE, DSATM P a g e | 20 Principles of Programming using C – 23ESCS11 Module – 1 3.1 HISTORY OF C The root of all modern languages is ALGOL, introduced in the early 1960s. ALGOL was the first computer language to use a block structure. Although it never became popular in USA, it was widely used in Europe. ALGOL gave the concept of structured programming to the computer science community. In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language) primarily for writing system software. In 1970, Ken Thompson created a language using many features of BCPL and called it simply B. B was used to create early versions of UNIX operating system at Bell Laboratories. Both BCPL and B were "typeless" system programming languages. C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories in 1972. C uses many concepts from these languages and added the concept of data types and other powerful features. Since it was developed along with the UNIX operating system, it is strongly associated with UNIX. This operating system, which was also developed at Bell Laboratories, was coded almost entirely in C. During 1970s, c had evolved into what is now known as "traditional C". The language became me popular after publication of the book The C Programming Language' by Brian Kerningham and Dennis Ritchie in 1978. The book was so popular that the language came to be known as "K&R C” To assure that the C language remains standard, in 1983, American National Standards institute (ANSI) appointed a technical committee to define a standard for C. The committee approved a version of C in December 1989 which is now known as ANSI C. It was then approved by the International Standards Organization (ISO) in 1990. This version of C is also referred to as C89. History of ANSI C Sridevi G M, Department of ISE, DSATM P a g e | 21 Principles of Programming using C – 23ESCS11 Module – 1 Uses of C It is primarily used for system programming. The portability, efficiency, the ability to access specific hardware addresses and low runtime demand on system resources makes it a good choice for implementing operating systems and embedded system applications Compilers, libraries and interpreters of other programming languages are often implemented in C C is sometimes used as an intermediate language for implementation of other languages Widely used to Implement end user applications 3.2 STRUCTURE OF C PROGRAM The figure shows the structure of a C program. Each section is as discussed below. A C program is composed of preprocessor commands, a global declaration section and one or more functions. The preprocessor directives contain special instructions that indicate how to prepare the program for compilation. include is the most commonly used preprocessor directive which tells the compiler that to execute the program, some information from the specified header file is needed. define is another preprocessor directive used to define constant values in the program C program contains one or more functions where a function is defined as a group of statements that are executed together. The statements in a C program are written in a logical sequence to perform a specific task. The main() function is the most important function and execution of a C program starts from main(). All functions are divided into 2 sections: the declaration section and the statements section. The declaration section precedes the statements and is used to describe the data that will be used in the function. Data declared within a function is called local declaration as it will be visible only within the function Data declared outside all the functions is called global declaration and are visible throughout the program. Sridevi G M, Department of ISE, DSATM P a g e | 22 Principles of Programming using C – 23ESCS11 Module – 1 NOTE: All sections, except the main function section may be absent when they are not required. Sridevi G M, Department of ISE, DSATM P a g e | 23 Principles of Programming using C – 23ESCS11 Module – 1 3.3 EXECUTING A ‘C’ PROGRAM Executing a program written in C involves a series of steps which is illustrated in figure 1.10. The steps are 1. Creating the program: Create the ‘C’ program by following the structure of ‘C’ program and type using standard editors like gedit or vim or vi or nano etc.., and it is called source program (example sum.c) 2. Compiling the program: compile the created source program with the compiler like gcc or cc. The output of this step is called object code. Example: cc sum.c 3. Linking the program with functions that are needed from the C library: If you have used math.h library or any external library functions in your program then link them to your program object code during compilation itself. Example: cc sum.c -lm 4. Executing the program: Finally execute the program to generate desired output. Example:./a.out Sridevi G M, Department of ISE, DSATM P a g e | 24 Principles of Programming using C – 23ESCS11 Module – 1 WRITING THE FIRST C PROGRAM Sridevi G M, Department of ISE, DSATM P a g e | 25 Principles of Programming using C – 23ESCS11 Module – 1 3.4 FILES USED IN A C PROGRAM 1. Source code file: contains the source code of the program. The file extension is ‘.c’. 2. Header files: Some of the predefined functions and user defined functions are kept in header files to reuse the functions without duplication. The file extension is ‘.h’ a. Standard header files: Functions provided by C compilers are included in standard header files. 3. Object files: they are generated by the compiler as a result of processing the source code file. They contain compact binary code of the function definitions. Linker uses this object file to produce and executable file (.exe) by combining the object files together. Object files have ‘.o’ or ‘.obj’ extension. 4. Binary executable file: is generated by the linker by linking various object files to produce a binary file that can be executed directly. Extension ‘.exe’ Sridevi G M, Department of ISE, DSATM P a g e | 26 Principles of Programming using C – 23ESCS11 Module – 1 3.5 COMPILING AND EXECUTING C PROGRAMS Sridevi G M, Department of ISE, DSATM P a g e | 27 Principles of Programming using C – 23ESCS11 Module – 1 USING COMMENTS Sridevi G M, Department of ISE, DSATM P a g e | 28 Principles of Programming using C – 23ESCS11 Module – 1 3.6 BASIC DATA TYPES IN C The data type defines the type of data stored in a memory-location and allocates memory for the data. The number of bytes allocated is based on architecture of the machine. C supports three classes of data types: 1. Primary data type Example: int, float, char, double, void 2. Derived data types Example: array 3. User-defined data types Example: structure C supports five types of primary data types as illustrated in the figure 2.4. int (integer) An int is a keyword which is used to define integers. Using int keyword, the programmer can inform the compiler that the data associated with this keyword should be treated as integer. Integer is used to store whole number with the range of values supported by a particular machine. Generally integer occupies one word of storage of machine which generally varies, (i.e. 16 or 32). In this notes 32 bit machine is considered. Integer will come up with signed and unsigned version. In signed integers out of allocated bits one bit i.e. MSB bit acts as sign bit and remaining bits are used store value. In unsigned integers all allocated bits are used to store value. C supports three different sizes of integer. Sridevi G M, Department of ISE, DSATM P a g e | 29 Principles of Programming using C – 23ESCS11 Module – 1 1. short int (2 bytes) 2. int (4 bytes) 3. long int (8 bytes) float (floating point single precision) A float is a keyword which is used to define floating point numbers. It allocates 4 bytes of memory Out of which 6 digit precision is provided, double (floating point double precision) A double is a keyword used to define long floating point numbers. It allocates 8 bytes of memory Out of which 14 digit precision is provided. The long double allocates 16 bytes in which it has 80 bits precision. The floating point supports both types of values storage i.e. fractional values and scientific value. Sridevi G M, Department of ISE, DSATM P a g e | 30 Principles of Programming using C – 23ESCS11 Module – 1 3.7 VARIABLES A variable is a data name that may be used to store a data value and which can be changed during the execution of program. A variable may take different values at different times during execution. A variable name can be chosen by the programmer in a meaningful way so as to reflect its function or nature in the program. Example: Average, sum. Total, Answer, number etc. The following are the rules for variable naming 1. They must begin with a letter. Some system permits underscore as first character. 2. ANSI standard recognizes a length of 31 characters. However, length should not be normally more than eight characters, since only the first eight characters are treated as significant by many compilers. 3. Uppercase and lowercase are significant. That is Total is not the same as total or TOTAL. 4. It should not be a keyword. 5. White space is not allowed. Numeric Variables Sridevi G M, Department of ISE, DSATM P a g e | 31 Principles of Programming using C – 23ESCS11 Module – 1 Character variables Declaring variables Initialising variables Declaring variables The declaration does two things It tells the compiler what is the name of the variable used It specifies what type of data the variable will hold. The syntax is |data type variablenamel, variablename2, variablename3; Where: data type is any data-type which is supported by C language. variablenamel, variablename2,... , variablenameN are variable-names which are taken by following the rules. Example: int sum, total, number; float marks, average, area; Initialising variables The variables are not initialized when they are declared. Hence, variables normally contain garbage values and hence they have to be initialized with valid data. To assign a value to variable assignment operator (=) is used. The value can be assigned in two ways When a variable is declared, such assignment is called initialization. Syntax: data type var_name = value; After some times of declaration called as variable assignment. Sridevi G M, Department of ISE, DSATM P a g e | 32 Principles of Programming using C – 23ESCS11 Module – 1 3.8 C TOKENS C tokens are the basic buildings blocks in C language which are constructed together to write a C program. Each and every smallest individual units in a C program are known as C tokens. C tokens are of six types. They are, 1. Keywords (eg: int, while), 2. Identifiers (eg: main, total), 3. Constants (eg: 10, 20), 4. Strings (eg: “total”, “hello”), 5. Special symbols (eg: (), {}), 6. Operators (eg: +, /,-,*) 1. KEYWORDS Keywords are reserve words which has predefined meaning in complier and which are used for their intended purpose only. There are 32 keywords in ANSI C and they are listed in following table Rules for using keywords Keywords cannot be used as a variable or function. All keywords should be written in lower letters. 2. IDENTIFIERS As the name indicates, identifier is used to identify various entities of program such as variables, constants, functions etc. Identifiers are user defined names and consists of sequence of letters and digits. Rules for identifiers Sridevi G M, Department of ISE, DSATM P a g e | 33 Principles of Programming using C – 23ESCS11 Module – 1 1. First character must be an alphabet (or underscore). 2. Must consist of only letters, Digits or underscore. 3. Only first 31 characters are significant 4. Cannot use a keyword. 5. Must not contain a white space. Example: sum, answer, area, number 10, hello. 3. CONSTANTS A constant is an identifier whose value remains fixed throughout the execution of the program. C supports several types of constants. Sridevi G M, Department of ISE, DSATM P a g e | 34 Principles of Programming using C – 23ESCS11 Module – 1 1. Integer constant In integer there are three types of constants a. Decimal: Consists of set of numbers between 0 and 9 and sign ‘-’ or ‘+’ are optional. Example: 112, -150, +652 etc. b. Hexadecimal: A sequence of digits preceded by Ox or OX is referred as hexadecimal constants. Example: 0x6, 0X55, OXabe Octal: It consist of any combination of digits between) through 7, with a leading 0. Example: 037, 045, 0123 Real Constants The quantities that represented by numbers containing fractional parts like 3.142, such numbers are called real (or floating point) constants. Example: 3.142, -4.124, +444.0 etc. A real number can also be expressed in exponential (or scientific) notation. Example: 215.65 can also be written as 2.1565e2 Where e2 means multiply by 102 The general form is mantissa e exponent Where mantissa is either a real number expressed in decimal notation or an integer. exponent is an integer number with an optional plus or minus sign. e separates the mantissa and the exponent can be written in either lowercase or uppercase. Example: 0.65e4 or 0.65E4 Single character constants A single character constant (or character constant) contains a single character enclosed with in a pair of single quotes. Example: ‘5’, ‘a’, etc. String Constants Sridevi G M, Department of ISE, DSATM P a g e | 35 Principles of Programming using C – 23ESCS11 Module – 1 A string constant is a sequence of characters enclosed in double quotes. Example: “Hello”, “546”, “;!>” etc. Backslash character constant A list of backslash character constants is given in following table. These are also called escape sequences. DEFINING A SYMBOLIC CONSTANT A symbolic constant is name that substitute for a sequence of character that cannot be changed. The character may represent a numeric constant, a character constant, or a string. When the program is compiled, each occurrence of a symbolic constant is replaced by its corresponding character sequence. They are usually defined at the beginning of the program. Sridevi G M, Department of ISE, DSATM P a g e | 36 Principles of Programming using C – 23ESCS11 Module – 1 The symbolic constants may then appear later in the program in place of the numeric constants, character constants, etc., that the symbolic constants represent. #define symbolic_name value_of_constant Where: #define is a pre-processor directive. symbolic name is the name taken by following the rules of identifiers. value of constant is the value which a symbolic name should hold. Example: Symbolic and Symbolic names are sometimes called constant identifiers. Since the symbolic names are constants they do not appear in declarations. The following rules apply to #define statement which defines a symbolic constant: 1. Symbolic names have the same form as variable names. (Symbolic names are written in CAPITALS to visually distinguish them from the normal variable names, which are written in lowercase letters. This is only a convention, not a rule.) 2. No blank space between the pound sign and the word define is permitted. 3. must be the first character in the line. 4. A blank space is required between ^define and symbolic name and between the symbolic name and the constant. 5. #define statements must not end with a semicolon. 6. After definition, the symbolic name should not be assigned any other value within the program by using an assignment statement. For example, STRENGTH = 200; is illegal constant. 7. Symbolic names are NOT declared for data types. Its data type depends on the type of 8. #define statements may appear anywhere in the program but before it is referenced in the program (the usual practice is to place them in the beginning of the program). DECLARING A VARIABLE AS CONSTANT The constant can also be defined by declaring the variable with the qualifier const at the time or initialization. Example: const int class size = 40; const is a new data type qualifier. This tells the compiler that the value int variable class size must not be modified by the program. Sridevi G M, Department of ISE, DSATM P a g e | 37 Principles of Programming using C – 23ESCS11 Module – 1 However, it can be used on the right side of an assignment statement like any other variable. This type of constant is also called as Memory constant. 4. STRINGS Strings are nothing but an array of characters ended with a null character ('\0'). This null character indicates the end of the string. Strings are always enclosed in double quotes. char string = {‘h’, ’e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘w’, ‘o’, ‘r’, ’l’, ‘d’, ‘\0’}; char string = “hello world”; char string [] = “hello world”; 5. SPECIAL SYMBOLS {,},[,],?,+,-,*,/,%,!,;, 6. OPERATORS Operators are symbols that represent operations to be performed on one or more operands. C provides a wide range of operators, which can be classified into different categories based on their functionality. Operators are used for performing operations on variables and values. Types of Operators: Arithmetic Operators, Relational Operators, Logical Operators, Bitwise Operators, Conditional Operators, Assignment Operator, Increment/Decrement Operators 3.9 INPUT/OUTPUT STATEMENTS IN C Sridevi G M, Department of ISE, DSATM P a g e | 38 Principles of Programming using C – 23ESCS11 Module – 1 FORMATTING INPUT/OUTPUT C language supports two formatting functions printf and scanf. printf is used to convert data stored in the program into a text stream for output to the monitor(Standard output device) scanf is used to convert the text stream coming from the keyboard(Standard input device) to data values and stores them in program variables. A program that uses standard I/O functions must contain the statement #include< stdio.h> printf()- Print formatting The printf function is used to display information required by the user and also to print the values of the variables Flags Specify output justification such as decimal point, numerical sign, trailing zeros or octal, decimal or hexadecimal prefixes. Sridevi G M, Department of ISE, DSATM P a g e | 39 Principles of Programming using C – 23ESCS11 Module – 1 Width specifies the minimum number of characters to print after being padded with zeros or blank spaces, that is it specifies the minimum number of positions in the output Sridevi G M, Department of ISE, DSATM P a g e | 40 Principles of Programming using C – 23ESCS11 Module – 1 Printf examples Sridevi G M, Department of ISE, DSATM P a g e | 41 Principles of Programming using C – 23ESCS11 Module – 1 Sridevi G M, Department of ISE, DSATM P a g e | 42 Principles of Programming using C – 23ESCS11 Module – 1 scanf()- scan formatting Reading Data from Keyboard: The scanf function is used to read Formatted data from the keyboard. This function takes the text stream from the keyboard Extracts and formats data from the stream According to a format control string and then stores the data in specified program variables. Width is an optional argument that specifies the maximum number of characters to be read. Modifier is an optional argument that can be h, l or L for the data pointed by the corresponding additional arguments. Type specifies the type of data that has to be read Sridevi G M, Department of ISE, DSATM P a g e | 43 Principles of Programming using C – 23ESCS11 Module – 1 Example: Sridevi G M, Department of ISE, DSATM P a g e | 44 Principles of Programming using C – 23ESCS11 Module – 1 Examples of printf/scanf Sridevi G M, Department of ISE, DSATM P a g e | 45 Principles of Programming using C – 23ESCS11 Module – 1 Sridevi G M, Department of ISE, DSATM P a g e | 46 Principles of Programming using C – 23ESCS11 Module – 1 3.8 ERRORS IN PROGRAMMING Errors in programming refer to issues or defects that arise within the program, resulting in abnormal behavior. Even experienced developers can make these mistakes, which are also referred to as bugs or faults. The process of eliminating these errors is called debugging. These Sridevi G M, Department of ISE, DSATM P a g e | 47 Principles of Programming using C – 23ESCS11 Module – 1 errors in Programming can be identified during the program’s compilation or execution, and it’s crucial to remove them to ensure the program runs smoothly. Here we will discuss the various types of errors in programming and some of the common causes behind them. So, let’s dive straight into the topic of Types of Errors in Programming. What are the Different Types of Errors in Programming? As mentioned above errors refers to issues that occur in a program that results in unwanted behavior of the program. Some common Types of Errors in Programming are listed below. Syntax Error Run-Time Error Linker Error Logical Error Semantic Error Let us discuss each of these types of errors in programming in detail. 1. Syntax Error A syntax error is the most common type of error in programming. It occurs when the programmer writes code that is not in accordance with the syntax of the programming language. Syntax errors are detected by the compiler, and the compiler reports an error message to the programmer. Common examples of syntax errors include, Forgetting to add a semicolon, Spelling a keyword incorrectly Missing a closing brace. Example of Syntax Error Here is an example code having a syntax error. #include int main() { printf( "Hello, world!") return 0; } Output: prog.c: In function ‘int main()’: prog.c:6:26: error: expected ‘;’ before ‘return’ printf( "Hello, world!") ^ Sridevi G M, Department of ISE, DSATM P a g e | 48 Principles of Programming using C – 23ESCS11 Module – 1 ; return 0; ~~~~~~ Explanation: In the above example, the programmer forgot to add a semicolon after the cout statement, resulting in a syntax error as shown in the output. 2. Run-time Error A run-time error occurs during the execution of a program. These errors occur when a program tries to perform an illegal operation, such as dividing by zero or attempting to access an invalid memory address. The program compiles without errors, but when it runs, it encounters an error that causes it to terminate abnormally. Run-time errors are often difficult to detect because they do not show up until the program is executed. Example of Run-Time Error Let us see a C++ code that throws a runtime error. #include int main() { int a = 5, b = 0; int c = a / b; printf("The result is %d ", c); return 0; } Output: Runtime error #stdin #stdout Explanation: In the above example, the program tries to divide a by b, which is zero. Since division by zero is undefined, the program will stop abruptly and we don’t get any output on the screen as this results in the runtime error. 3. Linker Error A linker error occurs when a program references a function or variable that is not defined in the program or the libraries it is linked against. Linker errors typically occur when a program is compiled and linked. The linker will report an error if it cannot find the necessary files or libraries to link the program. Example of Linker Error Here is the code that will show the linker error. #include Sridevi G M, Department of ISE, DSATM P a g e | 49 Principles of Programming using C – 23ESCS11 Module – 1 int main() { printf( "Hello, world!"); myFunction(); return 0; } Output: prog.cpp: In function ‘int main()’: prog.cpp:7:3: error: ‘myFunction’ was not declared in this scope myFunction(); ^~~~~~~~~~ Explanation: In the above code, we call the function named as myFunction(), but the function is not defined in the program or any of its libraries. As soon as we compile the program, the linker reports the error “myFunction() is undefined” on the output screen. 4. Logical Error A logical error occurs when the program compiles and runs without any syntax, run-time, or linker errors, but the output is incorrect. These errors occur when the program's logic or algorithms are incorrect. Logical errors are challenging to detect because the program does not generate any error messages. Example of Logical Error Let us understand this error with the help of an example. #include int main() { int a = 5, b = 7; if (a > b) { printf( "a is less than b"); } else { printf( "b is less than a"); } return 0; } Output: b is less than a Explanation: Sridevi G M, Department of ISE, DSATM P a g e | 50 Principles of Programming using C – 23ESCS11 Module – 1 In the above example, the program intends to check if a is less than b. However, the program checks if a is greater than b, resulting in incorrect output. The logic for checking the smaller number is wrong because of the usage of the ‘>’ sign instead of ‘

Use Quizgecko on...
Browser
Browser