<<

LECTURE NOTES

ON

COMPUTER PROGRAMMING

(USING C)

Revision 1.0

1 December, 2014

PROF B. PADMAJA Associate Professor Department of Computer Science and Engineering

INSTITUTE OF AERONAUTICAL ENGINEERING

DUNDIGAL – 500 043, HYDERABAD

2014 - 2015

1. INTRODUCTION TO COMPUTERS 1.1 INTRODUCTION TO COMPUTERS A Computer is an electronic device that can perform activities that involve Mathematical, Logical and graphical manipulations. Generally, the term is used to describe a collection of devices that function together as a system. It performs the following three operations in sequence. 1. It receives data & instructions from the input device. 2. Processes the data as per instructions. 3. Provides the result (output) in a desired form. 1.1.1 Basic Elements of a Computer System: Basic elements of a computer system are Mouse, Keyboard, monitor, memory, CPU, motherboard, Hard Disk, Speakers, Modem, power supply and processor. Mouse: Mouse is used for operating the system. Nowadays, optical mouse is popular as compared to simple mouse. Keyboard: Keyboard is used to input data in to the system so that the system gives output to the user. Therefore, the keyboard is an integral part of the input system. A computer is essentially incomplete without a keyboard. Monitor: Monitor, again is a very essential part of the computer system, displays the actions that the computer performs on our command. Motherboard: Motherboard again a necessary element of the computer system contains different elements as memory, processor, modem, slots for graphic card and LAN card. Hard Disk: Hard disk is used to store data permanently on computer. Modem: Modem is used to connecting to the Internet. Two types of modems are widely used. One is known as software modems and the other is known as hardware modems. Speakers: Speakers are also included in basic elements of a computer. It is not indispensible, because a computer can perform its function without speakers. However, we use them to for multiple purposes.

1.1.2 Basic Computer Functioning A computer can be defined as an electronic device that accepts data from an input device, processes it, stores it in a disk and finally displays it on an output device such as a monitor. To understand the basic rudiments of the functioning of the computer refer to the basic block diagram of a computer as shown .This flow of information holds true for all types of computers such as Personal Computers, Laptops, Palmtops etc. In other words, the fundamental principle of working is the same.

[Block Diagram of a Computer]

As shown in Fig, there are four main building blocks in a computer's functioning input, processor, output and memory. The data is entered through input devices like the keyboard, disks or mouse. These input devices convert data and programs into the language that the computer can process. The data received from the keyboard is processed by the CPU, i.e. the Central Processing Unit. The CPU controls and manipulates the data that produce information. The CPU is usually housed within the protective cartridge. The processed data is either stored in the memory or sent to the output device, as per the command given by the user. The memory unit holds data and program instructions for processing data. Output devices translate the processed information from the computer into a form that we can understand. 1.1.3 Advantages of Computers 1. High speed: Computers have the ability to perform routine tasks a greater speed than human beings. They can perform millions of calculations in seconds. 2. Accuracy: Computers are used to perform tasks in a way that ensures accuracy. 3. Storage: Computers can store large amount of information. Any item of data or any instruction stored in the memory can be retrieved by the computer at lightning speeds. 4. Automation: Computers can be instructed to perform complex tasks automatically (which increases the productivity). 5. Diligence: Computers can perform the same task repeatedly & with the same accuracy without getting tired. 6. Versatility: Computers are flexible to perform both simple and complex tasks. 7. Cost effectiveness: Computers reduce the amount of paper work and human effort, thereby reducing costs. 1.2 GENERATIONS OF COMPUTERS The Computer Generations: The development of computers has followed different steps in the terminology used and these steps of technological differences are called as GENERATIONS in computer terminology. There are totally five generations of computers till today. 1. First Generation Computers (1950's): These computer which used vaccum tubes (valves) as major electronic component the advantage of vaccum tubes technology is that it made the advent of Electronic digital computer vaccum tubes were only electronic devices available during those days which made computing possible. 2. Second Generation Computers (1960's): With the development of Transistors and there use in circuits, magnetic core for memory storage, the vaccum tubes are replaced by transistors to arrive at 2nd generation of computers. The size of transistors is much smaller when compared to vaccum tubes, they consume power, generated less heat and faster and reliable. Advantages: (1) Size of Computer has come down as well as power consumption. (2) The Cost of Computer reduced. Third Generation Computers (1970's): The development of silicon chips, the third generation of computers came into existence. These computers are used Integrated Circuits (IC's) of silicon chips, in the place of transistors. Each of these IC’s consisting of large number of chips in very small packages. Advantage: The size of computers, cost, heat generation and power consumption decreased to great extent, speed and reliability increased as compared to previous generation. These machines used IC's with large scale Integration (LSI). Fourth Generation (1980's): The Computers belonging to these generations used Integrated circuits with Very Large Scale Integration (VLSI). Advantages: 1) These computers have high processing powers, low maintenance, high reliability and very low power consumption. 2) The size & cost of computers come down drastically Fifth Generation (Late 1990's) :- These computers use optic fiber technology to handle Artificial Intelligence, Expert systems, Robotics etc., these computers have very processing speeds and are more reliable. Generation Component Used First Generation Vacuum tubes (1946-1954 ) Second Generation Transistors (1955-1965) Third Generation Integrated Circuits (IC) (1968-1975 ) Fourth Generation Very Large Scale Integrated Circuits(VLSI) ( 1976-1980) Fifth Generation Ultra Scale Integrated Circuits (ULSI) (1980 – till today ) Micro Processor (SILICON CHIP)

1.3 CLASSIFICATION OF COMPUTERS Computers in general can be classified into major categories based on. (a) According to the purpose of the computer. (b) According to the operation size of computer. Classification as per purpose of the Computer : Classification of digital computer as per the purpose of their use 1. General purpose digital computers. 2. Special purpose digital computer. 1. General Purpose digital Computers: These computers are theoretically used for any of applications. These computers can be used in solving a business Problem and also used to solve mathematical equation with same accuracy and consistency. of the computer now is general purpose digital computers. All the P.C's, which have become household affair. 2. Special Purpose Computers: These digital computers are designed, made and used for any specific job. These are usually used for those purposes which are critical and need great accuracy and response like Satellite launching weather forecasting etc. Computers are classified according to the storage capacity, speed and the purpose for which they are developed. These can be classified into three types: 1. Analog Computes 2. Digital Computers 3. Hybrid Computers 1. Analog computers: They operate by ―measuring‖ instead of ―counting‖. The name (derived from Greek word analog) denotes that the computer functions by establishing similarities between the two quantities. They are powerful tools for solving differential equations. 2. Digital Computers: These computers operate by ―counting‖. All quantities are expressed as discrete digits or numbers. These are useful for evaluating arithmetic expressions and manipulations of data. 3. Hybrid Computers: Computers which combine the features of analog and digital computers are known as Hybrid computers. According to size and capabilities 1. Super Computers 2. Main frame Computer 3. Medium scale Computer 4. Mini Computers 5. Micro Computers. (1) Super Computers: These computers are characterized as being the fastest, with very high processing speed, very large size, most powerful. There are widely used in complex scientific applications like processing geological data, weather data, genetic engineering etc. These computers with 16 microprocessors will recognize words up to length 64 bits and more. The speed of calculation is up to 1.2 billion instructions/second, and they can take input from more than 1000 individual work station. . PARAM developed in India. (2) Mainframe Computers: These Computer will has capability to support many peripheral devices and terminals, which can process several Million Instructions / second (MIPS), as well which support 1000 remote systems, these computers are mostly used for Railway reservation etc. (3) Medium Scale (size) Computers: These computers are mini versions of mainframe computers; they are relatively smaller than mainframes and have less processing power than Mainframes their processing speed support up to 200 remote systems. (4) Mini Computers: These computers are smaller and less experience than Mainframe and medium sized computers. They are relatively faster it can support about 10-20 user terminals. These computers are generally easy to use. They can handle database, statistical problems Accounting etc. (5) Micro Computer: These are the mostly used category of computes called as personal computers (PC's). The word Micro suggests only the size, but not the capacity. They are capable to do all input - output operations. They can also be connected to peripheral devices. Anatomy of Computers: Major Components of Computer:- Computer is basically composed of essentially the following: 1. Hardware 2. Software 1. Hardware: Computer hardware is the collection of various physical components of the computer, like the computer itself, the input-output devices. This computer Hardware performs some operations like addition, Subtraction, data transfer, control transfers and simple tests. 2. Software: Software is set of instructions usually termed as programs which are required for processing activities of the computer. These set of programs can be used to solve real world problems. The capability of computer depends upon the software components. 1.4 COMPUTER LANGUAGES There are three types of programming languages. 1. Machine Languages: Computers respond only to machine language. This language is in terms of binary codes (0,1). i.e. all programs should be written with these codes, which is difficult, consuming and leading to errors while writing the programs. There is no unique standard machine language. Rather there are many machine languages. These are machine dependent. These are referred as the first generation languages. 2. Assembly Languages: It uses mnemonic codes rather than numeric codes (as in machine languages). Ex. Add or A is used as a symbol for addition. It requires translators to convert into machine language. Like machine language, writing program in assembly language is also time consuming. These are also machine dependent. 3. High Level Languages (HLL): These are referred as problem oriented languages (POL). These are referred as third generation languages. The advantages of these languages are  The high level languages are convenient for writing programs as they can be written without any codes. These languages follow rules like ―English‖ language.  Because of their English like nature, less time is required to a program.  They are machine independent. A program written in any HLL can be run on computers of different types without any modifications. Several High Level Languages which are in common use: FORTRAN : FORmula TRANslation COBOL : Common Business Oriented Language BASIC : Beginner‘s All purpose Symbolic Instruction Code PROLOG: PROgramming in LOGic ALGOL : ALGOrithmic Language 1.5 ALGORITHMS An algorithm is procedure consisting of a finite set of unambiguous rules (instructions) which specify a finite sequence of operations that provides the solution to a problem, or to a specific class of problems for any allowable set of input quantities (if there are inputs). In other word, an algorithm is a step-by- step procedure to solve a given problem. Alternatively, we can define an algorithm as a set or list of instructions for carrying out some process step by step. A recipe in a cookbook is an excellent example of an algorithm. The recipe includes the requirements for the cooking or ingredients and the method of cooking them until you end up with a cooked dish. The word is derived from the phonetic pronunciation of the last name of Abu Ja'far Mohammed ibn Musa al-Khowarizmi, was an Arabic mathematician who invented a set of rules for performing the four basic arithmetic operations (addition, subtraction, multiplication and division) on decimal numbers. An algorithm is a representation of a solution to a problem. 1.5.1 Structure and Properties of Algorithm An algorithm has the following structure 1. Input Step 2. Assignment Step 3. Decision Step 4. Repetitive Step 5. Output Step An algorithm is endowed with the following properties: 1. Finiteness: An algorithm must terminate after a finite number of steps. 2. Definiteness: The steps of the algorithm must be precisely defined or unambiguously specified. 3. Generality: An algorithm must be generic enough to solve all problems of a particular class. 4. Effectiveness: the operations of the algorithm must be basic enough to be put down on pencil and paper. They should not be too complex to warrant writing another algorithm for the operation. 5. Input-Output: The algorithm must have certain initial and precise inputs, and outputs that may be generated both at its intermediate and final steps. An algorithm does not enforce a language or mode for its expression but only demands adherence to its properties. Practical Algorithm Design Issues: 1. To save time (Time Complexity): A program that runs faster is a better program. 2. To save space (Space Complexity): A program that saves space over a competing program is considerable desirable. 1.5.2 Efficiency of Algorithms The performances of algorithms can be measured on the scales of time and space. The performance of a program is the amount of computer memory and time needed to run a program. We use two approaches to determine the performance of a program. One is analytical and the other is experimental. In performance analysis we use analytical methods, while in performance measurement we conduct experiments. Time Complexity: The time complexity of an algorithm or a program is a function of the running time of the algorithm or a program. In other words, it is the amount of computer time it needs to run to completion. Space Complexity: The space complexity of an algorithm or program is a function of the space needed by the algorithm or program to run to completion. The time complexity of an algorithm can be computed either by an empirical or theoretical approach. The empirical or posteriori testing approach calls for implementing the complete algorithms and executing them on a computer for various instances of the problem. The time taken by the execution of the programs for various instances of the problem are noted and compared. The algorithm whose implementation yields the least time is considered as the best among the candidate algorithmic solutions. 1.6 PSEUDO CODE Pseudo code is an artificial and informal language that helps programmers develops algorithms. Pseudo code is a "text-based" detail (algorithmic) design tool. The rules of Pseudo code are reasonably straightforward. All statements showing "dependency" are to be indented.  Artificial and Informal language  Helps programmers to plan an algorithm  Similar to everyday English  Not an actual programming language e.g : Pseudo code Read A, B Calculate C = A*B Display C Stop e.g. Selection – IF , IF / ELSE and IF / ELSE IF IF A is less than B BIG = B SMALL = A ELSE BIG = A SMALL = B Converting a pseudo code to a programming language is much easier than converting a flowchart. As compared to flowchart, it is easier to modify a pseudo code of program logic when program modifications are necessary. In the cases of pseudo code, a graphic representation of program logic is not available. There are no standard rules to follow for using a pseudo code. Different programmers use their own style of writing pseudo code; and hence, Communication problem occurs due to lack of standardization. e.g. – IF/ELSE Read student ‘s grade IF student's grade is greater than or equal to 60 Print "passed" ELSE Print "failed“ Stop e.g. – WHILE Set total to zero Set grade counter to one WHILE grade counter is less than or equal to ten Input the next grade Add the grade into the total Set the class average to the total divided by ten Print the class average Stop 1.7 FLOW CHARTS The flowchart is a means of visually presenting the flow of data through an information processing systems, the operations performed within the system and the sequence in which they are performed. A flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem. Flowcharts are generally drawn in the early stages of formulating computer solutions. These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write the program in any high level language. 1.7.1 Basic Flowchart Symbols

F if T Statement 2 (Condition) Statement 1

1.8 METHOD A Software Development Method is a process, also known as a software development life-cycle (SDLC), is a structure imposed on the development of a software product. There are several models for such processes, each describing approaches to a variety of tasks or activities that take place during the process. Some people consider a life-cycle model a more general term and a software development process a more specific term. Several models exist to streamline the development process. Each one has its pros (advantages) and cons (disadvantages), and it is up to the development team to adopt the most appropriate one for the project. Sometimes a combination of the models may be more suitable. General Software Process Models are: 1. Waterfall Model 2. Prototype Model 3. Spiral Model 4. Iterative/Incremental Development Model 5. Rapid Application Development Model 6. Extreme Programming The waterfall model is the classical model of software engineering. This model is one of the oldest models and is widely used in government projects and in many major companies. As this model emphasizes planning in early stages, it ensures design flaws before they develop.With Iterative Development, the project is divided into small parts. This allows the development team to demonstrate results earlier on in the process and obtain valuable feedback from system users. Often, each iteration is actually a mini-Waterfall process with the feedback from one phase providing vital information for the design of the next phase. The spiral model is similar to the incremental model, with more emphases placed on risk analysis. The spiral model has four phases: Planning, Risk Analysis, Engineering and Evaluation. A software project repeatedly passes through these phases in iterations (called Spirals in this model). The baseline spirals, starting in the planning phase, requirements are gathered and risk is assessed. Each subsequent spiral builds on the baseline spiral. Requirements are gathered during the planning phase. In the risk analysis phase, a process is undertaken to identify risk and alternate solutions. A prototype is produced at the end of the risk analysis phase. Software is produced in the engineering phase, along with testing at the end of the phase. Rapid application development (RAD) is a type of software development methodology that uses minimal planning in favor of rapid prototyping. The "planning" of software developed using RAD is interleaved with writing the software itself. The lack of extensive pre-planning generally allows software to be written much faster, and makes it easier to change requirements. Extreme Programming is an approach to software development, based on the development and delivery of very small increments of functionality. It relies on constant code improvement, user involvement in the development team and pair wise programming. 1.8.1 Applying The Software Development Method A software development process or life cycle is a structure imposed on the development of a software product. There are several models for such processes, each describing approaches to a variety of tasks or activities that take place during the process. Process Activities/Steps Software Engineering processes are composed of many activities, notably the following: 1. Requirements Analysis: Extracting the requirements of a desired software product is the first task in creating it. While customers probably believe they know what the software is to do, it may require skill and experience in software engineering to recognize incomplete, ambiguous or contradictory requirements. 2. Specification: Specification is the task of precisely describing the software to be written, in a mathematically rigorous way. In practice, most successful specifications are written to understand and fine-tune applications that were already well-developed, although safety- critical software systems are often carefully specified prior to application development. Specifications are most important for external interfaces that must remain stable. 3. Software architecture: The architecture of a software system refers to an abstract representation of that system. Architecture is concerned with making sure the software system will meet the requirements of the product, as well as ensuring that future requirements can be addressed. 4. Implementation: Reducing a design to code may be the most obvious part of the software engineering job, but it is not necessarily the largest portion. 5. Testing: Testing of parts of software, especially where code by two different engineers must work together falls to the software engineer. 6. Documentation: An important task is documenting the internal design of software for the

purpose of future maintenance and enhancement. 7. Training and Support: A large percentage of software projects fail because the developers fail to realize that it doesn't matter how much time and planning a development team puts into creating software if nobody in an organization ends up using it. People are occasionally resistant to change and avoid venturing into an unfamiliar area, so as a part of the deployment phase, it’s very important to have training classes for the most enthusiastic software users (build excitement and confidence), shifting the training towards the neutral users intermixed with the avid supporters, and finally incorporate the rest of the organization into adopting the new software. Users will have lots of questions and software problems which lead to the next phase of software. 8. Maintenance: Maintaining and enhancing software to cope with newly discovered problems or new requirements can take far more time than the initial development of the software. Not only may it be necessary to add code that does not fit the original design but just determining how software works at some point after it is completed may require significant effort by a software engineer. About 60% of all software engineering work is maintenance, but this statistic can be misleading. A small part of that is fixing bugs. Most maintenance is extending systems to do new things, which in many ways can be considered new work.

1.8.2 Basic Waterfall Model:

1.9 CREATING AND RUNNING PROGRAM Computer understands machine language only. So, we will convert the given HLL code in to machine language by using compiler. First, we need to write the program then execute it to get the desired output. There are 4 steps in this process. i. Writing and editing programs ii. Compiling programs iii. Linking programs iv. Program execution i. Writing and editing programs:- Text editor software is used to write, change and store the program. If, we want to modify any data in the program first, we should open the and point to the data with cursor where, we need to modify the data. Then apply the changes and press F2 key to save the file. Every file in C must be stored with .c extension. Like “add.c”. ii. Compiling programs: - Compiler is needed to convert the given source code in to machine language (in the form of 0’s and 1’s). In Turbo-c short command alt-F9 is used to compile the given source file (add.c). Then the source code will be converted and saved in “add.obj”. iii. Linking programs: - The object file is not only enough to get the output. The object code of the keywords used in the program is needed to be combined with the object file. For example in any program, We use printf keyword and the object code of printf is needed to be combined with object file. iv. Program execution: - Once the program has been linked, it is ready for execution. The program must be loaded in to the primary memory to execute it. Loader will load the program in to main memory. We use Run to execute the program. 1.9.1 How to Run a C Program 1. Open the bin folder ("C:\TC\BIN") 2. Click on "TC" icon as shown below.

3. You will see the following screen

4. Now, Click on File->New. Please image below for your reference.

5. Write your C Program. Press F2 (or File->Save) to save your program. On pressing F2, pop window will open (as shown below). You need to specify the name of the program. For C Program, use .C as extension.

6. To compile a C Program you can either press Alt+F9 or Compile->Compile. After you compile your C Program you will see the following screen.

7. To run a C Program you can either press Ctrl+F9 or Run->Run. After you run your C Program you will see the output screen as shown below.

2. INTRODUCTION TO C LANGUAGE BRIEF OF DENNIS MACALISTAIR RITCHIE - FATHER OF C AND UNIX Dennis MacAlistair Ritchie (1941 - 2011) was an American Computer Scientist also popularly known as “dmr” is best known as the creator of the C Programming Language and co-creator of UNIX along with his colleague Ken Thompson at Bell Laboratories. Education: 1. Harvard University, Bachelor's degrees in physics and applied mathematics, 1963 2. Harvard University, PhD, 1968 Today, C remains the second most popular programming language in the world. 2.1 BRIEF HISTORY OF C PROGRAMMING LANGUAGE 1. C was developed at Bell Laboratories in 1972 by Dennis Ritchie. 2. C is a general-purpose computer programming language and was the descendent of CPL (Combined Programming Language and BCPL (Basic CPL). 3. Dennis Ritchie wrote the improved and portable version named C that could run on any machine. 4. By virtue of C's portability, UNIX was rewritten in 1973 was also a portable that could work on different computers. 2.1.1 Significant Features of C Language 1. C is a powerful, flexible language that provides fast program execution. 2. C is a Procedural Language i.e. the programmer is required to provide step-by-step instructions for the CPU (central processing unit). 3. The success of C is due to its simplicity, efficiency, flexibility and small memory requirements. 4. Low Level features: C's power and fast program execution come from its ability to access low level commands, similar to assembly language, but with high level syntax. 5. Portability: C programs are portable i.e. they can run on any compiler with little or no modification. Compiler and Preprocessor makes it possible for C program to run it on different PC. 6. Bit Manipulation: C Programs can be manipulated using bits and it provides wide variety of bit manipulation operators. 7. Modular Programming: It is a software design technique that increases the extent to which software is composed of separate parts, called modules. C program consist of different modules that are integrated together to form a complete program. 8. Efficient Usage of Pointers: C supports efficient use of pointers and pointers has direct access to memory. 9. Standard Library Concept: 10. Powerful and varied repertoire of Operators 11. Elegant Syntax: 12. Ready Access to Hardware when needed: 13. Structured Programming Language: C supports 2.1.2 Areas of Application The C programming language is used in many different areas of application, but the most prolific area is UNIX operating system applications.  Computer Games  System level Programming – making Operating System Assemblers, Compilers, Interpreter, Cross-Compilers, Text Editors, and Device Drivers.  Application Development – e.g. making Reservation System, Library System, Inventory Control System etc.  Writing Embedded Software/firmware for various electronics, industrial and communication products.  Used in developing verification software, code, and simulators for various applications and hardware products. 2.2 BASIC STRUCTURE OF C LANGUAGE Documentation Section (Optional) The documentations section consists of comment lines giving the name of the program, the author and other details which the programmer would like to use later. Single Line Comment: // This is a sample program Multiple Line Comment: \* This is a sample Program*\ Preprocessor Statements The preprocessor statements begin with # symbol and are also called the preprocessor directive. These statements instruct the compiler to include C preprocessors such as header files and symbolic constants or macros before compiling the C program. e.g. # include Header Files # include # define PI 3.142 Symbolic Constants # define MAX 100 Global Declaration The variables are declared before the main () functions as Section(Optional) well as user defined functions are called global variables. main() Function Section (must) The C program execution starts with main() function. The main() function should be written in small (lowercase) letters and it should not be terminated by semicolon. Syntax: main() { Local Declarations; Processing Statements; } User Defined Functions (Optional) This section contains all the user defined functions that are called in the main() function. User defined functions are generally placed immediately before /after the main function. 2.3 C TOKENS

C Tokens

Identifier Constants Keywords Operators Special Characters

A token is the basic building block of a C program which can be recognized by the compiler. 2.3.1 Identifier An identifier is used to give a name to an object. An identifier refers to the names of variables, constants, functions, arrays, types (typedefs, structs, unions, enums), type members and macros etc. These are user-defined names and consist of sequence of letters and digits, with a letter or underscore as a first character. Both uppercase and lowercase letters are permitted. Rules for Identifiers: 1. First character must be an alphabet or underscore. 2. Identifier names must consist of only letters, digits or underscore. 3. It must not be a keyword. 4. It must not contain white space, operators and special characters. 5. There is no rule for the length of an identifier. 6. The first 31 characters of an identifier are discriminated by the compiler. 2.3.2 Constants A constant is a quantity that doesn’t change. There are mainly to types of constants. 1. Numeric Constants a. Integer Constants e.g. 5, 9, 35 b. Floating Point Constants e.g. 5.25,0.22E-5, -2.0 2. Non numeric or Character Constants a. Single Character Constants e.g. ‘a’,’x’,’p’ b. String Constants e.g. “hello”, “sample”,”good”

2.3.3 Keywords These are reserved words used in programming. Each keyword has fixed meaning and that cannot be changed by user. e.g. int n; Here int is keyword and it indicates n is of type integer. Here is the list of all keywords predefined by ANSI C. Standard Keywords in C Language: Keywords used while declaring variables int char float double long short signed unsigned volatile void const Control flow related Keywords if else switch case default do while for return break continue goto Storage classes related Keywords auto static register extern User defined data type related Keywords enum typedef struct union Special operator related Keyword sizeof 2.4 OPERATORS An operator is used to describe an operation applied to one or several objects. 1. Arithmetic Operators 2. Increment and Decrement Operators 3. Assignment Operators 4. Relational Operators 5. Logical Operators 6. Conditional operators 7. Bitwise Operators 8. Special Operators Arithmetic Operators: Operator Meaning of Operator + Addition or unary plus - Subtraction or unary minus * Multiplication / Division % Remainder after division (modulo division) Increment and Decrement Operators: Operator Meaning of Operator ++ Increment operator (unary) a++; //post increment ++a; //pre increment -- Decrement operator (unary) a--; //post decrement --a; //pre decrement Assignment Operators: There are two types of assignment operators. 1. Simple Assignment 2. Compound Assignment

