0 likes | 32 Views
Introduction to Computing elements, Components of computer system: Hardware, Software, CPU, Computer Memory unit, Operating System, Algorithms, Flow charts, <br>C: Fundamentals, Variable, Character Set u2013 Identifier and keywords u2013 Data Types u2013 Constants u2013 Variables declarations u2013 Expressions u2013 Statements u2013 Operators, Library functions. Data Input and Output statements, Simple C Programs
E N D
UNIT-I Syllabus: Introduction to Computing elements, Components of computer system: Hardware, Software, CPU, Computer Memory unit, Operating System, Algorithms, Flow charts, C: Fundamentals, Variable, Character Set – Identifier and keywords – Data Types – Constants – Variables declarations – Expressions – Statements – Operators, Library functions. Data Input and Output statements, Simple C Programs Definition: Computer can be defined on an electronic device that accept data, process then at a high speed according to a set of instructions provide to it and produces the desired output. So, computer is a programmable machine. Generation of computer Generation means variation between different hardware technologies. 1st generation: (1946-1956) First generation computers are made with the use of vacuum tubes. These computers used machine language for programming. Disadvantages: 1. Occupied lot of space 2. Consumed lot of power 3. Produced lot of heat 4. Costly system Example: ENIAC (Electronic numeric integrator and computer) UNIVAC (Universal Accounting company) 2nd generation: (1957-1963) The computer in which vacuum tubes were replaced by transistors are called second generation of computers these computers used assembly language for programming. Advantages: 1. Less expensive 2. Consumed less power 3. Produced little heat 4. Less cost and work at higher speed Example: IBM 7090, IBM 7094 3rd generation: (1964-1981) The computers using the integrated circuits came to be known on the third generation of computers. These used high level language. Example: IBM 370, Cyber 175 4th generation: (1982-1989) The computers which were built with microprocessor are identified on the fourth-generation computers these computers use VLSI chips for both CPU and memory. Note: VLSI (very large-scale integration)-It is the process of creating on integrated circuit by combining millions or billions of transistors on to one chip. Example: CRAY-2, IBM 3090 5th generation: (1990- till now) Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Fifth generation computers are under development stage these computers use ULSI chips. ULSI chip contains thousands of components into a single IC. Aim of these computers is develop the artificial intelligence. Note: ULSI (Ultra large-scale integration)-Which refers to the chips with complexity of more than one million transistors. -gaming -Expert system -Natural language -Robotics -Machine learning Block Diagram of Computer System: The working of computer can be broadly categorized into following four functions or steps. i) Receive input: Accept data/information from user through various input devices like the key board, Mouse, Scanner etc. ii) Process information: Perform arithmetic or logical operations on data/information. iii) Store information: Store the information in storage device like hard disk, CD (compact disk), Pen drive, DVD (Digital versatile disc). iv) Produce Output: Communicate information to the user through any of the avarice output device like monitor Printer, speaker, projector. The hardware components of the computer specialize in any one of these functions. Computer hardware falls into two categories: processing hardware and the peripheral devices. The processing hardware consists of the Central Processing Unit (CPU), and as its name implies, it is where the data processing is done. Peripheral devices allow people to interact with the CPU. Together, they make it possible to use the computer for a variety of tasks. COMPONENTS OF A COMPUTER Computer has four main components •Input Devices: These are the devices that are used to accept data and instructions from the user. Keyboard, mouse, scanner etc., are the examples of input devices. •Central Processing Unit (CPU): This is known as the ‘Brain of the Computer’ as it controls the complete working of the computer. •Memory: The data and instructions are stored in this component of the computer. Hard disk, DVD, pen drive, CD etc., are the examples of memory storage devices. •Output Devices: These are the devices that are used to display the desired result or information. Monitor, printer, speaker etc., are the examples of output devices. Let us now learn each of the components in detail. Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
INPUT DEVICES: An input device is used to get data or instructions from the user. This data is then passed on to CPU for processing so as to produce the desired result. Although keyboard and mouse are the two common input devices, other devices such as Optical Character Recognition (OCR), Magnetic Ink Character Recognition (MICR), and mark sense reader, etc., are also used as per our requirement. Keyboard The keyboard is very much like a standard typewriter with a few additional keys. Generally, we find a QWERTY keyboard with 104 keys on it. The additional keys may be included in modern multimedia keyboards. Mouse The mouse is another very commonly used input device. It is basically a pointing device that controls the movement of the cursor or pointer on a display screen. It is a small object that you can roll along a hard and flat surface. As you move the mouse, the pointer on the display screen moves in the same direction. A mouse may contain one, two or three buttons which have different functions depending on what program is running. Scanner Scanner is an input device that can read text or an illustration printed on paper and translates the information into a form that the computer can use. A scanner works by digitizing an image - dividing it into a grid of boxes and representing each box with either a zero or a one, depending on whether the box is filled in. The resulting matrix of bits, called a bit map, can then be stored in a file, displayed on a screen and manipulated by programs. Optical scanners do not distinguish text from illustrations; they represent all images as bit maps. Therefore, you cannot directly edit text that has been scanned. To edit text read by an optical scanner, you need an Optical Character Recognition (OCR) system to translate the image into ASCII characters. •Optical Character Recognition (OCR) An Optical Character Recognition (OCR) is a device that is used for reading text from paper and translating the images into a form that the computer can understand. An OCR is used to convert books, magazines and other such printed information into digital form. •Magnetic Ink Character Recognition (MICR) An MICR can identify characters printed with a special magnetic ink. This device particularly finds applications in banking industry. The cheques used for transactions have a unique MICR code that can be scanned by an MICR device. •Optical Mark Recognition (OMR) Optical Mark Recognition, also called mark sense reader, is a technology where an OMR device senses the presence or absence of a mark, such as pencil mark. OMR is widely used for assessing the objective examinations involving multiple choice questions. •Bar Code Reader A bar code reader is an input device that is generally seen in super markets, bookshops, libraries etc., A bar-code reader is a photoelectric scanner that reads the bar codes (vertical striped black and white marks), printed on product containers. The bar code reader scans the bar code of the product and checks the description and the latest price of the product. Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
CENTRAL PROCESSING UNIT (CPU): CPU is the ‘Brain of your computer’. This is because it processes or executes the instructions given to the computer. Any type of instruction given to the computer using any of the input devices has to be sent to the CPU for execution. In a microcomputer, the CPU is based on a single chip called the microprocessor. A typical CPU has the following components: •Control Unit (CU) •Arithmetic Logic Unit (ALU) •Memory Registers Control Unit (CU): The Control unit manages the instructions given to the computer. It coordinates the activities of all the other units in the system by instructing rest of the components of the computer about how to carry out a program’s instructions. It reads and interprets instructions from memory and transforms them in to series of signals to be executed or stored. It also directs the movement of these electronic signals between memory and ALU or between CPU and input/output devices. Hence it controls the transfer of data and information between various units. The user’s program provides the basic control instructions. Conceptually, the control unit fetches instructions from the memory, decodes them and directs the various units to perform the specified functions. Arithmetic Logic Unit (ALU) Arithmetic Logic Unit or ALU performs two types of operations - arithmetic and logical. Arithmetic operations are the fundamental mathematical operations consisting of addition, subtraction, multiplication and shifting operations. Logical operations consist of boolean comparisons such as AND, OR and NOT. Memory Registers The CPU processes data and instruction with high speed. There is also movement of data between various units of the computer. It is necessary to transfer the processed data with high speed. So the computer uses a number of special memory units called registers. A memory register is a sort of special storage area that holds the data and instructions temporarily during processing. OUTPUT DEVICE: Output devices receive information from the CPU and present it to the user in the desired form. Some of the output devices are monitor, printers, plotters, etc. Monitor The monitor is just like a television screen and it is used to display data and information. When some data or instruction is being keyed in, the monitor displays the characters being typed. The monitors are available in various sizes. They may also differ for different types of computers. The standard size is 24 lines by 80 characters. The output displayed on the monitor is called soft copy. Printer: Printer is a device that produces the output on paper. Such an output is also known as hard copy and it may be in the form of text or graphics. There are many different types of printers. These printers vary in terms of size, speed and quality of output. Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
i)Dot Matrix Printer: It is a type of printer that uses a print head to print characters on paper. The print head moves in back and forth or up and down motion on the page. The print head strikes on an ink-soaked cloth ribbon that is laid against a paper. The characters formed from dots are thus printed on the paper. ii)Ink-jet Printer: Ink-jet printers work by spraying ionized ink on a sheet of paper. Magnetized plates in the ink’s path direct the ink onto the paper in the desired shapes. Ink-jet printers are capable of producing a better print than the dot matrix printers. A typical ink-jet printer provides a resolution of 300 dots per inch, although some newer models offer higher resolutions. These are also known as Line printers as the output is produced line by line. iii)Laser Printer: It works on the principle of a photocopier. It utilizes a laser beam to produce an image on a drum. The light of the laser alters the electrical charge on the drum wherever it hits. The drum is then rolled through a reservoir of toner, which is picked up by the charged portions of the drum. Finally, the toner is transferred to the paper through a combination of heat and pressure. Speakers: The speakers are used to produce audio output. The computers have sound cards that enable the computer to produce audio output through the speakers. Now-a-days, 3D audio is a technique for giving more depth to traditional stereo sound. Typically, 3D sound or 3D audio is produced by placing a device in a room with stereo speakers. The device dynamically analyses the sound coming from the speakers and sends feedback to the sound system so that it can read just the sound to give the impression that the speakers are further apart. MEMORY UNIT There are two kinds of computer memory: primary and secondary. Primary memory is accessible directly by the Central Processing Unit. RAM is an example of primary memory. As soon as the computer is switched off, the primary memory loses its contents. But data can be stored and retrieved at much faster rate with primary memory as compared to secondary memory. Examples of secondary memory storage devices are floppy disk, magnetic disk, hard disk, CD, pen drive etc. The secondary memory devices may be inside or located outside the computer. Primary memory is more expensive than secondary memory. Measuring Memory The primary or internal storage unit is made up of several small storage locations called cells. Each of these cells can store a fixed number of bits called word length. Each cell has a unique number assigned to it called the address of the cell and it is used to identify the cells. Data in computer is stored in the form of 0s and 1s. Each of these digits is known as a bit. A collection of 8 bits constitutes a byte. Each cell of memory contains one character or 1 byte of data. So, the capacity is defined in terms of bytes or words. However higher units of memory are Kilobytes, Megabytes, Gigabytes etc. 1 Kilobyte is equal to 1024 bytes. Thus 64 Kilobyte (KB) memory is capable of storing 64 × 1024 = 32,768 bytes. Other units of memory are listed in the table below: Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Primary Memory Primary memory is the memory that is accessed by the processor directly. It is also known as main memory or internal memory. It helps in executing applications that are temporarily stored in a specific memory location. Primary memory is of two types – RAM and ROM. Random Access Memory (RAM) Random Access Memory (RAM) is the type of memory in which it is possible to randomly select and use any location of the memory directly to store and retrieve data. It is also called as read/write memory. Since it is volatile, the data from RAM is lost as soon as the power to the computer is switched off. Read Only Memory (ROM) This is another type of primary memory from which data can only be read. We cannot write or modify data once written on to the ROM. Also, this type of primary memory is not volatile. The storage of program and data in the ROM is permanent. •Programmable Read Only Memory (PROM): You know that it is not possible to modify or erase programs stored in ROM, but it is possible for you to store your program in PROM chip. Once the programs are written it cannot be changed. Also, the program is not lost even if power is switched off. •Erasable Programmable Read Only Memory (EPROM): This type of ROM overcomes the problem of PROM and ROM. EPROM chip can be programmed time and again by erasing the information stored earlier in it. Information stored in EPROM can be erased by exposing it to ultraviolet light. This memory can be reprogrammed using a special programming facility. When the EPROM is in use, information can only be read. •Electrically Erasable Programmable Read Only Memory (EEPROM): This type of ROM is somewhat similar to EPROM. The only difference is that unlike EPROM, electrical signals are used to erase the contents of EEPROM. Also, this type of ROM need not be completely erased. Partial modification of ROM is possible. Secondary Memory: These high-speed storage devices are very expensive and hence the cost per bit of storage is also very high. Again, the storage capacity of the main memory is also very limited. Therefore, additional memory is required in all the computer systems. This memory is called auxiliary memory or secondary storage. Huge volume of data are stored here on permanent basis and transferred to the primary storage as and when required. Most widely used secondary storage devices are hard disks, CDs, DVDs and pen drives. But before learning about these modern storage devices let us also have a look at some primitive storage devices like magnetic tapes, magnetic drums and floppy disks. •Magnetic Tape Magnetic tapes are used for large computers like mainframe computers where large volume of data is stored for a longer time. Earlier these were used with PCs also. The cost of storing data in tapes is inexpensive. Tapes consist of magnetic materials that store data permanently. It can be 12.5 mm to 25 mm wide plastic film-type and 500 meter to 1200 meter long which is coated with magnetic material. The deck is connected to the central processor and Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
information is fed into or read from the tape through the processor. It is similar to a cassette tape recorder. •Magnetic Disk which is circular like a disk and coated with magnetic material. Magnetic disks used in computer are also made on the same principle. It rotates with very high speed inside the disk drive. Data are stored on both the surfaces of the disk. Magnetic disks are most popular for direct access storage. Each disk consists of a number of invisible concentric circles called tracks. Information is recorded on tracks of a disk surface in the form of tiny magnetic spots. The presence of a magnetic spot represents one bit (1) and its absence represents zero bit (0). The information stored in a disk can be read many times without affecting the stored data. So, the reading operation is non-destructive. But if you want to write a new data, then the existing data is erased from the disk and new data is recorded. •Floppy Disk It is similar to magnetic disk. It is 3.5 inch in diameter. The capacity of a 3.5-inch floppy is 1.44 megabytes. It is cheaper than any other storage devices and is portable. The floppy is a low-cost device particularly suitable for personal computer system. •Hard Disk A hard disk is the most commonly used secondary storage device. Although generally it is fixed inside the CPU cabinet but still external hard disks are also available. It can store huge amount of data and also and provides relatively quick access to data stored on it. A hard disk is a set of numerous disks stacked one above the other with a cylindrical spindle in-between Fig. The data is recorded electromagnetically in the form of concentric circles called tracks. The tracks are further divided into blocks as shown in the figure. In the hard disk drive, there is a Read/Write head mounted on the arm placed next to the stacked disks. This head moves horizontally and vertically to read or write data on the disks. Optical Disk: Optical disks can be divided into the following categories. •Compact Disk - Read Only Memory (CD-ROM): CD-ROMs are made of reflective metals. A CD-ROM is written during the process of manufacturing by high power laser beam. Here the storage density is very high, storage cost is very low and access time is relatively fast. Each disk is approximately 4 ½ inches in diameter and can hold over 600 MB of data. As the CD-ROM can be read only, we cannot write or make changes into the data contained in it. •Compact Disk - Recordable(CD-R): These CDs can be used to write data on to them provided your computer has a CD writer. The CD writer uses a special laser light to write data Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
on to a blank CD. Once the CD-R has been burnt, i.e., data has been written on it, it cannot be modified. The information can be added to it but the parts that have been burnt cannot be edited. •Compact Disk – Read/Write (CD- R/W): This type of CD can be used for both reading and writing. Also, these can be written and erased again and again. •Digital Versatile Disk (DVD): A DVD is an optical storage disk with much larger storage capacity than that of CDs. A single sided DVD can store upto 4.7 GB of data. Due to its high storage capacity, DVDs are generally used to store movies and other audio video files. COMPUTER SOFTWARE A complete set of instructions written to solve a problem on a computer is called software. i.e., software refers to the set of computer programs that cause the hardware (computer system) to function in the desired manner. Computer software is normally classified into two broad categories: (i) System Software (ii) Application Software System Software: System software includes general programs written for a computer. It consists of pre-written programs and documentation supplied by the manufacturer along with the computer. These programs are held permanently in the machine. The primary objectives of this software are to: (i) enhance the efficiency of hardware utilization (ii) make computers simple to use. The first objective is realized by that component of system software which is commonly known as operating system. System software is a set of instruction to the machine to interpret and execute application software. For example, language translators (called compilers and interpreters), operating systems, utilities and special purpose software. •Operating systems: An operating system is a collection of system programs that control the operations of the computer system. Operating system is the infraction between user and hardware. Factions of Operating Systems: 1)Process Management 2)File Management User Software Operating Systems Hardware Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
3)Memory Management 4)Security Management 5)Manages the computer Hardware 6)Provides a User Interface. Process Management: The operating System enables a user to execute more than on job at the same time to enhance productivity. File Management: The Operating system allows users to create, copy, delete and rename files. Memory Management: Finding vacant spaces in the primary memory, loading the appropriate data and programs in the loader space, executes them and remaining them from memory done by operating system. Security Management: The operating system protects stored information from users. It Ensures that the data and files stored cannot be accessed by unauthorized users. Ex: Windows, Linux Ex: Ms-Dos, Unix Manages the computer hardware: The Operating system controls and efficiently utilizes hardware components such as CPU, Memory and Input/Output devices. Provides a User Interfaces: The operating system enables users to easily interact with the computer hardware. •Utility Software: Utility software may be considered as system software which is used quite often in the development of a program. Sort merge programs are used to sort records in a particular manner or sequence. Such programs are normally provided by the manufacturers. The programmer can also develop his/her own utility software and keep it in the secondary memory of the computer. Application Software Application software is written to perform a specific task or process, such as accounting, payroll, mailing list, result preparation and so on. The majority of application software is written in high-level languages. It is divided into 2 classes General purpose software •These are purchased from software developers •They can be used for more than one application •Eg: word processors, DBMS etc… Application Specific Software •It can be used only for intended purpose i.e., for which they were designed eg: Accounting system, hospital management system, banking system. Etc. Interfaces of Operating system G.U.I(Graphical User Interface) C.U.I(Command User Interface) Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
COMPUTER LANGUAGES Computer programming languages are used to give instructions to the computer in a language which computer understands (0’s and 1’s) Computer languages are classified into 2 types 1.Low-level Language (Machine Language and Assembly Language) (Close to Machine) 2.High level languages (C, C++, Java, Python, etc.,) (Close to Human) Translators: Computer is a machine and since its memory can store only 1’s and 0’s, instructions must be given to the computer in streams of 1’s and 0’s i.e., binary code. So, computer cannot Under Stand anything written other than 0’s and 1’s. These are easily understandable by the machine Programs written in binary code can be directly feed to computer for execution and it is known as machine language. So that computer written in other language must be translated into machine language using translator. Advantage: Execution is very fast since there is no need of conversion Disadvantage: Writing and reading programs in machine language is very difficult Machine instructions are difficult to remember There are Three types of translators 1.Assembler 2.Complier 3.Interpreter 1.Assembler •A program which translates as assembly language program into a machine language program. It is also called as assembly language or assembler. •An assembly program contains “Mnemonics”. •“Mnemonic” means information can be memorized easily and is generally in the form of abbreviations. Advantage: •Easy to read and write programs in assembly language when compared to machine language Mnemonics are easy to remember Disadvantage: •Assembly programs are machine dependent •Execution is slow since it needs conversion into machine language •“Assembler” is used to convert assembly language program into machine language. Example: LDA, MOV B, ADD A Assembly language program Assembler Machine Language code 2.Complier: It is a program which translates a high-level language program into machine language program. A complier is a program that convert the code written in high level language (like C, C++, Java, Python Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
etc.,) into Low level language (like assembly language and machine language). Machine language is the binary code which is under standable by the computer machine. Some examples of complier for C, C++ language are portable C, turbo C/C++, GCC etc., also during their conversion process complier Identifies and report any error in the source of the program. HLL Code LLL Code (C, C++, Java) Target Program/ Code Interpreter: An interpreter is a program which translates statement of a high-level language program into machine language. An interpreter is a program which translate and executed the statement line by line. It continuous translating the program until the first error is mode. As it gets first error it stops. For example, language such as python, LISP, Ruby etc., use interpreter. interpreter High level language Machine language (statements) Difference Between Complier and Interpreter: Complier 1.Scan the entire program and translates it as a whole into machine code 2. It takes less time to execute. 3.processing is fast 4. C, C++ use complier LINKER: In high level languages built in header files or libraries are stored. These libraries are pre- defined and contain basic functions which are essential for executing the program. These functions are linked to the libraries by a program called linker (Also known as link editor or binder). If linker does not find a library of a function, then it informs to complier and complier generates an error. Complier automatically involves the linker as last step in compiling a program. LOADER: A loader is a special type of program that copies programs from a storage device to the main memory, where they can be executed. Most of the loaders are transparent to the users. NUMBER SYSTEM: - A System for representing numbers of a certain type. Number system is represented by its base (also called radix). We general have four number system. 1.Binary Number System: - Base(radix)2 Digits 0 to 1 2.Octal Number System: - Base (radix) 8, Digits 0 to 7 3.Decimal Number System: - Base(radix)10, Digits 0 to 9 Complier Error Interpreter 1. Translates programs statement at a time. 2.It takes more time to execute. 3. Processing is slow. 4. Python, Ruby use interpreter Executable binary Program Object Modules Source Program Translator Linker Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
4.Hex decimal Number System: - Base(radix)16, Digits 0 to 9, letter: A to F Where A-10, B-11, C-12, D-13, E-14, F-15. Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
ALGORITHM: •It is a step – by – step procedure for solving a problem (or) •An algorithm is step- by-step solution of a problem is known as algorithm (or) •An algorithm is sequence of finite and well-defined instructions for completing a task or solving problem. Algorithm is given an initial state proceed through a well-defined serious of sequence state. If algorithm is written in English like sentences, then it is called as ‘PSEUDO CODE’ Properties of an Algorithm An algorithm must possess the following 5 properties. They are 1. Input 2. Output 3. Finiteness 4. Definiteness 5. Effectiveness 1. Input: An algorithm must have zero (or) more number of inputs 2. Output: Algorithm must produce one (or) more number of outputs 3. Finiteness: An algorithm must terminate in countable number of steps 4. Definiteness: Each step of the algorithm must be stated clearly 5. Effectiveness: Each step of the algorithm must be easily convertible into program statements Types of algorithms: Algorithm are classified to the three types of control algorithms. 1.Sequence 2.Branching (Decision)(selection) 3.Loop (repetition) 1.Sequence: •In sequence control structure each step of the algorithm is executed in the specific order. •Algorithm performs the steps in a purely sequential order Algorithm for finding the sum of two numbers. Step1: Input 1st Number A Step2: Input 2nd Number B Step3: Set sum=A+B Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Step4: print sum Step5: End Algorithm for finding the average of 3 numbers 1. start 2. Read 3 numbers a, b, c 3. Compute sum = a+b+c 4. compute avg = sum/3 5. Print avg value 6. Stop Algorithm to calculate area of circle. Algorithm: Area of circle Input: R=Radius Output: A=Area Steps: Step 1: BEGIN Step 2: Accept the R Step3: Find the square of R and store it in A=R*R Step4: Multiply R with 3.14 and store the result in A Step5: Display the value of A Step6: END Algorithm: Swap two numbers Input: Two numbers Output: Swapped numbers Step 1 : Start Step 2 : READ num1, num2 Step 3 : temp = num1 Step 4 : num1 = num2 Step 5 : num2 = temp Step 6 : PRINT num1, num2 Step 7 : Stop 2.Decision: •Decision control structures can be used for making decisions and branching of statements, where the outcome of the process depends on some condition. Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
•A condition in this context is any statement that may evaluate either to a TRUE or FALSE value. •This form is commonly known as the if—else construct. Example: Step 1: Start Step 2: Input first number as A Step 3: Input Second number as B Step 4: IF A==B Print Equal ELSE Print Not Equal Step 5: Stop Write an algorithm to find largest number amongst three numbers. Algorithm: Greatest Number Input: Three Numbers Output: Greatest among three Numbers Steps: Step 1: BEGIN Step2: Read values for NUM 1, NUM2 and NUM3 Step3: if NUM1>NUM2 Check if Num1>NUM3, if true then display NUM 1 is Largest number Else check if NUM2>NUM1 Check if Num2>NUM3 display NUM 2 is largest number Else check if NUM3>NUM1 Check if Num3>NUM2 display NUM 3 is largest number Step4: END 3. Repetition: •These control structures are used for executing one or more steps for a number of times. •It can be implemented using constructs such as for loop, while loop etc. Example: Step 1: Start Step 2: Initialize I=1, N=10 Step 3: Repeat Steps 3 and 4 while I<=N Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Step 4: Print I Step 5: Set I=I+1 Step: Stop FLOWCHARTS: •A Flowchart is a graphical representation of a Algorithm. •The sequence of steps in algorithm is maintained and represented in the flowchart by using some standard symbols such as rectangles and directed lines. •As flowchart uses the pictorial representation of an algorithm, it becomes easier to understand what is going on. •One of the most common ways to express algorithm with writing a program is a flowchart. •Symbols used in flowchart: S.No.Symbol 1 Oval Name of the Symbol Start/End Terminal Use of the symbol Indicate start and end of the algorithm. Represented as rounded rectangle. 2 Rectangle Action or Process Indicate set of operations like assignments, Initialization, calculations etc. 3 Decision Indicates the decision-making statements. It indicates a condition on which decision are made. Diamond 4 Input/Output Indicate Input provided to algorithm and outputs processed by algorithm. It Parallelogram is represented by parallelogram. 5 Flow line Indicates the flow of algorithm. Represented as arrow of line. 6 Connector Circle Draw a flowchart to find greater number amongst two numbers. Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Draw a flowchart to check whether a given number is even or odd. Flowchart for calculating area of circle Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
C Programming Language: •C programming language was developed in 1972 by Denies Ritchie at AT & T BELL labs to developed the Unix operating System. •C programming language took the concept from ALGOL, BPCL, B and added some feature of his own. •C has no full form, this is the successor language of B. Characteristics of C programming: 1.C is Structured Programming Language 2.C is a case-sensitive language 3.C is Portable language 4.C is simple, fast and Efficient 5.C has rich set of data types 6.C has rich set of operators Building a C Program: Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
C Programming Structure: General form of a ‘C’ program /* documentation section */ preprocessor directives global declaration main ( ) { local declaration executable statements } return type function name (argument list) { local declaration executable statements } Pre-Processor Directives: It comes at the beginning of the program. All pre-processor commands start with a hash sign (#). It can start in any column, but they traditionally start at beginning of program. Example: <stdio.h>: standard input output header file which have process identifier. printf (); - To print a message/conversion scanf (): - To put input address of variable. main (): - Every C program can contain one or more functions. Every function should have a name and it should be unique in that program. Every program should have one main function. The complier starts the execution of the program from main () function and generally the execution ends at the end of main function. Syntax: 1)int main () { ------ ------ return 0; } 2. int main(void) { ------ ------ return 0; } 3.void main () { ------ ------ } 4.void main (void) Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
{ ------ ------ } Here int and void are return types, return type specifies the type of data returned by the function. If function does not return any value, its return _type must be void. Int main () say that’s the function will return on integer value to the operating system that the functions name is main and that it has no parameters. printf ():- •It is a predefined function •It is defined in<stdio.h> header file •It is case sensitive (always write in lower case) •It is used to print data or information on to the output screen. Syntax: a)Without variable printf(“Hello”); b)With variable printf (“Format specifier”, variable name); scanf ();- it is predefined function and use case sensitive. The header file<stdio.h> is used and take their input at run time. Syntax: scanf (“format specifier”, address of variable); Note that &(ampersand) is used to get address of variable. For example: scanf (“%d”, &a); The ampersand (&) before the variable in the scanf () function is must it is an “ address of” operator.It gives the location number used by the variable in memory. Program (1): - #include<stdio.h> void main () { printf (“Hello”); } Program (2): - #include<stdio.h> void main () { int roll no=201; printf (“Your roll_no=%d”, roll_no); } Program (3): - #include<stdio.h> void main () { Int a=201; Float b= 80.5; printf (“%d %f”, a, b); } Example: Your first C program Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
#include<stdio.h> void main () { printf (“Hello, World!”); getch (); } /*Aim: Program for finding circumference of circle*/ #include<stdio.h> #include<conio.h> #define PI 3.1415 main ( ) { float c, r; clrscr ( ); printf (“enter radius of circle”); scanf (“%f”, &r); c = 2 * PI * r; printf (“Circumference = %f”, c); getch ( ); } Error: An error is an action which is inaccurate or incorrect. It is synonymous with a mistake. Thus errors should be removed before compiling and executing. Types of Errors: 1.Syntax error: it is the outcomes of misspelled keywords, missing punction character, a missing bracket or parenthesis. Example: #include<stdio.h> void main () { printf (“Hello”) // semicolon missed } 2.Logical errors: Logical errors are those errors that present your program from doing what you expected to do. You do not get error massage with logical errors. Example: #include<stdio.h> void main () { int i; for (i=1; i<4; i++); \* logical error. A semicolon after the loop*/ printf (“%d”, i); } Output: 5 Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Standard I/O in C: The standard I/O functions are declared in <stdio.h>header files. Some of them are: Functions Descriptions printf scanf fprintf fscanf putchar getchar Read an ASCII Character from the keyboard Example: \* To read and display two numbers */ # include<stdio.h> void main () { int a, b; printf (“Enter the a, b”); scanf (“%d %d”, &a, &b); // To read printf (“%d %d”, a, b); //To display } Components of C language: The basic elements recognised by complier for passage or statements of text masks are called components/token or lexical unit. There are five main components for c language 1.Character set 2.Keywords 3.Identifier 4.Data type 5.Variables 6.Constants Character Set: The character set of ‘C’ consist of alphabets, numbers and special symbols used to represent information is denoted by character. The ‘C’ character is grouped into four categories. a)Alphabets: - A to Z and a to z b)Numbers: - 0 to 9 c)Special symbols: - (~ ‘! @ # % & * () - + / $ = \ { } [] : ; “ “ ? , etc) d)White Space: - Blank space, carrier return, form feed, newline, horizontal tab, vertical tab Keywords: - •Keywords are reserve words. •They already have predefined meaning. •Keywords should always be written in lowercase. •The keywords meaning cannot be changed. -Display a formatted string -Reads a formatted string. -Write a formatted string to a file. -Reads a formatted string from a file -Display an ASCII Character to the screen. Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
•Keywords cannot be used as variable name. •There are totally 32 keywords supported in C they are auto break continue default enum extern if int short signed switch typedef volatile while Identifier: •It refers to the name of the objects. •These are the names given to variables, arrays, functions, structures and micros etc. •The rules to write an identifier are follows. i) It must contain only alphabets (A to Z, a to z), numbers (0 to 9) and underscore (_ ). ii) It must start with alphabet or underscore but not numeric character. iii) It should not contain any special symbols a part from underscore. iv) It should not have any space. v) Keywords cannot be used as identifiers. vi) Identifier are case sensitive. vii) Maximum length of an identifier is 31 characters. Some examples of c identifiers: Valid identifiers: - integer, minimum, sum, total, row1, name, ptr Invalid identifiers: - float - it is a keyword I am - it has space 123_Abc - It is starting with number N1+n2 – It contains special symbols (+) Data types: The data type defines the type of data stored in memory location or the type of data the variable can hold. The classification of data types are: case do float long sizeof union char double for register static unsigned const else goto return struct void Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Integer data type(int): •It is to store whole numbers •The keyword ‘int’ is used to declare variable of integer type. •int types 2B and 4B of storage depending on machine size. •‘int’ can be augmented with four modifiers: short, long, unsigned, signed. •These modifiers limit the range of the values which can be stored in an integer value. The standard integer types with its storage sizes and value ranges: Type Storage size (in bytes) Int (or) signed int 2 bytes Unsigned int 2 bytes Signed short int (or) signed short (or) short Unsigned short (or) unsigned short int Signed long int (or) signed long (or) long Unsigned long (or) unsigned long int Floating point data type(float): - •It is used to store decimal numbers •The keyword float is used to declare variable of floating-point data type. •Float type takes 4B or 8B of storage depending on machine size. •It can be expressed in fractional or exponential form. •The range is -3.4e38 to +3.4e38. The standard float types with its storage sizes and value ranges: Type Storage size bytes) Floating point 4B Double 8B Long Double 10B Double data type(double): •It is used to store double precision floating point numbers. •The keyword double is used to declare variable of floating-point data type. •Double takes 8B of storage. •Double precision is related to accuracy of data. •The range is from 1.7e-308 to 1.7e308 •Double can hold real constant up to 16 digits after the decimal point. Character data type(char): - •It is used to store character type data. •The keyword char is used to declare variable of character type. •Char type take 1B of storage. Value range Format specifier %d %d %d -32,768 to 32,767 0 to 65,535 -32,768 to 32,767 2 bytes 2 bytes %d 0 to 65,535 4 bytes %d -2,147,483,648 2,147,483,647 0 to 4,294,967,295 to 4 bytes %ld Format specifier Value range (in 3.4e-38 to 3.4e38 1.7e-308 to 1.7e308 3.4e-4932 to3.4e4932 %f %lf %lf Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
•The range is from -128 to +127. •Each character stored in the memory is associated with a unique value termed as ASCII (American Standard Code for Information Interchange). •It is used to represent character and strings. Void data type(void): It is a special data type that has no value. It does not have size. It is used for returning the result of function that returns nothing. Variable •A variable is a name given to memory location where data can be stored. •Using variable name data can be stored in a memory location and can be accessed or manipulated very easily. Rules for variables •The First character should be an alphabet or an underscore _ •Then First character is followed by any number of letters or digits. •No extra symbols are allowed other than letters, digits and Underscore •Keywords cannot be used as an identifier Syntax: Variable name = value; Example: Sum – valid For1- valid for -invalid (it is a keyword) Declaration of variables: •Giving a name to memory location is called declaring a variable. •Reserving the required memory space to store the data is called defining a variable. •General Syntax: datatype variable; (or) datatype variable1, variable2,……...variable n; example: int a; float x, y; double sum; •From the examples we will come to know that “a” is a variable of type integer and allocates 2 bytes of memory. “x” and “y” are two variable of type float which will be allocated 4 bytes of memory for each variable. “sum” is a double type variable which will be allocated with 8 bytes of memory for each. Variable Initialization •Variables are not initialized when they are declared and defined, they contain garbage values (meaningless values) •The method of giving initial values for variables before they are processed is called variable initialization. General Syntax: Var_name = expr; Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Where, Var_name is the name of the variable, expr is the value of the expression. •The “expr” on the right-hand side is evaluated and stored in the variable name (Var_name) on left hand side. •The expression on the right-hand side may be a constant, variable or a larger formula built from simple expressions by arithmetic operators. Examples: •int a=10; // assigns the value 10 to the integer variable a •float x; x=20; // creates a variable y of float type and assigns value 20 to it. •int a=10, b, b=a; // creates two variables a and b. “a” is assigned with value 10, the value of “a” is assigned to variable “b”. Now the value of b will be 10. •price = cost*3; //assigns the product of cost and 3 to price. •Square = num*num; // assigns the product of num with num to square. Scope of variable: In c, variable can be either local or global. Global variables: Global variables defined outside of all the functions, generally on top of the program. Local variables: Local variables defined within the body of a function or a block. Ex: #include<stdio.h> #include<conio.h> int a; void main () { int b; a=10; b=20; printf (“%d”, a); printf (“%d”, b); getch (); } \* write a program in c to accept input from user and print it on the screen. */ #include<stdio.h> #include<conio.h> void main () { int roll; Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
float maths, sci, pps, che, phy, English; clrscr (); printf (“\n Enter roll no:\n”); scanf (“%d”, &roll); printf (“\n Enter marks for maths, sci, pps, che, phy, English:”); scanf (“%f %f %f%f%f%f”, &maths, &sci, &pps, &phy, &che, &English); printf (“\n……………………………………….\n”); printf (“\n Details for student with roll no.=%d”, roll); printf (“\n maths \t sci \t pps \t phy \t che \t English”); printf (“%f %f%f%f%f \n”, maths, sci, pps, phy, che, English); getch (); } Constants: Constants refers to fixed values that do not change during the execution of a program Ex: #include<stdio.h> void main () { int a=56; // here ‘a’ is a constant printf (“%d”, a); } The different types of constants are: 1. Integer constant 2. Real constant/Floating Pointing constant 3. Enumeration constant 4. Character constant 5. String constant 1. Integer constant An integer is whole number without any decimal point.no extra characters are allowed other than + or _. Three types of integers •Decimal integers: It is a constant with a combination of digits 0 to 9, it can be preceded or optional + or - Ex: 123, -345, 0, 5436, +79 •Octal integers: it is an integer constant with a combination of Digits from 0 to 7 but it has a prefix of 0 Ex: 027, 0657, 0777645 •Hexadecimal integers: Digits from 0 to 9 and characters from a to f, it has to start with 0X or 0x Ex: 0X2 0x56 0X5fd 0xbdae 2. Real constants/Floating point: ➢Floating point constants are base 10 numbers that are represented by fractional parts, such as 10.5. They can be positive or negative. ➢Two forms are: Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
i. Fractional form: ➢A floating-point number represented using fractional form has an integer part followed by dot and a fractional part. •Ex: 0.0083 •215.5 •-71. •+0.56 etc.. ii. Exponential form: ➢A floating-point number represented using Exponent form has 3 parts ➢mantissa e exponent ➢Mantissa is either real number expressed in decimal notation or integer. ➢Exponent must be integer with optional + or – ➢Ex 9.86 E 3 => 9.86*103 ➢Ex 9.86 E -3 => 9.86*10-3 3. Enumeration constant ➢A set of named integer constants defined using the keyword enum are called enumeration constants. Syntax: enum identifier {enum list}; ➢enum Boolean {NO, YES}; NO is assigned with 0 YES is assigned with value 1 ➢enum days {mon, Tue, wed}; mon is assigned with 0 tue is assigned with 1 wed is assigned with 2 4.Character constant ➢A symbol enclosed within pair of single quotes is called character constant. ➢Each character is associated with unique value called ASCII value. ➢Ex: ‘9’ ➢‘$’ •Backslash constants (Escape sequence character) ➢An escape sequence character begins with backslash and is followed by one character. ➢A backslash along with a character give rise to special print effects. ➢It always start with backslash, hence they are called as backslash constants. character name \a Bell \b Backspace Meaning Beep sound Cursor moves towards left by one position Cursor moves to next line Cursor moves towards right by 8 positions Cursor moves towards beginning of the same line Double quotes Single quotes \n \t Newline Horizontal tab \r Carriage return \” \’ Double quotes Single quotes Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
\? \\ \0 Question mark Backslash NULL Question mark Backslash 5.String constant •A sequence of characters enclosed within pair of double quotes is called string constant. •The string always ends with a NULL character. •Ex: “9” •“IILM” IILM\0 Example: Consider another example program to find the simple interest #include<stdio.h> void main () { float p,t,r; float si; printf (“enter the values of p, t, r\n”); scanf (“%f %f %f”, &p, &t, &r); si = (p*t*r)/100; printf ("Simple Interest=%f", si); } The above program illustrates the calculation of simple interest. •Firstly, we have declared the header files stdio.h for including standard input and output which will be printf and scanf statements. •Next we start with the main program indicated by void main() •Within the main program we declare the required variables for calculating the simple interest. So we declare p, t and r as float type and si as float type. •After which the values to p, t and r are read from keyboard using scanf. •Computed the simple interest by the formula (p*t*r)/100 and the result is assigned to si. •Display the result si. Storage classes: •A storage class defines the scope, visibility and life time of the variables, functions within a C program. •A storage class is an attribute that tells us where the variable would be stored, what will be initial value of the variable if no value is assigned to that variable. Type of storage classes: - There are four types of storage classes. 1.Automatic storage classes 2.External storage classes 3.Static storage classes 4.Register storage classes Automatic storage classes: •This is default storage class. •All variables declared are of ‘auto’ by default. •The keyword used for automatic storage class is ‘auto’. Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Features: Storage scope Life time Memory local Exists as long as control remains in the block Garbage Default value Example: #include<stdio.h> void main () { auto int a=20; printf (“%d”, a); } External storage classes: •Global variables are declared outside the function and are accessible to all function in the program. •The keyword used for external storage class is ‘extern. Features: Storage Memory Scope Global Lifetime •Exists as long as variable is running. •Return value within the function. Default value zero Example: #include<stdio.h> int a=7; void main () { extern int a; printf (“%d”, a); } Static storage classes: Static variables have property of presenting their value even after they are out of the scope. Hence life of variable persists between different function calls. Features: Storage Memory Scope Local & global Life time Exists as long as variable is running Keyword Static Default value Zero Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Example: #include<stdio.h> static int a=10; void main () { static int a=20; printf (“%d”, a); } Register storage classes: •The keyword used for register storage class is register. •Local variable and stored in register instead of ‘RAM’. •As variable is stored is register Maximum size of variable= Maximum size of register •This is generally used for faster access. Features: Storage Memory Scope local default value Garbage keyword register Example: #include<stdio.h> void main () { int a=10, b=20; register int sum; sum=a+b; printf (“%d”, sum); } Operators and Expressions: Operators and operands create expression these are predefined symbols. Each oprator has special and unique meaning. For example: Here, an operator is a symbol that tells that complier to perform specific mathematical or logical operations, relations, etc. When a programmer wants to perform some type of mathematical operations. The purpose of operators is mainly for mathematical and logical calculations. Types of operators in C: - In C, there are various types of operators available to perform various operations. 1)Arithmetic operator (Binary operator) 2)Assignment operators Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
3)Relational operators 4)Logical operators 5)unary operator 6)Increment and decrement operators 7)Bitwise operators 8) conditional operators (Ternary operator) 9) comma operator/Special operator Arithmetic operator (binary operator): An operator that deals with two operands is called binary operators. It deals with all the mathematical and operations. These are OperatorMeaning Expression + Addition c=a+b - Subtraction c=a-b * Multiplicationc=a*b / Division c=a/b % Remainder c=a%b The expression formed with arithmetic operator and variables and/or constants are arithmetical expressions. Example: a, a+b, a*f, e-q, sum+1 program using arithmetic operators // Working of arithmetic operators #include <stdio.h> int main () { int a = 9, b = 4, c; c = a+b; printf ("a+b = %d \n", c); c = a-b; printf ("a-b = %d \n", c); c = a*b; printf ("a*b = %d \n", c); c = a/b; printf ("a/b = %d \n", c); c = a%b; printf ("Remainder when a divided by b = %d \n”, c); return 0; } Output: a+b = 13 a-b = 5 a*b = 36 a/b = 2 Remainder when a divided by b=1 Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
The operators +, - and * computes addition, subtraction, and multiplication respectively as you might have expected. In normal calculation, 9/4 = 2.25. However, the output is 2 in the program. It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after the decimal point and shows answer 2 instead of 2.25. The modulo operator % computes the remainder. When a=9 is divided by b=4, the remainder is 1. The % operator can only be used with integers. Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming, // Either one of the operands is a floating-point number a/b = 2.5 a/d = 2.5 c/b = 2.5 // Both operands are integers c/d = 2 /*Write a program in C to calculate Total and Average of 4 subjects for a student. */ #include<stdio.h> #include<conio.h> void main () int science, maths, English, C programming, total; float average; clrscr (); printf (“Enter marks for science:”); scanf (“%d”, &science); printf (“Enter marks for maths:”); scanf (“%d”, &maths); printf (“Enter marks for English:”); scanf (“%d”, &English); printf (“Enter the marks C programming:”); scanf (“%d”, &C programming); total=science + maths + English + C programming; average=total/4; printf (“The total of all 4 subjects is %d and average is %2f\n”, total, average); getch (); } Output: Enter marks for science: 85 Enter marks for maths: 85 Enter marks for English: 95 Enter marks for C programming: 95 The total of all 4 subjects is 360 and average is: 90 /* Write a program in C to accept the Height of a person in Inches and convert it into Feet and Inches */ Formulea:1 foot=12 inches Number of feet=Inches/12 #include<stdio.h> #include<conio.h> Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
void main () { int inches, feet; clrscr (); printf (“Enter the height of person in inches \n”); scanf (“%d”, &inches); feet=inches/12; // calculate number of feet inches=inches%12 // Calculate inches i.e., Remainder printf (“The height of the person is %d feet and % inches.”, feet, inches); getch (); } Output: Enter the height of person in inches 65 The height of the person is 5 feet and 5 inches. /*Write a program in C to accept a number from user and calculate the square and cube of that number. */ # include<stdio.h> #include<conio.h> void main () { float number, square, cube; clrscr (); printf (“Enter the number:”); scanf (“%f”, &number); square=number * number; cube= number *number *number; printf (“square %.3f is %.3f and Cube %.3f is %.3f”, square, cube); getch (); } Output: Enter the number:12.528 Square of 12.528 is 156.951 and cube of 12.528 is 1966.279 Assignment Operators An assignment operator is used for assigning a value to a variable. The most common assignment operator is= Operator Example Same as = a = b a = b += a += b a = a+b -= a -= b a = a-b Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Operator Example Same as *= a *= b a = a*b /= a /= b a = a/b %= a %= b a = a%b // Working of assignment operators #include <stdio.h> int main () { int a = 5, c; c = a; // c is 5 printf ("c = %d\n", c); c += a; // c is 10 printf ("c = %d\n", c); c -= a; // c is 5 printf ("c = %d\n", c); c *= a; // c is 25 printf ("c = %d\n", c); c /= a; // c is 5 printf ("c = %d\n", c); c %= a; // c = 0 printf ("c = %d\n", c); return 0; } Output: c = 5 c = 10 c = 5 c = 25 c = 5 c = 0 Simple Assignment Operator (=): It is the operator used to assign the right-side operand or variable to the left side variable. Syntax int a = 5; or int b = a; ch = 'a'; program to use the simple assignment operator in C. #include <stdio.h> #include <conio.h> int main () Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
{ // initialize variables int n1, n2, c, x, y; n1 = 15; n2 = n1; c = n1 + n2; x = 25/ 5* 4 + 5; printf (" \n The value of n1: %d", n1); printf (" \n The value of n2: %d", n2); printf (" \n The value of c: %d", c); printf (" \n The value of x: %d", x); return 0; } Output: The value of n1: 15 The value of n2: 15 The value of c: 30 The value of x: 25 Plus and Assign Operator (+=): The operator is used to add the left side operand to the left operand and then assign results to the left operand. Syntax A += B; Or A = A + B; Program to use the Plus and assign operator in C. #include <stdio.h> #include <conio.h> int main () { // initialize variables int n1, n2, c; n1 = 5; n2 = 10; n2 += n1; printf (" \n The value of n1: %d", n1); printf (" \n The value of n2: %d", n2); return 0; } Output: The value of n1: 5 The value of n2: 15 Subtract and Assign Operator (-=): The operator is used to subtract the left operand with the right operand and then assigns the result to the left operand. Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Syntax A -= B; Or A = A - B; Write a program to use the Subtract and Assign (-=) operator in C. #include <stdio.h> #include <conio.h> int main () { // initialize variables int n1, n2, c; n1 = 5; n2 = 10; n2 -= n1; // Use Subtract and Equal operator (b = b - a) printf (" \n The value of n1: %d", n1); printf (" \n The value of n2: %d", n2); return 0; } Output The value of n1: 5 The value of n2: 5 Multiply and Assign Operator (*=) The operator is used to multiply the left operand with the right operand and then assign result to the left operand. Syntax A *= B; Or A = A * B; Write a program to use the multiply and assign operator (*=) in C. #include <stdio.h> #include <conio.h> int main () { // initialize variables int n1, n2, c; n1 = 5; n2 = 10; n2 *= n1; // Use Multiply and Equal operator (b = b * a) printf (" \n The value of n1: %d", n1); printf (" \n The value of n2: %d", n2); return 0; } Output The value of n1: 5 The value of n2: 50 Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Divide and Assign Operator (/=): An operator is used between the left and right operands, which divides the first number by the second number to return the result in the left operand. Syntax A /= B; Or A = A / B; Write a program to use the divide and assign operator (/=) in C. #include <stdio.h> #include <conio.h> int main () { // initialize variables int n1, n2, c; n1 = 5; n2 = 10; n2 /= n1; // Use divide and Equal operator (b = b / a) printf (" \n The value of n1: %d", n1); printf (" \n The value of n2: %d", n2); return 0; } Output The value of n1: 5 The value of n2: 2 Modulus and Assign Operator (%=): An operator used between the left operand and the right operand divides the first number (n1) by the second number (n2) and returns the remainder in the left operand. Syntax A %= B; Or A = A % B; Write a program to use the divide and assign operator (%=) in C. #include <stdio.h> #include <conio.h> int main () { // initialize variables int n1, n2, c; printf (" Enter the value of n1: "); scanf ("%d", &n1); printf (" \n Enter the value of n2: "); scanf ("%d", &n2); Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
n1 %= n2; // Use modulus and Equal operator (a = a % b) printf (" \n The modulus value of n1: %d", n1); return 0; } Output Enter the value of n1: 23 Enter the value of n2: 5 The modulus value of n2: 3 Relational operators: It is the operator which is used to compare two operands and shows the relation between two operands. It will always produce true (1) and false (0) as are output. Types of Relational operators: Relational operator < Less than x<y 5<3, so return 0 (false) <= Less than equals to > Greater than x>y 5>3, so it will return 1(as 5 is greater than 3, condition is true) >= Greater than equals to to 3, but showing greater, so if one condition is satisfied it will take it as true. = = Equals to x= =y 5! =3, so return 1(True), Here 5 is not equal to 3 != Not equals to x! =y 5= = 3, so return 0(False) Note: Double equal only used to compare two variable and if we want to give value to variable, we need to use =(single equal). Less than Operator (<) It is used to check whether the value of the left operand is less than the right operand, and if the statement is true, the operator is known as the less than operator. Syntax: A<B; Here the operand A is less than operand B. Meaning Example Description x<=y 5<=3, so return 0 (false) x>=y 5>3, so it will return 1(Ture). Here 5 is not equal Example: Write a program to use the less-than operator (<) to compare the operand value in C. #include <stdio.h> int main () { int num1, num2; printf (" Enter the value of num1: "); Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
scanf (" %d", &num1); printf (" \n Enter the value of num2: "); scanf (" %d", &num2); // use less than operator (<) if (num1 < num2) { printf (" \n The value of num1 is less than num2."); } else { printf (" \n The value of num2 is less than num1."); } return 0; } Output Enter the value of num1: 45 Enter the value of num2: 89 The value of num1 is less than num2. Less than Equal to Operator (<=) The operator checks whether the value of the left operand is less than or equal to the right operand, and if the statement is true, the operator is said to be the Less than Equal to Operator. Syntax: A <= B; Here, operand A is less than or equal to operand B. So, it is a Less than Equal to Operator. Example: Write a program to use the Less than Equal to operator (<=) to compare the operand value in C. #include <stdio.h> int main () { int num1, num2; printf (" Enter the value of num1: "); scanf (" %d", &num1); printf (" \n Enter the value of num2: "); scanf (" %d", &num2); // use less than equal to operator (<=) if (num1 < num2) { printf (" \n The value of num1 is less than num2."); } else if (num1 <= num2 ) { printf (" \n The value of num1 is equal to num2."); } Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
else { printf (" \n The value of num2 is less than num1."); } return 0; } Output Enter the value of num1: 45 Enter the value of num2: 45 The value of num1 is equal to num2. Greater than Operator (>) The operator checks the value of the left operand is greater than the right operand, and if the statement is true, the operator is said to be the Greater Than Operator. Syntax: A > B; Here, operand A is greater than operand B. Example: Write a program to use the greater than operator (>) to compare the operand value in C. #include <stdio.h> int main () { int num1, num2; printf (" Enter the value of num1: "); scanf (" %d", &num1); printf (" \n Enter the value of num2: "); scanf (" %d", &num2); // use greater than operator (>) if (num1 > num2) { printf (" \n The value of num1 is greater than num2."); } else { printf (" \n The value of num2 is greater than num1."); } return 0; } Output Enter the value of num1: 20 Enter the value of num2: 30 The value of num2 is greater than num1. Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Greater than Equal To Operator (>=) The operator checks whether the left operand's value is greater than or equal to the right operand. If the statement is true, the operator is said to be the Greater than Equal to Operator. Syntax: A >= B; Here, operand A is greater than equal to the right operand B. So, it is the Greater than Equal To operator. Example: Write a program to use the Greater than Equal To operator to compare the operand value in C. #include <stdio.h> int main () { int num1, num2; printf (" Enter the value of num1: "); scanf (" %d", &num1); printf (" \n Enter the value of num2: "); scanf (" %d", &num2); // use greater than equal to operator (>=) if (num1 > num2) { printf (" \n The value of num1 is greater than num2."); } else if (num1 >= num2 ) // greater than operator (>=) { printf (" \n The value of num1 is equal to num2."); } else { printf (" \n The value of num2 is greater than num1."); } return 0; } Output Enter the value of num1: 28 Enter the value of num2: 79 The value of num2 is greater than num1. Equal To Operator (==) It is used to compare both operands and returns 1 if both are equal or the same, and 0 represents the operands that are not equal. Syntax Operand1 == Operand2 Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Example: Write a program to use the double equal to operator (==) for comparing the operands value in C. #include <stdio.h> #include <math.h> int main () { int a = 5; int b = 10; // Use Equal to Operator printf (" a == b : %d", (a == b)); if (a == b) printf ("\n %d is equal to %d", a, b); else printf (" \n %d is not equal to %d", a, b); int x = 5; int y = 5; // Use Equal to Operator printf (" \n x == y : %d", (x == y)); if (a == b) printf (" \n %d is equal to %d", x, y); else printf ("\n %d is not equal to %d", x, y); return 0; } Output a == b: 0 5 is not equal to 10 x == y: 1 5 is not equal to 5 Not Equal to Operator (! =) The Not Equal To Operator is the opposite of the Equal To Operator and is represented as the (!=) operator. The Not Equal to Operator compares two operands and returns 1 if both operands are not the same; otherwise, it returns 0. Syntax: Operand1! = Operand2; Example: Write a simple program to use the Not equal to (! =) operator for comparing the values of variable in C. #include <stdio.h> #include <math.h> int main () { int a = 5; int b = 10; Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
// Use Not Equal To (!=) Operator printf (" a != b : %d", (a != b)); if (a != b) printf ("\n %d is equal to %d", a, b); else printf (" \n %d is not equal to %d", a, b); int x = 5; int y = 5; // Use Not Equal To (!=) Operator printf (" \n x != y : %d", (x != y)); if (a != b) printf (" \n %d is equal to %d", x, y); else printf ("\n %d is not equal to %d", x, y); return 0; } Output a! = b: 1 5 is equal to 10 x! = y: 0 5 is equal to 5 Logical operators: It is the operator which combine some conditions into a single new condition and always produces boolean results. Types of logical Operators: Three are three types, these are: 1.AND (&&) operator 2.OR (| |) operator 3.NOT(!) operator Here ! is a unary operator. Other operators are binary. The logical expression is formed by combining relational expressions and the result of the expression is either true (1) or false (0). AND (&&) operator: For the logical OP1 and OP2, the results of && are as follows: OP1 OP2 OP1&&OP2 0 0 0 1 1 0 1 1 Example: #include<stdio.h> void main (() { int a=5,b=7,c=9,d; 0 0 0 1 Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
d=a<b&&c>a; printf (“d=%d”, d); } Output: d =a<b&& c>a d=5<7&& 9>5 d=T && T d= 1 && 1 d=1 OR (| |) operator: For the logical expression OP1and OP2, the results of | | are as follows OP1 OP2 0 0 1 1 Program: #include<stdio.h> void main (() { int a=5, b=7, c=9,d; d=a<b | | c>a; printf (“d=%d”, d); } Output: d =a<b | | c>a d=5<7 | | 9>5 d=T | | T d= 1 | | 1 d=1 NOT (!) operator: For the logical expression OP1, the results of ! are as follows. OP1 0 1 Syntax: a !=b; Program: #include<stdio.h> void main (() { int a=5, b=7, c; d=a! =b; printf (“c=%d”, c); } OP1 | | OP2 0 1 1 1 0 1 0 1 ! OP1 1 0 Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
Output: c = a! =b; c = 5! =7 c = T c=1 Increment/Decrement operator: Increment operators are the operator of the C programming language used to increase the given variable's value by 1. The increment operator can increase the given value by 1 before assigning it to the variable. On the other hand, the increment operator can increase the given value by 1 after assigning the variable. The increment operator is represented as the double plus (++) symbol, which means the value is incremented by 1. Properties of the Increment operator There are some properties of the increment operator, as follows: The increment operator is used to increase the current value of the variable by 1. We can only use these operators with variables. It is the operator represented by the double plus (++) symbol. There are two types of the increment operators Pre-increment operator Post-increment operator Pre-increment operator The pre-increment operator is represented as the double plus (++a) symbol, appended before the variable's name. The pre-increment operator is used to increment the value of an operand by 1 before using it in the mathematical expression. In other words, the value of a variable is first incremented, and then the updated value is used in the expression. Syntax x = ++a; In the above syntax, the value of variable 'a' is first incremented by 1 before using in the expression. Example: Write a simple program to use the pre-increment operator in C programming language. #include <stdio.h> #include <conio.h> int main () { // declaration of the variables int a = 7; int b = 2 // print the value of the increment operator printf (" Use the pre-increment operator " ); printf (" The value of a is %d ", a); printf (" The value of b is %d ", b); // use pre-increment operator Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering
b = ++a; printf (" After using the pre-increment operator "); printf (" The value of a is %d ", a); printf (" The value of b is %d ", b); return 0; } Output Use the pre-increment operator The value of a is 7 The value of b is 2 After using the pre-increment operator The value of a is 8 The value of b is 10 Example: Let's create another program to use the pre-increment operator in mathematical expression. #include <stdio.h> #include <conio.h> int main () { // declare integer variables int a, b, c, d, x; // initialization of the variables a = 5; b = 7; c = 12; d = 15; // use pre-increment operator in the mathematical expression x = ++a + ++b + ++c + ++d; printf ( " The value of x is: %d ", x); // print the updated value of a, b, c, and d printf (" \n The updated value of a = %d, b = %d, c = %d and d = %d ", a, b, c, d); return 0; } Output The value of x is: 43 The updated value of a = 6, b = 8, c = 13 and d = 16 Post-increment Operator Post-increment is an increment operator, represented as the double plus (a++) symbol followed by an operator 'a'. It increments the value of the operand by 1 after using it in the mathematical expression. In other words, the variable's original value is used in the expression first, and then the post-increment operator updates the operand value by 1. Syntax x = a++; Mr Sreenu Banoth, Assistant Professor, Department of Computer Science and Engineering