PDS Unit 1 (Part 1) Notes PDF
Document Details
Uploaded by CleanFermat
Tags
Summary
This document provides an introduction to computer hardware, including input and output devices, and different types of memory like cache, primary (RAM and ROM), and secondary memory. It also explains the basic concepts of computer programming.
Full Transcript
PDS_UNIT-I_Part-1 UNIT-I_SYLLABUS: Introduction Computer Hardware, Bits and Bytes, History of Programming Languages, Character Set, Variables and Identifiers, Built-in Data Types. Operators and Expressions, Constants and Literals, Simple Assignment Statement, Basic Inp...
PDS_UNIT-I_Part-1 UNIT-I_SYLLABUS: Introduction Computer Hardware, Bits and Bytes, History of Programming Languages, Character Set, Variables and Identifiers, Built-in Data Types. Operators and Expressions, Constants and Literals, Simple Assignment Statement, Basic Input/output Statement, Simple 'C' Program, Conditional Statements and Loops. 1.1 Introduction Computer Hardware: Hardware represents the physical and tangible components of a computer, i.e. the components that can be seen and touched. Examples of Hardware are the following − Input devices − keyboard, mouse, etc. Output devices − printer, monitor, etc. Secondary storage devices − Hard disk, CD, DVD, etc. Internal components − CPU, motherboard, RAM, etc. Input devices: Following are some of the important input devices which are used in a computer − Keyboard Mouse Joy Stick Light pen Track Ball Scanner Graphic Tablet Microphone Magnetic Ink Card Reader(MICR) Optical Character Reader(OCR) Bar Code Reader Optical Mark Reader(OMR) Output devices: Following are some of the important output devices used in a computer. Monitors Printer Headphones. Computer Speakers. Projector. 1 Memory: A memory is just like a human brain. It is used to store data and instructions. Computer memory is the storage space in the computer, where data is to be processed and instructions required for processing are stored. The memory is divided into large number of small parts called cells. Each location or cell has a unique address, which varies from zero to memory size minus one. For example, if the computer has 64k words, then this memory unit has 64 * 1024 = 65536 memory locations. The address of these locations varies from 0 to 65535. Memory is primarily of three types − Cache Memory Primary Memory/Main Memory Secondary Memory Cache Memory Cache memory is a very high speed semiconductor memory which can speed up the CPU. It acts as a buffer between the CPU and the main memory. It is used to hold those parts of data and program which are most frequently used by the CPU. The parts of data and programs are transferred from the disk to cache memory by the operating system, from where the CPU can access them. Advantages The advantages of cache memory are as follows − Cache memory is faster than main memory. It consumes less access time as compared to main memory. It stores the program that can be executed within a short period of time. It stores data for temporary use. Disadvantages The disadvantages of cache memory are as follows − Cache memory has limited capacity. It is very expensive. 2 Primary Memory (Main Memory) Primary memory holds only those data and instructions on which the computer is currently working. It has a limited capacity and data is lost when power is switched off. It is generally made up of semiconductor device. These memories are not as fast as registers. The data and instruction required to be processed resides in the main memory. It is divided into two subcategories RAM and ROM. Characteristics of Main Memory These are semiconductor memories. It is known as the main memory. Usually volatile memory. Data is lost in case power is switched off. It is the working memory of the computer. Faster than secondary memories. A computer cannot run without the primary memory. 3 Secondary Memory This type of memory is also known as external memory or non-volatile. It is slower than the main memory. These are used for storing data/information permanently. CPU directly does not access these memories, instead they are accessed via input-output routines. The contents of secondary memories are first transferred to the main memory, and then the CPU can access it. For example, disk, CD-ROM, DVD, etc. Characteristics of Secondary Memory These are magnetic and optical memories. It is known as the backup memory. It is a non-volatile memory. Data is permanently stored even if power is switched off. It is used for storage of data in a computer. Computer may run without the secondary memory. Slower than primary memories. Secondary Storage: Secondary or external storage is not directly accessible by the CPU. The data from secondary storage needs to be brought into the primary storage before the CPU can use it. Secondary storage contains a large amount of data permanently. The different types of secondary storage devices are Hard Disk Hard disks are the most famously used secondary storage devices. They are round, flat pieces of metal covered with magnetic oxide. They are available in many sizes ranging from 1 to 14 inch diameter. 4 Floppy Disk They are flexible plastic discs which can bend, coated with magnetic oxide and are covered with a plastic cover to provide protection. Floppy disks are also known as floppies and diskettes. Memory Card This has similar functionality to a flash drive but is in a card shape. It can easily plug into a port and removed after its work is done. A memory card is available in various sizes such as 8GB, 16GB, and 64GB etc... Flash Drive This is also known as a pen drive. It helps in easy transportation of data from one system to another. A pen drive is quite compact and comes with various features and designs. CD-ROM This is short for compact disk - read only memory. A CD is a shiny metal disk of silver color. It is already prerecorded and the data on it cannot be altered. It usually has a storage capacity of 700 MB. 5 Tertiary Storage This provides a third level of storage. Most of the rarely used data is archived in tertiary storage as it is even slower than primary storage. Tertiary storage stores a large amount of data that is handled and retrieved by machines, not humans. The different tertiary storage devices are − Tape Libraries These may contain one or more tape drives, a barcode reader for the tapes and a robot to load the tapes. The capacity of these tape libraries is more than a thousand times that of hard drives and so they are useful for storing large amounts of data. Optical Jukeboxes These are storage devices that can handle optical disks and provide tertiary storage ranging from terabytes to petabytes. They can also be called optical disk libraries, robotic drives etc. Introduction to Software Software: Software is a set of programs, which is designed to perform a well-defined function. A program is a sequence of instructions written to solve a particular problem. (Or) Software is a program that enables a computer to perform a specific task, as opposed to the physical components of the system (hardware). (Or) Software, which is abbreviated as SW or S/W, is a set of programs that enables the hardware to perform a specific task. All the programs that run the computer are software. The software can be of three types: system software, application software, and programming software. System Software The system software is a collection of programs designed to operate, control, and extend the processing capabilities of the computer itself. System software is generally prepared by the 6 computer manufacturers. System software serves as the interface between the hardware and the end users. The system software is the main software that runs the computer. When you turn on the computer, it activates the hardware and controls and coordinates their functioning. The application programs are also controlled by system software. Here is a list of some of the most prominent features of a system software − Fast in speed Difficult to design Difficult to understand Difficult to manipulate Some examples of system software are Operating System, Compilers, Interpreter, Assemblers, etc… Operating System: An Operating System (OS) is an interface between a computer user and computer hardware. An operating system is a program that acts as an interface between the user and the computer hardware and controls the execution of all kinds of programs. Following are some of important functions of an operating System. Memory Management Processor Management Device Management File Management Control over system performance Coordination between other software and users Types of Operating System (OS) Following are the popular types of Operating System: Batch Operating System Multitasking/Time Sharing OS Multiprocessing OS Real Time OS Distributed OS Network OS Mobile OS The examples of operating system are Windows Windows 10 Windows 8 7 Windows 7 Windows XP Unix systems Fedora, Ubuntu and zorin Macsystems Application software: Application software is a set of programs designed to perform a specific task. It does not control the working of a computer as it is designed for end-users. A computer can run without application software. Application software can be easily installed or uninstalled as required. It can be a single program or a collection of small programs. Features of application software are as follows − Close to the user Easy to design More interactive Slow in speed Generally written in high-level language Easy to understand Examples of Application software are the following − Student Record Software Income Tax Software Railways Reservation Software Microsoft Office Suite Software Microsoft Word Microsoft Excel Microsoft PowerPoint Programming Software: 8 It is a set or collection of tools that help developers in writing other software or programs. It assists them in creating, debugging, and maintaining software or programs or applications. Some examples of programming software include: Eclipse: It is a java language editor. Coda: It is a programming language editor for Mac. Notepad++: It is an open-source editor for windows. Sublime text: It is a cross-platform code editor for Linux, Mac, and Windows. Utility Software: Application software that assist OS in carrying out certain specialized tasks are called utility software. Let us look some of the most popular utility software. These software analyze and maintain a computer. These software are focused on how OS works on that basis it perform task to enable smooth functioning of computer. Some of popular utility software are described below Antivirus- boot virus, Trojan, worm, spyware, etc. File management tools- Google desktop, Directory Opus, Double Commander Compression tools- WinRAR, PeaZip, The Unarchiver, etc. Disk Cleanup Backup 1.2 Bits and Bytes: Bit: a "bit" is atomic: the smallest unit of storage A bit stores just a 0 or 1 "In the computer it's all 0's and 1's"... bits Anything with two separate states can store 1 bit In a chip: electric charge = 0/1 In a hard drive: spots of North/South magnetism = 0/1 A bit is too small to be much use Group 8 bits together to make 1 byte Byte: One byte = collection of 8 bits e.g. 0 1 0 1 1 0 1 0 One byte can store one character, e.g. 'A' or 'x' or '$' 9 1.3 History of Programming Languages: A language is the main medium of communicating between the Computer systems and the most common are the programming languages. Computer language includes various languages that are used to communicate with a Computer machine. Some of the languages like programming language which is a set of codes or instructions used for communicating the machine. Machine code is also considered as a computer language that can be used for programming. And also HTML which is a computer language or a markup language but not a programming language. Similarly there are different types of languages developed for different types of work to be performed by communicating with the machine. But all the languages that are now available are categorized into two basic types of languages including Low-level language and High level language. Computer languages are the languages through which the user can communicate with the computer by writing program instructions. Every computer programming language contains a set of predefined words and a set of rules (syntax) that are used to create instructions of a program. Computer Languages Classification: Over the years, computer languages have been evolved from Low-Level to High-Level Languages. In the earliest days of computers, only Binary Language was used to write programs. The computer languages are classified as follows... 10 Low-Level Language (Machine Language) Low-Level language is the only language which can be understood by the computer. Binary Language is an example of a low-level language. Low-level language is also known as Machine Language. The binary language contains only two symbols 1 & 0. All the instructions of binary language are written in the form of binary numbers 1's & 0's. A computer can directly understand the binary language. Machine language is also known as the Machine Code. As the CPU directly understands the binary language instructions, it does not require any translator. CPU directly starts executing the binary language instructions and takes very less time to execute the instructions as it does not require any translation. Low-level language is considered as the First Generation Language (1GL). Advantages A computer can easily understand the low-level language. Low-level language instructions are executed directly without any translation. Low-level language instructions require very less time for their execution. Disadvantages Low-level language instructions are very difficult to use and understand. Low-level language instructions are machine-dependent, that means a program written for a particular machine does not execute on another machine. In low-level language, there is more chance for errors and it is very difficult to find errors, debug and modify. Middle-Level Language (Assembly Language) Middle-level language is a computer language in which the instructions are created using symbols such as letters, digits and special characters. Assembly language is an example of middle-level language. In assembly language, we use predefined words called mnemonics. Binary code instructions in low-level language are replaced with mnemonics and operands in middle-level language. But the computer cannot understand mnemonics, so we use a translator called Assembler to translate mnemonics into binary language. Assembler is a translator 11 which takes assembly code as input and produces machine code as output. That means, the computer cannot understand middle-level language, so it needs to be translated into a low-level language to make it understandable by the computer. Assembler is used to translate middle- level language into low-level language. Advantages Writing instructions in a middle-level language is easier than writing instructions in a low-level language. Middle-level language is more readable compared to low-level language. Easy to understand, find errors and modify. Disadvantages Middle-level language is specific to a particular machine architecture that means it is machine-dependent. Middle-level language needs to be translated into low-level language. Middle-level language executes slower compared to low-level language. High-Level Language A high-level language is a computer language which can be understood by the users. The high- level language is very similar to human languages and has a set of grammar rules that are used to make instructions more easily. Every high-level language has a set of predefined words known as Keywords and a set of rules known as Syntax to create instructions. The high-level language is easier to understand for the users but the computer cannot understand it. High-level language needs to be converted into the low-level language to make it understandable by the computer. We use Compiler or interpreter to convert high-level language to low-level language. Languages like COBOL, FORTRAN, BASIC, C, C++, JAVA, etc., are examples of high-level languages. All these programming languages use human-understandable language like English to write program instructions. These instructions are converted to low-level language by the compiler so that it can be understood by the computer. Advantages Writing instructions in a high-level language is easier. A high-level language is more readable and understandable. The programs created using high-level language runs on different machines with little change or no change. Easy to understand, create programs, find errors and modify. Disadvantages High-level language needs to be translated into low-level language. High-level language executes slower compared to middle and low-level languages. 12 Understanding Computer Languages The following figure provides a few key points related to computer languages. From the above figure, we can observe the following key points... The programming languages like C, C++, Java, etc., are written in High-level language which is more comfortable for the developers. A high-level language is closer to the users. Low-level language is closer to the computer. Computer hardware can understand only the low-level language (Machine Language). The program written in the high-level language needs to be converted to low-level language to make communication between the user and the computer. Middle-level language is not closer to both user and computer. We can consider it as a combination of both high-level language and low-level language. Introduction to C Language: C language was developed Dennis Ritchie in 1972 at AT&T Bell Laboratories (USA). C language was derived from B language which was developed by Ken Thomson in 1970. This B language was adopted from a language BCPL (Basic Combined Programming Language), which was developed by Martin Richards at Cambridge University. The language B named as so by borrowing the first initial from BCPL language. Dennis Ritchie modified and improved B language and named it as C language, using second initial from BCPL. C language is not high level language and not a low level language. It is a middle level language with high level and low level features. C is a general purpose, structured programming language. C language is one of the most popular computer languages today because it is a structured, high level, machine independent language. It allows software developers to develop software without worrying about the hardware platforms where they will be implemented. The following flowchart shows the history of ANSI C. 13 Here are most common reasons why C is still so popular: C is one of the most popular programming languages of all time to create system software as well as application software. C is a standardized programming language with international standards. C is the base for almost all popular programming languages. C is one of the foundations for modern computer science and information technology. Importance of C It is a robust language whose rich set of built in functions and operators can be used to write any complex program. The C compiler combines the capabilities of an assembly language with the features of a higher level language and therefore it is well suited for both system software and business packages. Features C is a general purpose language C can be used for system programming as well as application programming. C is middle level language C is portable language An application program written on C language will work on many different computers with little or no modifications. C Block structured language. In C , a block is marked by two curly braces({ }) C programs are compact, fast and efficient C is case sensitive language C is function oriented language 14 C language includes advanced data types like pointers, structures, unions, enumerated types etc. C language supports recursion and dynamic storage allocation C can manipulate with bits, bytes and addresses Parameter passing can be done using call-by-value and call-by-reference Why Use c? Powerful and flexible C is a powerful and flexible language. The language itself places no constraints on you. C is used for projects as diverse as operating systems, Word Processors, graphics, spreadsheets, and even compilers for other languages. Popular C is a popular language preferred by professional programmers. As a result, a wide variety of C compilers and helpful accessories are available for use by programmers. Portable C is a portable language. Portable means that a C program written for one computer system (say an IBM PC) can be compiled and run on another system (say a DEC VAX system) with little or no modification. Portability is enhanced by the ANSI standard for C, the set of rules for C compilers. Minimum keywords C is a language of few words, containing only a handful of terms, called keywords, which serve as the base on which the language's functionality is built. There is a misconception with many that a language with more key words (sometimes called reserved words) would be more powerful. This isn't true. Modular C is a modular. C code can (and should) be written in routines called functions. These functions can be reused in other applications or programs. By passing pieces of information to the functions, you can create useful, reusable code 1.4 The C Character Set: We know that English language has 26 alphabets. We will use combinations of these alphabets to form words, sentences, paragraphs etc. In a similar way we will use the available characters while writing programs in any programming language. 15 There are two set of characters in “C” language Source characters Execution characters Source Characters These are characters that are used to create source text file. Source characters include Alphabets A to Z, a to z Digits 0,1,2,3,4,5,6,7,8,9 Special Characters ,. ; : ? ‘ “ ! | / \ ~ _ $ % # & ^ * + - ( ) { } [ ] and blank Execution Characters The meaning of these characters is interpreted at the time of execution. These are also known as “Escape sequences because the backslash (\) is considered as an ‘escape’ character. It causes an escape from normal interpretation of a string. so that the next character is recognized as one having special meaning. Escape sequences Comments: Comments are used by programmers to add remarks and explanations within the program. Compiler ignores all the comments and they do not have any effect on the executable program. Comments are of two types; single line comments and multi-line comments. Single line comments start with two slashes ( // ) and all the text until the end of the line is considered a comment. // this is a single line comment Multi-line comments start with characters. Any text between those characters is considered a multi-line comment. 16 1.5 Various kinds of C Data (Tokens): The data in C language can be divided into 1. Constants/literals 2. Variables/Identifiers 3. Reserved Words/Key words 4. Delimiters 1.5.1 Constants: Constant can be defined as a value that can be stored in memory and cannot be changed during execution of the program. Constants are used to define fixed values like pi. C has four basic types of constants. They are: Integer Constant An integer constant must have at least one digit and should not have a decimal point. It can be either positive or negative. Examples for integer constants: 1 9 234 999 Floating point Constant A floating point constant is decimal number that contains either a decimal point or an exponent. In the other words, they can be written in 2 forms: fractional and exponential. When expressed in fractional form, note the following points. 1. There should be at least one digit, and could be either positive or negative value. A decimal point is must. 2. There should be no commas or blanks. Examples for fractional form 12.33 -19.56 +123.89 -0.7 When expressed in exponential form, a floating point constant will have 2 parts. One is before e and after it. The part which appears before e is known as mantissa and the one which follows is known as exponent. When expressed in this format, note the following points. 1. Mantissa and exponential should be separated by letter E. 17 2. Mantissa can have a positive and negative sign. 3. Default is positive. Examples for fractional form 2E-10 0.5e2 1.2E+3 -5.6E-2 Character Constant These are single character enclosed in single quotes. A character can be single alphabet, single digit, single special symbol enclosed with in single quotes. Not more than a single character is allowed. Example ‘a’ ‘Z’ ‘5’ ‘$’ String Constant A String constant is sequence of characters enclosed in double quotes. So “a” is not same as ‘a’. The characters comprising the string constant are stored in successive memory locations. Example: “hello” “programming” “cse” 1.5.2 Variables/Identifiers Variable is named memory location that can be used to store values. These variables can take different values but one value at a time. These values can be changed during execution of a program. Identifiers are basically names given to program elements such as variables, arrays and functions. Rules for naming a Variable/Identifier 1. The only characters allowed are alphabets, digits and underscore (_). 2. They must start with an alphabet or an underscore (_). 3. It can not include any special characters or punctuation marks (like #, $, ^, ?,., etc.) except underscore (_). 4. They can be of any reasonable length. They should not contain more than 31 characters. But it is preferable to use 8 characters. 5. There cannot be two successive underscores. 6. Reserved words/keywords cannot be identifiers. 7. Lower case or uppercase letters are significant. 1.5.3 Key words: These are also called as reserved words. All Keywords have fixed meanings and these meanings cannot be changed. 18 There are 32 keywords in C programming. Keywords serve as basic building blocks for a program statement. All keywords must be written in lowercase only. 1.5.4 Delimiters Delimiters are used for syntactic meaning in C. These are given below: 1.5.5 Variables Declaration & Initialization in C : A variable is named memory location that stores a value. When using a variable, we actually refer to address of the memory where the data is stored. C language supports two basic kinds of variables: 1. Numeric variables 2. Character variables Numeric variables Numeric variables can be used to store either integer values or floating point values. While an integer value is a whole number without a fraction part or decimal point. A floating point value can have a decimal point. Numeric values may be associated with modifiers like short, long, signed, and unsigned. Character variables 19 Character variables can include any letter from the alphabet or from ASCII chart and numbers 0-9 that are given within single quotes. Variable declaration To declare a variable, specify the data type of the variable followed by its name. The data type indicates the kind of data that the variable will store. Variable names should always be meaningful and must reflect the purpose of their usage in the program. In C, variable declaration always ends with a semicolon, For example: char grade; int emp_no; float salary; double bal_amount unsigned short int acc_no; C allows multiple variable of same type to be declared in one statement, so the following statement is absolutely legal in C float temp_in_deg, temp_in_farh; Initializing variables Assigning value to variable is called variable initialization. For example: char grade= ‘A’; int emp_no=1007; float salary=8750.25; double bal_amount=100000000 Note: When variables are declared but not initialized they usually contain garbage values. Basically variable declaration can be done in three different places in a C program. 1. Inside main() function are called local variables. 2. Outside main() function are called global variables. 3. In the function definition header are called formal parameters. Declaring Constants To declare a constant, precede the normal variable declaration with const keyword and assign it a value. For example, const float pi=3.1415; This const keyword specifies that the value of cannot change 20 1.6 Data Types of C: C supports different types of data. The type or Data type refers a type of data that is going to be stored in variable. Data types can be broadly classified as shown in figure. C provides a standard minimal set of data types. Sometimes these are also called as ‘Primitive types’. They are: ‘char’ is used to store any single character. ‘int’ is used to store integer value. ‘float’ is used to store floating point value ‘double’ is used for storing long range of floating point number. Type Qualifiers In addition, C has four type qualifiers, also known as type modifiers which precede the basic data type. A type modifier alters the meaning of basic data type to yield a new data type. They are as follows: Short long ( to increase the size of an int or double type) signed unsigned The qualifiers can be classified into two types: 1. Size qualifier (e.g., short and long) 2. Sign qualifier (e.g., signed and unsigned) Size qualifiers: Alters the size of basic data type. The keywords long and short are two size qualifiers. 21 For example: long int i; The size of int is 2 bytes but, when long keyword is used, that variable will be either 4 bytes or 8 bytes. Sign qualifiers: Whether a variable can hold only positive value or both values is specified by sign qualifiers. Keywords signed and unsigned are used for sign qualifiers. a. Each of these type modifiers can be applied to base type int. b. The modifiers signed and unsigned can also be applied to base type char. c. In addition long can also be applied to double. d. When base type is omitted from a declaration, int is assumed. Example Suppose a variable can be assigned only an integer value. Such variable can be declared as int a; This declaration reserves two bytes of memory for storing the number. Such a variable can store a number in range -32768 to 32767. In order to increase the range you can add a qualifier to the declaration. long int a; The following table shows the basic data types with qualifiers and their ranges. Void type: This type holds no value and thus valueless. It is primarily used in three cases: 22 1. To specify the return type of a function (when the function returns no value) 2. To specify the parameters of the function (when the function accepts no arguments from the caller. 3. To create generic pointers. 1.7 Structure of a C Program: C program is a collection of one or more functions. Every function is collection of statements, performs a specific task. The structure of a basic C program is: Documentation section The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later. There are two types of comment lines. 1. Block comment lines and 2. Single line comment lines. // Link section The link section provides instructions to the compiler to link functions from the system library. #include directive The #include directive instructs the compiler to include the contents of the file "stdio.h" (standard input output header file) enclosed within angular brackets. Definition section The definition section defines all symbolic constants. #define PI 3.1413 23 Global declaration section There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined functions. Main () function section Every C program must have one main function section. This section contains two parts: 1. Declaration part 2. Executable part Declaration part: It declares all the variables used in the executable part. Executable part: There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration and executable part end with a semicolon. Subprogram section The subprogram section contains all the user-defined functions that are called in the main () function. User-defined functions are generally placed immediately after the main () function, although they may appear in any order. For Example a ‘C’ program that prints welcome message: #include int main( ) { printf(“Welcome to C Programming\n”); return 0; } Output: Welcome to C Programming. 1.8 Formatted input and output functions: When input and output is required in a specified format the standard library functions scanf() and printf() are used 24 Output function printf( ) printf() is a function that is used to print any data on the video monitor screen. It has the following form: printf(“control string”,list_of_variables); The function accepts two arguments - control string, which controls what gets printed, and list of variables. The control string is all-important because it specifies 1. The type of each variable in the list and how user wants it printed. It is also called as format specifier. 2. Characters that are simply printed as they are. Control string that begins with a % sign. Escape sequences that begin with a \ sign List of variables must be separate by comma. The number of format specifiers must exactly match the number of variables. Input function scanf() C provides scanf( ) function for entering input data. This function accepts all types of data as input (numeric, character, string). The general form of scanf() is given below Syntax 25 scanf(“control string”,variable1,variable2,…,variable n); This function should have at least two parameters. First parameter is control string which is conversion specification character. It should be within double quotes. This may be one or more, it depends on the number of variables. The other parameter is variable names. Each variable must preceded by ampersand (&) sign. This gives starting address of the variable name in memory. scanf ( ) uses all the format specifiers used in printf( ) function. Note: comments are not allowed in scanf() For example, consider the following simple programs. #include int main() { int x; printf(“Enter number:”); scanf(“%d”, &x); printf(“The value of x is %d\n”, x); return 0; } Output Enter a number: 45 The value of x is 45 For accessing multiple values from keyboard using scanf() function #include int main() { int x,y; printf(“Enter two numbers:”); scanf(“%d%d”, &x,&y); printf(“The value of x is %d\n”, x); printf(“The value of y is %d\n”, y); return 0; } 26 Output Enter two numbers: 29 47 The value of x is 29 the value of x is 47 1.9 Operators and Expressions An operator is defined as a symbol that operates on operands and does Something. The something may be mathematical, relational or logical operation. C language Supports a lot of operators to be used in expressions. These operators can be categorized into The following groups: 1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Increment/Decrement operators 5. Bit wise operators 6. Assignment operators 7. Conditional operators 8. Special operators 1.9.1 Arithmetic operators These are used to perform mathematical operations. These are binary operators since they operate on two operands at a time. They can be applied to any integers, floating-point number or characters. C supports 5 arithmetic operators. They are +, -, *, /, %. The modulo (%) operator can only be applied to integer operands and cannot be used on float or double values. Consider three variables declared as, int a=9,b=3,result; We will use these variables to explain arithmetic operators. The table shows the arithmetic Operators, their syntax, and usage in C language. 27 a and b are called operands. An Example ‘C’ program that illustrates the usage of arithmetic operators. #include int main() { int a=9,b=3; printf("%d+%d=%d\n",a,b,a+b); printf("%d-%d=%d\n",a,b,a-b); printf("%d*%d=%d\n",a,b,a*b); printf("%d/%d=%d\n",a,b,a/b); printf("%d%%%d=%d\n",a,b,a%b); return 0; } Output 9+3=12 9-3=6 9*3=27 9/3=3 9%3=0 1.9.2 Relational operators A relational operator, also known as a comparison operator, is an operator that Compares two operands. The operands can be variables, constants or expressions. Relational Operators always return either true or false depending on whether the conditional relationship 28 Between the two operands holds or not. C has six relational operators. The following table shows these operators along with their Meanings An example program that illustrates the use of arithmetic operators. #include int main() { int a=9,b=3; printf("%d>%d=%d\n",a,b,a>b); printf("%d>=%d=%d\n",a,b,a>=b); printf("%d>= and c=%d\n",c); c &= 2; printf("Operator is &= and c = %d\n", c ); c ^= 2; printf("Operator is ^= and c = %d\n", c ); c |= 2; printf("Operator is |= and c = %d\n", c ); return 0; } Output Operator is = and c = 21 Operator is += and c=42 Operator is −= and c=21 Operator is *= and c=441 Operator is /= and c=21 Operator is %= and c=0 Operator is = and c=0 Operator is &= and c = 0 Operator is ^= and c = 2 39 Operator is |= and c = 2 Advantages: 1. Short hand expressions are easier to write. 2. The statement involving short hand operators are easier to read as they are more concise. 3. The statement involving short hand operators are more efficient and easy to understand. 1.9.7 Conditional operator (? : ) It is also called ternary operator because it takes three operands. It has the general form: variable = expression1 ? expression2 : expression3; If the expression1 is evaluated to true then it evaluates expression2 and its value is assigned to variable, otherwise it evaluates expression3 and its value is assigned to variable. It is an alternative to simple if..else statement For example #include int main() { int a=5,b=6,big; big = a>b ? a : b; printf("%d is big\n", big); return 0; } Output 6 is big 1.9.8 Special operators: Comma operator (,) 40 This operator allows the evaluation of multiple expressions, separated by the comma, from left to right in the order and the evaluated value of the rightmost expression is accepted as the final result. The general form of an expression using a comma operator is expressionM= ( expression1, expression2, expressionN) For example #include int main() { int k=5,i,j; i=k++, j=(k++,k++,++k); printf(“i=%d\t j=%d”, i,j); return 0; } Output: i=5 j=9 #include int main() { int k=5,i,j; i=k++, j=k++,k++,++k; printf(“i=%d\t j=%d”, i,j); return 0; } Output: i=5 j=6 Sizeof() Operator The operator sizeof is a unary operator used calculates the size of data types and 41 variables. The operator returns the size of the variable, data type in bytes. i.e. the sizeof operator is used to determine the amount of memory space that the variable/data type will take. The outcome is totally machine-dependent. For example: #include int main() { printf("char occupies %d bytes\n",sizeof(char)); printf("int occupies %d bytes\n",sizeof(int)); printf("float occupies %d bytes\n",sizeof(float)); printf("double occupies %d bytes\n",sizeof(double)); printf("long double occupies %d bytes\n",sizeof(long double)); return 0; } Output char occupies 1 bytes int occupies 4 bytes float occupies 4 bytes double occupies 8 bytes long double occupies 16 bytes 2. Expressions: In C programming, an expression is any legal combination of operators and operands that evaluated to produce a value.Every expression consists of at least one operand and can have one or more operators. Operands are either variables or values, whereas operators are symbols that represent particular actions. In the expression x + 5; x and 5 are operands, and + is an operator. In C programming, there are mainly two types of expressions are available. They are as follows: 1. Simple expression 2. Complex expression 42 Simple expression: In which contains one operator and two operands or constants. Example: x+y; 3+5; a*b; x-y etc. Complex expression: In which contains two or more operators and operands or constants. Example: x+y-z; a+b-c*d; 2+5-3*4; x=6-4+5*2 etc. Operators provided mainly two types of properties. They are as follows: 1. Precedence and 2. Associativity 1. Operator Precedence It defines the order in which operators in an expression are evaluated depends on their relative precedence. Example: Let us see x=2+2*2 1 st pass- 2+2*2 2 nd pass- 2+4 3 rd pass- 6 that is x=6. 2. Associativity It defines the order in which operators with the same order of precedence are evaluated. Let us see x=2/2*2 1 st pass-- 2/2*2 2 nd pass-- 1*2 3 rd pass-- 2that is x=2 The below table lists C operators in order of precedence (highest to lowest) and their associativity indicates in what order operators of equal precedence in an expression are applied 43 An example ‘C’ program that illustrates the use of expressions #include int main() { int a, b=4,c=8,d=2,e=4,f=2; a=b+c/d+e*f; // expression1 printf(" The value of a is%d\n", a); a=(b+c)/d+e*f; // expression2 printf("The value of a is%d\n", a); a=b+c/((d+e)*f); //expression 3 printf("The value of a is%d\n", a); return 0; } Output: The value of a is 16 The value of a is 14 44 The value of a is 4 45