Operator Meaning of Operator Simple Assignment = Assignment Operator e.g. x=5 5 is assigned to x Compound Assignment += a += b is equivalent to a = a + b -= a -= b is equivalent to a = a - b *= a *= b is equivalent to a = a * b /= a /= b is equivalent to a = a / b %= a %= b is equivalent to a = a % b &= a &= b is equivalent to a = a & b |= a |= b is equivalent to a = a | b ^= a ^= b is equivalent to a = a ^ b <<= a <<= b is equivalent to a = a << b >>= a >>= b is equivalent to a = a >> b Relational Operators: Relational Operators are used to check the relationship between two operands. If the relation is true, it returns value 1 and if the relation is false, it returns value 0. Relational operators are used in decision making and loops in C programming. Operator Meaning of Operator == Equal to e.g. 5 == 3 returns false or 0 > Greater than e.g. 5 > 3 returns true or 1 < Less than e.g. 5 < 3 returns fase or 0 != Not equal to 5 != 3 returns true or 1 >= Greater than or equal to e.g. 5 >= 3 returns true or 1 <= Less than or equal to e.g. 5 <= 3 returns false or 0 Logical Operators: Logical operators are used to combine expressions containing relation operators. In C, there are 3 logical operators: Operator Meaning of Operator && Logical AND e.g. if c=5 and d=2 then ((c == 5) && (d > 5)) returns false or 0 || Logical OR e.g. if c=5 and d=2 then ((c == 5) || (d > 5)) returns true or 1 ! Logical NOT e.g. if c=5 then !(c == 5) returns false or 0 Conditional Operator: Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example: c = (c > 0) ? 10 : 20; If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be 20. Bitwise Operators: A bitwise operator works on each bit of data. Operator Meaning of Operator & Bitwise AND | Bitwise OR ^ Bitwise Exclusive OR << Shift Left >> Shift Right ~ Bitwise Complement (One’s Complement) Special Operators: Operator Meaning of Operator , Comma operators are used to separate the variables or expressions. Example: int a,b,c =5*3; sizeof It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc. e.g. sizeof int = 2 bytes sizeof float = 4 bytes (based on MS-DOS OS) sizeof double = 8 bytes sizeof char = 1 byte . Access Operator is used to access any member of structure or union.  This operator is used to access any member of structure or union using pointer. 2.5 OPERATOR PRECEDENCE TABLE Operator Description Associativity ( ) Parentheses (function call) (see Note 1) left-to-right [ ] Brackets (array subscript) . Member selection via object name -> Member selection via pointer ++ -- Postfix increment/decrement (see Note 2) Prefix increment/decrement right-to-left ++ -- Unary plus/minus + - Logical negation/bitwise complement ! ~ Cast (convert value to temporary value of (type) type) * Dereference & Address (of operand) sizeof Determine size in bytes on this implementation * / % Multiplication/division/modulus left-to-right + - Addition/subtraction left-to-right << >> Bitwise shift left, Bitwise shift right left-to-right Relational less than/less than or equal to left-to-right < <= Relational greater than/greater than or equal > >= to == != Relational is equal to/is not equal to left-to-right & Bitwise AND left-to-right ^ Bitwise exclusive OR left-to-right | Bitwise inclusive OR left-to-right && Logical AND left-to-right | | Logical OR left-to-right ? : Ternary conditional right-to-left = Assignment right-to-left += -= Addition/subtraction assignment *= /= Multiplication/division assignment %= &= Modulus/bitwise AND assignment ^= |= Bitwise exclusive/inclusive OR assignment <<= >>= Bitwise shift left/right assignment , Comma (separate expressions) left-to-right Note 1: Parentheses are also used to group sub-expressions to force a different precedence; such parenthetical expressions can be nested and are evaluated from inner to outer. Note 2: Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the statement completes execution). So in the statement y = x * z++; the current value of z is used to evaluate the expression (i.e., z++ evaluates to z) and z only incremented after all else is done. 2.6 EXPRESSIONS AND EVALUATION 2.6.1 Rules for Evaluation of Arithmetic expressions 1. All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from the inside out, with the innermost expressions evaluated first. 2. The operator precedence rule: Operators in the same sub expression are evaluated in the following order: Unary + and – are evaluated first. *, /, % are evaluated next . binary operator + and – are evaluated last . 3. The associativity rule: Unary operators in the same sub expression and at the same precedence level (such as + and -) are evaluated right to left (right associativity). Binary operators in the same sub expression and at the same precedence level are evaluated left to right (left associativity). Example: Consider the expression -a + ( c + b * ( c + a ) / c – b / a ) + a – b / 2 In the above expression the innermost parenthesis (c + a ) is evaluated first, then the next innermost parenthesis ( c + b * ( c + a ) / c – b / a ) is evaluated. In this sub-expression, first b * (c + a) is evaluated then b * (c + a) / c is evaluated, then b / a is evaluated, then the whole expression is evaluated. Then –a is evaluated, then b / 2 is evaluated and finally the whole expression is evaluated. 2.6.2 Type Conversions C allows types to be mixed in expressions, and permits operations that result in type conversions happening implicitly.In the C programming language, a type conversion is the conversion two different sorts of data type into a common form, in order for them to be manipulated. There are different basic data types, such as int, char, float, double; there are also some user defined data types such as structures, arrays, etc. If the operator is taking operands of different data types, then they are converted to a common data types by certain rules. Generally, automatic conversions are those which can convert a narrower operand into a wider one without loss of information. For example, converting an integer to floating point in examples like float + integer (on 64-bit machine). A char is simply a small integer, so chars may be freely used in arithmetic expressions. 2.7 INPUT AND OUTPUT STATEMENTS Input : In any programming language input means to feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of built- in functions to read given input and feed it to the program as per requirement. Output : In any programming language output means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to output required data.

Reading and writing Characters: The simplest of the console I/O functions are getche (), which reads a character from the keyboard, and putchar (), which prints a character to the screen. The getche () function waits until a key is pressed and then returns its value. The key pressed is also echoed to the screen automatically. The putchar () function will write its character argument to the screen at the current cursor position. The prototypes for getche () and putchar () are shown here: int getche (void); int putchar (int c);

The header file for getche () and putchar () is in CONIO.H. The following programs inputs characters from the keyboard and prints them in reverse case. That is, uppercase prints as lowercase, the lowercase prints as uppercase. The program halts when a period is typed. The header file CTYPE.H is required by the islower() library function, which returns true if its argument is lowercase and false if it is not.

# include # include # include main(void) { char ch; printf (“enter chars, enter a period to stop\n”); do { ch = getche (); if ( islower (ch) ) putchar (toupper (ch)); else putchar (tolower (ch)); } while (ch! = ‘.’); /* use a period to stop */ return 0; } There are two important variations on getche().

 The first is getchar(), which is the original, UNIX-based character input function.

 The trouble with getchar() is that it buffers input until a carriage return is entered. The reason for this is that the original UNIX systems line-buffered terminal input, i.e., you had to hit a carriage return for anything you had just typed to actually be sent to the computer.

 The getchar() function uses the STDIO.H header file.

 A second, more useful, variation on getche() is getch(), which operates precisely like getche () except that the character you type is not echoed to the screen. It uses the CONIO.H header.

Reading and writing : On the next step, the functions gets() and puts() enable us to read and write strings of characters at the console. The gets() function reads a string of characters entered at the keyboard and places them at the address pointed to by its argument. We can type characters at the keyboard until we strike a carriage return. The carriage return does not become part of the string; instead a null terminator is placed at the end and gets() returns. Typing mistakes can be corrected prior to striking ENTER. The prototype for gets() is:

char* gets (char *str);

Where, str is a character array that receives the characters input by the user. Its prototype is found in STDIO.H. The following program reads a string into the array str and prints its length.

# include # include main(void) { char str[80]; gets (str); printf (“length is %d”, strlen(str)); return 0; }

The puts() function writes its string argument to the screen followed by a . Its prototype is. int puts (char str);

It recognizes the same backslash codes as printf(), such as “\t” for tab. It cannot output numbers or do format conversions. Therefore, puts() takes up less space and runs faster than printf(). Hence, the puts() function is often used when it is important to have highly optimized code. The puts() function returns a non negative value if successful, EOF otherwise. The following statement writes “hello” on the screen.

puts (“hello”);

The puts() function uses the STDIO.H header file.

Basic console I/O functions:

Function Operation getchar() Reads a character from the keyboard and waits for carriage return getche() Reads a character with and does not waits for carriage return Reads a character from the keyboard with out echo and not waits for getch() carriage return Putchar() Writes a character to the screen gets() Reads a string from the keyboard puts() Writes a string to the screen

Distinguishion between getchar() and gets() functions:

getchar() gets() Used to receive a single character. Used to receive a single string, white spaces and blanks. Does not require any argument. It requires a single argument.

Reading Character Data in a C Program

All data that is entered into a C program by using the scanf function enters the computer through a special storage area in memory called the standard input buffer (or stdin). A user's keystrokes (including the new line character \n generated when the Enter key is pressed) are stored in this buffer, which can then be read using functions such as scanf. When numbers are read from this area, the function converts the keystrokes stored in the buffer (except for the \n) into the type of data specified by the control string (such as "%f") and stores it in the memory location indicated by the second parameter in the scanf function call (the variable's address). The \n remains in the buffer. This can cause a problem if the next scanf statement is intended to read a character from the buffer. The program will mistakenly read the remaining \n as the character pressed by the user and then proceed to the next statement, never even allowing the user to enter a character of their own.

You can solve this problem when writing C statements to read character data from the keyboard by adding a call to a special function named fflush that clears all characters (including \n's) from the given input buffer. The statement would be place ahead of each statement in your program used to input characters, such as:

fflush(stdin); scanf("%c", &A); or fflush(stdin); A=getchar();

Formatted Console I/O (printf() and scanf()):

printf() function

This is one of the most frequently used functions in C for output.

#include

main() { int dec = 5; char str[] = "abc"; char ch = 's'; float pi = 3.14;

printf("%d %s %f %c\n", dec, str, pi, ch); }

The output of the above would be:

5 abc 3.140000 c

Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to print a float and %c is being used to print a character. scanf() function

This is the function which can be used to to read an input from the command line.

#include main() { int x; int args;

printf("Enter an integer: "); if (( args = scanf("%d", &x)) == 0) { printf("Error: not an integer\n"); } else { printf("Read in %d\n", x); }

}

Here %d is being used to read an integer value and we are passing &x to store the vale read input. Here &indicates the address of variable x.

This program will prompt you to enter a value. Whatever value you will enter at command prompt that will be output at the screen using printf() function. If you enter a non-integer value then it will display an error message.

Enter an integer: 20 Read in 20

Questions on Variables, Constant, Data Types, Arithmetic Expressions, Input & Output Functions: Q1) What is input function? Ans: It is used to read values from input device. Q2) What is output function? Ans: It is used to display output of a program. Q3) What is a Variable? Ans: A variable is a data name that is used to store a value. Q4) What is Constant? Ans: Constant is a fixed values that do not change during the execution of a program. Q5) What is data type? Ans: This indicates type of data. Q6) What are the rules to define a variable? Ans:  It must begin with a letter, or with underscore.  It must not be a keyword.  It must not contain white space or special characters.  It can have digits at middle or end. Q7) Give few examples for valid variable names? Ans: T_raise, delhi, x1, ph_value, mark, sum1, distance Q8) Is char a valid variable name? Ans: No, char is a keyword Q9) Is price$ a valid variable name? Ans: NOT VALID, dollar sign is illegal. Q10) Is 'group one' a valid variable name? Ans: NOT VALID blank space not permitted. Q11) Is int_type a valid variable name? Ans: Valid, keyword may be a part of a name. Q12) What are the data types that ANSI c supports? Ans: ANSI c supports three classes of data types .they are 1. Primary (or fundamental/ primitive)data type 2. Derived data types 3. User defined data types. Q13) What are primary data types? Ans : char , int , long , float & double. Q14) What are derived data types? Ans : Array , pointer. Q15) What are user defined data types. Ans : Structure, union and enum. Q16) What is the size and range of the basic data types? Ans: The size and range of the basic data types are: Data Type size (bytes) range int 21 -32,768 to +32767 long int 4 -231 to 231-1 char 1 -128 to +127 float 4 3.4e-38 to 3.4e+38 double 8 1.7e-308to1.7e+308

Q17) What is the size and range of short int(or)signed short int, long int (or)signed long int? Ans: Data Type size (bytes) range Short int or signed short int 2 -215 to +215-1 Long int or signed long int 4 -231 to +231-1

Q18) How many types of constants exist in C? Ans: C has two types of constants. Those are 1. Numeric constants 2. Character constants Q19) How many types of numeric constants exist in C? Ans: There are two types of numeric constants. They are: 1. Integer constants 2. Real constants Q20) How many types of character constants exist in? Ans: There are two types of character constants. Those are 1. Single character constants 2. String constants Q21) Is embedded spaces, commas and non digit characters are permitted between decimal integer constants? Ans: No, embedded spaces, commas and non digit characters are NOT permitted between decimal integer constants. Q22) Is '20,000' a valid decimal integer constant? Ans: Not valid Q23) Give few examples of octal integer constants? Ans: 037, 0435, 0551 Q24) Give few examples of hexa decimal integer constants? Ans: 0x2, 0x9f, 0xbcd, ox1234. Q25) Give few examples of real type constants? Ans: 0.0083,-.75,435.36,+247.008 Q26) Give few examples of single character type constant? Ans: '5', 'x', ';' Q27) Give few examples of string constant? Ans: ”rana”, ”123”, ”seetha123”. ”Rama Rao” Q28) What are the basic escape sequence characters & meaning ? Ans: ’\a’ - --- alarm ’\b’ ----- BackSpace ’\f’ ---- form feed ’\n’ ---- newline ’\r’ ---- carriage Return ’\t’ ---- tab ’\v’ ---- vertical Tab Q29) What is an integer expression? Ans: When both the operands in an expression are integers then the expression is known as an integer expression. Q30) Let a=14, b=4 what will be the output for the following a) a-b b) a+b c) a*b d) a/b e) a%b Ans: a) 10 b) 18 c) 56 d) 3 e) 2 Q31) When an expression is called mixed mode arithmetic? Ans: When one of the operands is real and the other is integer, the expression is called mixed mode arithmetic. Q32) What will be the value of c,d,e & f in the below code. float c=15/10.0 & int d=15/10; float e = 15/10 and float f= 15.0/10.0; Ans: c = 1.5 d = 1 e = 1.0, f = 1.5. Output Prediction: 1. What will be the output of the following program: int main() { printf("%%",7); return(0); } 2. What will be the output of the following program : int main() { printf("//",5); return(0); }

3. What will be the output of the following program : int main() { printf("d%",8); return(0); }

4. What will be the output of the following program : int main() { printf("%d"+0,123); return(0); }

5. What will be the output of the following program : int main() { printf("%d"+1,123); return(0); }

6. What will be the output of the following program : int main() { printf("%d",printf("Hi!")+printf("Bye")); return(0); }

7. What will be the output of the following program : int main() { printf("%d",printf("")+printf("")); return(0); }

8. What will be the output of the following program : int main() { printf("Hi Friends"+3); return(0); }

9. What will be the output of the following program : int main() { printf("D For ") + printf("DOG"); return(0); }

10. What will be the output of the following program : 10. int main() { printf("\/\*\-*\/"); return(0); }

11. What will be the output of the following program : int main() { int main=7; { printf("%d",main); return main; } printf("Bye"); return(0); }

12. What will be the output of the following program : int main() { printf("Work" "Hard"); return(0); }

13. What will be the output of the following program : int main() { char str[]="%d"; int val=25; printf(str,val); return(0); }

14. What will be the output of the following program : int main() { int val=10; printf("%d",val+1,"%d",val--); return(0); } 15. What will be the output of the following program [NOTE : ASSUME 2 values are entered by the user are stored in the variables 'val' & 'num' respectively] : int main() { int val=5,num; printf("%d",scanf("%d %d",&val,&num)); return(0); } 16. What will be the output of the following program : #define Compute(x,y,z) (x+y-z) int main() { int x=2,y=3,z=4; printf("%d",Compute(y,z,(-x+y)) * Compute(z,x,(-y+z))); return(0); } 17. What will be the output of the following program : int main() { int m=10,n=20; printf("%d %d %d",m/* M */,/* N */n,m*/* Compute m*n */n); return(0); }

18. What will be the output of the following program : int main() { int val=97; "Printing..."+printf("%c",val); return(0); }

19. What will be the output of the following program : int main() { int val=5; val=printf("C") + printf("Skills"); printf("%d",val); return(0); }

20. What will be the output of the following program : int main() { int val=5; printf("%*d",val,val); return(0); }

21. What will be the output of the following program : int main() { printf("%f",123.); return(0); }

22. What will be the output of the following program : int main() { char str[]="look at me"; printf("%d",sizeof str); return(0); }

23. What will be the output of the following program : int main() { char str[]="look at me"; printf("%d",-sizeof(str)); return(0); }

24. What will be the output of the following program : int main() { printf("%d",!(100==100)+1); return(0); }

25. What will be the output of the following program : int main() { int x=5,y=6,z=2; z/=y/z==3?y/z:x*y; printf("%d",z); return(0); }

26. What will be the output of the following program : int main() { printf("%d %d %d",5,!5,25-!25); return(0); }

27. What will be the output of the following program : int main() { int a=500,b=100,c=30,d=40,e=19; a+=b-=c*=d/=e%=5; printf("%d %d %d %d %d",a,b,c,d,e); return(0); }

28. What will be the output of the following program : int main() { int a=500,b=100,c=30,d=40,e=19; if ((((a > b) ? c : d) >= e) && !((e <= d) ? ((a / 5) == b) : (c == d))) printf("Success"); else printf("Failure"); return(0); }

29. What will be the output of the following program : int main() { int a=1,b=2,c=3,d=4; printf("%d",!a?b?!c:!d:a); return(0); }

30. What will be the output of the following program [NOTE : 3 values entered by the user are:100 200 300] : int main() { int a=1,b=2,c=3; scanf("%d %*d %d",&a,&b,&c); printf("a=%d b=%d c=%d",a,b,c); return(0); }

31. What will be the output of the following program [NOTE : THE USER INPUT IS:Dear Friends, What is the output?] : int main() { char line[80]; // Max. length=80 Chars scanf("%[^,]s",line); printf("\n%s",line); return(0); }

32. What will be the output of the following program [NOTE : THE USER INPUT IS :A B C] : int main() { char a,b,c; scanf("%c%c%c",&a,&b,&c); printf("a=%c b=%c c=%c",a,b,c); return(0); }

33. What will be the output of the following program [NOTE : THE USER INPUT IS:5 5.75] : void main() { int i=1; float f=2.25; scanf("%d a %f",&i,&f); printf("%d %.2f",i,f); }

34. What will be the output of the following program [NOTE : THE USER INPUT IS :ABC DEF GHI] : int main() { char a,b,c; scanf("%c %c %c",&a,&b,&c); printf("a=%c b=%c c=%c",a,b,c); return(0); }

35. What will be the output of the following program [NOTE : THE USER INPUT IS:CMeansSea Ocean Vast] : int main() { char a[80],b[80],c[80]; scanf("%1s %5s %3s",a,b,c); printf("%s %s %s",a,b,c); return(0); }

36. What will be the output of the following program [NOTE : THE USER INPUT IS :123456 44 544] : int main() { int a,b,c; scanf("%1d %2d %3d",&a,&b,&c); printf("=%d",a+b+c); return(0); }

37. What will be the output of the following program : int main() { char line[80]; scanf("%[^1234567890\n]",line); return(0); }

38. What will be the output of the following program : int main() { char line[80]; scanf("%[^*]",line); return(0); } Questions on different types of Operators Q1) How many arithmetic operators exist in C ? Ans: Five. Q2) What are the different arithmetic operators? Ans: The different arithmetic operators are: + (addition), - (subtraction), * (multiplication), / (division), % (modulo division). Q3) What is precedence of an operator? Ans: Precedence of an operator decides the order in which different operators are applied. Q4) What is associativity ? Ans: Associativity decides the order in which operands are associated with operator. Q5) How many types of associativity exist in C ? Ans : Two types. Q6) What are two types of associativity ? Ans : Left to Right & Right to Left. Q7) Which arithmetic operator/s has highest precedence? Ans: * , / and % Q8) Which arithmetic operator/s has lowest precedence? Ans: + and - Q9) What is the associativity of arithmetic operators? Ans: Left to Right. Q10) Which operator has highest precedence level in c? Ans: ( ) [] has highest precedence level in c . Q11) What will be the value of x, y, z for a=9,b=12,c=3 (all are declared as float data type) x = a-b/3+c*2-1; y = a-b/(3+c)*(2-1); z = a-(b/(3+c)*2)-1; Ans: x = 10.0000 y = 7.0000 z = 4.000. Q12) How many relational operators exist in C? Ans: Six Q13) What are the different relational operators? Ans: The different relational operators are: < (is less than), <= (less than or equal to), > (greater than), >= (greater than or equal to), == (equal to), !=(not equal to). Q14) Which relational operators have highest precedence? Ans: >, <, >=, <= Q15) Which relational operator has lowest precedence? Ans: = =, != Q16) What is the associativity of relational operators? Ans: Left to Right. Q17) What are the different assignment operators? Ans: =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>= Q18) What is the associativity of assignment operators? Ans: Right to Left Q19) What will be the values of a, b, c, d (all are integer data types) and initially a=10,b=3,c=2,d=8 a+=1; b-=1; c*=2; d/=4; Ans: a=11, b=2, c=8, d=2. Q20) How many Logical operators exist in C? Ans: Three Q21) What are the different logical operators? Ans: && (LOGICAL AND), || (LOGICAL OR), ! (LOGICAL NOT) Q22) What is the associativity of logical and (&&), logical or (||) ? Ans: Left to Right Q23) What is the associativity of logical not ? Ans: Right to Left Q24) What is the associativity of increment and decrement operators? Ans: Right to Left Q25) What is an increment operator? Ans: The operator which automatically increments the the value by one. Q26) How many types of increment operators exist in C ? Ans: Two types. Q27) What are the two types of increment operators exist in C ? Ans : Post increment and pre increment. Q28) Which is a pre / post increment operator? Ans: ++ Q29) Give an example for usage of pre increment operator Ans: ++a Q30) Give an example for usage of post increment operator Ans: a++ Q31) What is post increment operator? Ans : An operator which increments the value of a variable after the operation Q32) What is pre increment operator? Ans : An operator which increments the value of a variable before the operation. Q33) What is a decrement operator? Ans: The operator which automatically reduce the value by one. Q34) How many types of decrement operators exist in C ? Ans: Two types. Q35) What are the two types of decrement operators exist in C ? Ans : Post decrement and pre decrement. Q36) Give an example for usage of pre decrement and post decrement operator? Ans: --a & a--; Q37) What is the value of m and y in the below expression? m = 5; y = ++m; Ans: m=6,y=6. Q38) What is the value of m and y in the below expression? m = 5; y = m++; Ans: y=5, m=6. Q39) Which is a conditional operator? Ans: A ternary operator (? :) is a conditional operator. Which is an alternate for if else statement. Q40) What is the associativity of a conditional operator? Ans: Right to Left Q41) What will be the value of x after evaluating the following expression? a=10; b=15; x= (a>b)?a:b; Ans: 15 Q41) How many bitwise operators exist in C ? Ans: Six. Q42) What are the different Bit wise operators? ans: Bit wise AND(&), bit wise OR(|), bit wise exclusive OR(^), shift left(<<), shift right (>>), and One’s complement ( ~) are called Bit wise operators. Q43) What is the associativity of bitwise operators? Ans: Left to Right. Output Prediction: 1. What will be output of the following c program? #include int main() { int goto=5; printf("%d",goto); return 0; } 2. What will be output of the following c program? #include int main() { long int 1a=5l; printf("%ld",1a); return 0; } 3. What will be output of the following c program? #include int main() { int max-val=100; int min-val=10; int avg-val; avg-val = max-val + min-val / 2; printf("%d",avg-val); return 0; } 4. What will be output of the following c program? #include int main() { int class=150, public=25, private=30; class = class >> private - public; printf("%d",class); return 0; } 5. What will be output of the following program? #include int main() { int i=1; i=2+2*i++; printf("%d",i); return 0; } 6. What will be output of the following program? #include int main() { int a=2,b=7,c=10; c=a==b; printf("%d",c); return 0; } 7. What will be output of the following program? #include void main() { int x; x=10,20,30; printf("%d",x); return 0; } 8. What will be output of the following program? #include int main() { int a; a=015 + 0x71 +5; printf("%d",a); return 0; } 9. What will be output of the following program? #include int main() { printf("%d %d %d",sizeof(3.14),sizeof(3.14f),sizeof(3.14L)); return 0; } 10. What will be output of the following program? #include int main() { int a=2; a=a++ + ~++a; printf("%d",a); return 0; } 11. What will be output of the following program? #include int main() { int a; a=sizeof(!5.6); printf("%d",a); return 0; } 12. What will be output of the following program? #include int main() { float a; (int)a= 45; printf("%d,a); return 0; } 13. What will be output of the following program? #include int main() { int i=5; int a=++i + ++i + ++i; printf("%d",a); return 0; } 14. What will be output of the following program? #include int main() { int x=100,y=20,z=5; printf("%d %d %d"); return 0; }

3. CONTROL STATEMENTS 3.1 DECISION MAKING IN C C program executes program sequentially. Sometimes, a program requires checking of certain conditions in program execution. C provides various key condition statements to check condition and execute statements according conditional criteria. These statements are called as 'Decision Making Statements' or 'Conditional Statements.' Followings are the different conditional statements used in C. 1. if Statement 2. if-else Statement 3. Nested if-else Statement 4. Switch Case 3.1.1 if Statement Syntax: if (test expression) { statement/s to be executed if test expression is true; }

If the test expression is true then, statements for the body if, i.e, statements inside parenthesis are executed. But, if the test expression is false, the execution of the statements for the body of if statements are skipped. e.g. int main() { int a=40,b=40; if (a == b) { printf("a and b are equal"); } } Output: a and b are equal Flowchart of if Statement if...else Statement The if...else statement is used, if the programmer wants to execute some code, if the test expression is true and execute some other code if the test expression is false. Syntax: if (test expression) { statements to be executed if test expression is true; } else { statements to be executed if test expression is false; } e.g. int main() { int a=40,b=20; if (a == b) { printf("a and b are equal"); } else { printf("a and b are not equal"); } } Output: a and b are not equal

Flowchart of if...else Statement

Nested if-else Statement Syntax: if (test expression) statements to be executed if test expression is true; else if(test expression 1) statements to be executed if test expressions 1 is true; else if (test expression 2) . . . else statements to be executed if all test expressions are false; If the test expression is true, it will execute the code before else part but, if it is false, the control of the program jumps to the else part and check test expression 1 and the process continues. If all the test expression are false then, the last statement is executed. The ANSI standard specifies that 15 levels of nesting may be continued. e.g. #include int main() { int a=40,b=20; if (a>b) { printf("a is greater than b"); } else if(a

Nested if-else Flowchart:

3.1.2 switch – case Statement The switch statement is very powerful decision making statement. A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. It reduces the complexity of the program. Hence increases the readability of the program. Syntax: switch(expression) { case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : statement(s); /* Optional */

} The following rules apply to a switch statement:  The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.  You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.  The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.  When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.  When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.  Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.  A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. e.g. #include int main () { char grade = 'B'; switch(grade) { case 'A' : printf("Excellent!\n" ); break; case 'B' : case 'C' : printf("Well done\n" ); break; case 'D' : printf("You passed\n" ); break; case 'F' : printf("Better try again\n" ); break; default : printf("Invalid grade\n" ); } printf("Your grade is %c\n", grade ); return 0; } Output: Well done Your grade is B Flowchart for switch – case Statement:

3.2 LOOPING STATEMENTS / ITERATIVE STATEMENTS 'A loop' is a part of code of a program which is executed repeatedly. A loop is used using condition. The repetition is done until condition becomes condition true. A loop declaration and execution can be done in following ways. 1. Check condition to start a loop 2. Initialize loop with declaring a variable. 3. Executing statements inside loop. 4. Increment or decrement of value of a variable. 3.2.1 Types of looping statements Basically, the types of looping statements depend on the condition checking mode. Condition checking can be made in two ways as: Before loop and after loop. So, there are 2(two) types of looping statements.  Entry controlled loop  controlled loop 1. Entry controlled loop : In such type of loop, the test condition is checked first before the loop is executed. Some common examples of this looping statements are : 1. while loop 2. for loop 2. Exit controlled loop : In such type of loop, the loop is executed first. Then condition is checked after block of statements are executed. The loop executed at least one time. Some common example of this looping statement is :

1. do-while loop while loop Statement Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. Syntax: while( test condition) { statement(s); } In the beginning of while loop, test expression is checked. If it is true, codes inside the body of while loop, i. e., code/s inside parentheses are executed and again the test expression is checked and process continues until the test expression becomes false. e.g. /*C program to demonstrate the working of while loop*/ #include int main() { int n,fact; printf("Enter a number: \n"); scanf("%d",&n); fact=1; while (n > 0) { /* while loop continues until test condition n > 0 is true */ fact=fact*n; --n; } printf("Factorial=%d", fact); return 0; } Output: Enter a number: 5 Factorial=120

Flowchart for while loop

do … while loop Statement Like a while statement, except that it tests the condition at the end of the loop body. Syntax: do { Statement1; ... Statement n; }while(condition); e.g. #include main() { int i = 5;

do{ printf("Hello %d\n", i ); i = i -1; }while ( i > 0 ); } Output: Hello 5 Hello 4 Hello 3 Hello 2 Hello 1 Flowchart for do…while loop

for loop Statement Syntax: for(initial expression; test expression; update expression) { code/s to be executed; } The initial expression is initialized only once at the beginning of the for loop. Then, the test expression is checked by the program. If the test expression is false, for loop is terminated. But, if test expression is true then, the codes are executed and update expression is updated. Again, the test expression is checked. If it is false, loop is terminated and if it is true, the same process repeats until test expression is false. e.g. #include int main() { int i;

for(i=1;i<6;i++) { printf("%d\n",i); } } Output: 1 2 3 4 5 Flowchart for for loop

3.3 SPECIAL CONTROL STATEMENTS: BREAK , CONTINUE, RETURN AND GOTO STATEMENTS C provides two commands to control how we loop:  break -- exit form loop or switch.  continue -- skip 1 iteration of loop. The execution of break statement causes immediate exit from the concern construct and the control is transferred to the statement following the loop. Execution of continue statement does not cause an exit from the loop but it suspend the execution of the loop for that iteration and transfer control back to the loop for the next iteration. e.g. for break statement: #include int main () { int a = 10;

while( a < 20 ) { printf("value of a: %d\n", a); a++; if( a > 15) { break; } }

return 0; } Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 e.g. for continue statement: #include main() { int i; int j = 10;

for( i = 1; i <= j; i++ ) { if( i == 5 ) { continue; } printf("Hello %d\n", i ); } } Output: Hello 1 Hello 2 Hello 3 Hello 4 Hello 6 Hello 7 Hello 8 Hello 9 Hello 10 Flowchart of break Statement:

Working of break statement in all types of loops:

Flowchart of continue Statement:

Working of continue statement in all types of loops:

return statement A return statement is used to return from a function. A function can use this statement as a mechanism to return a value to its calling function. If no value is specified, a garbage value is returned (some compilers will return 0).

The general form of return statement is:

return expression;

Where expression is any valid rvalue expression.

Example:

return x; or return(x); return x + y or return(x + y); return rand(x); or return(rand(x)); return 10 * rand(x); or return (10 * rand(x));

We can use as many return statements as we like within a function. However, the function will stop executing as soon as it encounters the first return. The } that ends a function also causes the function to return. It is same way as return without any specified value.

A function declared as void should not return a value. But it may contain a simple return statement(i.e. return; goto statement: goto statement provides a method of unconditional transfer control to a labeled point in the program. The goto statement requires a destination label declared as:

label:

The label is a word (permissible length is machine dependent) followed by a colon. The goto statement is formally defined as: goto label; … … … label: … …

Since, C has a rich set of control statements and allows additional control using break and continue, there is a little need for goto. The chief concern about the goto is its tendency to render programs unreachable. Rather, its a convenience, it used wisely, can be a benefit in a narrow set of programming situations. So the usage of goto is highly discouraged.

Example:

void main() { int x, y, z; printf(“\n Enter the value of x and y”); scanf(“%d%d”, &x, &y); if( y == 0 ) goto ERROR; else printf(“ \n Div = %d”,x/y) ERROR : Printf(“\n Divide by zero error “);

}

The compiler doesn’t require any formal declaration of the label identifiers. MULTIPLE CHOICE QUESTIONS 1) What will be the output of the following program : void main() { int i=1; for (; i<4; i++); printf("%d\n",i); } a.No Output b. 1 c. 4 d. None of these 2 3

2) What will be the output of the following program : void main() { int a,b; for (a=0; a<10; a++); for (b=25; b>9; b-=3); printf("%d %d",a,b); } a. Compile-Time error b. 10 9 c.10 7 d. None of these

3)What will be the output of the following program : void main { float i; for (i=0.1; i<0.4; i+=0.1) printf("%.1f",i); } a. 0.10.20.3 b. Compile-Time Error c. Run-Time Error d. No Output

4) What will be the output of the following program : void main() { int i; for (i=-10; !i; i++); printf("%d",-i); } a. 0 b. Compile-Time Error c.10 d. No Output

5) What will be the output of the following program : void main() { int i=5; do; printf("%d",i--); while (i>0); } a. 5 b. 54321 c. Compile-Time Error d. None of these

6) What will be the output of the following program : void main() { int i; for (i=2,i+=2; i<=9; i+=2) printf("%d",i); } a. Compile-Time error b. 2468 c. 468 d. None of these

7) What will be the output of the following program : void main() { int i=3; for (i--; i<7; i=7) printf("%d",i++); } a. No Output b. 3456 c. 23456 d. None of these.

8) What will be the output of the following program : void main() { int i; for (i=5; --i;) printf("%d",i); } a. No Output b. 54321 c. 4321 d. None of these

9) What will be the output of the following program : void main() { for (;printf("");); } a. Compile-Time error b. Executes ONLY once c. Executes INFINITELY d. None of these

10)What will be the output of the following program : void main() { int i; for (;(i=4)?(i-4):i++;) printf("%d",i); } a. Compile-Time error b. 4 c . Infinite Loop d.No Output 11) What will be the output of the following program : void main() { printf("Hi!"); if (-1) printf("Bye"); } a. No Output b. Hi! C. Bye d.Hi!Bye

12) What will be the output of the following program : void main() { printf("Hi!"); if (0 || -1) printf("Bye"); } a. No Output b. Hi! C. Bye d. Hi!Bye

13) What will be the output of the following program : void main() { printf("Hi!"); if (!1) printf("Bye"); } a. Compile-Time error b. Hi! c. Bye d. Hi!Bye

14) What will be the output of the following program : void main() { printf("Hi!"); if !(0) printf("Bye"); } a. Compile-Time error b. Hi! c .Bye d. Hi!Bye

15) What will be the output of the following program : void main() { printf("Hi!"); if (-1+1+1+1-1-1-1+(-1)-(-1)) printf("Bye"); } a. No Output b. Hi! c. Bye d. Hi!Bye

16) What will be the output of the following program : void main() { if (sizeof(int) &&sizeof(float) &&sizeof(float)/2-sizeof(int)) printf("Testing"); printf("OK"); } a. No Output b. OK c. Testing d. TestingOK

17) What will be the output of the following program : void main() { int a=1,b=2,c=3,d=4,e; if (e=(a & b | c ^ d)) printf("%d",e); } a. 0 b. 7 c. 3 d. No Output

18) What will be the output of the following program : void main() { unsigned val=0xffff; if (~val) printf("%d",val); printf("%d",~val); } a. Compile-Time error b. -1 c. 0 d. -1 0

19) What will be the output of the following program : void main() { unsigned a=0xe75f,b=0x0EF4,c; c=(a|b); if ((c > a) && (c > b)) printf("%x",c); } a. No Output b. 0xe75f c. 0xefff d. None of these

20) What will be the output of the following program : void main() { unsignedval=0xabcd; if (val>>16 | val<<16) { printf("Success"); return; } printf("Failure"); } a. No Output b. Success c. Failure d. SuccessFailure

21) What will be the output of the following program : void main() { unsigned x=0xf880,y=5,z; z=x<>y-1); } a. 1000 f87 b. 8800 0xf88 c. 1000 f88 d. 0x1000 0xf88

22) What will be the output of the following program : void main() { register int a=5; int *b=&a; printf("%d %d",a,*b); } a. Compile-Time error b. Run-Time error c. 5 5 d. Unpredictable

23) What will be the output of the following program : autoint a=5; void main() { printf("%d",a); } a. Compile-Time error b. Run-Time error c. 5 d. Unpredictable

24) What will be the output of the following program : void main() { autoint a=5; printf("%d",a); } a. Compile-Time error b. Run-Time error c. 5 d. Unpredictable

25) What will be the output of the following program : void main() { int a=1,b=2,c=3,d=4; if (d > c) if (c > b) printf("%d %d",d,c); else if (c > a) printf("%d %d",c,d); if (c > a) if (b < a) printf("%d %d",c,a); else if (b < c) printf("%d %d",b,c);

} a. 4 3 3 4 b. 4 3 3 2 c. 4 32 3 d. 4 33 1

26) What will be the output of the following program : void main() { int a=1,b=2,c=3,d=4; if (d > c) if (c > b) printf("%d %d",d,c); if (c > a) printf("%d %d",c,d); if (c > a) if (b < a) printf("%d %d",c,a); if (b < c) printf("%d %d",b,c);

} a. 4 32 3 b. 4 33 42 3 c. 4 3 3 4 2 3 d. None of these

27) What will be the output of the following program : void main() { int a=1; if (a == 2); printf("C Program"); } a. No Output b . C Program c. Compile-Time Error d. none of these

28) What will be the output of the following program : void main() { int a=1; if (a) printf("Test"); else; printf("Again"); } a. Again b. Test c. Compile-Time Error d. TestAgain

29) What will be the output of the following program void main() { int choice=3;

switch(choice) { default: printf("Default");

case 1: printf("Choice1"); break; case 2: printf("Choice2"); break; } } a. No Output b. Default c. DefaultChoice1 d. None of these

30) What will be the output of the following program : void main() { staticint choice; switch(--choice,choice-1,choice-1,choice+=2) { case 1: printf("Choice1"); break;

case 2: printf("Choice2"); break;

default: printf("Default"); } } a. Choice1 b. Choice2 c. Default d. None of these

OUTPUT PREDICTION

(1) What will be output of following c code? #include extern int x; int main() { do { do { printf("%o",x); }while(!-2); }while(0); return 0; } int x=8;

(2) What will be output of following c code #include int main() { int i=2,j=2; while(i+1?--i:j++) printf("%d",i); return 0; }

(3) What will be output of following c code? #include int main() { int x=011,i; for(i=0;i

4) What will be output of following c code? #include int main() { int i,j; i=j=2,3; while(--i&&j++) printf("%d %d",i,j); return 0; }

(5) What will be output of following c code? #include int main() { staticint i; for(++i;++i;++i) { printf("%d ",i); if(i==4) break; } return 0; }

(6) What will be output of following c code? #include int main() { int i=1; for(i=0;i=-1;i=1) { printf("%d ",i); if(i!=1) break; } return 0; }

(7) What will be output of following c code? #include int main() { for(;;) { printf("%d ",10); } return 0; }

(8) What will be output of following c code? #include #define p(a,b) a##b #define call(x) #x int main() { do { int i=15,j=3; printf("%d",p(i-+,+j)); }while(*(call(625)+3)); return 0; }

(9) #include int main() { int i; for(i=0;i<=5;i++); printf("%d",i) return 0; } (10) What will be output of following c code? #include int i=40; extern int i; int main() { do { printf("%d",i++); }while(5,4,3,2,1,0); return 0; } (11) What will be output of following c code? #include int main() { int i; for(i=10;i<=15;i++) { while(i) { do { printf("%d ",1); if(i>>1) continue; }while(0); break; } } return 0; }

(12) How many times this loop will execute? #include int main() { char c=125; do printf("%d ",c); while(c++); return 0; }

(13) What will be output of following c code? #include int main() { int x=123; int i; { printf("c" "++") }; for(x=0;x<=i;x++) { printf("%x ",x); } return 0; }

5. FUNCTIONS 5.1 INTRODUCTION TO FUNCTIONS A large C program is divided into basic building blocks called a function. C function contains set of instructions enclosed by “{ }” which performs specific operation in a program.  Functions can be invoked from anywhere within a program.  main() function is the function from where every C program is started to execute.  Name of the function is unique in a C program. In other words, a function is a module or block of program code which deals with a particular task. It is a self contained block of statements which performs a coherent task of a same kind. C program does not execute the functions directly. It is required to invoke or call that functions. When a function is called in a program then program control goes to the function body. Then, it executes the statements which are involved in a function body. Therefore, it is possible to call function whenever we want to process that functions statements. Structure of a Function: data_type function_name (parameters) { Body of function; } e.g. int add (int a , int b) { int sum; sum = a+b; return sum; } Where,

Before calling and defining a function, we have to declare function prototype in order to inform the compiler about the function name, function parameters and return value type. e.g. #include float square ( float x ); // function prototype, also called function declaration int main( ) // main function, program starts from here {

float m, n ; printf ( "\n Enter a number for finding square: "); scanf ( "%f", &m ) ; n = square ( m ) ; // function call printf ( "\nSquare of the given number %f is %f",m,n );

} float square ( float x ) // function definition { float p ; p = x * x ; return ( p ) ; } Output: Enter a number for finding square: 2 Square of the given number 2.000000 is 4.000000 5.2 TYPES OF FUNCTION There are 2(two) types of functions as: 1. Built in Functions 2. User Defined Functions Built in/Library Functions: There are many inbuilt functions available in C language. We can directly use of these inbuilt functions in our C program to get the predefined outputs instead of writing our own function to get those outputs. In particular, all input and output operations (e.g., writing to the terminal) and all math operations (e.g., evaluation of sines and cosines) are implemented by library functions. In order to use a library function, it is necessary to call the appropriate header file at the beginning of the program. The header file informs the program of the name, type, and number and type of arguments, of all of the functions contained in the library in question. A header file is called via the preprocessor statement. #include where filename represents the name of the header file. A library function is accessed by simply writing the function name, followed by a list of arguments, which represent the information being passed to the function. The arguments must be enclosed in parentheses, and separated by commas: they can be constants, variables, or more complex expressions. Note that the parentheses must be present even when there are no arguments. 1. stdio.h: I/O functions: 1. getchar() returns the next character typed on the keyboard. 2. putchar() outputs a single character to the screen. 3. printf() as previously described 4. scanf() as previously described 2. string.h: String functions 1. strcat() concatenates a copy of str2 to str1 2. strcmp() compares two strings 3. strcpy() copies contents of str2 to str1 3. ctype.h: Character functions 1. isdigit() returns non-0 if argument is digit 0 to 9 2. isalpha() returns non-0 if argument is a letter of the alphabet 3. isalnum() returns non-0 if argument is a letter or digit 4. islower() returns non-0 if argument is lowercase letter 5. isupper() returns non-0 if argument is uppercase letter 4. math.h: Mathematics functions 1. acos() returns arc cosine of argument 2. asin() returns arc sine of argument 3. atan() returns arc tangent of argument 4. cos() returns cosine of argument 5. exp() returns natural logarithmic 6. fabs() returns absolute value of num 7. sqrt() returns square root of num 5. time.h: Time and Date functions 1. time() returns current calendar time of system 2. difftime() returns difference in seconds between two times 3. clock() returns number of system clock cycles since program execution 6. stdlib.h: Miscellaneous functions 1. malloc() provides dynamic memory allocation, covered in future sections 2. rand() as already described previously 3. srand() used to set the starting point for rand() 5.3 USER DEFINED FUNCTIONS C provides programmer to define their own function according to their requirement known as user defined functions. Suppose, a programmer wants to find factorial of a number and check whether it is prime or not in same program. Then, he/she can create two separate user-defined functions in that program: one for finding factorial and other for checking whether it is prime or not. Syntax: #include void function_name() { ...... } int main() { ...... function_name(); ...... } Every C program begins from main() and program starts executing the codes inside main() function. When the control of program reaches to function_name() inside main() function. The control of program jumps to void function_name() and executes the codes inside it. When, all the codes inside that user-defined function are executed, control of the program jumps to the statement just after function_name() from where it is called.

e.g. #include int add(int a, int b); //function prototype(declaration) int main() { int num1,num2,sum; printf("Enters two number to add\n"); scanf("%d %d",&num1,&num2); sum=add(num1,num2); //function call printf("sum=%d",sum); return 0; } int add(int a,int b) //function declaratory { int add; add=a+b; return add; //return statement of function } 5.3.1 Advantages of User Defined Functions 1. User defined functions helps to decompose the large program into small segments which makes programmar easy to understand, maintain and debug. 2. If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function. 3. Programmar working on large project can divide the workload by making different functions. 5.3.2 Function prototype (declaration) Every function in C programming should be declared before they are used. This type of declaration are also called function prototype. Function prototype gives compiler information about function name, type of arguments to be passed and return type. Syntax of function prototype return_type function_name(type(1) argument(1),....,type(n) argument(n)); e.g. int add(int a, int b); is a function prototype which provides following information to the compiler: 1. name of the function is add() 2. return type of the function is int. 3. two arguments of type int are passed to function. Function prototype are not needed if user-definition function is written before main() function. 5.4 CALLING A FUNCTION There are two ways that a C function can be called from a program. They are, 1. call by value 2. call by reference 5.4.1 call by value Arguments are passed by value while calling a function in C program. e.g. #include void swap(int a, int b); // function prototype, also called function declaration int main() { int m = 22, n = 44; printf(" values before swap m = %d and n = %d", m, n); // calling swap function by value swap(m, n); } void swap(int a, int b) { int tmp; tmp = a; a = b; b = tmp; printf(" \nvalues after swap m = %d\n and n = %d", a, b); } Output: values before swap m = 22 and n = 44 values after swap m = 44 and n = 22 5.4.2 call by reference Arguments are passed by address while calling a function in C program. e.g. #include void swap(int *a, int *b); // function prototype, also called function declaration int main() { int m = 22, n = 44; printf("values before swap m = %d and n = %d",m,n); // calling swap function by reference swap(&m, &n); } void swap(int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; printf("\n values after swap a = %d and b = %d", *a, *b); } Output: values before swap m = 22 and n = 44 values after swap a = 44 and b = 22 How many values can be returned from a function at a time? Only one value can be returned. If you want to return more than one values, pointers can be used. 5.4.3 Advantages of writing functions 1. Modular and Structural Programming can be done: we can divide a program into smaller modules and we can call a module whenever required. Modular programming makes a program more readable and it enhances re-useablitity. 2. It follows -Down execution approach, so main() can be kept small: Every C program starts from main() function and every function is called directly or indirectly through main(). 5.5 TYPES OF USER-DEFINED FUNCTIONS For better understanding of arguments and return in functions, user-defined functions can be categorized as: 1. Function with no arguments and no return value 2. Function with no arguments and return value 3. Function with arguments but no return value 4. Function with arguments and return value. Let's take an example to find whether a number is prime or not using above 4 categories of user defined functions. 5.5.1 Function with no arguments and no return value /*C program to check whether a number entered by user is prime or not using function with no arguments and no return value*/ #include void prime(); int main() { prime(); //No argument is passed to prime(). return 0; } void prime() { int num,i,flag=0; printf("Enter positive integer enter to check:\n"); scanf("%d",&num); for(i=2;i<=num/2;++i) { if(num%i==0) { flag=1; } } if (flag==1) printf("%d is not prime",num); else printf("%d is prime",num); } Function prime() is used for asking user a input, check for whether it is prime of not and display it accordingly. No argument is passed and returned from prime() function. 5.5.2 Function with no arguments and return value /*C program to check whether a number entered by user is prime or not using function with no arguments but having return value */ #include int input(); int main() { int num,i,flag; num=input(); /* No argument is passed to input() */ for(i=2,flag=i;i<=num/2;++i,flag=i){ if(num%i==0) { printf("%d is not prime",num); ++flag; break; } } if(flag==i) printf("%d is prime",num); return 0; } int input() { int n; printf("Enter positive enter to check:\n"); scanf("%d",&n); return n; } There is no argument passed to input() function But, the value of n is returned from input() to main() function. 5.5.3 Function with arguments but no return value /*Program to check whether a number entered by user is prime or not using function with arguments and no return value */ #include void check_display(int n); int main() { int num; printf("Enter positive enter to check:\n"); scanf("%d",&num); check_display(num); /* Argument num is passed to function. */ return 0; } void check_display(int n) { int i,flag; for(i=2,flag=i;i<=n/2;++i,flag=i) { if(n%i==0) { printf("%d is not prime",n); ++flag; break; } } if(flag==i) printf("%d is prime",n); } Here, check_display() function is used for check whether it is prime or not and display it accordingly. Here, argument is passed to user-defined function but, value is not returned from it to calling function. 5.5.4 Function with arguments and return value /* Program to check whether a number entered by user is prime or not using function with argument and return value */

#include int check(int n); int main() { int num,num_check=0; printf("Enter positive enter to check:\n"); scanf("%d",&num); num_check=check(num); /* Argument num is passed to check() function. */ if(num_check==1) printf("%d in not prime",num); else printf("%d is prime",num); return 0; } int check(int n) { int i; for(i=2;i<=n/2;++i) { if(n%i==0) return 1; } return 0; } Here, check() function is used for checking whether a number is prime or not. In this program, input from user is passed to function check() and integer value is returned from it. If input the number is prime, 0 is returned and if number is not prime, 1 is returned. 5.6 RECURSIVE FUNCTIONS A function that calls itself is known as recursive function and the process of calling function itself is known as recursion in C programming. e.g. Write a C program to find sum of first n natural numbers using recursion. Note: Positive integers are known as natural number i.e. 1, 2, 3....n #include int sum(int n); int main() { int num,add; printf("Enter a positive integer:\n"); scanf("%d",&num); add=sum(num); printf("sum=%d",add); } int sum(int n) { if(n==0) return n; else return n+sum(n-1); /*self call to function sum() */ } Output: Enter a positive integer:5 15 In, this program, sum() function is invoked from the same function. If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous argument it was called with. Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1. sum(5) =5+sum(4) =5+4+sum(3) =5+4+3+sum(2) =5+4+3+2+sum(1) =5+4+3+2+1+sum(0) =5+4+3+2+1+0 =5+4+3+2+1 =5+4+3+3 =5+4+6 =5+10 =15 Every recursive function must be provided with a way to end the recursion i.e. called the stopping case or base case.. In this example when, n is equal to 0, there is no recursive call and recursion ends. 5.6.1 Recursion Versus Iteration In iteration repetition structure is explicitly used whereas in recursion the same function is invoked by itself. Both recursion and iteration go through the termination test. Iteration terminates when the loop continuation condition fails. The recursion also terminates when the test for termination is satisfied. Both iteration and recursion can be executed infinitely. When recursion and iteration are defined without termination condition, they turn to infinite loop. Recursion has several overheads. Each time a function is executed, a new copy of function is created. Memory is occupied by the functions. In iteration only once the variable is created. Thus, iteration is very useful and efficient as compared to recursion. However, there are a few problems that cannot be solved with iteration, and recursion perfectly works. 5.6.2 Rules for Recursive Function 1. In recursion, it is essential to call a function itself, otherwise recursion would not take place. 2. Only the user-defined function can be involved in the recursion. Library function cannot be involved in recursion because their source code cannot be viewed. 3. A recursive function can be invoked by itself or by other function. It saves return address with the intention to return at proper location when return to a calling statement is made. The last-in-first-out nature of recursion indicates that stack data structure can be used to implement it. 4. Recursion is turning out to be increasingly important in non-numeric applications and symbolic manipulations. 5. To stop the recursive function, it is necessary to base the recursion on test condition, and proper terminating statement such as exit() or return must be written . 5.6.3 Direct Versus Indirect Recursion In direct recursion, only one function is involved which calls itself until the given condition is true. In Indirect recursion, two or more functions are involved in the recursion. The indirect recursion does not make any overhead as direct recursion. When control exits from one function and enter into another function, the local variables of former function are destroyed. Hence, memory is not engaged. 5.6.4 Advantages and Disadvantages of Recursion Advantages: 1. Recursion is more elegant and requires few variables which make program clean. 2. Recursion can be used to replace complex nesting code by dividing the problem into same problem of its sub-type. 3. Using recursion, the length of the program can be reduced. Disadvantages: 1. It requires extra storage space. The recursive calls and automatic variables are stored on the stack. For every recursive calls separate memory is allocated to automatic variables with the same name. 2. The recursion function is not efficient in execution speed and time. 5.7 STORAGE CLASS Every variable and function in C programming has two properties: type and storage class. Type refers to the data type of variable whether it is character or integer or floating-point value etc. There are 4 types of storage class: 1. automatic 2. external 3. static 4. register 5.7.1 Automatic storage class (Keyword: auto) Variables declared inside the function body are automatic by default. These variable are also known as local variables as they are local to the function and doesn't have meaning outside that function Since, variable inside a function is automatic by default, keyword auto are rarely used. 5.7.2 External storage class External variable can be accessed by any function. They are also known as global variables. Variables declared outside every function are external variables. In case of large program, containing more than one file, if the global variable is declared in file 1 and that variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is used in file 2 to indicate that, the variable specified is global variable and declared in another file. e.g. #include void Check(); int a=5; /* a is global variable because it is outside every function */ int main() { a+=4; Check(); return 0; } void Check() { ++a; /* Variable a is not declared in this function but, works in any function as they are global variable */

printf("a=%d\n",a); } Output: a=10 5.7.3 Register Storage Class Register variables are similar to automatic variable and exists inside that particular function only. If the compiler encounters register variable, it tries to store variable in microprocessor's register rather than memory. Values stored in register are much faster than that of memory. In case of larger program, variables that are used in loops and function parameters are declared register variables. Since, there are limited number of register in processor and if it couldn't store the variable in register, it will automatically store it in memory. 5.7.4 Static Storage Class (Keyword: static) The value of static variable persists until the end of the program. A variable can be declared static using keyword: static. For example: static int i; Here, i is a static variable. #include void Check(); int main() { Check(); Check(); Check(); } void Check(){ static int c=0; printf("%d\t",c); c+=5; } Output: 0 5 10 During first function call, it will display 0. Then, during second function call, variable c will not be initialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10 in third call. If variable c had been automatic variable, the output would have been: 0 0 0 Function Examples: /*C program to find the factorial of a number*/ #include long factorial(int); int main() { int number; long fact = 1; printf("Enter a number to calculate it's factorial\n"); scanf("%d", &number); printf("%d! = %ld\n", number, factorial(number)); return 0; } long factorial(int n) { int c; long result = 1; for (c = 1; c <= n; c++) result = result * c; return result; } Output: Enter a number to calculate it's factorial 7 7! = 5040 Program to Display Prime Numbers between Intervals This program takes two positive integers from user and displays all prime numbers between these two intervals. To perform this task, user-defined function is created which will check whether a number is prime or not. #include int check_prime(int num); int main() { int n1,n2,i,flag; printf("Enter two numbers(intervals): "); scanf("%d %d",&n1, &n2); printf("Prime numbers between %3d and %3d are: ", n1, n2); for(i=n1+1;i int prime(int n); int main() { int n, i, flag=0; printf("Enter a positive integer: "); scanf("%d",&n); for(i=2; i<=n/2; ++i) { if (prime(i)!=0) { if ( prime(n-i)!=0) { printf("%d = %d + %d\n", n, i, n-i); flag=1; } } } if (flag==0) printf("%d can't be expressed as sum of two prime numbers.",n); return 0; } int prime(int n) /* Function to check prime number */ { int i, flag=1; for(i=2; i<=n/2; ++i) if(n%i==0) flag=0; return flag; } Enter a positive integer: 100 100 = 3 + 97 100 = 11 + 89 100 = 17 + 83 100 = 29 + 71 100 = 41 + 59 100 = 47 + 53 Program to Check Prime and Armstrong Number by Making Function In this program, user is asked to enter a positive integer and a character either 'p' or 'a'. If user enters p then, this program checks whether that number is prime or not and if user enters a then, this program checks whether that number is an Armstrong number or not. To perform this task, two user-defined functions are defined to check prime number and Armstrong number. /* C program to check either prime number or Armstrong number depending upon the data entered by user. */ #include #include int prime(int n); int armstrong(int n); int main() { char c; int n,temp=0; printf("Enter a positive integer: "); scanf("%d",&n); printf("Enter P to check prime and A to check Armstrong number: "); c=getche(); if (c=='p' || c=='P') { temp=prime(n); if(temp==1) printf("\n%d is a prime number.", n); else printf("\n%d is not a prime number.", n); } if (c=='a' || c=='A') { temp=armstrong(n); if(temp==1) printf("\n%d is an Armstrong number.", n); else printf("\n%d is not an Armstrong number.",n); } return 0; } int prime(int n) { int i, flag=1; for(i=2; i<=n/2; ++i) { if(n%i==0) { flag=0; break; } } return flag; } int armstrong(int n) { int num=0, temp, flag=0; temp=n; while(n!=0) { num+=(n%10)*(n%10)*(n%10); n/=10; } if (num==temp) flag=1; return flag; } /* Enter a positive integer: 153 Enter P to check prime and A to check Armstrong number: p 153 is not a prime number. Enter a positive integer: 153 Enter P to check prime and A to check Armstrong number: a 153 is an Armstrong number. */ Program to Find Sum of Natural Numbers using Recursion In this program, user is asked to enter a positive integer and sum of natural numbers up to that integer is displayed by this program. Suppose, user enters 5 then, Sum will be equal to 1+2+3+4+5 = 15 #include int add(int n); int main() { int n; printf("Enter an positive integer: "); scanf("%d",&n); printf("Sum = %d",add(n)); return 0; } int add(int n) { if(n!=0) return n+add(n-1); /* recursive call */ } Output: Enter an positive integer: 10 Sum = 210 Program to Find factorial of a number using Recursion /*C program to find the factorial of a number using recursion*/ #include long factorial(int); int main() { int n; long f; printf("Enter an integer to find factorial\n"); scanf("%d", &n); if (n < 0) printf("Negative integers are not allowed.\n"); else { f = factorial(n); printf("%d! = %ld\n", n, f); } return 0; } long factorial(int n) { if (n == 0) return 1; else return(n * factorial(n-1)); } Output: Enter an integer to find factorial -5 Negative integers are not allowed.

Enter an integer to find factorial 7 7! = 5040 Program to Calculate Factorial of a Number Using Recursion This program takes a positive integer from user and calculates the factorial of that number. Instead of loops to calculate factorial, this program uses recursive function to calculate the factorial of a number. /* Source code to find factorial of a number. */

#include int factorial(int n); int main() { int n; printf("Enter an positive integer: "); scanf("%d",&n); printf("Factorial of %d = %ld", n, factorial(n)); return 0; } int factorial(int n) { if(n!=1) return n*factorial(n-1); } Output: Enter an positive integer: 6 Factorial of 6 = 720 Program to Find H.C.F or GCD Using Recursion This program takes two positive integers from user and calculates HCF or GCD using recursion. /* Example to calculate GCD or HCF using recursive function. */ #include int hcf(int n1, int n2); int main() { int n1, n2; printf("Enter two positive integers: "); scanf("%d%d", &n1, &n2); printf("H.C.F of %d and %d = %d", n1, n2, hcf(n1,n2)); return 0; } int hcf(int n1, int n2) { if (n2!=0) return hcf(n2, n1%n2); else return n1; } Output: Enter two positive integers: 366 60 H.C.F of 366 and 60 = 6 Program to Reverse a Sentence Using Recursion This program takes a sentence from user and reverses that sentence using recursion. This program does not use string to reverse the sentence or store the sentence. /* Example to reverse a sentence entered by user without using strings. */ #include void Reverse(); int main() { printf("Enter a sentence: "); Reverse(); return 0; } void Reverse() { char c; scanf("%c",&c); if( c != '\n') { Reverse(); printf("%c",c); } } Output: Enter a sentence: margorp emosewa awesome program Program to Calculate the Power of a Number Using Recursion This program takes two integers from user ( base number and a exponent) and calculates the power. Instead of using loops to calculate power, this program uses recursion to calculate the power of a number. /* Source Code to calculate power using recursive function */ #include int power(int n1,int n2); int main() { int base, exp; printf("Enter base number: "); scanf("%d",&base); printf("Enter power number(positive integer): "); scanf("%d",&exp); printf("%d^%d = %d", base, exp, power(base, exp)); return 0; } int power(int base,int exp) { if ( exp!=1 ) return (base*power(base,exp-1)); } Output: Enter base number: 3 Enter power number(positive integer): 3 3^3 = 27 Program to Convert Binary Number to Decimal and Decimal to Binary This program converts either binary number entered by user to decimal number or decimal number entered by user to binary number in accordance with the character entered by user. /* C programming source code to convert either binary to decimal or decimal to binary according to data entered by user. */

#include #include int binary_decimal(int n); int decimal_binary(int n); int main() { int n; char c; printf("Instructions:\n"); printf("1. Enter alphabet 'd' to convert binary to decimal.\n"); printf("2. Enter alphabet 'b' to convert decimal to binary.\n"); scanf("%c",&c); if (c =='d' || c == 'D') { printf("Enter a binary number: "); scanf("%d", &n); printf("%d in binary = %d in decimal", n, binary_decimal(n)); } if (c =='b' || c == 'B') { printf("Enter a decimal number: "); scanf("%d", &n); printf("%d in decimal = %d in binary", n, decimal_binary(n)); } return 0; } int decimal_binary(int n) /* Function to convert decimal to binary.*/ { int rem, i=1, binary=0; while (n!=0) { rem=n%2; n/=2; binary+=rem*i; i*=10; } return binary; } int binary_decimal(int n) /* Function to convert binary to decimal.*/ { int decimal=0, i=0, rem; while (n!=0) { rem = n%10; n/=10; decimal += rem*pow(2,i); ++i; } return decimal; } Output: Instructions: 1. Enter alphabet’d’ to convert binary to decimal. 2. Enter alphabet 'b' to convert decimal to binary. d Enter a binary number: 1000 1000 in binary = 8 in decimal Instructions: 1. Enter alphabet 'd' to convert binary to decimal. 2. Enter alphabet 'b' to convert decimal to binary. b Enter a decimal number: 8 8 in decimal = 1000 in binary */ Program to Convert Octal Number to Decimal and Decimal to Octal This program converts either octal number entered by user to decimal number or decimal number entered by user to octal in accordance with the character entered by user. /* C programming source code to convert either octal to decimal or decimal to octal according to data entered by user. */ #include #include int decimal_octal(int n); int octal_decimal(int n); int main() { int n; char c; printf("Instructions:\n"); printf("1. Enter alphabet 'o' to convert decimal to octal.\n"); printf("2. Enter alphabet 'd' to convert octal to decimal.\n"); scanf("%c",&c); if (c =='d' || c == 'D') { printf("Enter an octal number: "); scanf("%d", &n); printf("%d in octal = %d in decimal", n, octal_decimal(n)); } if (c =='o' || c == 'O') { printf("Enter a decimal number: "); scanf("%d", &n); printf("%d in decimal = %d in octal", n, decimal_octal(n)); } return 0; } int decimal_octal(int n) /* Function to convert decimal to octal */ { int rem, i=1, octal=0; while (n!=0) { rem=n%8; n/=8; octal+=rem*i; i*=10; } return octal; } int octal_decimal(int n) /* Function to convert octal to decimal */ { int decimal=0, i=0, rem; while (n!=0) { rem = n%10; n/=10; decimal += rem*pow(8,i); ++i; } return decimal; } Output: Instructions: 1. Enter alphabet 'o' to convert decimal to octal. 2. Enter alphabet 'd' to convert octal to decimal. o Enter a decimal number: 8 8 in decimal = 10 in octal Instructions: 1. Enter alphabet 'o' to convert decimal to octal. 2. Enter alphabet 'd' to convert octal to decimal. d Enter an octal number: 10 10 in octal = 8 in decimal Program to Convert Binary Number to Octal and Octal to Binary This program converts either binary number entered by user to octal number or octal number entered by user to binary number in accordance with the character entered by user. /* C programming source code to convert either binary to octal or octal to binary according to data entered by user. */ #include #include int binary_octal(int n); int octal_binary(int n); int main() { int n; char c; printf("Instructions:\n"); printf("Enter alphabet 'o' to convert binary to octal.\n"); printf("2. Enter alphabet 'b' to convert octal to binary.\n"); scanf("%c",&c); if ( c=='o' || c=='O') { printf("Enter a binary number: "); scanf("%d",&n); printf("%d in binary = %d in octal", n, binary_octal(n)); } if ( c=='b' || c=='B') { printf("Enter a octal number: "); scanf("%d",&n); printf("%d in octal = %d in binary",n, octal_binary(n)); } return 0; } int binary_octal(int n) /* Function to convert binary to octal. */ { int octal=0, decimal=0, i=0; while(n!=0) { decimal+=(n%10)*pow(2,i); ++i; n/=10; }

/*At this point, the decimal variable contains corresponding decimal value of binary number. */

i=1; while (decimal!=0) { octal+=(decimal%8)*i; decimal/=8; i*=10; } return octal; } int octal_binary(int n) /* Function to convert octal to binary.*/ { int decimal=0, binary=0, i=0; while (n!=0) { decimal+=(n%10)*pow(8,i); ++i; n/=10; } /* At this point, the decimal variable contains corresponding decimal value of that octal number. */ i=1; while(decimal!=0) { binary+=(decimal%2)*i; decimal/=2; i*=10; } return binary; } Output: Instructions: Enter alphabet 'o' to convert binary to octal. 2. Enter alphabet 'b' to convert octal to binary. o Enter a binary number: 1000 1000 in binary = 10 in octal Instructions: Enter alphabet 'o' to convert binary to octal. 2. Enter alphabet 'b' to convert octal to binary. b Enter a octal number: 10 10 in octal = 1000 in binary Program Swap Numbers in Cyclic Order Using Call by Reference This program takes three enters from user which is stored in variable a, b and c respectively. Then, these variables are passed to function using call by reference. #include void Cycle(int *a, int *b, int *c); int main() { int a,b,c; printf("Enter value of a, b and c respectively: "); scanf("%d%d%d",&a,&b,&c); printf("Value before swapping:\n"); printf("a=%d\nb=%d\nc=%d\n",a,b,c); Cycle(&a,&b,&c); printf("Value after swapping numbers in cycle:\n"); printf("a=%d\nb=%d\nc=%d\n",a,b,c); return 0; } void Cycle(int *a,int *b,int *c) { int temp; temp=*b; *b=*a; *a=*c; *c=temp; } Output: Enter value of a, b and c respectively: 5 3 4 Value before swapping: a=5 b=3 c=4 Value after swapping numbers in cycle: a=4 b=5 c=3 ONE WORD ANSWERS

Q1) What is a function?

Ans: A function is a self-contained block of code that performs a particular task.

Q2) How many types of functions exist in C,what are they?

Ans: There are two types of functions they are a.User-defined functions

b.standard library functions.

Q3) What are the advantages of using functions?

Ans: a. The length of the source program can be reduced by using function.

b.It is easy to and isolate a faulty functions for further investigations.

Q4) What is Function definition?

Ans: It is an independent program module that is especially written to implement the requirements of the function.

Q5) What are the elements involved in function definition?

Ans: The six elements that are involved in a function definition are:

a.Function return type

b.Function name

c.Parameter list

d.Local variables

e.Function statements and

f.Return statement

Q6) What is function header?

Ans: The function type,function name and the parameter list together is called

a function header.

Q7) What is function body?

Ans: The local variables the function statements and the return statement on a whole is known as function body.

Q8) What are formal parameters?

Ans: The parameter list declares the variables that will receive the data sent by the calling programme. They serve as the input data to function to carry out the specified task since they represent actual input values, they are called as the "formal parameters".

Q9) What are actual parameters?

Ans: The parameters which are used in the function call are called as actual parameters. These may be simple constants, variables or expressions.

Q10) what is an Argument?

Ans: This is one type of parameter which collects the value from the calling function.

Q11) what is Local variable ?

Ans: The variables which are declared inside the function is known as local variable

Q12) what is global variable ?

Ans: The variables which are declared outside the function is known as global variable

Q13) What is function declaration?

Ans: The calling function should declare any function that is to be used later in the program this is known as function declaration or function prototype.

Q14) what are the main elements required in the function prototype?

Ans: The main elements required in the function prototype are:

a.function return type

b.function name

c.parameters list

d.terminating semicolon

NOTE: Terminating semicolon(;) is important.

Q15) What are the types of functions depending upon categories of arguments and return statements?

Ans: Depending upon categories of arguments and return statements there are four types of functions

a. function with no arguments and no return values

b. function with arguments and no return value

c. function with arguments and one return value

d. function with no arguments but return a value

Q16) How do you return multiple values to the calling function?

Ans: Multiple values to the calling function can be returned using "POINTERS".

Q17) How do you pass multiple variables using pointers? Ans: Multiple values can be passed using pointers by using addresses of variables in the actual parameters.

Q18) What are the rules to pass an array to a function?

Ans: The rules are:

a.the function must be called by passing only the name of an array

b.the function definition, the formal parameter must be an array type; the size of an array does not need to be specified.

c.the function prototype must show that the argument is an array.

Q19) Is it possible to pass an entire array to a function as an argument?

A: , it is possible to pass an entire array to a function as an argument.

Q20) How to pass an array to a function?

Ans: To pass an array to a function ,the name of the array must appear itself, without brackets or subscripts, as an actual argument with in the function call.

Q21) What are automatic variables?

Ans: These are the variables declared inside a function in which they are utilised. They are cerated when the function is 'called' and destroyed automatically when the function is exited.

Q22) What are static variables? what are its types?

Ans: These are the variables which persist until the end of the program. They are of two types

a.Internal static variables: are those declared inside a function.

b.External static variables: are those declared outside a function.

Q23) What is a recursive function?

Ans: a function which calls itself is known as recusive function.

Q24) Give an example where we use recursion?

Ans: Recusion can be used for doing progrms like mathematical induction, fibbonaci series etc.....

Multiple Choice Questions

1. The default return type of a function is ______a. Void b. Int c. Float d. Char

2. Which of the following are the incorrect fuction declaration? a. int funct(int a,b;); b. int funct(int a,int b); c. int funct(int ,int ); d. int funct(int, );

3. Which of the following is not feasible? a. fuctions with no arguments and no return values b. function with arguments and no return values c. function with no arguments but return value d. all the above are feasible

4. Recursion is function where: a. A function calls a main function b. A function calls any of the system function c. A function calls itself d. None of the above

5. Which of the following is not a variable storage class a. automatic b. extern c. static d. dynamic

6. Which of the fillowig keywords is used for declaring an external variable? a. external b. extern c. auto extern d. ext

7. Which of the following types of variables remain alive for the entire life time of the program? a. extern b. auto c. register d. static

8. Which of the following refers to the region of a programme where a variable is available for use? a. scope b. visibility c. life time d. None of the above 9. The formal parameters in the function header must be prefixed by which of the following indirection operator? a. * b. + c. - d. / 10. What will be the output of the following program : static int funct(int val) { static int sum; sum+=val; return sum; } void main() { int i,n=9; for (i=1; i

11. What will be the output of the following program : void print(int a[],...) { while (*a != -1) printf("%d",*a++); } void main() { int a[]={1,2,3,4,5,-1}; print(a,5,6,7,8,9,-1); } a.1 b.2 c.12345 d.34

12. What will be the output of the following program : void print(int *); void print(int *); void main() { int x=100; print(&x); } void print(int *a) { printf("%d",*a); } a.12 b.321 c.101 d.100

13. What will be the output of the following program : void main() { void funct1(void); void funct2(void); clrscr(); funct1(); } void funct1(void) { printf("Ocean of "); funct2(); } void funct2(void) { printf("Knowledge"); } a.ocean b.know c. Knowledge d.compile timeerror

14. What will be the output of the following program : int func(int *ptr,int a,int b) { return (a+b); *ptr=25; } void main() { int var=7,sum; sum=func(&var,5,6); printf("%d %d",sum,var); }

a.11 b.11 7 c.7 d.17

15. What will be the output of the following program : int func(int *ptr,int a,int b) { return (a+b); *ptr=25; return *ptr; } void main() { int var=7; sum=func(&var,5,6); printf("%d %d",sum,var); } a.1 b.7 c.11 7 d.17

16. What will be the output of the following program : int func(int *ptr,int a,int b) { *ptr=25; return *ptr; return (a+b); } void main() { int var=7; sum=func(&var,5,6); printf("%d %d",sum,var); } a.25 b.25 25 c.30 d.30 25 17. What will be the output of the following program : #include #define ToStr(s) #s #define Swap(x,y) y##x void Swap(in,ma)() { if (printf(ToStr("Friends"))){} } a. Friends b.friend c.error d.none of these 18. What will be the output of the following program : int add(int a,int b) { return a+b; } main() { int a=1,b=2; printf("%d",add(add(add(a,b),add(a,b)),add(add(a,b),add(a,b)))); } a.23 b.12 c.52 OUTPUT PREDICTION

1) The following code is not well-written. What does the program do ? void main() { int a=1,b=2; printf("%d",add(a,b)); } int add(int a,b) { return (a+b); }

2) What will be the output of the following program : int add(int a,int b) { int c=a+b; } void main() { int a=10,b=20; printf("%d %d %d",a,b,add(a,b)); }

3) What will be the output of the following program : int add(int a,int b) { int c=a+b; return; } void main() { int a=10,b=20; printf("%d %d %d",a,b,add(a,b)); }

4) What will be the output of the following program : void main() { int add(int,int); int a=7,b=13; printf("%d",add(add(a,b),add(a,b))); } int add(a,b) int a,b; { return (a+b); }

5) What will be the output of the following program : int add(a,b) { int c=a+b; return c; } void main() { int a=10,b=20; printf("%d",add(a,b)); }

6) What will be the output of the following program : int funct2(int b) { if (b == 0) return b; else funct1(b--); } int funct1(int a) { if (a == 0) return a; else funct2(a--); } void main() { int a=7; printf("%d",funct1(a)); }

7) What will be the output of the following program : int funct2(int b) { if (b == 0) return b; else funct1(--b); } int funct1(int a) { if (a == 0) return a; else funct2(--a); } void main() { int a=7; printf("%d",funct1(a)); }

8) What will be the output of the following program : int funct1(int a) {{;}{{;}return a;}} void main() { int a=17; printf("%d",funct1(a)); }

9) What will be the output of the following program : int funct1(int a) { if (a) return funct1(--a)+a; else return 0; } void main() { int a=7; printf("%d",funct1(a)); }

10) What will be the output of the following program : int compute(int a,int b) int c; { c=a+b; return c; } void main() { int a=7,b=9; printf("%d",compute(ab)); }

11) What will be the output of the following program : int a=10; void compute(int a) { a=a; } void main() { int a=100; printf("%d ",a); compute(a); printf("%d",a); }

12) What will be the output of the following program : int funct(char ch) { ch=ch+1; return ch; } void main() { int a=127; printf("%d %d",a,funct(a)); }

13) What will be the output of the following program : auto int a; void change(int x) { a=x; } void main() { a=15; printf("%d",a); changeval(75); printf("%d",a); }

14) What will be the output of the following program : int val; static int funct() { return val*val; } void main() { val=5; funct(); val++; printf("%d",funct()); }

15) What will be the output of the following program : static int count=1; void funct3(void) { printf("%d",++count); } void funct2(void) { printf("%d",count); funct3(); } void funct1(void) { printf("Counting...%d",count++); funct2(); } void Main() { funct1(); }

4. ARRAY 4.1 ARRAY BASICS Array is a simple data structure which can store collection of elements of same data type. All elements are stored in the contiguous memory. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

4.1.1 Declaring Arrays To declare an array, a programmer specifies the type of the elements and the number of elements required by an array as follows: type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement: double balance[10];

Now balance is avariable array which is sufficient to hold up to 10 double numbers. 4.1.2 Initializing Arrays You can initialize array either one by one or using a single statement as follows: double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array:

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write: double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th ie. last element because all arrays have 0 as the index of their first element which is also called base index. 4.1.3Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example: double salary = balance[9];

The above statement will take 10th element from the array and assign the value to salary variable. e.g.

#include int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i,j;

for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; /* set element at location i to i + 100 */ }

for (j = 0; j < 10; j++ ) { printf("Element[%d] = %d\n", j, n[j] ); }

return 0; }

When the above code is compiled and executed, it produces the following result:

Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 4.2 MULTIDIMENSIONAL ARRAYS C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration: type name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array: int threedim[5][10][4];

4.3 TWO-DIMENSIONAL ARRAYS The simplest form of the multidimensional array is the two-dimensional array. A two- dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y you would write something as follows: type arrayName [ x ][ y ];

Where type can be any valid C data type and arrayName will be a valid C identifier. A two dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimentional array a which contains three rows and four columns can be shown as below:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.

4.3.1 Initializing Two-Dimensional Arrays Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ }; The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example: int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

4.3.2 Accessing Two-Dimensional Array Elements: An element in 2-dimensional array is accessed by using the subscripts ie. row index and column index of the array. For example: int val = a[2][3];

The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two dimensional array:

#include int main () { /* an array with 5 rows and 2 columns*/ int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int i, j;

for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 2; j++ ) { printf("a[%d][%d] = %d\n", i,j, a[i][j] ); } } return 0; }

When the above code is compiled and executed, it produces following result: a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8 ONE WORD ANSWERS Q1) What is an array? Ans: Array is collection of homogeneous data.It stores data in contigeous memory location.

Q2) How many types of arrays exist and what are they? Ans: There are 3 types of arrays they are a) one dimensional array b) two dimensional array c) multi dimensional array

Q3) What is an one dimensional array? Ans: A list of items given in one variable name using only one subscript is known as one dimensional array. Example: int a[3]

Q4) What is two dimensional array? Ans: Collection of homogeneous elements in rows and columns is known as two-dimensional array. Example: int matrix[3][3]

Q5) What is the general format of declaring an array? Ans: datatype Arrayname[size] note: the size must be an integer.

Q6) What is the value of starting index of an array? Ans: zero

Q7) What is the use of const qualifier? Ans: The compiler allows to associate the const qualifier with variables whose values will not be changed by the program.

Q8) What value is automatically assigned to those array elements that are not explicitly initialized? Ans: All of array elements automatically set to zero except those that have been explicitly initialized with in array definitions.

Q9) State the rule that determines the order in which initial values are assigned to multi dimensional array elements? Ans: the rule is that the last (right most) subscript increases most rapidly and the first (left most) increases least rapidly.

MULTIPLE CHOICE QUESTIONS 1. A array an example of ---? a. derived types b. fundamental types c. user-defined types d. none of the above

2. Which of the following is not a data structure? a. linked list b. stack c. d. pointer

3. int a[n] will reserve how many locations in the memory? a. n b. n-1 c. n+1 d. none of the above

4. Which of the following is the correct syntax for the initialisation of one dimensioal array? a. num[3]={0 0 0}; b. num[3]={0,0,0}; c. num[3]={0;0;0}; d. num[3]=0

5. Which of the following is the correct syntax for initialisation of Two dimensional array? a.table[2][3]={0,0,0,1,1,1}; b.table[2][3]={ {0,0,0} {1,1,1} }; c.table[2][3]={0,1},{0,1},{0,1}; d.None of the above

6. Which of the following multi-dimensional array declaration is correct for realizing a 2x3 matrix? a. int m[2][3] b. int m[3][2] c. int m[3],m[2] d. None of the above

7. Which of the following is not the name of sorting technique? a.Bubble b.Selection c.Binary d.Insertion

8. Which of the following is not the name of a searching technique? a.Selection b.Sequential c.Binary d.All of the above are searching techniques

9. Which is the last element of character string? a. Last element of the string b. Blank space c. Null character d. New line character OUTPUT PREDICTION What will be output if you will execute following c code? #include void main() { char arr[11]="The African Queen"; printf("%s",arr);

}

2. What will be output if you will execute following c code? #include void main() { char arr[20]="MysticRiver"; printf("%d",sizeof(arr)); }

3. What will be output if you will execute following c code? #include void main() { int const SIZE=5; int ; double value[SIZE]={2.0,4.0,6.0,8.0,10.0}; expr=1|2|3|4; printf("%f",value[expr]); }

4. What will be output if you will execute following c code? #include #define var 3 void main() { char data[2][3][2]={0,1,2,3,4,5,6,7,8,9,10,11}; printf("%o",data[0][2][1]); }

5. What will be output if you will execute following c code? #include void main() { int arr[][3]={{1,2},{3,4,5},{5}}; printf("%d %d %d",sizeof(arr),arr[0][2],arr[1][2]); }

6. What will be output if you will execute following c code? #include void main() { int xxx[10]={5}; printf("%d %d",xxx[1],xxx[9]); }

7. What will be output if you will execute following c code? #include #define WWW -1 enum {,rat}; void main() { int Dhoni[]={2,'b',0x3,01001,'\x1d','\111',rat,WWW}; int i; for(i=0;i<8;i++) printf(" %d",Dhoni[i]); }

8. What will be output if you execute the following c code? #include void main() { long double a; signed char b; int arr[sizeof(!a+b)]; printf("%d",sizeof(arr)) }

SAMPLE C – PROGRAMS

1. Program to find whether a given year is leap year or not.

# include

main() { int year;

printf("Enter a year:\n"); scanf("%d", &year);

if ( (year % 4) == 0) printf("%d is a leap year", year); else printf("%d is not a leap year\n", year); }

Output:

Enter a year: 2000 2000 is a leap year

RUN2:

Enter a year: 1999 1999 is not a leap year

2. Program to multiply given number by 4 using bitwise operators.

# include

main() { long number, tempnum; printf("Enter an integer:\n"); scanf("%ld", &number); tempnum = number; number = number << 2; /*left shift by two bits*/

printf("%ld x 4 = %ld\n", tempnum, number); }

Output:

Enter an integer: 15 15 x 4 = 60

RUN2: Enter an integer: 262 262 x 4 = 1048

3. Program to compute the value of X ^ N given X and N as inputs.

#include #include

void main() { long int x, n, xpown; long int power(int x, int n);

printf("Enter the values of X and N: \n"); scanf("%ld %ld", &x, &n);

xpown = power (x, n);

printf("X to the power N = %ld\n"); }

/*Recursive function to computer the X to power N*/

long int power(int x, int n) { if (n==1) return(x); else if ( n%2 == 0) return (pow(power(x,n/2),2)); /*if n is even*/ else return (x*power(x, n-1)); /* if n is odd*/ }

Output:

Enter the values of X and N: 2 5 X to the power N = 32

RUN2: Enter the values of X and N: 4 4 X to the power N ==256

RUN3: Enter the values of X and N: 5 2 X to the power N = 25

RUN4: Enter the values of X and N: 10 5 X to the power N = 100000

4. Program to swap the contents of two numbers using bitwise XOR operation. Don't use either the temporary variable or arithmetic operators.

# include

main() { long i, k; printf("Enter two integers: \n"); scanf("%ld %ld", &i, &k); printf("\nBefore swapping i= %ld and k = %ld", i, k); i = i^k; k = i^k; i = i^k; printf("\nAfter swapping i= %ld and k = %ld", i, k); }

Output:

Enter two integers: 23 34 Before swapping i= 23 and k = 34 After swapping i= 34 and k = 23

5. Program to find and output all the roots of a quadratic equation, for non-zero coefficients. In case of errors your program should report suitable error message.

#include #include #include main() { float A, B, C, root1, root2; float realp, imagp, disc; clrscr(); printf("Enter the values of A, B and C\n"); scanf("%f %f %f", &A,&B,&C);

if( A==0 || B==0 || C==0) { printf("Error: Roots cannot be determined\n"); exit(1); } else { disc = B*B - 4.0*A*C; if(disc < 0) { printf("Imaginary Roots\n"); realp = -B/(2.0*A) ; imagp = sqrt(abs(disc))/(2.0*A); printf("Root1 = %f +i %f\n", realp, imagp); printf("Root2 = %f -i %f\n", realp, imagp); } else if(disc == 0) { printf("Roots are real and equal\n"); root1 = -B/(2.0*A); root2 = root1; printf("Root1 = %f \n",root1); printf("Root2 = %f \n",root2); } else if(disc > 0 ) { printf("Roots are real and distinct\n"); root1 =(-B+sqrt(disc))/(2.0*A); root2 =(-B-sqrt(disc))/(2.0*A); printf("Root1 = %f \n",root1); printf("Root2 = %f \n",root2); } }

}

Output:

RUN 1 Enter the values of A, B and C: 3 2 1 Imaginary Roots Root1 = -0.333333 +i 0.471405 Root2 = -0.333333 -i 0.471405

RUN 2 Enter the values of A, B and C: 1 2 1 Roots are real and equal Root1 = -1.000000 Root2 = -1.000000

RUN 3 Enter the values of A, B and C: 3 5 2 Roots are real and distinct Root1 = -0.666667 Root2 = -1.000000

6. Write a C programme to accept a list of data items & find the II largest & II smallest in it & take average of both & search for that value. Display appropriate message on successful search. main () { int i,j,a,n,counter,ave,number[30]; printf ("Enter the value of N\n"); scanf ("%d", &n); printf ("Enter the numbers \n"); for (i=0; i

7. Write a C programme to arrange the given numbers in ascending order. main () { int i,j,a,n,number[30]; printf ("Enter the value of N\n"); scanf ("%d", &n); printf ("Enter the numbers \n"); for (i=0; i number[j]) { a= number[i]; number[i] = number[j]; number[j] = a; } } } printf("Number in Asscending order:\n"); for(i=0;i

8. Program to convert the given binary number into decimal.

# include main() { int num, bnum, dec = 0, base = 1, rem ; printf("Enter the binary number(1s and 0s)\n"); scanf("%d", &num); /*maximum five digits */ bnum = num; while( num > 0) { rem = num % 10; if(rem>1) { printf("\nError in input"); break; } dec = dec + rem * base; num = num / 10 ; base = base * 2; } if(num==0) { printf("The Binary number is = %d\n", bnum); printf("Its decimal equivalent is =%d\n", dec); } }

9. Program to generate the fibonacci sequence.

#include main() { int fib1=0, fib2=1, fib3, limit, count=0;

printf("Enter the limit to generate the fibonacci sequence\n"); scanf("%d", &limit);

printf("Fibonacci sequence is ...\n"); printf("%d\n",fib1); printf("%d\n",fib2); count = 2; /* fib1 and fib2 are already used */

while( count < limit) { fib3 = fib1 + fib2; count ++; printf("%d\n",fib3); fib1 = fib2; fib2 = fib3; } }

10. Program to reverse the given integer (palindrome).

#include main() { int num, rev = 0, found = 0, temp, digit;

printf("Enter the number\n"); scanf("%d", &num);

temp = num; while(num > 0) { digit = num % 10; rev = rev * 10 + digit; num /= 10; } printf("Given number =%d\n", temp); printf("Its reverse is =%d\n", rev);

if(temp == rev ) printf("Number is a palindrome\n"); else printf("Number is not a palindrome\n"); }

11. Program to determine the given number is odd.

#include main() { int numb; printf(" Enter the number\n"); scanf("%d", &numb);

if((numb%2)!=0) printf(" %d , is an odd number\n", numb);

}

12. Program to find the largest among three numbers.

#include main() { int a, b, c; printf(" Enter the values for A,B,C\n"); scanf("%d %d %d", &a, &b, &c); if( a > b ) { if ( a > c) printf(" A is the Largest\n"); else printf("C is the largest\n"); } else if ( b > c) printf(" B is the Largest\n"); else printf("C is the Largest\n"); }

13. Program to find the areas of different geometrical figures using switch statement.

#include main() { int fig_code; float side, base, length, bredth, height, area, radius; printf("------\n"); printf(" 1 --> Circle\n"); printf(" 2 --> Rectangle\n"); printf(" 3 --> Triangle\n"); printf(" 4 --> Square\n"); printf("------\n");

printf("Enter the Figure code\n"); scanf("%d", &fig_code);

switch(fig_code) { case 1: printf(" Enter the radius\n"); scanf("%f",&radius); area=3.142*radius*radius; printf("Area of a circle=%f\n", area); break; case 2: printf(" Enter the bredth and length\n"); scanf("%f %f",&bredth, &length); area=bredth *length; printf("Area of a Reactangle=%f\n", area); break; case 3: printf(" Enter the base and height\n"); scanf("%f %f", &base, &height); area=0.5 *base*height; printf("Area of a Triangle=%f\n", area); break; case 4: printf(" Enter the side\n"); scanf("%f", &side); area=side * side; printf("Area of a Square=%f\n", area); break; default: printf(" Error in figure code\n"); break; }

}

14. Program to find the factorial of a number.

#include main() { int i,fact=1,num; printf("Enter the number\n"); scanf("%d",&num); if( num <0) printf(“Factorial is not there for –ve numbers”); else if(num==0 || num==1) fact=1; else { for(i=1;i<=num; i++) fact *= i; } printf(" Factorial of %d =%5d\n", num,fact); }

15. Program to illustrate for loop without initial and increment/decrement expressions.

#include main() { int i=0,limit=5; printf(" Values of I\n"); for( ; i

16. Program to accept a string and find the sum of all digits in the string.

#include main() { char string[80]; int count, nc=0, sum=0; printf("Enter the string containing both digits and alphabet\n"); scanf("%s", string); for(count=0; string[count]!='\0'; count++) { if((string[count]>='0') && (string[count]<='9')) { nc += 1; sum += (string[count] - '0'); } } printf("NO. of Digits in the string= %d\n",nc); printf("Sum of all digits= %d\n",sum);

} 17. Program to find the sum of the sine series.

#include #include #define pi 3.142 main() { int i,n,k,sign; float sum=0,num,den,xdeg,xrad,xsqr,term; printf("Enter the angle( in degree): \n"); scanf("%f",&xdeg); printf("Enter the no. of terms: \n"); scanf("%d",&n); xrad=xdeg * (pi/180.0); /* Degrees to radians*/ xsqr= xrad*xrad; sign=1; k=2; num=xrad; den=1;

for(i=1;i<=n; i++) { term=(num/den)* sign; sum += term; sign *= -1; num *= xsqr; den *= k*(k+1); k += 2; } printf("Sum of sine series of %d terms =%8.3f\n",n,sum); }

18. Program to find the sum of cos(x) series.

#include #include main() { float x, sign, cosx, fact; int n,x1,i,j; printf("Enter the number of the terms in a series\n"); scanf("%d", &n); printf("Enter the value of x(in degrees)\n"); scanf("%f", &x); x1=x; x=x*(3.142/180.0); /* Degrees to radians*/ cosx=1; sign=-1; for(i=2; i<=n; i=i+2) { fact=1; for(j=1;j<=i;j++) { fact=fact*j; } cosx=cosx+(pow(x,i)/fact)*sign; sign=sign*(-1); } printf("Sum of the cosine series=%f\n", cosx); printf("The value of cos(%d) using library function=%f\n",x1,cos(x)); }

19. Program to reverse the given integer.

#include main() { int num, rev = 0, found = 0, temp, digit;

printf("Enter the number\n"); scanf("%d", &num);

temp = num; while(num > 0) { digit = num % 10; rev = rev * 10 + digit; num /= 10; } printf("Given number =%d\n", temp); printf("Its reverse is =%d\n", rev); }

20. Program to accept a decimal number and convert to binary and count the number of 1's in the binary number.

#include main() { long num, dnum, bin = 0, base = 1; int rem, no_of_1s = 0 ; printf("Enter a decimal integer:\n"); scanf("%ld", &num); /*maximum five digits */ dnum = num; while( num > 0) { rem = num % 2; if (rem==1) /*To count number of 1s*/ { no_of_1s++; } bin = bin + rem * base; num = num / 2 ; base = base * 10; } printf("Input number is = %ld\n", dnum); printf("Its Binary equivalent is =%ld\n", bin); printf("No. of 1's in the binary number is = %d\n", no_of_1s); }

Output:

Enter a decimal integer: 75 Input number is = 75 Its Binary equivalent is =1001011 No. of 1's in the binary number is = 4

RUN2 Enter a decimal integer: 128 Input number is = 128 Its Binary equivalent is=10000000 No. of 1's in the binary number is = 1

21. Program to find the number of characters, words and lines.

#include #include #include void main() { int count=0,chars,words=0,lines,i; char text[1000]; clrscr(); puts("Enter text:"); gets(text); while (text[count]!='\0') count++; chars=count; for (i=0;i<=count;i++) { if ((text[i]==' '&&text[i+1]!=' ')||text[i]=='\0') words++; } lines=chars/80+1; printf("no. of characters: %d\n", chars); printf("no. of words: %d\n", words); printf("no. of lines: %d\n", lines); getch(); }

22. Program to find the GCD and LCM of two integers output the results along with the given integers. Use Euclids' algorithm.

#include main() { int num1, num2, gcd, lcm, remainder, numerator, denominator; clrscr(); printf("Enter two numbers: \n"); scanf("%d %d", &num1,&num2); if (num1 > num2) { numerator = num1; denominator = num2; } else { numerator = num2; denominator = num1; } remainder = numerator % denominator; while(remainder !=0) { numerator = denominator; denominator = remainder; remainder = numerator % denominator; } gcd = denominator; lcm = num1 * num2 / gcd; printf("GCD of %d and %d = %d \n", num1,num2,gcd); printf("LCM of %d and %d = %d \n", num1,num2,lcm); }

Output:

Enter two numbers: 5 15 GCD of 5 and 15 = 5 LCM of 5 and 15 = 15

23. Program to find the sum of odd numbers and sum of even numbers from 1 to N. Output the computed sums on two different lines with suitable headings.

#include main() { int i, N, oddsum = 0, evensum = 0; printf("Enter the value of N: \n"); scanf ("%d", &N); for (i=1; i <=N; i++) { if (i % 2 == 0) evensum = evensum + i; else oddsum = oddsum + i; } printf ("Sum of all odd numbers = %d\n", oddsum); printf ("Sum of all even numbers = %d\n", evensum); }

Output:

RUN1 Enter the value of N: 10 Sum of all odd numbers = 25 Sum of all even numbers = 30

RUN2 Enter the value of N: 50 Sum of all odd numbers = 625 Sum of all even numbers = 650 24. Program to check whether a given number is prime or not and output the given number with suitable message.

#include #include main() { int num, j, flag; clrscr();

printf("Enter a number: \n"); scanf("%d", &num); if ( num <= 1) { printf("%d is not a prime numbers\n", num); exit(1); } flag = 0; for ( j=2; j<= num/2; j++) { if( ( num % j ) == 0) { flag = 1; break; } } if(flag == 0) printf("%d is a prime number\n",num); else printf("%d is not a prime number\n", num); } Output:

RUN 1 Enter a number: 34 34 is not a prime number

RUN 2 Enter a number: 29 29 is a prime number

25. Program to generate and print prime numbers in a given range. Also print the number of prime numbers.

#include #include main() { int M, N, i, j, flag, temp, count = 0; clrscr(); printf("Enter the value of M and N: \n"); scanf("%d %d", &M,&N); if(N < 2) { printf("There are no primes upto %d\n", N); exit(0); } printf("Prime numbers are\n"); temp = M; if ( M % 2 == 0) { M++; } for (i=M; i<=N; i=i+2) { flag = 0; for (j=2; j<=i/2; j++) { if( (i%j) == 0) { flag = 1; break; } } if(flag == 0) { printf("%d\n",i); count++; } } printf("Number of primes between %d and %d = %d\n",temp,N,count); }

Output:

Enter the value of M and N: 15 45 Prime numbers are 17 19 23 29 31 37 41 43 Number of primes between 15 and 45 = 8

26. Write to accept a 1-dimensional array of N elements & into 2 halves & 1st half in ascending order & 2nd into descending order.

#include main () { int i,j,a,n,b,number[30]; printf ("Enter the value of N\n"); scanf ("%d", &n); b = n/2; printf ("Enter the numbers \n"); for (i=0; i number[j]) { a = number[i]; number[i] = number[j]; number[j] = a; } } } for (i=b; i

27. Program to delete the desired element from the list.

# include main() { int vectx[10]; int i, n, found = 0, pos, element; printf("Enter how many elements\n"); scanf("%d", &n); printf("Enter the elements\n"); for(i=0; i

28. Write a "C" program to Interchange the main diagonal elements with the scondary diagonal elements.

#include main () { int i,j,m,n,a; static int ma[10][10]; printf ("Enetr the order of the matix \n"); scanf ("%dx%d",&m,&n); if (m==n) { printf ("Enter the co-efficients of the matrix\n"); for (i=0;i

29 Program to insert an element at an appropriate position in an array.

#include #include main() { int x[10]; int i, j, n, m, temp, key, pos; clrscr(); printf("Enter how many elements\n"); scanf("%d", &n); printf("Enter the elements\n"); for(i=0; i x[j]) { temp = x[i]; x[i] = x[j]; x[j] = temp; } } } printf("Sorted list is:\n"); for(i=0; i

printf("Final list is:\n"); for(i=0; i

30. Program to compute mean, varience and standard deviation. main() { float x[10]; int i, n; float avrg, var, SD, sum=0, sum1=0;

printf("Enter how many elements\n"); scanf("%d", &n); printf("Enter %d numbers:",n); for(i=0; i

avrg = sum /(float) n; /* Compute varaience and standard deviation */ for(i=0; i

7 POINTERS 7.1 INTRODUCTION TO POINTERS Pointer is a fundamental part of C. If you cannot use pointers properly then you have basically lost all the power and flexibility that C allows. The secret to C is in its use of pointers. C uses pointers a lot because:

 It is the only way to express some computations.  It produces compact and efficient code.  Pointers provided an easy way to represent multidimensional arrays.  Pointers increase the execution speed.  Pointers reduce the length and complexity of program.

C uses pointers explicitly with arrays, structures and functions.

A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type.

The unary operator & gives the “address of a variable''. The indirection or dereference operator * gives the “contents of an object pointed to by a pointer''.

To declare a pointer to a integer variable do:

int *pointer;

We must associate a pointer to a particular type. We can't assign the address of a short int to a long int.

Consider the effect of the following code:

#include main() { int x = 1, y = 2; int *ip; ip = &x; y = *ip; *ip = 3; }

It is worth considering what is going on at the machine level in memory to fully understand how pointer works. Assume for the sake of this discussion that variable x resides at memory location 100, y at 200 and ip at 1000 shown in figure 4.1. int x = 1, y = 2; int *ip; ip = & x ;

x 1 y 2 ip 100 100 200 1000 y = *ip;

x 1 y 1 ip 100 100 200 1000 *ip = 3;

x 3 y 1 ip 100 100 200 1000

Fig. 4.1 Pointer, Variables and Memory

Now the assignments x = 1 and y = 2 obviously load these values into the variables. ip is declared to be a pointer to an integer and is assigned to the address of x (&x). So ip gets loaded with the value 100.

Next y gets assigned to the contents of ip. In this example ip currently points to memory location 100 -- the location of x. So y gets assigned to the values of x -- which is 1. Finally, we can assign a value 3 to the contents of a pointer (*ip).

IMPORTANT: When a pointer is declared it does not point anywhere. You must set it to point somewhere before you use it. So,

int *ip; *ip = 100; will generate an error (program crash!!). The correct usage is:

int *ip; int x; ip = &x; *ip = 100; ++ip;

We can do integer arithmetic on a pointer, for example:

char m = ‘j’; char *ch_ptr = &m; float x = 20.55; float *flp, *flq; flp = &x; *flp = *flp + 10; ++*flp; (*flp)++; flq = flp;

The reason we associate a pointer to a data type is that it knows how many bytes the data is stored in. When we increment a pointer we increase the pointer by one “block “ of memory.

So, for a character pointer ++ch_ptr adds 1 byte to the address. For an integer or float ++ip or ++flp adds 2 bytes and 4 bytes respectively to the address.

Here is another example showing some of the uses of pointers:

#include void main (void) { int m = 0, n = 1, k = 2; int *p; char msg[] = "hello world"; char *; p = &m; /* p now points to m */ *p = 1; /* m now equals 1 */ k = *p; /* k now equals 1 */ cp = msg; /* cp points to the first character of msg */ *cp = 'H'; /* change the case of the 'h' in msg */ cp = &msg[6]; /* cp points to the '' */ *cp = 'W'; /* change its case */ printf ("m = %d, n = %d, k = %d\nmsg = \"%s\"\n", m, n, k, msg); }

Output: m = 1, n = 1, k = 1 msg = “Hello World”

Note the very important point that the name of an array (`msg' in the above example), if used without an index, is considered to be a pointer to the first element of the array.

In fact, an array name followed by an index is exactly equivalent to a pointer followed by an offset.

Example:

#include void main (void) { char msg[] = "hello world"; char *cp; cp = msg; cp[0] = 'H'; *(msg+6) = 'W'; printf ("%s\n", msg); printf ("%s\n", &msg[0]); printf ("%s\n", cp); printf ("%s\n", &cp[0]); }

Output:

Hello World Hello World Hello World Hello World

Note, however, that `cp' is a variable, and can be changed, whereas`msg' is a constant, and is not an lvalue. 7.2 POINTERS AND ARRAYS There is a close association between pointers and arrays. Let us consider the following statements:

int x[5] = {11, 22, 33, 44, 55}; int *p = x;

The array initialization statement is familiar to us. The second statement, array name x is the starting address of the array. Let we take a sample memory map as shown in figure 4.2.:

From the figure 4.2 we can see that the starting address of the array is 1000. When x is an array, it also represents an address and so there is no need to use the (&) symbol before x. We can write int *p = x in place of writing int *p = &x[0].

The content of p is 1000 (see the memory map given below). To access the value in x[0] by using pointers, the indirection operator * with its pointer variable p by the notation *p can be used.

M e mo ry

1000 11 x[0]

1002 22 x[1]

1004 33 x[2]

1006 44 x[3]

1008 55 x[4]

1 0 1 0

Fig ure 4. 2. Memory map - Array s

The increment operator ++ helps you to increment the value of the pointer variable by the size of the data type it points to. Therefore, the expression p++ will increment p by 2 bytes (as p points to an integer) and new value in p will be 1000 + 2 = 1002, now *p will get you 22 which is x[1].

Consider the following expressions:

*p++; *(p++); (*p)++;

How would they be evaluated when the integers 10 & 20 are stored at addresses 1000 and 1002 respectively with p set to 1000. p++ : The increment ++ operator has a higher priority than the indirection operator * . Therefore p is increment first. The new value in p is then 1002 and the content at this address is 20.

*(p++): is same as *p++.

(*p)++: *p which is content at address 1000 (i.e. 10) is incremented. Therefore (*p)++ is 11.

Note that, *p++ = content at incremented address.

Example:

#include main() { int x[5] = {11, 22, 33, 44, 55}; int *p = x, i; /* p=&x[0] = address of the first element */ for (i = 0; i < 5; i++) { printf (“\n x[%d] = %d”, i, *p); /* increment the address*/ p++; } } Output: x [0] = 11 x [1] = 22 x [2] = 33 x [3] = 44 x [4] = 55

The meanings of the expressions p, p+1, p+2, p+3, p+4 and the expressions *p, *(p+1), *(p+2), *(p+3), *(p+4) are as follows:

P = 1000 *p = content at address 1000 = x[0] P+1 = 1000 + 1 x 2 = 1002 *(p+1) = content at address 1002 = x[1] P+2 = 1000 + 2 x 2 = 1004 *(p+2) = content at address 1004 = x[2] P+3 = 1000 + 3 x 2 = 1006 *(p+3) = content at address 1006 = x[3] P+4 = 1000 + 4 x 2 = 1008 *(p+4) = content at address 1008 = x[4]

7.3 POINTERS AND STRINGS A string is an array of characters. Thus pointer notation can be applied to the characters in strings. Consider the statements:

char tv[20] = “ONIDA”; char *p = tv;

For the first statement, the compiler allocates 20 bytes of memory and stores in the first six bytes the char values as shown below:

V a ria ble t v[ 0] tv[1] tv[2] tv[3] tv[4] tv[5]

V alue ‘O’ ‘N’ ‘I’ ‘D’ ‘A’ ‘\0’

A d d ress 1000 1001 1002 1003 1004 1005

The statement:

char *p = tv; /* or p = &tv[0] */

Assigns the address 1000 to p. Now, we will write a program to find the length of the string tv and print the string in reverse order using pointer notation.

Example:

#include main() { int n, i; char tv[20] = “ONIDA”; /* p = 1000 */ char *p = tv, *q; /* p = &tv[0], q is a pointer */ q = p; while (*p != ‘\0’) /* content at address of p is not null character */ p++; n = p - q; /* length of the string */ --p; /* make p point to the last character A in the string */ printf (“\nLength of the string is %d”, n); printf (“\nString in reverse order: \n”); for (i=0; i

Output:

Length of the string is 5 String in reverse order: ADINO 7.4 POINTERS AND STRUCTURES

You have learnt so far that pointers can be set to point to an int, float, char, arrays and strings. Now, we will learn how to set pointers to structures. Consider the structure definition.

struct student { int rollno; char name [20]; }; and the declarations:

struct student s; struct student * = &s; in the last statement, we have declared a pointer variable ps and initialized it with the address of the structure s. We say that ps points to s. To access the structure members with the help of the pointer variable ps, we use the following syntax:

ps  rollno (or) (*ps).rollno ps  name (or) (*ps).name

The symbol  is called arrow operator and is made up of a minus sign and a greater than sign. The parentheses around ps are necessary because the member operator (.) has a higher precedence than the indirection operator (*).

We will now write a program to illustrate the use of structure pointers.

# include # include struct invent { char name[20]; int number; float price; }; main() { float temp; struct invent product[3], *ps; int size ; ps = &product[0]; printf("input product details:"); size = sizeof(product[0]); printf("\n sizeof(product[0]) = %d",size ); printf("\n product = %u ",product); printf("\n &product[0] = %u ",&product[0]); printf("\n &product[1] = %u ",&product[1]); printf("\n &product[2] = %u ",&product[2]); printf("\nproduct + 3 = %u\n",(product+3) ); printf("\n Name \t Number \t Price\n"); for (ps=product; ps < product+3; ps++) { scanf ("%s %d %f", ps->name, &ps->number, &temp); ps->price = temp; } printf("\n Item Details...\n Name\tNumber\t Price\n"); for (ps=product; ps < product+3; ps++) printf ("\n%s %d %f", ps->name, ps->number, ps->price); getch(); }

Output: input Product details: sizeof(product[0]) = 26 product = 9478 &product[0] = 9478 &product[1] = 9504 &product[2] = 9530 product + 3 = 9556

Name Number Price Pen 101 10.45 Pencil 102 5.67 Book 103 12.63

Item Details…….

Name Number Price Pen 101 10.45 Pencil 102 5.67 Book 103 12.63

The compiler reserves the memory locations as shown below:

product[0] product[1] pro d uc t [2]

name number price name number price name number price

Address 9478 9498 9500 9504 9524 9526 9530 9550 9552

7.5 POINTER AND FUNCTION Pointer has deep relationship with function. We can pass pointer to the function and also addresses can be passed to the function as pointer argument. This can be represented by two ways as defined below:

1. Pointer as function argument. 2. Pointer to function. 7.5.1 Pointer as function argument This is achieved by call by reference. The call by reference method copies the address of an argument into the formal parameter. Inside the function, this address is used to access the argument used in the call. In this way, changes made to the parameter affect the variable used in the call to the function.

Call by reference is achieved by passing a pointer as the argument. Of course, in this case, the parameters must be declared as pointer types. The following program demonstrates this:

Example:

# include void swap (int *x, int *y); /* function prototype */ main () { int x, y; x = 10; y = 20; swap (&x, &y); /* addresses passed */ printf (“%d %d\n”, x, y); } void swap (int *a, int *b) { int temp;

temp = *a; *a = *b; *b = temp; } 7.5.2 Pointer to Function A function works like a variable. It is also similar to data type declaration like the other variable. Pointer to a function variable occurs when you define a function as a pointer. As function has address location in memory the syntax used to declare pointer to function is as:

Return _type (*function name) (list of arguments); or return_type (*fptr) (void); or void (*fptr) (float, int);

Where, return_type is the data type which may be integer, float or character and *(fptr) (argument list) is pointer to function. The procedure to illustrate this concept is as follows:

void add (int, int); void (*f1) (int, int); f1 = & add;

By using the above example, we say that add() is a simple function. But f1 is pointer variable which work as pointer to function and third statement the address of the add() function is assigned to f1 variable which is a memory variable. So, (*f1)(int, int) is a function pointer linked to the function add.

Example:

/* Program to add and substract two numbers by using the pointer to function. */

#include void add (int, int); void sub (int, int); void (*f1) (int, int); main() { f1 = & add; (*f1) (10, 15); f1 = & sub; (*f1) (11, 7); } void add (int a, int b) { printf ("\n Sum = %d", a + b); } void sub (int a, int b) { printf("\n sub = %d", a - b); }

Output:

Sum = 25 Sub = 4 7.6 ARRAY OF POINTERS We can have array of pointers since pointers are variables. Array of Pointers will handle variable length text lines efficiently and conveniently. How can we do this is:

Example:

#include void main(void) { char *p[5]; int x; p[0] = "DATA"; p[1] = "LOGIC"; p[2] = "MICROPROCESSOR"; p[3] = "COMPUTER"; p[4] = "DISKETTE"; for (x = 0; x < 5; ++x) printf("%s\n", p[x]); }

Output:

DATA LOGIC MICROPROCESSOR COMPUTER DISKETTE 7.6.1 Multidimensional arrays and pointers A 2D array is really a 1D array, each of whose elements is itself an array. Hence:

a[n][m] notation.

Array elements are stored row by row.

When we pass a 2D array to a function we must specify the number of columns -- the number of rows are irrelevant. The reason for this is pointers again. C needs to know how many columns in order that it can jump from row to row in memory. Consider int a[5][35] to be passed in a function:

We can do:

fun (int a[][35]) { … statements... } or even:

fun (int (*a)[35]) { …statements... }

We need parenthesis (*a) since [] have a higher precedence than *. So:

int (*a)[35]; declares a pointer to an array of 35 ints. int *a[35]; declares an array of 35 pointers to ints.

Now lets look at the difference between pointers and arrays. Strings are a common application of this. Consider:

char *name[10]; char aname[10][20];

 aname is a true 200 elements 2D char array.

 name has 10 pointer elements.

The advantage of the latter is that each pointer can point to arrays of different length. Let us consider (shown in figure 4.3):

char *name[10] = {“no month”, “jan”, “feb”}; char aname[10][20] = {“no month'', “jan”, ”feb”};

aname 20 elements n a me

n o mo n t h\ 0 0 n o mo n t h\ 0 ja n\ 0 1 ja n\ 0 fe b\ 0 10 2 fe b\ 0

Fig. 4.3. 2D Arrays and Arrays of Pointers

7.7 POINTER TO POINTER The concept of a pointer having the exclusive storage address of another pointer is called as pointer to pointer. Normally we do not use pointers to pointers very often but they can exist. The following program demonstrates this: Example:

#include void main(void) { int x, *p, **ptp; x = 454; p = &x; ptp = &p; printf("%d %d\n", *p, **ptp); }

Output:

454 454

**ptp is declared as a pointer to pointer of type int. This means that ptp handles the address of another pointer p. Variable x is assigned a value of 454, then its address is assigned to pointer p. Next, the address of pointer p is assigned to pointer to a pointer ptp. **ptp accesses the value of x. 7.8 DYNAMIC MEMORY ALLOCATION AND DYNAMIC STRUCTURES Dynamic allocation is a unique feature to C among high level languages. It enables us to create data types and structures of any size and length to suit our program need. The process of allocating memory at run time is known as dynamic memory allocation.

The four important memory management functions for dynamic memory allocation and reallocation are:

1. malloc 2. calloc 3. free 4. realloc

The malloc function:

The function malloc is used to allocate a block of memory of specified size. It is defined by: void *malloc (number_of_bytes)

The malloc function returns a pointer to the first byte of the allocated memory block.

Since a void * is returned the C standard states that this pointer can be converted to any type. For example,

char *cp; cp = (char *) malloc (100); attempts to get 100 bytes and assigns the starting address to cp.

We can also use the sizeof() function to specify the number of bytes. For example

int *ip; ip = (int *) malloc (100*sizeof(int));

Some C compilers may require to cast the type of conversion. The (int *) means force to an integer pointer. Forcing to the correct pointer type is very important to ensure pointer arithmetic is performed correctly.

It is good practice to use sizeof() even if you know the actual size you want - it makes for device independent (portable) code.

The sizeof can be used to find the size of any data type, variable or structure. Simply supply one of these as an argument to the function. So:

int i; struct complex { int real; int imaginary; }; typedef struct complex comp; sizeof(int), sizeof(i), sizeof(struct complex) and sizeof(comp) are all ACCEPTABLE.

The free function:

It frees (releases) the memory space allocated for a block. The syntax is:

free (ptr);

This releases the block of memory allocated which is currently pointed to by the pointer variable ptr. The advantage is simply memory management when we no longer need a block.

The calloc and realloc functions:

There are two additional memory allocation functions, calloc() and realloc(). Their prototypes are given below:

void *calloc ( num_elements, element_size}; void *realloc ( void *ptr, new_size); malloc does not initialise memory (to zero) in any way. If you wish to initialise memory then use calloc. The calloc is slightly more computationally expensive but, occasionally, more convenient than malloc. The syntax difference between calloc and malloc is that calloc takes the number of desired elements, num_elements, and element_size, as two individual arguments.

Thus to assign 100 integer elements that are all initially zero you would do:

int *ip; ip = (int *) calloc (100, sizeof(int));

The realloc is a function, which attempts to change the size of a previous allocated block of memory by malloc function. The new size can be larger or smaller. If the block is made larger than the older, it will extend only if it can find additional space in the same region. Otherwise, it may create entirely a new region (again, if space is available) and move the contents of the old block into the new block without any loss.

The realloc function to increase the size of block to 200 integers instead of 100, simply do: ip = (int *) calloc (ip, 200); If the size is to be made smaller then the remaining contents are unchanged. The realloc function to reduce the size of block to 50 integers instead of 200, simply do:

ip = (int *) calloc (ip, 50);

Example:

# include # include # include main() { char *ptr, *qtr; ptr = (char *) malloc ( 12); strcpy(ptr, "hello world" ); printf("\n Block now contains: %s", ptr); qtr =(char *) realloc(ptr,25); strcpy(qtr, "Hello beautiful world"); printf("\n The Block contents after reallocation: %s", qtr); ptr =(char *) realloc(qtr, 5); printf("\n After reducing the size: %s", ptr); }

Output:

Block now contains: hello world The Block contents after reallocation: Hello beautiful world After reducing the size: Hello ONE WORD ANSWERS

Q1). What is a pointer? Ans: A pointer is a variable which stores the address of other variable.

Q2) What are pointer constants? Ans: Memory address within a computer memory are reffered to as pointer constants.we cannot change them.we can use them only to store values.

Q3) How the address of the varible can be accessed? Ans: by using '&' operator.

Q4) How the pointer varible can be declared? Ans: By using the syntax given below data type *pt_name where data type is - what type of data the varible is going to assigned pt - means pointer

Q5. What is meant by initialization of pointers? Ans: The process of assigning the address of variable to a pointer is known as initialization of pointer.

Chain of pointers: The process of linking the pointer varible to another pointer varible is known as chain of pointers.this can be shown as **ptr.

Q6) What are pointer expressions? Ans: The experssion is a squence of operators and operands.if the operands used here are pointers then the expression becomes pointer expressions.

Q7) Can the pointer increments are possible? Ans: Yes,it is possible.

Q8) What is scale ? Ans: When the pointer is incremented,its value is increased by the 'size of the data type'.this is known as scale factor.

Q9) What the compiler does when the array name has been assigned to pointer variable? Ans: The compiler allocate the address of the first member of an array to the pointer.

Q10) What is meant by call by value? Ans: The process of passing th actual address of varibles to the function is known as call by value.

Q11) Which operator is used to access the structure member when we use pointer in structures? Ans: Arrow operator(->) or member selection operator.

Q12) What are the disadvantages of the pointer? Ans: a.Debugging becomes difficult task. b.Direct access of memory loose data security

Q13) Which arithmetic operations are allowed in pointers? Ans: Addition and Subtraction.

Q14) What is a near pointer? Ans: A pointer which can store an address value between 0 to 65,535. near pointer requires 2 bytes of memory.

Q15) What is a far pointer? Ans: A pointer which can store an address value between 0 to 232-1. far pointer requires four bytes of memory.

Q16) What is a generic pointer? Ans: A pointer which can store any type of address, that pointer is known as generic pointer.

Q17) How to represent a generic pointer ? Ans: void * is used to represent generic pointer

Q18) what is wild pointer? Ans: A pointer which is not initialized with any addresss is known as wild pointer

Q19) What is single pointer? Ans: A single pointer stores address of a variable. example: int *ptr,val; val=54; ptr=&val;

Q20) What is double pointer? Ans: A pointer which stores address of single pointer Example: int **p2,*p1,x; p1=&x; p2=&p1;

Multiple Choice Questions 1. Pointer is an example of which of the following type? a. derived type b. fundamental type c. User-defined type d. none of the above

2. An integer pointer: a. Points to the address of another integer value b. Points to any data type c. Points to itself d. None of the above

3. In the expression *ptr=&a,what does & signify a. address of a b. address of ptr c. value of a d. none of the above

4. Which of the following expressions in c is used for accessing the address Of a variable var? a. &(*var) b. *var c. &var d. *(&var)

5. Which of the following is a syntactically correct pointer declaration? a. float* X b. float *x c. float * X d. all are correct

6. Which of the following expressions will give the value stored in variable X? a. X b. *x C. *&X d. &X

7. If(int a1,*a2) a1=2 and a2=&a1 then what does a2++ depict(consider the address value of a1 to be 3802,a1&a2 are integer pointers) a. 3 b. 3803 c. 3804 d. 3802

8. If a1=2 and a2=&a1 then what does a2++ depict(consider the address value of a1 to be 3802,a1&a2 are char pointers) a. 3 b. 3803 c. 3804 d. 3802

9. If a1=2 and a2=&a1 then what does a2++ depict(consider the address value of a1 to be 3802,a1&a2 are float pointers) a. 3 b. 3803 c. 3804 d. 3806

10. If a1=&x and a2=&a1,what will be the output generated by the expression **a2? a. address of a2 b. address of a1 c. value of x d. address of x

11. How to get address of ith element of an array A? a. A[i] b. &A[i] c. *A[i] d. A[&i]

12. What is the size of an integer & float pointer? a. 2 & 4 b. 4 & 4 c. 2 & 2 d. 1 & 1

13) What is meaning of following declaration? int(*ptr[5])(); a. ptr is pointer to function. b. ptr is array of pointer to function. c. ptr is pointer to such function which return type is array. d. ptr is pointer to array of function. e. None of these

14) What is meaning of following pointer declaration? int(*(*ptr1)())[2];

a. ptr is pointer to function. b. ptr is array of pointer to function. c. ptr is pointer to such function which return type is pointer to an array d. ptr is pointer array of function. e. None of these

15) What will be the output of the following program : void main() { int val=50; const int *ptr1=&val; int const *ptr2=&ptr1; printf("%d %d %d",++val,*ptr1,*ptr2); *(int *)ptr1=98; printf("\n%d %d %d",++val,*ptr1,*ptr2); } a. Compile-Time Error b. 51 50 50 99 98 98 c. Run-Time Error d. None of these

16) What will be the output of the following program : void main() { int (*a)[5]; printf("%d %d",sizeof(*a),sizeof(a)); } a. Compile-Time Error b. 2 5 c. 5 2 d. None of these

17) What will be output of following program? #include void main() { char far *p =(char far *)0x55550005; char far *q =(char far *)0x53332225; *p = 25; (*p)++; printf("%d",*q); getch(); } a. 25 b. Address c. Garbage d. Compilation error e. None of above

18) What will be the output of the following program : void main() { int val=1234; int* ptr=&val; printf("%d %d",++val,*ptr); } a.1235 1235 b.1235 1234 c. 1235 1236 d. 1235 1237 19) What will be the output of the following program : void main() { int val=1234; int* ptr=&val; printf("%d %d",val,*ptr++); } a.1235 1235 b.1235 1234 c. 1234 1234 d. 1235 1237

20) What will be the output of the following program : void main() { int val=1234; int *ptr=&val; printf("%d %d",val,++*ptr); } a.1239 1239 b.1235 1234 c. 1235 1236 d. 1235 1235

21) What will be the output of the following program : void main() { int val=1234; int *ptr=&val; printf("%d %d",val,(*ptr)++); } a.1235 1235 b.1235 1236 c. 1235 1234 d. 1235 1237

22) What will be the output of the following program : void main() { int val=1234; int *ptr=&val; printf("%d %d",++val,(*(int *)ptr)--); } a.1234 1234 b.1235 1234 c. 1235 1236 d. 1235 1237

23) What will be the output of the following program : void main() { int a=555,*ptr=&a,b=*ptr; printf("%d %d %d",++a,--b,*ptr++); } a.556 555 554 b. 556 555 554 c. 556 554 555 d. 556 555 554 24) What will be the output of the following program : void main() { int a=555,b=*ptr,*ptr=&a; printf("%d %d %d",++a,--b,*ptr++); } a.compile time error b.456 564 c. 555 554 d. 555 555

25) What will be the output of the following program : void main() { int a=555,*ptr=&a,b=*ptr; printf("%d %d %d",a,--*&b,*ptr++); } a.56 564 b.56 68 666 c.555 554 555 d.56 57 578

26) What will be the output of the following program : void main() { int a=555,*ptr=&a,b=*ptr=777; printf("%d %d",--*&b,*(int *)&b); } a.46 6478 b.776 777 c.8 878 d.777 777

27) What will be the output of the following program : void main() { int a=5u,*b,**c,***d,****e; b=&a; c=&b; d=&c; e=&d; printf("%u %u %u %u",*b-5,**c-11,***d-6,65535+****e); } a. 0 65530 65535 5 b. 0 65530 65534 4 c.0 65530 65535 4 d. 0 65530 65502 5

28) What will be the output of the following program : void main() { float val=5.75; int *ptr=&val; printf("%.2f %.2f",*(float *)ptr,val); } a.508 509 b.5.6 5.6 c.5.8 5.9 d.5.75 5.75

29) What will be the output of the following program : void main() { int val=77; const int *ptr1=&val; int const *ptr2=ptr1; printf("%d %d %d",--val,(*ptr1)++,*ptr2); } a.58 b.96 c.compile time error d.69 30) What will be the output of the following program : int main() { int a=50,b=60; int* const ptr1=&a; printf("%d %d",--a,(*ptr1)++); ptr1=&b; printf("\n%d %d",++b,(*ptr1)++); } a.58 b. compile time error c.586 d.69

31) What will be the output of the following program : void main() { int a=50; const int* const ptr=&a; printf("%d %d",*ptr++,(*ptr)++); } a.50 b.96 c.compile time error d.69

32) What will be the output of the following program : void main() { int val=77; const int const *ptr=&val; printf("%d",*ptr); } a.78 b.56 c.77 d.79 33) What will be the output of the following program : void main() { int a[]={1,2,3,4,5,6}; int *ptr=a+2; printf("%d %d",--*ptr+1,1+*--ptr); } a.25 b.56 c.89 d.23

34) What will be the output of the following program : void main() { int a[]={1,2,3,4,5,6}; int *ptr=a+2; printf("%d %d",*++a,--*ptr); } a.12 b.32 c. compile time error d.56

35) What will be the output of the following program : void main() { int a[]={1,2,3,4,5,6}; int *ptr=a+2; printf("%d %d",*(1+a),--*ptr); } a.36 b.6 6 c.3 3 d.2 2

36) What will be the output of the following program : void main() { int matrix[2][3]={{1,2,3},{4,5,6}}; printf("%d %d %d\n",*(*(matrix)),*(*(matrix+1)+2),*(*matrix+1)); printf("%d %d %d",*(matrix[0]+2),*(matrix[1]+1),*(*(matrix+1))); } a.162 b.163 c.158 d.569 354 325 356 589 OUTPUT PREDICTION 1) What will be output of following program? #include void main() { int a = 320; char *ptr; ptr =( char *)&a; printf("%d ",*ptr); getch(); }

2) What will be output of following program? #include #include void main() { void (*p)(); int (*q)(); int (*r)(); p = clrscr; q = getch; r = puts; (*p)(); (*r)("gayathri degree college"); (*q)(); }

3) What will be output of following program? #include void main() { int i = 3; int *j; int **k; j=&i; k=&j; printf(“%u %u %d ”,k,*k,**k); }

4) What will be output of following program? #include #include void main() { char *ptr1 = NULL; char *ptr2 = 0; strcpy(ptr1," c"); strcpy(ptr2,"questions"); printf("\n%s %s",ptr1,ptr2); getch(); }

5) What will be output of following program? #include #include void main() { register int a = 25; int far *p; p=&a; printf("%d ",*p); getch(); }

6) What will be output of following program? #include #include void main() { int register a; scanf("%d",&a); printf("%d",a); getch(); } //if a=25

7) What will be output of following program? #include void main() { char arr[10]; arr = "world"; printf("%s",arr); getch(); }

8) What will be output if you will compile and execute the following c code? #include int main() { int a=5,b=10,c=15; int *arr[]={&a,&b,&c}; printf("%d",*arr[1]); return 0;

}

9) What will be output of following program? #include #include void main() { int a = 5,b = 10,c; int *p = &a,*q = &b; c = p - q; printf("%d" , c); getch(); }

10) What will be output of following program? #include unsigned long int (* avg())[3] { static unsigned long int arr[3] = {1,2,3}; return &arr; } void main() { unsigned long int (*ptr)[3]; ptr = avg(); printf("%d" , *(*ptr+2)); }

11) What will be output of following program? #include void main() { int * p , b; b = sizeof(p); printf(“%d” , b); }

12) What will be output of following program? #include void main() { int i = 5 , j; int *p , *q; p = &i; q = &j; j = 5; printf("value of i : %d value of j : %d",*p,*q); }

13) What will be output of following program? #include void main() { int i = 5; int *p; p = &i; printf(" %u %u", *&p , &*p);

}

14) What will be output of following program? #include void main() { int i = 100;/* note address of i 3000*/ printf("value of i : %d addresss of i : %u",i,&i); i++; printf("\nvalue of i : %d addresss of i : %u",i,&i); }

15) What will be output of following program? #include void main() { int i = 3; int *j; int **k; j = &i; k = &j; printf(“%u %u %u”,i,j,k); }

16) What will be output if you will compile and execute the following c code? #include int main() { static char *s[3]={"math","phy","che"}; typedef char *( *ppp)[3]; static ppp p1=&s,p2=&s,p3=&s; char * (*(*array[3]))[3]={&p1,&p2,&p3}; char * (*(*(*ptr)[3]))[3]=&array; p2+=1; p3+=2; printf("%s",(***ptr[0])[2]); return 0; }

6. STRINGS 6.1 INTRODUCTION TO STRINGS A string in the C language is simply an array of characters. Strings must have a NULL or \0 character after the last character to show where the string ends. A string can be declared as a character array or with a string pointer. The string can be declared as follow : Syntax: char string_nm[size]; Example: char name[50]; When compiler assigns string to character array then it automatically supplies null character ('\0') at the end of string. Thus, size of string = original length of string + 1. char name[7]; name = "TECHNO"

Take a look at this example: #include int main() { char str[20]; str[0] = 'H'; str[1] = 'E'; str[2] = 'L'; str[3] = 'L'; str[4] = 'O'; str[5] = '\n'; str[6] = '\0'; printf("%s", str); return 0; } Note: %s is used to print a string. String pointers are declared as a pointer to a char. When there is a value assigned to the string pointer the NULL is put at the end automatically. Ex: #include int main() { char *ptr_str; ptr_str = "HELLO"; printf("%s\n", ptr_str); return 0; } 6.2 READING AND WRITING STRINGS 6.2.1 Read Strings To read a string, we can use scanf() function with format specifier %s. char name[50]; scanf("%s",name); The above format allows accepting only string which does not have any blank space, tab, new line, forming feed, carriage return. 6.2.2 Write Strings To write a string, we can use printf() function with format specifier %s. char name[50]; scanf("%s",name); printf("%s",name); 6.2.3 Array of strings To create an array of strings, a two dimensional character array is used with the size of the left- Index determining the number of strings and the size of the right Index specifying the maximum length of each string.

For example, to declare an array of 30 strings each having a max length of 80 characters.

char str_array[30][80];

6.3 STRING HANDLING FUNCTIONS 'string.h' is a header file which includes the declarations, functions, constants of string handling utilities. These string functions are widely used today by many programmers to deal with string operations. Comparison functions memcmp Compare Memory Blocks strcmp String Compare String Compare Using Locale-Specific Collating strcoll Sequence strncmp Bounded String Compare strxfrm Transform Locale-Specific String Concatentation functions strcat String Concatenation Bounded String strncat Concatenation Copying functions memcpy Copy Memory Block memmove Copy Memory Block strcpy String Copy strncpy Bounded String Copy Search functions memchr Search Memory Block for Character strchr Search String for Character Search String for Intial Span of Characters strcspn Not in Set strpbrk Search String for One of a Set of Characters strrchr Search String in Reverse for Character Search String for Initial Span of Characters strspn in Set strstr Search String for Substring strtok Search String for Token Miscellaneous functions memset Initialize Memory Block strerror Convert Error Number to String strlen String Length Ex: #include #include #include void main() { char str[50]; clrscr(); printf("\n\t Enter your name : "); gets(str); printf("\nLower case of string: %s",strlwr(str)); printf("\nUpper case of string: %s",strupr(str)); printf("\nReverse of string: %s",strrev(str)); printf("\nLength of String: %d",strlen(str)); getch(); } Output: Enter your name : akanksha Lower case of string: akanksha Upper case of string: AKANKSHA Reverse of string: AHSKNAKA Length of String: 8 String Manipulation Functions 1. char *strcpy (char *dest, char *src) - Copy src string string into dest string. 2. char *strncpy(char *string1, char *string2, int n) - Copy first n characters of string2 to stringl . 3. int strcmp(char *string1, char *string2) - Compare string1 and string2 to determine alphabetic order. 4. int strncmp(char *string1, char *string2, int n) - Compare first n characters of two strings. 5. int strlen(char *string) - Determine the length of a string. 6. char *strcat(char *dest, const char *src); - Concatenate string src to the string dest. 7. char *strncat(char *dest, const char *src, int n); - Concatenate n chracters from string src to the string dest. 8. char *strchr(char *string, int c)- Find first occurrence of character c in string. 9. char *strrchr(char *string, int c) - Find last occurrence of character c in string. 10. char *strstr(char *string2, char string*1) - Find first occurrence of string string1 in string2. 11. char *strtok(char *s, const char *delim)- Parse the string s into tokens using delim as delimiter. String functions examples 1) int strlen(char array):This function accepts string as parameter and return integer i.e the length of String passed to it. Example #include #include void main(void) { char string[]="hello"; int len; len=strlen(string); printf("length of %s is %d\t",string,len); } Output::length of hello is 5. Note: strlen() does not include '\n' in string length or else length would be 6. 2) strcpy (Destination string,source string):This function accepts 2 strings as parameter,1st one is destination string and 2nd is source string. This function copies source string to destination string. Example #include #include void main(void) { char src[]="hello",dest[15]; strcpy(dest,src); printf("%s is copied to dest string\t",dest); } Output: hello is copied to dest string. 3) strcat (Destination string,source string): This function accepts two,strings source string is appended to the destination string. Example #include #include void main(void) { char src[]="sea",dest[]="programming"; strcat(dest,src); printf("concatenated string is %s",dest); } Output: concatenated string is programmingsea 4) strrev (string):This function accepts single string as parameter and reverse that string. Example #include #include void main(void) { char string[]="sea"; strrev(string); printf("reverse string is %s",string); } Output: reverse string is aes. 5)int strcmp (string 1, string2):This function compares two strings passed as parameters and returns either +ve number,0,-ve number.

+ve value indicates string1 > string2. 0 indicates string1 and string2 are equal -ve value indicates string1 < string2. Example #include #include void main(void) { char string1[]="sea",string2[]="programming"; int ; cmp=strcmp(string1,string2); if(cmp>0) printf("%s > %s",string1,string2); else { if(cmp<0) printf("%s < %s",string1,string2); else printf("%s = %s",string1,string2); } }

Output: sea > programming. .this is because alphabetically p comes first then s. so the string compare function returns difference between ASCII of s and p which would be +ve. 6) strcmpi (string 1, string2):This function is similar to strcmp().The onlyy difference is that it ignores the case . Example SparK and spark both are same. Example #include #include void main(void) { char string1[]="spark",string2[]="SPArk"; int cmp; cmp=strcmpi(string1,string2); if(cmp>0) printf("%s > %s",string1,string2); else { if(cmp<0) printf("%s < %s",string1,string2); else printf("%s = %s",string1,string2); } } Output: spark = SPArk. 7) strlwr (string)::This function accepts single string that can be in any case(lower or upper).It converts the string in lower case. Example #include #include void main(void) { char string1[]="Hello"; strlwr(string1); printf("%s is in lower case",string1); } Output: hello is in lower case. 8) strupr (string)::This function accepts single string that can be in any case(lower or upper).It converts the string in upper case. Example #include #include void main(void) { char string1[]="hello"; strupr(string1); printf("%s is in upper case",string1);

} Output: HELLO is in upper case. 9)char* strstr (main string,substring): This function accepts two strings i.e main string and substring. It searches for the first occurrence substring in main string and returns the character pointer to the first char. Example #include #include void main() { char str1[]="programmingsea",str2[]="ming",*ptr; ptr=strstr(str1, str2); printf("substring is: %s",ptr); getch(); } Output : substring is mingsea

C program to count the number of vowels and consonants in a string Here is the program to count number of vowels and consonants in c. #include #include #include void main() { char str[50]; int vovels=0,consonants=0,len,i; printf("Enter the String:\n"); gets(str); len=strlen(str); for(i=0;i64&&str[i]<91)||(str[i]>96&&str[i]<123)) //Firstly checking the character is alphabet or not { if(str[i]=='a'||str[i]=='A'||str[i]=='e'||str[i]=='E'||str[i]=='i'||str[i]=='I'||str[i]=='o'||str[i]=='O'||str[i]=='u'| |str[i]=='U') //checking if it is vowel or not vovels++; else consonants++; } } printf("Number of vovels = %d and consonants = %d ",vowels, consonants); getch(); } Output: Enter the String: Welcome to C Number of vovels = 4 and consonants = 6 C program to count number of words,spaces,characters,digits and special symbols #include //#include void main() { int i=0,chr=0,sp=0,words=1,ss=0,digits=0; char line[100],temp=32; //clrscr(); printf("\nEnter the line:\n"); gets(line);

while(line[i]!='\0') //to check for string termination { if((line[i]>64&&line[i]<91)||(line[i]>96&&line[i]<123)) // ascii range of characters chr++; else { if(line[i]==32) //ascii value of space is 32 { sp++; if(temp!=32) words++; } else { if(line[i]>47&&line[i]<58) //ascii range of digits digits++; else ss++; } } temp=line[i]; i++; } printf("\nNumber of characters = %d words = %d spaces %d special symbols = %d digits = %d",chr,words,sp,ss,digits); } Output: Enter the line: Hello3847 Wor#4@ld

Number of characters = 10 words = 2 spaces 1 special symbols = 2 digits = 5 ONE WORD ANSWERS Q1. What is a string? Ans: Sstring is a collection of characters.

Q2) Which is the last character of a string ? Ans: Null character is the last char of a string

Q3). Write the general form of the declaration of a simple string? Ans: char string_name[size];

Q4) Other than the scanf function,what is the other function that can be used to read the string? Ans: gets() is the other function that can be used to read the string.

Q5) What is the funtcion we use to write the string on the screen? Ans: printf() function by using format code %s.

Q6) What is getchar()? Ans: it reads a charactor from the keyboard.

Q7) What is meant by concatenation? Ans: The process of combining one string with another is known as string concatneation.

Q8) What is meant by strcmp? Ans: The process of comparing the one string into another is known as strcmp.

Q9) Which header file is used for string operations? Ans: string.h .

Q10) What is meant by strncmp? Ans: This is a three parametre function that compares only 'n' characters of both the given strings. the general format of the function is strncmp(s1,s2,n); MULTIPLE CHOICE QUESTIONS 1. Which of the following is used to represent the end of a string? a. blank space b. null character c. newline character d. last element of the string

2. Which of the following is used to display a string on I/O console? a. %s b. %d c. %c d. %f

3. Which of the following is true for getchar? a. read a string of characters b. read a character c. read the characters until \n is encountered d. none of the above

4. What is the value of x in the following character arithmetic expression? X='A'-2; a. 63 b. 64 c. 65 d. 66

5. Which function is used to determine the length of a string? a. strcmp b. strcpy c. strlen d. strcat

6. What value will strlen functions return for the string {'r','a','m','\0'} a. 3 b. 4 c. 5 d. None of the above

7. Which of the following is the correct syntax for copying a string S1 into S2? a. strcmp(S2,S1); b. strcpy(S1,S2); c. strcmp(S1,S2); d. strcpy(S2,S1);

8. Which of the following should be used for printing using printf statement"? a. """ b. "\ c \" d. /" OUTPUT PREDICTION 1. What will be output when you will execute following c code? #include void main() { char arr[7]="Network"; printf("%s",arr); }

2. What will be output when you will execute following c code? #include void main() { char arr[11]="The African Queen"; printf("%s",arr); }

3. What will be output when you will execute following c code? #include void main() { int const SIZE=5; int expr; double value[SIZE]={2.0,4.0,6.0,8.0,10.0}; expr=1|2|3|4; printf("%f",value[expr]); }

4.What will be output when you will execute following c code? #include enum power { Dalai, Vladimir=3, Barack, Hillary}; void main() { float leader[Dalai+Hillary]={1.f,2.f,3.f,4.f,5.f}; enum power p=Barack; printf("%0.f",leader[p>>1+1]); }

5) What will be output when you will execute following c code? #include #define var 3 void main() { char *cricket[var+~0]={"clarke","kallis"}; char *ptr=cricket[1+~0]; printf("%c",*++ptr); }

6) What will be output when you will execute following c code? #include void main() { char data[2][3][2]={0,1,2,3,4,5,6,7,8,9,10,11}; printf("%o",data[0][2][1]); }

7) What will be output when you will execute following c code? #include void main() { short num[3][2]={3,6,9,12,15,18}; printf("%d %d",*(num+1)[1],**(num+2)); }

8) What will be output when you will execute following c code? #include void main() { char *ptr="cquestionbank"; printf("%d",-3[ptr]); } 9) What will be output when you will execute following c code? #include void main() { long myarr[2][4]={0l,1l,2l,3l,4l,5l,6l,7l}; printf("%ld\t",myarr[1][2]); printf("%ld%ld\t",*(myarr[1]+3),3[myarr[1]]); printf("%ld%ld%ld\t",*(*(myarr+1)+2),*(1[myarr]+2),3[1[myarr]]); }

10) What will be output when you will execute following c code? #include void main() { int array[2][3]={5,10,15,20,25,30}; int (*ptr)[2][3]=&array; printf("%d\t",***ptr); printf("%d\t",***(ptr+1)); printf("%d\t",**(*ptr+1)); printf("%d\t",*(*(*ptr+1)+2)); }

11. What will be output when you will execute following c code? #include void main() { static int a=2,b=4,c=8; static int *arr1[2]={&a,&b}; static int *arr2[2]={&b,&c}; int* (*arr[2])[2]={&arr1,&arr2}; printf("%d %d\t",*(*arr[0])[1], *(*(**(arr+1)+1))); }

12.What will be output when you will execute following c code? #include #include double myfun(double); void main() { double(*array[3])(double); array[0]=exp; array[1]=sqrt; array[2]=myfun; printf("%.1f\t",(*array)((*array[2])((**(array+1))(4)))); } double myfun(double d) { d-=1; return d; }

13) What will be output when you will execute following c code? #include typedef struct { char *name; double salary; }job; void main() { static job a={"TCS",15000.0}; static job b={"IBM",25000.0}; static job c={"Google",35000.0}; int x=5; job * arr[3]={&a,&b,&c}; printf("%s %f\t",(3,x>>5-4)[*arr]); } double myfun(double d) { d-=1; return d; }

14)What will be output when you will execute following c code? #include union group { char xarr[2][2]; char yarr[4]; }; void main() { union group x={'A','B','C','D'}; printf("%c",x.xarr[x.yarr[2]-67][x.yarr[3]-67]); }

15.What will be output when you will execute following c code? #include void main() { int a=5,b=10,c=15; int *arr[3]={&a,&b,&c}; printf("%d",*arr[*arr[1]-8]); }

16) What will be output when you will execute following c code? #include void main() { int arr[][3]={{1,2},{3,4,5},{5}}; printf("%d %d %d",sizeof(arr),arr[0][2],arr[1][2]); }

17)What will be output when you will execute following c code? #include void main() { int xxx[10]={5}; printf("%d %d",xxx[1],xxx[9]); }

18) What will be output when you will execute following c code? #include #define WWW -1 enum {cat,rat}; void main() { int Dhoni[]={2,'b',0x3,01001,'\x1d','\111',rat,WWW}; int i; for(i=0;i<8;i++) printf(" %d",Dhoni[i]); }

19)What will be output when you will execute following c code? #include void main() { long double a; signed char b; int arr[sizeof(!a+b)]; printf("%d",sizeof(arr)); }

20)What will be output when you will execute following c code? #include void main() { char array[]="Ashfaq \0 Kayani"; char *str="Ashfaq \0 Kayani"; printf("%s %c\n",array,array[2]); printf("%s %c\n",str,str[2]); printf("%d %d\n",sizeof(array),sizeof(str)); }

8 STRUCTURES AND UNIONS 8.1 INTRODUCTION TO STRUCTURES A structure is a user defined data type. Using a structure we have the ability to define a new type of data considerably more complex than the types we have been using.

A structure is a collection of variables referenced under one name, providing a convenient means of keeping related information together. The variables which make up a structure are called structure elements.

In the following, the C keyword struct tells the compiler that a structure template is being defined:

struct addr { char name[30]; char street[40]; int postalcode; };

In this example, addr is known as the structure tag. A structure definition is actually a statement hence it is terminated by a semicolon.

A structure variable declaration of type addr is:

struct addr addr_info;

Variables may also be declared as the structure is defined. This can be done as follows:

struct addr { char name[30]; char street[40]; int postalcode; } addr_info, binfo, cinfo;

If only one variable is needed, the structure tag is not needed, for example:

struct { char name[30]; char street[40]; int postalcode; } addr_info;

8.1.1 Structure Assignments ANSI C compilers allow the information in one structure to be assigned to another structure as:

binfo = addr_info; 8.1.2 Declaring Structure Pointers Assuming the previously defined structure addr, the following declares addr_pointer as a pointer to data of that type:

struct addr *addr_pointer; 8.2 REFERENCING STRUCTURE ELEMENTS Individual elements of a structure are referenced using the operator. The pointer to a structure member operator -> is used to access a member of a structure using a pointer variable. 8.2.1 Accessing Structure members using dot operator Individual elements of a structure are referenced using the dot operator, for example:

addr_info. postalcode = 1234; printf ("%d",addr_info. postalcode);

Example:

# include # include struct { char name[15]; /* childs name */ int age; /* childs age */ int grade; /* childs grade in school */ } boy, girl; int main() { strcpy (boy.name, “Herbert”); boy.age = 15; boy.grade = 75; girl.age = boy.age - 1; /* she is one year younger */ girl.grade = 82; strcpy (girl.name, “Fousett”); printf ("%s is %d years old and got a grade of %d\n", girl.name, girl.age, girl.grade); printf ("%s is %d years old and got a grade of %d\n", boy.name, boy.age, boy.grade); return 0; } Output:

Fousett is 14 years old and got a grade of 82 Herbert is 15 years old and got a grade of 75 8.2.2 Accessing Structure Pointers using -> operator Structure pointers may be used to generate a call by reference to a function and to create linked lists and other dynamic data structures. Call by reference can be used for structures to avoid overheads occurred by the push and pop operations of all the structure elements of the stack. For example if:

struct addr_info *ptr;

To access the elements of a structure using a pointer, the -> operator is used:

ptr -> postalcode where, ptr has been declared as a pointer to the type of structure and assigned the address of a variable of that type, and postalcode is a structure element within that variable.

This can also be expressed as:

(*ptr). postalcode

The parenthesis is necessary because the structure member operator “. “ takes higher precedence than does the indirection operator.

Example:

#include struct { char initial; int age; int grade; } kids[12], *point, extra; int main() { int index;

for (index = 0 ; index < 12 ; index++) { point = kids + index; point->initial = 'A' + index; point->age = 16; point->grade = 84; }

kids[3].age = kids[5].age = 17; kids[2].grade = kids[6].grade = 92; kids[4].grade = 57;

for (index = 0 ; index < 12 ; index++) { point = kids + index; printf("%c is %d years old and got a grade of %d\n", (*point).initial, kids[index].age, point->grade); } extra = kids[2]; /* Structure assignment */ extra = *point; /* Structure assignment */

return 0; }

Output:

A is 16 years old and got a grade of 84 B is 16 years old and got a grade of 84 C is 16 years old and got a grade of 92 D is 17 years old and got a grade of 84 E is 16 years old and got a grade of 57 F is 17 years old and got a grade of 84 G is 16 years old and got a grade of 92 H is 16 years old and got a grade of 84 I is 16 years old and got a grade of 84 J is 16 years old and got a grade of 84 K is 16 years old and got a grade of 84 L is 16 years old and got a grade of 84 8.3 ARRAYS OF STRUCTURES The following example declares a 100-element array of type addr:

struct addr addr_arr [100]; in which the postalcode element of structure 3 would be accessed by:

printf ("%d", addr_info [2]. postalcode);

Example:

#include struct { char initial; int age; int grade; } kids[12]; int main() { int index; for (index = 0 ; index < 12 ; index++) { kids[index].initial = 'A' + index; kids[index].age = 16; kids[index].grade = 84; }

kids[3].age = kids[5].age = 17; kids[2].grade = kids[6].grade = 92; kids[4].grade = 57;

kids[10] = kids[4]; /* Structure assignment */

for (index = 0 ; index < 12 ; index++) printf("%c is %d years old and got a grade of %d\n", kids[index].initial, kids[index].age, kids[index].grade); return 0; }

Output:

A is 16 years old and got a grade of 84 B is 16 years old and got a grade of 84 C is 16 years old and got a grade of 92 D is 17 years old and got a grade of 84 E is 16 years old and got a grade of 57 F is 17 years old and got a grade of 84 G is 16 years old and got a grade of 92 H is 16 years old and got a grade of 84 I is 16 years old and got a grade of 84 J is 16 years old and got a grade of 84 E is 16 years old and got a grade of 57 L is 16 years old and got a grade of 84 8.4 PASSING STRUCTURES TO FUNCTIONS When an element of a non-global structure is to be passed to a function, the value of that element is passed (unless that element is complex, such as an array of characters).

Example:

struct fred { char x; int y; char s[10]; } mike; each element would be passed like this:

funct (mike.x); /* passes character value of x */ funct (mike.y); /* passes integer value of y */ funct (mike.s); /* passes address of string */ funct (mike.s[2]); /* passes character val of s[2] */

If the address of the element is required to be passed, the & operator is placed before the structure name. In the above example, this would apply except in funct (mike.s);. 8.5 PASSING ENTIRE STRUCTURES TO FUNCTIONS When a structure is used as an argument to a function, the entire structure is passed using the standard call-by-value method. Of course, this means that changes made to the contents of the structure inside the function do not affect the structure used as the argument.

8.6 ARRAYS AND STRUCTURES WITH IN STRUCTURES Structure elements may be arrays and structures. When a structure is an element of another structure, it is called a nested structure. Example:

#include struct person { char name[25]; int age; char status; /* M = married, S = single */ }; struct alldat { int grade; struct person descrip; char lunch[25]; }; int main() { struct alldat student[53]; struct alldat teacher, sub; teacher.grade = 94; teacher.descrip.age = 34; teacher.descrip.status = 'M'; strcpy(teacher.descrip.name, "Mary Smith"); strcpy(teacher.lunch, "Baloney sandwich");

sub.descrip.age = 87; sub.descrip.status = 'M'; strcpy(sub.descrip.name, "Old Lady Brown"); sub.grade = 73; strcpy(sub.lunch, "Yogurt and toast");

student[1].descrip.age = 15; student[1].descrip.status = 'S'; strcpy(student[1].descrip.name, "Billy Boston"); strcpy(student[1].lunch, "Peanut Butter"); student[1].grade = 77;

student[7].descrip.age = 14; student[12].grade = 87;

return 0; }

Output:

This program does not generate any output 8.7 TYPEDEF typedef allows a new data type to be explicitly defined. Note that it does not actually create a new data class, but simply defines a new name for an existing type. This process helps in making machine-dependent code more portable, since only the typedef statements need be changed. It can also aid in self-documenting a program by allowing the use of more descriptive names for the standard data types.

The general form of defining a new data type is:

typedef data type identifier;

Where, identifier refers to new name(s) given to the data type. User defined types obey the same scope rules as identifiers, so if one defined in a function, it is recognized only within that function. Few examples of type definitions are

typedef int age; typedef float average; typedef char string;

Where age symbolizes int, average symbolizes float and string symbolizes char. They can be later used to declare variables as:

age child, adult; average mark1, mark2; string name[20];

Where child and adult are declared as integer variables, mark1 and mark2 are declared as floating point variables and name is declared as character array variable.

The typedef can also be used to define structures. The main advantage of type definition is that, you can create meaningful data type names for increasing the readability of the program. They also suggest the purpose of the data type names used in the program.

8.8 UNIONS A union is a memory location, which is shared by two or more different variables, generally of different types, at different times. The general form of a union definition is:

union tag { type variable_name; type variable_name; type variable_name; . . } union_variables;

An example definition is as follows:

union u_type { int i; char ch; };

Declaration options are as for structures, i.e, variable names may be placed at the end of the definition or a separate declaration statement may be used.

A union shares the memory space instead of wasting storage on variables that are not being used. The compiler allocates a piece of storage that is large enough to hold the largest type in the union. 8.8.1 Accessing Union Elements Union elements are accessed using the same methods used for accessing structure elements.

The union aids in the production of machine-independent code because the compiler keeps track of the actual sizes of the variables, which make up the union. unions are frequently used when type conversions are needed because the data held in a union can be referred to in different ways.

Example 1: union exam { int roll_no; char name[15]; int mark1,mark2,mark3; } u1; struct exam1 { int roll_no; char name[15]; int mark1, mark2, mark3; } s1; void main() { printf(“The size of union is %d\n”, sizeof(u1)); printf(“The size of structure is %d”, sizeof(s1)); }

Output:

The size of the union is 15 The size of the structure is 23

In the above example, union exam has 5 members. The first member is a character array name having 15 characters (i.e., 15 bytes). The second member is of type int that requires 2 bytes for their storage. All the other members mark1, mark2, mark3 are of type int which requires 2 bytes for their storage. In the union, all these 5 members are allocated in a common place of memory (i.e., all the members share the same memory location). As union shares the memory space instead of wasting storage on variables that are not being used, the compiler allocates a piece of storage that is large enough to hold the largest type in the union. In the above declaration, the member name requires, 15 characters, which is the maximum of all members, hence a total memory space of 15 bytes is allocated. In case of structures, the total memory space allocated will be 23 (i.e. 15+2+2+2+2) bytes.

Example 2:

#include void main() { union dec { int x; char name[4]; } dec1; int i; dec1.x = 300; printf(“Size of union = %d\n”, sizeof(dec1)); printf(“The value of x = %u\t”, dec1.x); printf(“\n%u %u %u %u”, dec1.name[0], dec1.name[1], dec1.name[2], dec1.name[3]); }

Output:

Size of union = 4 The value of x = 300 44 1 65461 74

The binary value of 300 is 0000 0001 0010 1100. As per the internal storage representation first 0010 1100 = 44 is stored then 0000 0010 = 01 is stored.

Example 3:

#include #include #include struct hos { char name[10]; char hostelname[20]; }; struct daysch { int phonenumber; char name[10]; char address[40]; int rollno; }; union student { struct hos hostler; struct daysch dayscholar ; } stu_data; void main() { int n; clrscr(); printf("\n MENU "); printf("\n 1. Hostler \n 2. Day Scholar\n"); printf("\n enter the choice: "); scanf("%d",&n); if(n==1) { strcpy(stu_data.hostler.name,"Herbert"); strcpy(stu_data.hostler.hostelname,"ss2"); printf("\n student name: %s",stu_data.hostler.name); printf("\n hostle name: %s",stu_data.hostler.hostelname); printf("\n Union Data size: %d",sizeof(stu_data) ); printf("\n Hostler Data size: %d",sizeof(stu_data.hostler) ); } else if(n==2) { strcpy(stu_data.dayscholar.name,"Schildt"); strcpy(stu_data.dayscholar.address,"balaji colony"); stu_data.dayscholar.phonenumber=5620; stu_data.dayscholar.rollno = 1290; printf("\n student name: %s", stu_data.dayscholar.name); printf("\n address: %s", stu_data.dayscholar.address); printf("\n phone number: %d", stu_data.dayscholar.phonenumber); printf("\n roll number: %d", stu_data.dayscholar.rollno); printf("\n Union Data size: %d", sizeof(stu_data) ); printf("\n Day Scholar Data size: %d", sizeof(stu_data.dayscholar) ); } else printf("\n it is wrong choice "); getch(); }

Output:

RUN 1:

MENU 1. Hostler 2. Day Scholar

Enter Your Choice: 2

Student name: Schildt Address: balaji colony Phone number: 5620 Roll no: 1290 Union data size: 54 Day scholar data size: 54

RUN 2:

MENU 1. Hostler 2. Day Scholar

Enter Your Choice: 1

Student name: Herbert Hostel name: ss2 Union data size: 54 Hostler data size: 30 In the above example, the declaration structure name hos requires 30 bytes and structure daysch requires 54 bytes of memory. In union stu_data both structures are allocated in a common place of memory (i.e. both are sharing same memory location). In our case a student can be either an hostler or a data scholar. So, the same memory can be used for both type of students. So instead of allocating 84 bytes of memory the same can be achieved using 54 bytes of memory. 8.9 ENUMERATIONS The keyword enum is used to declare enumeration types. It provides a means of naming a finite set, and of declaring identifiers as elements of the set. Enumerations are defined much like structures. An example definition for user defined type day is as follows:

enum day {sun, mon, tue, wed, thu, fri, sat};

An example declaration is:

enum day day_of_week;

This creates the user defined type enum day. The keyword enum is followed by the tag name day. The enumerators are the identifiers sun, mon, . . ., sat. They are constants of type int. By default the first one 0 and each succeeding one has the next integer value.

Initialization:

The enumerators can be initialized. Also we can declare variables along with the template. The following example do so:

enum suit {clubs = 1, diamonds, hearts, spades} a, b, c; clubs has been initialized to 1, diamonds, hearts and spades have the values 2, 3, and 4 respectively. a, b, and c are variables of this type.

As another example of initialization:

enum fruit {apple = 7, pear, orange = 3, lemon} frt;

Because the enumerator apple has been initialized to 7, pear has value 8. Similarly, because orange has a value 3, lemon has a value 4. Multiple values are allowed, but the identifiers themselves must be unique.

Example:

# include # include enum day {sun, mon, tue, wed, thu, fri, sat}; main() { int n; clrscr (); printf (“Enter a day number (0 for sunday and so on upto 6):”); scanf (“%d”,&n);

switch (n) { case sun: printf(“\nSunday“); break; case mon: printf(“\nMonday“); break; case tue: printf(“\nTuesday“); break; case wed: printf(“\nWednesday“); break; case thu: printf(“\nThursday“); break; case fri: printf(“\nFriday“); break; case sat: printf(“\nSaturday“); break; } getch(); }

8.10 BIT-FIELDS C has a built-in method for accessing a single bit within a byte. This is useful because:  If memory is tight, several Boolean (true/false) variables can be stored in one byte, saving memory.  Certain devices transmit information encoded into bits within one byte.  Certain encryption routines need to access individual bits within a byte.

Tasks involving the manipulation of bits may, of course, be performed using C's bitwise operators. However, the bit-field provides a means of adding more structure and efficiency to the coding.

Bit-Fields - A Type of Structure:

To access bits using bit-fields, C uses a method based on the structure. In fact, a bit-field is simply a special type of structure element, which defines how long in bits the field is to be.

The general form of a bit-field definition is:

struct tag { type name1: length; type name2: length; type name3: length; } variable_list;

A bit-field must be declared as either int, unsigned, or signed. Bit-fields of length 1 should be declared as unsigned because a single bit cannot have a sign.

An Example Application:

Bit-fields are frequently used when analyzing input from a hardware device. For example, the status port of a serial communications device might return a status byte like this: Bit Meaning When Set 0 Change in -to-send line. 1 Change in data-set-ready. 2 Trailing edge detected. 3 Change in receive line. 4 Clear-to-send. 5 Data-set-ready. 6 Telephone ringing. 7 Received signal.

Defining the Bit-Field:

The foregoing can be represented in a status byte using the following bit-field definition/declaration:

struct status_type { unsigned delta_cts: 1; unsigned delta_dsr: 1; unsigned tr_edge: 1; unsigned delta_rec: 1; unsigned cts: 1; unsigned dsr: 1; unsigned ring: 1; unsigned rec_line: 1; } status;

Using this bit-field, the following routine would enable a program to determine whether it can send or receive data:

status = get_port_status; if(status.cts) printf("Clear to send"); if(status.dsr) printf("Data set ready);

Referencing Bit-Field Elements:

Values are assigned to a bit-field using the usual method for assigning values to structure elements, e.g.:

status.ring = 0;

As with structures, if an element is referenced through a pointer, the -> operator is used in lieu of the dot operator.

Variations in Definition:

All bit-fields need not necessarily be named, which allows unused ones to be bypassed. For example, if, in the above example, access had only been required to cts and dsr, status_type could have been declared like this:

struct status_type { unsigned: 4; unsigned cts: 1; unsigned dsr: 1; } status;

Example:

#include union { int index; struct { unsigned int x : 1; unsigned int y : 2; unsigned int z : 2; } bits; } number; int main () { for (number.index = 0 ; number.index < 20 ; number.index++) { printf ("index = %3d, bits = %3d%3d%3d\n", number.index, number.bits.z, number.bits.y, number.bits.x); }

return 0; }

Output: index = 0, bits = 0 0 0 index = 1, bits = 0 0 1 index = 2, bits = 0 1 0 index = 3, bits = 0 1 1 index = 4, bits = 0 2 0 index = 5, bits = 0 2 1 index = 6, bits = 0 3 0 index = 7, bits = 0 3 1 index = 8, bits = 1 0 0 index = 9, bits = 1 0 1 index = 10, bits = 1 1 0 index = 11, bits = 1 1 1 index = 12, bits = 1 2 0 index = 13, bits = 1 2 1 index = 14, bits = 1 3 0 index = 15, bits = 1 3 1 index = 16, bits = 2 0 0 index = 17, bits = 2 0 1 index = 18, bits = 2 1 0 index = 19, bits = 2 1 1

Mixing Normal and Bit-Field Structure Elements:

Normal and bit-field structure elements may be mixed, as in:

struct emp { struct addr address; float pay; unsigned lay-off: 1; /* lay-off or active */ unsigned hourly: 1; /* hourly pay or wage */ unsigned deducts: 3; /* tax deductions */ } which demonstrates the use of only one byte to store information which would otherwise require three bytes.

Limitations of bit-fields:

Bit-field variables have certain limitations. For example:  The address of a bit-field variable cannot be taken.  Bit-field variables cannot be arrayed.  Integer boundaries cannot be overlapped.  There is no certainty, from machine to machine, as to whether the fields will run from right to left or from left to right. In other words, any code using bit-fields may have some machine dependencies. ONE WORD ANSWERS Q1) What is a structure? Ans: A structure is a collection of heterogeneous data.

Q2) What is the general format of the structure? Ans: The general format\ of a structure is struct tag_name { datatype name1; datatype name2; : : : }; where name1,name2...... are called as structure members.

Q3). What are the major differences between arrays and structures? Ans: a. an array is a collection of similar datatypes where as the stuctrure is a collection of different data types. b. an array is derived datatype where as a structure is user defined datatype.

Q4). How the members of a structure can be accessed? Ans: The members of a structure can be accessed using the dot operator or arrow operator.

Q5) How is the structure initialized at compiletime? Ans: Structure at compiletime can be initialised in this way struct Test { int a; char c[10]; }; struct tag_name s1={10,"ravi"};

Q6). How is the structure initialised at runtime? Ans: Structure at runtime can be initialised in this way struct tag_name { int a; char c[10]; }; struct tag_name s1; scanf("%d,%c",&s1.a,s1.c);

Q7). What is nested structure? Ans: A structure within a structure is called as nested structure.

Q8) Give an example of array of structures? Ans: struct student s[100];

Q9). What is the general format of sending a copy of a structure to the called function? Ans: The general fomrat of sending a copy of a structure to the called function is function_name(structure_variable name); Q10) What is enum? Ans: It is a special keyword which allows to define symbolic constants.

Q11) How is enum defined? Ans: It is defined as follows enum identifier{value1,value2,...... valuen};

Q12) Give examples for enumerated datatypes. Ans: enum day {monday,tuesday...... sunday}; enum day week_st,week_end;

Q13) What is the starting value of enumerated set? Ans: zero

Q14) What is typedef? Ans: It is a keyword , used to redfine an existing data type.

Q15) Give some examples how to use typedef? Ans: typedef int units; typedef float marks; they can later be used to declare the variables as follows units batch1,batch2; marks name1[50],name2[50];

Q16) Illustrate the use of data type conversion Ans: average=(float) total/n; the value of the variable total; is converted to type float before the operation is performed, thereby guarantee that the division will be carried out as a floating point operation

MULTIPLE CHOICE QUESTIONS 1. A structure should store ---? a. multiple values of the same type b. multiple values of different types c. multiple values of the same user-defined type d. None of the above

2. Which of the following is the correct way of assigning a value to the "rollno" of a simple structure variable student a. student.rollno b. student->rollno c. student(rollno) d. None of the above

3. The uninitialized integer data type of a structure contains which of the following default values? a. garbage b. zero c. one d. None of the above

4. Which of the following expressions arre correct for accessing the 'num' variable value of the ith element of a structure array 'student' a. student[i].num b. student.num[i] c. student[i]_>num d. None of the above

5. which is necessary at the end of definition of a structure? a. * b. & c. : d. ;

6. What comes after the closing brace when we use typedef definition a. type_name; b. type name; c. type_type; d. None of the above

7. what must be used to declare a variable in an independent statement? a. name b. type c. type_name d. None of the above

8. A structure member can be accessed using______a. arrow operator b. dot operator c. both a&b d. None of the above

9. A structure can contain a. only int data types b. only char data types c. any data type d. None of the above OUTPUT PREDICTION 1) What will be the output of the following program : struct { int i; float f; }var; void main() { var.i=5; var.f=9.76723; printf("%d %.2f",var.i,var.f); }

2) What will be the output of the following program : struct { int i; float f; }; void main() { int i=5; float f=9.76723; printf("%d %.2f",i,f); }

3) What will be the output of the following program : struct values { int i; float f; }; void main() { struct values var={555,67.05501}; printf("%2d %.2f",var.i,var.f); }

4) What will be the output of the following program : typedef struct { int i; float f; }values; void main() { static values var={555,67.05501}; printf("%2d %.2f",var.i,var.f); }

5) What will be the output of the following program : struct my_struct { int i=7; float f=999.99; }var; void main() { var.i=5; printf("%d %.2f",var.i,var.f); }

6) What will be the output of the following program : struct first { int a; float b; }s1={32760,12345.12345}; typedef struct { char a; int b; }second; struct my_struct { float a; unsigned int b; }; typedef struct my_struct third; void main() { static second s2={'A',- -4}; third s3; s3.a=~(s1.a-32760); s3.b=-++s2.b; printf("%d %.2f\n%c %d\n%.2f %u",(s1.a)-- ,s1.b+0.005,s2.a+32,s2.b,++(s3.a),--s3.b); } 7) What will be the output of the following program : struct { int i,val[25]; }var={1,2,3,4,5,6,7,8,9},*vptr=&var; void main() { printf("%d %d %d\n",var.i,vptr->i,(*vptr).i); printf("%d %d %d %d %d %d",var.val[4],*(var.val+4), vptr- >val[4],*(vptr->val+4),(*vptr).val[4],*((*vptr).val+4)); }

8) What will be the output of the following program : typedef struct { int i; float f; }temp; void alter(temp *ptr,int x,float y) { ptr->i=x; ptr->f=y; } void main() { temp a={111,777.007}; printf("%d %.2f\n",a.i,a.f); alter(&a,222,666.006); printf("%d %.2f",a.i,a.f); }

9) What will be the output of the following program : typedef struct { int i; float f; }temp; temp alter(temp tmp,int x,float y) { tmp.i=x; tmp.f=y; return tmp; } void main() { temp a={111,777.007}; printf("%d %.3f\n",a.i,a.f); a=alter(a,222,666.006); printf("%d %.3f",a.i,a.f); }

10) What will be the output of the following program : typedef struct { int i; float f; }temp; temp alter(temp *ptr,int x,float y) { temp tmp=*ptr; printf("%d %.2f\n",tmp.i,tmp.f); tmp.i=x; tmp.f=y; return tmp; } void main() { temp a={65535,777.777}; a=alter(&a,-1,666.666); printf("%d %.2f",a.i,a.f); }

11) What will be the output of the following program : struct my_struct1 { int arr[2][2]; }; typedef struct my_struct1 record; struct my_struct2 { record temp; }list[2]={1,2,3,4,5,6,7,8}; void main() { int i,j,k; for (i=1; i>=0; i--) for (j=0; j<2; j++) for (k=1; k>=0; k--) printf("%d",list[i].temp.arr[j][k]); }

12) What will be the output of the following program : struct my_struct { int i; unsigned int j; }; void main() { struct my_struct temp1={-32769,-1},temp2; temp2=temp1; printf("%d %u",temp2.i,temp2.j); }

13) What will be the output of the following program : struct names { char str[25]; struct names *next; }; typedef struct names slist; void main() { slist *list,*temp; list=(slist *)malloc(sizeof(slist)); // Dynamic Memory Allocation strcpy(list->str,"Hai"); list->next=NULL; temp=(slist *)malloc(sizeof(slist)); strcpy(temp->str,"Friends"); temp->next=list; list=temp; while (temp != NULL) { printf("%s",temp->str); temp=temp->next; } }

14) Which of the following declarations is NOT Valid : (i) struct A{ int a; struct B { int b; struct B *next; }tempB; struct A *next; }tempA;

(ii) struct B{ int b; struct B *next; }; struct A{ int a; struct B tempB; struct A *next; };

(iii)struct B{ int b; }tempB; struct { int a; struct B *nextB; };

(iv) struct B { int b; struct B { int b; struct B *nextB; }tempB; struct B *nextB; }tempB;

15) What will be the output of the following program : union A { char ch; int i; float f; }tempA; void main() { tempA.ch='A'; tempA.i=777; tempA.f=12345.12345; printf("%d",tempA.i); }

16) What will be the output of the following program : struct A { int i; float f; union B { char ch; int j; }temp; }temp1; void main() { struct A temp2[5]; printf("%d %d",sizeof temp1,sizeof(temp2)); }

17) What will be the output of the following program : void main() { static struct my_struct { unsigned a:1; unsigned b:2; unsigned c:3; unsigned d:4; unsigned :6; // Fill out first word }v={1,2,7,12}; printf("%d %d %d %d",v.a,v.b,v.c,v.d); printf("\nSize=%d bytes",sizeof v); }

18) What are the largest values that can be assigned to each of the bit fields defined in [Q017] . (a)a=0 b=2 c=3 d=4 (b)a=1 b=2 c=7 d=15 (c)a=1 b=3 c=7 d=15 (d)None of thes

19) What will be the output of the following program : void main() { struct sample { unsigned a:1; unsigned b:4; }v={0,15}; unsigned *vptr=&v.b; printf("%d %d",v.b,*vptr); }

20) What will be the output of the following program : void main() { static struct my_struct { unsigned a:1; int i; unsigned b:4; unsigned c:10; }v={1,10000,15,555}; printf("%d %d %d %d",v.i,v.a,v.b,v.c); printf("\nSize=%d bytes",sizeof v); }

21) What will be output of following c code? void main() { struct employee { unsigned id: 8; unsigned sex:1; unsigned age:7; }; struct employee emp1={203,1,23}; printf("%d\t%d\t%d",emp1.id,emp1.sex,emp1.age); }

22) What will be output of following c code? void main() { struct bitfield { unsigned a:5; unsigned c:5; unsigned b:6;

}bit; char *p; struct bitfield *ptr,bit1={1,3,3}; p=&bit1; p++; printf("%d",*p); }

23) What will be output of following c code? void main() { struct bitfield { signed int a:3; unsigned int b:13; unsigned int c:1; }; struct bitfield bit1={2,14,1}; printf("%d",sizeof(bit1)); }

24) What will be output of following c code? void main() { struct bitfield { unsigned a:3; char b; unsigned c:5; int d; }bit; clrscr(); printf("%d",sizeof(bit)); }

25) What will be output of following c code? void main() { struct field { int a; char b; }bit; struct field bit1={5,'A'}; char *p=&bit1; *p=45; printf("\n%d",bit1.a); }

26) What will be output of following c code? void main() { struct india { char c; float d; }; struct world { int a[3]; char b; struct india orissa; }; struct world st ={{1,2,3},'P','q',1.4}; printf("%d\t%c\t%c\t%f",st.a[1],st.b,st.orissa.c,st.orissa.d); }

9 CONSOLE AND FILE I/O 9.1 INTRODUCTION TO FILES File is a bunch of bytes stored in a particular area on some storage devices like floppy disk, hard disk, magnetic tape and -rom etc., which helps for the permanent storage.

There are 2 ways of accessing the files. These are:

 Sequential access: the data can be stored or read back sequentially.  Random access: the data can be access randomly.

If a file can support random access (sometimes referred to as position requests), opening a file also initializes the file position indicator to the start of a file. This indicator is incremented as each character is read from, or written to, the file.

The close operation disassociates a file from a specific stream. If the file was opened for output, the close operation will write the contents (if any) of the stream to the device. This process is usually called flushing the stream.

All files are closed automatically when the program terminates, but not when it crashes. Each stream associated with a file has a file control structure of type FILE. 9.1.1 Streams Even though different devices are involved (terminals, disk drives, etc), the buffered file system transforms each into a logical device called a stream. Because streams are device-independent, the same function can write to a disk file or to another device, such as a console. There are two types of streams:

Text Streams: A text stream is a sequence of characters. In a text stream, certain character translations may occur (for example, a newline may be converted to a carriage return/line-feed pair). This means that there may not be a one-to-one relationship between the characters written and those in the external device.

Binary Streams: A binary stream is a sequence of bytes with a one-to-one correspondence to those on the external device (i.e, no translations occur). The number of bytes written or read is the same as the number on the external device. However, an implementation-defined number of bytes may be appended to a binary stream (for example, to pad the information so that it fills a sector on a disk).

9.2 FILE INPUT AND OUTPUT FUNCTIONS The ANSI file system comprises several interrelated functions. These are:

Function Description fopen() Opens a file. fclose() Closes a file. putc() Writes a character. fputc() Writes a character. getc() Reads a character. fgetc() Reads a character. fseek() Seeks a specified byte in a file. fprintf() Is to a file what printf() is to the console. fscanf() Is to a file what scanf() is to a console. feof() Returns TRUE if end-of-file is reached. ferror() Returns TRUE if an error is detected. rewind() Resets file position to beginning of file. remove() Erases a file. fflush() Flushes a file.

Most of these functions begin with the letter "f". The header file stdio.h provides the prototypes for the I/O function and defines these three types:

typedef unsigned long size_t typedef unsigned long fpos_t typedef struct _FILE FILE stdio.h also defines the following:

EOF -1 /* value returned at end of file */ SEEK_SET 0 /* from beginning of file */

SEEK_CUR 1 /* from current position */ SEEK_END 2 /* from end of file */

The latter three are used with fseek() function which performs random access on a file. 9.3 FILE POINTER C treats a file just like a stream of characters and allows input and output as a stream of characters. To store data in file we have to create a buffer area. This buffer area allows information to be read or written on to a data file. The buffer area is automatically created as soon as the file pointer is declared. The general form of declaring a file is:

FILE *fp;

FILE is a defined data type, all files should be declared as type FILE before they are used. FILE should be compulsorily written in upper case. The pointer fp is referred to as the stream pointer. This pointer contains all the information about the file, which is subsequently used as a communication between the system and the program.

A file pointer fp is a variable of type FILE that is defined in stdio.h. 9.4 FILE OPERATIONS 9.4.1 Opening a File fopen() opens a stream for use, links a file with that stream and returns a pointer associated with that file. The prototype of fopen() function is as follows:

FILE *fopen (const char * filename, const char * mode);

Where, filename is a pointer to a string of characters that make a valid filename (and may include a path specification) and mode determines how the file will be opened. The legal values for mode are as follows:

Value Description r Open a text file for reading. w Create a text file for writing. a Append to a text file. rb Open a binary file for reading. wb Create a binary file for writing. ab Append to a binary file. r+ Open a text file for read/write. w+ Create a text file for read/write. a+ Append or create a text file for read/write. r+b Open a binary file for read/write. w+b Create a binary file for read/write. a+b Append a binary file for read/write.

A file may be opened in text or binary mode. In most implementations, in text mode, CR/LF sequences are translated to newline characters on input. On output, the reverse occurs. No such translation occurs on binary files.

The following opens a file named TEST for writing:

FILE *fp; fp = fopen ("test", "w");

However, because fopen() returns a null pointer if an error occurs when a file is opened, this is better written as:

FILE *fp; if ((fp = fopen ("test", "w")) == NULL) { printf("cannot open file\n"); exit(1); }

9.4.2 Closing a File fclose() closes the stream, writes any data remaining in the disk buffer to the file, does a formal operating system level close on the file, and frees the associated file control block. fclose() has this prototype:

int fclose (FILE *fp);

A return value of zero signifies a successful operation. Generally, fclose() will fail only when a disk has been prematurely removed or a disk is full. 9.4.3 Writing a Character Characters are written using putc() or its equivalent fputc(). The prototype for putc() is:

int putc (int ch, FILE *fp); where ch is the character to be output. For historical reasons, ch is defined as an int, but only the low order byte is used.

If the putc() operation is successful, it returns the character written, otherwise it returns EOF. 9.4.4 Reading a Character Characters are read using getc() or its equivalent fgetc(). The prototype for getc() is:

int getc(FILE *fp);

For historical reasons, getc() returns an integer, but the high order byte is zero. getc() returns an EOF when the end of file has been reached. The following code reads a text file to the end:

do { ch = getc (fp); } while(ch != EOF);

9.4.5 Using feof() As previously stated, the buffered file system can also operate on binary data. When a file is opened for binary input, an integer value equal to the EOF mark may be read, causing the EOF condition. To solve this problem, C includes the function feof(), which determines when the end of the file is reached when reading binary data.

The prototype is:

int feof (FILE *fp);

The following code reads a binary file until end of file is encountered:

while (! feof (fp)) ch = getc(fp);

Of course, this method can be applied to text files as well as binary files. 9.4.6 Working With Strings - fputs() and fgets() In addition to getc() and putc(), C supports the related functions fputs() and fgets(), which read and write character strings. They have the following prototypes:

int fputs (const char *str, FILE *fp); char *fgets (char *str, int length, FILE *fp);

The function fputs() works like puts() but writes the string to the specified stream. The fgets() function reads a string until either a newline character is read or length-1 characters have been read. If a newline is read, it will be part of the string (unlike gets()). The resultant string will be null-terminated. 9.4.7 rewind () rewind() resets the file position indicator to the beginning of the file. The syntax of rewind() is:

rewind(fptr); where, fptr is a file pointer. 9.4.8 ferror () ferror() determines whether a file operation has produced an error. It returns TRUE if an error has occurred, otherwise it returns FALSE. ferror() should be called immediately after each file operation, otherwise an error may be lost. 9.4.9 fread () and fwrite () To read and write data types which are longer than one byte, the ANSI standard provides fread() and fwrite(). These functions allow the reading and writing of blocks of any type of data. The prototypes are:

size_t fread (void *buffer, size_t num_bytes, size_t count, FILE *fp); size_t fwrite (const void *buffer, size_t num_bytes, size_t count, FILE *fp);

For fread(), buffer is a pointer to a region of memory which will receive the data from the file. For fwrite(), buffer is a pointer to the information which will be written. The buffer may be simply the memory used to hold the variable, for example, &l for a long integer.

The number of bytes to be read/written is specified by num_bytes. count determines how many items (each num_bytes in length) are read or written. fread() returns the number of items read. This value may be less than count if the end of file is reached or an error occurs. fwrite() returns the number of items written.

One of the most useful applications of fread() and fwrite() involves reading and writing user- defined data types, especially structures. For example, given this structure:

struct struct_type { float balance; char name[80]; } cust;

The following statement writes the contents of cust:

fwrite (&cust, sizeof(struct struct_type), 1, fp); 9.4.10 fseek() and Random Access I/O Random read and write operations may be performed with the help of fseek(), which sets the file position locator. The prototype is:

int fseek(FILE *fp, long numbytes, int origin); in which numbytes is the number of bytes from the origin, which will become the new current position, and origin is one of the following macros defined in stdio.h:

Origin Macro Name Beginning of file SEEK_SET Current position SEEK_CUR End-of-file SEEK_END fseek() returns 0 when successful and a non-zero value if an error occurs. fseek() may be used to seek in multiples of any type of data by simply multiplying the size of the data by the number of the item to be reached, for example:

fseek (fp, 9*sizeof (struct list), SEEK_SET);

Which seeks the tenth address.

9.4.11 fprint() and fscanf() fprint() and fscanf() behave exactly like print() and scanf() except that they operate with files. The prototypes are:

int fprintf (FILE *fp, const char *control_string, ...); int fscanf (FILE *fp, const char *control_string, ...);

Although these functions are often the easiest way to read and write assorted data, they are not always the most efficient. Because formatted ASCII data is being written as it would appear on the screen (instead of in binary), extra overhead is incurred with each call. If speed or file size is of concern, use fread() and fwrite(). 9.5 THE Whenever a C program starts execution, three streams are opened automatically. These are:

 Standard input (stdin)  Standard output (stdout)  Standard error (stderr)

Normally, these streams refer to the console, but they may be redirected by the operating system to some other device or environment. Because the standard streams are file pointers, they may be used to provide buffered I/O operations on the console, for example:

putchar(char c) { putc(c, stdout); }

9.6 COMMAND LINE ARGUMENTS Sometimes it is very useful to pass information into a program when we run it from the command prompt. The general method to pass information into main() function is through the use of command line arguments.

A command line argument is the information that follows the program’s name on the command prompt of the operating system.

For example: TC program_name

There are three special built_in_arguments to main(). They are:

 The first argument is argc (argument count) must be an integer value, which represents the number arguments in the command prompt. It will always be at least one because the name of the program qualifies as the first argument.

 The second argument argv (argument vector) is a pointer to an array of strings.

 The third argument (environment data) is used to access the DOS environmental parameters active at the time the program begins execution.

When an array is used as an argument to function, only the address of the array is passed, not a copy of the entire array. When you call a function with an array name, a pointer to the first element in the array is passed into a function. (In C, an array name without as index is a pointer to the first element in the array). Each of the command line arguments must be separated by a space or a tab. If you need to pass a command line argument that contains space, you must place it between quotes as:

“this is one argument”

Declaration of argv must be done properly, A common method is:

char *argv[];

That is, as a array of undetermined length.

The env parameter is declared the same as the argv parameter, it is a pointer to an array of strings that contain environmental setting. Example

/* The following program will print “hello tom”. */

# include # include main( int argc, char *argv[]) { if(argc!=2) { printf(“You forgot to type your name\n”); exit(0); } printf(“Hello %s “, argv[1]); } if the name of this program is name.exe, at the command prompt you have to type as:

 name tom

Output: hello tom

Example

/* This program prints current environment settings */ # include main (int argc, char *argv[], char *env[]) { int i; for(i=0; env[i]; i++) printf(“%s\n”, env[i]); }

We must declare both argc and argv parameters even if they are not used because the parameter declarations are position dependent. Example Programs on File I/O and Command Line Arguments:

The following programs demonstrate the use of C's file I/O functions.

Example

Program on fopen(), fclose(), getc(), putc(). Specify filename on command line. Input chars on keyboard until $ is entered. File is then closed. File is then re-opened and read.

#include #include void main(int argc, char *argv[]) { FILE *fp; /* file pointer */ char ch;

if(argc!=2) { printf("You forgot to enter the file name\n"); exit(1); }

if((fp=fopen(argv[1], "w"))==NULL) /* open file */ { printf("Cannot open file\n"); exit(1); } do /* get keyboard chars until `$' */ { ch = getchar(); putc(ch, fp); } while (ch! = '$');

fclose(fp); /* close file */

if((fp=fopen(argv[1], "r"))==NULL) /* open file */ { printf("Cannot open file\n"); exit(1); } ch = getc(fp); /* read one char */

while(ch != EOF) { putchar(ch); /* print on screen */ ch = getc(fp); /* read another char */ }

fclose(fp); /* close file */ }

Example

Program on feof() to check for EOF condition in Binary Files. Specify filenames for input and output at command prompt. The program copies the source file to the destination file. feof() checks for end of file condition. The feof() can also be used for text files.

#include #include void main(int argc, char *argv[]) { FILE *in, *out; /* file pointers */ char ch;

if(argc != 3) { printf("You forgot to enter the filenames\n"); exit(1); }

if((in=fopen(argv[1], "rb"))==NULL) /* open source file */ { /* for read binary */ printf("Cannot open source file\n"); exit(1); }

if((out=fopen(argv[2], "wb"))==NULL) /* open dest file */ { /* for write binary */ printf("Cannot open destination file\n"); exit(1); } while(! feof(in)) /* here it is */ { ch = getc(in);

if(! feof(in)) /* and again */ putc(ch, out); }

fclose(in); /* close files */ fclose(out); }

Example

Program on fputs(), fgets and rewind(). Strings are entered from keyboard until blank line is entered. Strings are then written to a file called ‘testfile'. Since gets() does not store the newline character, ‘\n’ is added before the string is written so that the file can be read more easily. The file is then rewind, input and displayed.

#include #include #include void main(void) { FILE *fp; /* file pointer */ char str[80];

if((fp=fopen("testfile", "w+"))==NULL) /* open file for text read & write */ { printf("Cannot open file\n"); exit(1); }

do /* get strings until CR and write to file */ { printf("Enter a string (CR to quit):\n"); gets(str); strcat(str, "\n"); fputs(str, fp); } while(*str != '\n');

rewind(fp); /* rewind */

while(! feof(fp)) /* read and display file */ { fgets(str, 79, fp); printf(str); }

fclose(fp); /* close file */ }

Example

Program on fread() and fwrite() (for Data Types Longer than Byte) which writes, then reads back, a double, an int and a long. Notice how sizeof () is used to determine the length of each data type. These functions are useful for reading and writing user-defined data types, especially structures.

#include #include void main(void) {

FILE *fp; double d=12.23; int i=101; long l=123023; if((fp=fopen("testfile", "wb+"))==NULL) /* open for binary read & write */ { printf("Cannot open file\n"); exit(1); }

/* parameters are: *buffer, number of bytes, count of items, file pointer */

fwrite(&d, sizeof(double), 1, fp); fwrite(&i, sizeof(int), 1, fp); fwrite(&l, sizeof(long), 1, fp);

rewind(fp);

fread(&d, sizeof(double), 1, fp); fread(&i, sizeof(int), 1, fp); fread(&l, sizeof(long), 1, fp);

printf("%2.3f %d %ld\n",d,i,l);

fclose(fp); }

Example

Program on fprintf() and fscanf(). Reads a string and an integer from the keyboard, writes them to a file, then reads the file and displays the data. These functions are easy to write mixed data to files but are very slow compared with fread() and fwrite().

#include #include #include void main (void) {

FILE *fp; char s[ 80]; int t; if ((fp=fopen("testfile", "w"))==NULL) /* open for text write */ { printf ("Cannot open file\n"); exit (1); }

printf ("Enter a string and a number: ");

/* parameters are: FILE *fp, const char *control_string, ... */

fscanf (stdin, "%s%d", s, &t); fprintf (fp, "%s %d", s, t); fclose (fp);

if ((fp=fopen("testfile", "r"))==NULL) /* open for text read */ { printf ("Cannot open file\n"); exit (1); }

fscanf (fp,"%s%d",s,&t); fprintf (stdout, "%s %d\n", s, t);

fclose (fp) } 9.7 THE C PREPROCESSOR As defined by the ANSI standard, the C preprocessor contains the following directives:

#if #ifdef #ifndef #else #elif #include #define #undef #line #error #pragma #define #define: Defines an identifier (the macro name) and a string (the macro substitution), which will be substituted for the identifier each time the identifier is encountered in the source file.

Once a macro name has been defined, it may be used as part of the definition of other macro names.

If the string is longer than one line, it may be continued by placing a backslash on the end of the first line.

By convention, C programmers use uppercase for defined identifiers. Example macro #defines are:

#define TRUE 1 #define FALSE 0

The macro name may have arguments, in which case every time the macro name is encountered, the arguments associated with it are replaced by the actual arguments found in the program, as in:

#define ABS(a) (a)<0 ? -(a) : (a) ... printf("abs of -1 and 1: %d %d", ABS(-1), ABS(1));

Such macro substitutions in place of real functions increase the speed of the code at the price of increased program size.

#error

#error forces the compiler to stop compilation. It is used primarily for debugging. The general form is:

#error error_message

When the directive is encountered, the error message is displayed, possibly along with other information (depending on the compiler). #include #include instructs the compiler to read another source file, which must be included between double quotes or angle brackets. Examples are:

#include "stdio.h" #include

Both instruct the compiler to read and compile the named header file.

If a file name is enclosed in angle brackets, the file is searched for the included file in a special known \include directory or directories. If the name is enclosed in double quotes, the file is searched in the current directory. If the file is not found, the search is repeated as if the name had been enclosed in angle brackets. 9.7.1 Conditional Compilation Several directives control the selective compilation of portions of the program code. They are:

#if #else #elif #endif

The general form of #if is:

#if constant_expression statement sequence #endif

#else works much like the C keyword else. #elif means "else if" and establishes an if-else-if compilation chain.

Amongst other things, #if provides an alternative method of "commenting out" code. For example, in

#if 0 printf("#d", total); #endif the compiler will ignore printf("#d", total);.

#ifdef and #ifndef

#ifdef means "if defined", and is terminated by an #endif. #indef means "if not defined".

#undef

#undef removes a previously defined definition.

#line

#line changes the contents of __LINE__ (which contains the line number of the currently compiled code) and __FILE__ (which is a string which contains the name of the source file being compiled), both of which are predefined identifiers in the compiler.

#pragma

The #pragma directive is an implementation-defined directive which allows various instructions to be given to the compiler.

Example

/* program to demonstrate #ifdef, #ifndef , #else and #endif */

# include # include # define a 10 main() { #ifdef a printf("\n Hello a is defined.."); #endif

#ifndef a printf("\n Not defined "); #else printf("\n defined "); #endif

getch(); }

Output:

Hello a is defined.. defined

The # and ## Preprocessor Operators:

The # and ## preprocessor operators are used when using a macro #define.

The # operator turns the argument it precedes into a quoted string. For example, given:

#define mkstr(s) # s the preprocessor turns the line:

printf (mkstr (I like C); into: printf ("I like C");

The ## operator concatenates two tokens. For example, given:

#define concat(a, b) a ## b int xy=10; printf("%d", concat (x, y)); the preprocessor turns the last line into: printf("%d", xy); ONE WORD ANSWERS Q1) What are character I/O functions? Ans: putchar and getchar are character I/O functions

Q2) When do we use getchar? Ans: getchar function is used when we want to read a single character at a time.

Q3) What is the use of putchar? Ans: It is used to display single character data

Q4) What are formatted I/O functions? Ans: scanf and printf are formatted I/O functions

Q5) What is a file ? Ans: File is collection of records ? It is stored in secondary storage area.

Q6) How many types files are exist in C ?what are they? Ans: Two types ,they are: i) text file ii) binary file

Q7) What does a text file stores? Ans: A text file stores different characters such as: upper case,lower case english alphabets,numeric characters, punctuation characters,special characters.

Q8) How to create a text file? Ans: Text files can be created by using text editor ( like tc and notepad.)

Q9) How to declare and open a file for writting? Ans: FILE *fp; fp=fopen("file name","w");

Q10) How to declare and open a file for reading? Ans: FILE *fp; fp=fopen("file name","r");

Q11) How to declare and open a file for appending? Ans: FILE *fp; fp=fopen("file name","a");

Q12) How to close a file? Ans: fclose(file_pointer);

Q13) What are the simplest file i/o functions? Ans: getc,putc,fprintf,fscanf

Q14) What is the general form of fgetc? Ans: fgetc(fp); reads a character from the file whose file pointer is fp.

Q15) What is the general form of putc? Ans: putc(c,fp);writes the character contained in the character variable c to the file associated with FILE pointer fp.

Q16) What are the simplest file i/o integer functions? Ans: getw,putw.

Q17) What is the general form of fprintf? Ans: fpintf(fp,"control string",list); example:fprintf(fp,"%s %d %f ",name,age,7.5);

Q18) What is the general form of fscanf? Ans: fscanf(fp ,"control string",list); example: fscanf(fp,"%s %d",item,&quantity);

Q19) How many types of status enquiry library functions are there?what are they? Ans: Two.They are 1.feof 2.ferror Q20) What is the use of status enquiry library functions? ans: they help to detect i/o errors with in the files.

Q21) What is the use of ftell? write the general form of ftell? Ans: ftell function is useful in saving the current position of file . it takes the general form: n=ftell(fp) it returns a number of type long.

Q22) what is the rewind function? Ans: rewind takes a file pointer and resets the position to the start of the file. general form:rewind(fp);

Q23) Where is fseek function used? Ans: fseek function is used to move the file position to a desired location with in the file.

Q24) What is the general form of fseek function? Ans: fseek(file_ptr,offset,position); offset specifies number of positions to be moved,position is 0(meaning begining of file),1(current position),2(end of file).

Q25) What is the meaning of the following statement? fseek(fp,m,1) Ans: go forward by m bytes from current file pointer position.

Q26) How many standard modes exist to open a file ? Ans : Three .

Q27) What are the standard modes exist to open a file ? R –reading W-writing A-appending OUTPUT PREDICTION 1) What will be the output of the following program : int fun(int a,int b) { #define NUM 5 return a+b; } main() { printf("Sum=%d",fun(NUM,NUM)); }

2) What will be the output of the following program : void main() { int a=5,b=6,c=7; printf("%d %d",a,b,c); }

3) What will be the output of the following program : int add(int a,int b) { return a+b; } main() { int a=1,b=2; printf("%d",add(add(add(a,b),add(a,b)),add(add(a,b),add(a,b)))); }

4) What will be the output of the following program : void main() { int a=5,b=6,c=7,d=8,e; e = a ? b , c : c , d; printf("%d",e); }

5) What will be the output of the following program : void main() { int a=5,b=6,c; c++ = b % (b - a) printf("%d",c); }

6) What will be the output of the following program : void main() { int x=5,y=6,z; z = x++ ;+++y; printf("%d %d %d",x,y,z); }