Click Here to Chat on WhatsApp
+12709848396

(Get Answer)

 c programming question and need support to help me learn.

Computer science programming in c
Requirements:
Page 1 Programming in “ C –Language ”   Unit-1  General Fundamentals of computers : Introduction to computers,Block diagram of computers,Characteristics and limitations of computers,Applications of computers ,Types of computers ,Computer genarations.Introduction to Algorithems And Programming Language:Algorithm – Key features of Algorithms, Flow Charts, Programming Languages – Generations of Programming Languages – Structured Programming Language- Design and Implementation of Correct, Efficient and Maintainable Programs   1. Introduction To Computers:  A computer is an electronic device . it takes data from the keyboard as input and Process the data and gives result through the monitor as output.  The literal meaning of computer is a device that can calculate. However, modern computers can do a lot more than calculate. Computer is an electronic device that receives input, stores or processes the input as per user instructions and provides output in desired format.  Input-Process-Output Model  Computer input is called data and the output obtained after processing it, based on user’s instructions is called information. Raw facts and figures which can be processed using arithmetic and logical operations to obtain information are called data.  The processes that can be applied to data are of two types –         Arithmetic operations − Examples include calculations like addition, subtraction, differentials, square root, etc.   Logical operations − Examples include comparison operations like greater than, less than, equal to, opposite, etc. 
Page 2 Programming in “ C –Language ”        The basic parts of a computer are as follows −   Input Unit − Devices like keyboard and mouse that are used to input data and instructions to the computer are called input unit.  Output Unit − Devices like printer and visual display unit that are used to provide information to the user in desired format are called output unit.  Control Unit − As the name suggests, this unit controls all the functions of the computer. All devices or parts of computer interact through the control unit.  Arithmetic Logic Unit − This is the brain of the computer where all arithmetic operations and logical operations take place.  Memory − All input data, instructions and data interim to the processes are stored in the memory. Memory is of two types – primary memory and secondary memory. Primary memory resides within the CPU whereas secondary memory is external to it.  Control unit, arithmetic logic unit and memory are together called the central processing unit or CPU. Computer devices like keyboard, mouse, printer, etc. that we can see and touch are the hardware components of a computer. The set of instructions or programs that make the computer function using these hardware parts are called software. We cannot see or touch software. Both hardware and software are necessary for working of a computer.  Characteristics of Computer  To understand why computers are such an important part of our lives, let us look at some of its characteristics −   Speed − Typically, a computer can carry out 3-4 million instructions per second.  Accuracy − Computers exhibit a very high degree of accuracy. Errors that may occur are usually due to inaccurate data, wrong instructions or bug in chips – all human errors.  Reliability − Computers can carry out same type of work repeatedly without throwing up errors due to tiredness or boredom, which are very common among humans.  Versatility – multitasking ,computer can perform more than two works at a time is called versatility  Storage Capacity − Computers can store a very large amount of data at a fraction of cost of traditional storage of files. Also, data is safe from normal wear and tear associated with paper.  Advantages of Using Computer 
Page 3 Programming in “ C –Language ”    Now that we know the characteristics of computers, we can see the advantages that computers offer−   Computers can do the same task repetitively with same accuracy.  Computers do not get tired or bored.  Computers can take up routine tasks while releasing human resource for more intelligent functions.  Disadvantages of Using Computer  Despite so many advantages, computers have some disadvantages of their own −   Computers have no intelligence; they follow the instructions blindly without considering the outcome.  Regular electric supply is necessary to make computers work, which could prove difficult everywhere especially in developing nations.  Booting  Starting a computer or a computer-embedded device is called booting. Booting takes place in two steps −The first program or set of instructions that run when the computer is switched on is called BIOS or Basic Input Output System. BIOS is a firmware, i.e. a piece of software permanently programmed into the hardware.  If a system is already running but needs to be restarted, it is called rebooting. Rebooting may be required if a software or hardware has been installed or system is unusually slow.  There are two types of booting −   Cold Booting − When the system is started by switching on the power supply it is called cold booting. The next step in cold booting is loading of BIOS.  Warm Booting − When the system is already running and needs to be restarted or rebooted, it is called warm booting. Warm booting is faster than cold booting because BIOS is not reloaded.  2. Block Diagram Of Computers Block diagram of a computer gives you the pictorial representation of a computer that how it works inside. Or you can say that, in computer's block diagram, we will see how computer works from feeding the data to getting the result. 
Page 4 Programming in “ C –Language ”    Here is the block diagram of a computer             system:  In the above diagram, both control (control unit or CU) and arithmetic & logic unit (ALU) combinely called as Central Processing Unit (CPU).  Let's describe about all the parts as included in the above diagram one by one.  The Processor Unit (CPU) It is the brain of a computer system.  All major calculation and comparisons are made inside the CPU and it is also responsible for activation and controlling the operation of other unit.  This unit consists of two major components, that are arithmetic logic unit (ALU) and control unit (CU).  Arithmetic Logic Unit (ALU) Here arithmetic logic unit performs all arithmetic operations such as addition, subtraction, multiplication and division. It also uses logic operation for comparison.  Control Unit (CU) And the control unit of a CPU controls the entire operation of a computer. It also controls all devices such as memory, input/output devices connected to the CPU.  CU fetches instructions from memory, decodes the instruction, interprets the instruction to know what the task are to be performed and sends suitable control signals to the other components to perform for the necessary steps to executes the instruction.  Input/Output Unit 
Page 5 Programming in “ C –Language ”    The input/output unit consists of devices used to transmit information between the external world and computer memory.  The information fed through the input unit is stored in computer's memory for processing and the final result stored in memory can be recorded or display on the output medium.  Memory Unit Memory unit is an essential component of a digital computer. It is where all data intermediate and final results are stored.  The data read from the main storage or an input unit are transferred to the computer's memory where they are available for processing.  Memory units are used to measure and represent data. Some of the commonly used memory units are:  1) Bit: The computer memory units start from bit. A bit is the smallest memory unit to measure data stored in main memory and storage devices. A bit can have only one binary value out of 0 and 1.  2) Byte: It is the fundamental unit to measure data. It contains 8 bits or is equal to 8 bits. Thus a byte can represent 2*8 or 256 values.  3) Kilobyte: A kilobyte contains 1024 bytes.  4) Megabyte: A megabyte contains 1024 kilobytes.  5) Gigabyte: A gigabyte contains 1024 megabyte.  A) Types of Computer Memory: Primary and Secondary Although many types of memory in a computer exist, the most basic distinction is between primary memory, often called system memory, and secondary memory, which is more commonly called storage.  The key difference between primary and secondary memory is speed of access. 
Page 6 Programming in “ C –Language ”       Primary memory includes ROM and RAM, and is located close to the CPU on the computer motherboard, enabling the CPU to read data from primary memory very quickly indeed. It is used to store data that the CPU needs imminently so that it does not have to wait for it to be delivered.   Secondary memory by contrast, is usually physically located within a separate storage device, such as a hard disk drive or solid state drive (SSD), which is connected to the computer system either directly or over a network. The cost per gigabyte of secondary memory is much lower, but the read and write speeds are significantly slower.  Primary Memory Types: RAM and ROM There are two key types of primary memory: 1. RAM, or random access memory 2. ROM, or read-only memory  Let's look in-depth at both types of memory.  1) RAM Computer Memory The most important things to understand about RAM are that RAM memory is very fast, it can be written to as well as read, it is volatile (so all data stored in RAM memory is lost when it loses power) and, finally, it is very expensive compared to all types of secondary memory in terms of cost per gigabyte. It is because of the relative high cost of RAM compared to secondary memory types that most computer systems use both primary and secondary memory.  Types of RAM   DRAM: DRAM stands for Dynamic RAM, and it is the most common type of RAM used in computers. The oldest type is known as single data rate (SDR) DRAM, but newer computers use faster dual data rate (DDR) DRAM. DDR comes in several versions including DDR2 , DDR3, and DDR4, which offer better performance and 
Page 7 Programming in “ C –Language ”    are more energy efficient than DDR. However different versions are incompatible, so it is not possible to mix DDR2 with DDR3 DRAM in a computer system. DRAM consists of a transistor and a capacitor in each cell.   SRAM: SRAM stands for Static RAM, and it is a particular type of RAM which is faster than DRAM, but more expensive and bulker, having six transistors in each cell. For those reasons SRAM is generally only used as a data cache within a CPU itself or as RAM in very high-end server systems. A small SRAM cache of the most imminently-needed data can result in significant speed improvements in a system  2) ROM Computer Memory ROM stands for read-only memory, and the name stems from the fact that while data can be read from this type of computer memory, data cannot normally be written to it. It is a very fast type of computer memory which is usually installed close to the CPU on the motherboard.  Types of ROMs  ROM is available in several different types, including PROM, EPROM, and EEPROM.   PROM PROM stands for Programmable Read-Only Memory, and it is different from true ROM in that while a ROM is programmed (i.e. has data written to it) during the manufacturing process, a PROM is manufactured in an empty state and then programmed later using a PROM programmer or burner.   EPROM EPROM stands for Erasable Programmable Read-Only Memory, and as the name suggests, data stored in an EPROM can be erased and the EPROM reprogrammed. Erasing an EPROM involves removing it from the computer and exposing it to ultraviolet light before re-burning it.   EEPROM EEPROM stands for Electrically Erasable Programmable Read-Only Memory, and the distinction between EPROM and EEPROM is that the latter can be erased and written to by the computer system it is installed in. In that sense EEPROM is not strictly read-only. However in many cases the write process is slow, so it is normally only done to update program code such as firmware or BIOS code on an occasional basis  .Secondary Memory Types  Secondary memory comprises many different storage media which can be directly attached to a computer system. These include:   hard disk drives   solid state drives (SSDs)   Optical (CD or DVD) drives   Tape drives  Secondary memory also includes:   Storage arrays including 3D NAND flash arrays connected over a storage area network (SAN) 
Page 8 Programming in “ C –Language ”     Storage devices which may be connected over a conventional network (known as network attached storage, or NAS)  Arguably cloud storage can also be called secondary memory.  Differences between RAM and ROM ROM:   Non-volatile   Fast to read   Usually used in small quantities   Cannot be written to quickly   Used to store boot instructions or firmware   Relatively expensive per megabyte stored compared to RAM  RAM:   Volatile   Fast to read and write   Used as system memory to store data (including program code) that the CPU needs to process imminently   Relatively cheap per megabyte stored compared to ROM, but relatively expensive compared to secondary memory  3. What is a computer ? Characteristcis And Limitations of Computers: The word “computer” comes from the word “compute” which means to calculate. So a computer is normally considered to be a calculating device that performs arithmetic operations at enormous speed. More accurately, a computer may be defined as a device that that operates upon information or data . Now a day’s more than 80 % of the work done by computers today is a non mathematical or non- numerical nature. Modern Definition of computers : A computer is an electronic device which is used to perform operation on raw data as per instruction given by user. All the Plugged with computer system( e.g. keyboard, mouse, printer,CPU etc) is called hardware, the language , instruction, data are the  called software 
Page 9 Programming in “ C –Language ”      . Characteristics or features of computers: 1. Speed: A computer is a very fast device. The computer takes a fraction of seconds to perform any operation. The speed of computer is measured in micro seconds (10-3), Milliseconds (10-6), nanoseconds (10-9) and even Picoseconds (10-12).A powerful computer is capable of performing about 3-4 million simple operations per second. 2. Accuracy: The accuracy of computer is very high and the degree of a particular computer depends upon its design. But for a particular computer, each and every calculation is performed with the same accuracy. Errors can occur in a computer but these are mainly due to human rather than technological weakness. 3. Storage Capacity : Computers can store data and instruction with a lot of volume and very high efficiency. 4. Diligence: unlike human being a computer is free from monotony, tiredness, luck of concentration etc. and hence can work for hours together without creating any error. A computer can perform the last calculation with exactly the same accuracy and seed as the first one. 5. Automation: Once a Program is in the computer’s memory, CPU follows the instructions until it meets the last instruction. Though the program concept many takes can be performed simultaneously, some on foreground and some on background. Thus automation bring the program execution fast 6. Reliability: Because, computer is an electronic device thus it perform all operations with 100 % accuracy and reliability. Reliability can affect only error prone by human mind. 7. Versatility: versatility is one of the most wonderful things about the computer. One moment it can do any one operation and next moment if can perform any other operation. A computer is capable of performing almost any task according to given instructions. 
Page 10 Programming in “ C –Language ”       Limitation or Drawback of Computer 1. No I.Q. : Computer is not a magical device. It performs only those works which man can does but the main difference is that computer can work those operations with very high speed and reliable accuracy. It has no any intelligence quality or thinking power 2. No Feeling: Because computer is only a machine, it has no feeling like human being. It has no brain for thinking as man can does. Man had successes to make computer memory be different inventions of technology but he couldn’t make heart. 3. Data Machine Readable : Computer data is read by machine, meaning data obtained from the computer can be read by the computer itself. 4. It required power to operate. 5. Problem may occur due to system breakdown.  4. Computer – Applications  In this chapter, we will discuss the application of computers in various fields.  Business accuracy, A computer has high speed of calculation, diligence, reliability, or versatility which has made it an integrated part in all business organizations.  Computer is used in business organizations for −   Payroll calculations 
Page 11 Programming in “ C –Language ”     Budgeting  Sales analysis  Financial forecasting  Managing employee database  Maintenance of stocks, etc.  Banking Today, banking is almost totally dependent on computers.  Banks provide the following facilities −   Online accounting facility, which includes checking current balance, making deposits and overdrafts, checking interest charges, shares, and trustee records.  ATM machines which are completely automated are making it even easier for customers to deal with banks.  Insurance Insurance companies are keeping all records up-to-date with the help of computers. Insurance companies, finance houses, and stock broking firms are widely using computers for their concerns.  Insurance companies are maintaining a database of all clients with information showing – Procedure to continue with policies  Starting date of the policies  Next due installment of a policy  Maturity date  Interests due  Survival benefits  Bonus  Education The computer helps in providing a lot of facilities in the education system.   The computer provides a tool in the education system known as CBE (Computer Based Education).  CBE involves control, delivery, and evaluation of learning.  Computer education is rapidly increasing the graph of number of computer students.  There are a number of methods in which educational institutions can use a computer to educate the students.  It is used to prepare a database about performance of a student and analysis is carried out on this basis.  Marketing 
Page 12 Programming in “ C –Language ”    In marketing, uses of the computer are following −  Advertising − With computers, advertising professionals create art and graphics, write and revise copy, and print and disseminate ads with the goal of selling more products.   Home Shopping − Home shopping has been made possible through the use of computerized catalogues that provide access to product information and permit direct entry of orders to be filled by the customers.  Healthcare Computers have become an important part in hospitals, labs, and dispensaries. They are being used in hospitals to keep the record of patients and medicines. It is also used in scanning and diagnosing different diseases. ECG, EEG, ultrasounds and CT scans, etc. are also done by computerized machines.  Following are some major fields of health care in which computers are used.  Diagnostic System − Computers are used to collect data and identify the cause of illness.   Lab-diagnostic System − All tests can be done and the reports are prepared by computer.  Patient Monitoring System − These are used to check the patient's signs for abnormality such as in Cardiac Arrest, ECG, etc.  Pharma Information System − Computer is used to check drug labels, expiry dates, harmful side effects, etc.  Surgery − Nowadays, computers are also used in performing surgery.  Engineering Design Computers are widely used for Engineering purpose.  One of the major areas is CAD (Computer Aided Design) that provides creation and modification of images. Some of the fields are −  Structural Engineering − Requires stress and strain analysis for design of ships, buildings, budgets, airplanes, etc.Industrial Engineering − Computers deal with design, implementation, and improvement of integrated systems of people, materials, and equipment.  Architectural Engineering − Computers help in planning towns, designing buildings, determining a range of buildings on a site using both 2D and 3D drawings.  Military Computers are largely used in defence. Modern tanks, missiles, weapons, etc. Military also employs computerized control systems. Some military areas where a computer has been used are −   Missile Control 
Page 13 Programming in “ C –Language ”     Military Communication  Military Operation and Planning  Smart Weapons  Communication Communication is a way to convey a message, an idea, a picture, or speech that is received and understood clearly and correctly by the person for whom it is meant. Some main areas in this category are –.E-mail   Chatting  Usenet  FTP  Telnet  Video-conferencing  Government Computers play an important role in government services. Some major fields in this category are − .Budgets   Sales tax department  Income tax department  Computation of male/female ratio  Computerization of voters lists  Computerization of PAN card  Weather forecasting    5. Computer - Types We can categorize computer in two ways: on the basis of data handling capabilities and size.  On the basis of data handling capabilities, the computer is of three types:   Analogue Computer  Digital Computer  Hybrid Computer  1) Analogue Computer Analogue computers are designed to process analogue data. Analogue data is continuous data that changes continuously and cannot have discrete values. We can say that analogue computers are used where we don't need exact values always such as speed, temperature, pressure and current.  Advantages of using analogue computers: 
Page 14 Programming in “ C –Language ”     It allows real-time operations and computation at the same time and continuous representation of all data within the rage of the analogue machine.  In some applications, it allows performing calculations without taking the help of transducers for converting the inputs or outputs to digital electronic form and vice versa.  Types of analogue computers:   Slide Rules: It is one of the simplest types of mechanical analogue computers. It was developed to perform basic mathematical calculations. It is made of two rods. To perform the calculation, the hashed rod is slid to line up with the markings on another rod.  Castle Clock: It was invented by Al-Jarazi. It was able to save programming instructions. Its height was around 11 feet and it was provided with the display of time, the zodiac, and the solar and lunar orbits. This device also could allow users to set the length of the day as per the current season.  Electronic Analogue Computer: In this type of analogue computer, electrical signals flow through capacitors and resistors to simulate physical phenomena. Here, the mechanical interaction of components does not take place. The voltage of the electrical signal generates the appropriate displays.  2) Digital Computer Digital computer is designed to perform calculations and logical operations at high speed. It accepts the raw data as input in the form of digits or binary numbers (0 and 1) and processes it with programs stored in its memory to produce the output. All modern computers like laptops, desktops including smartphones that we use at home or office are digital computers.  Advantages of digital computers:   It allows you to store a large amount of information and to retrieve it easily whenever you need it.  You can easily add new features to digital systems more easily.  Different applications can be used in digital systems just by changing the program without making any changes in hardware  The cost of hardware is less due to the advancement in the IC technology.  It offers high speed as the data is processed digitally.  3) Hybrid Computer Hybrid computer has features of both analogue and digital computer. It is fast like an analogue computer and has memory and accuracy like digital computers. It can process both continuous and discrete data. It accepts analogue signals and convert them into digital form before processing. So, it is widely used in specialized applications where both analogue and digital data is processed. For example, a processor is used in petrol pumps that converts the measurements of fuel flow into quantity and price. Similarly, they are used in airplanes, hospitals, and scientific applications.  Advantages of using hybrid computers:   Its computing speed is very high due to the all-parallel configuration of the analogue subsystem.  It produces precise and quick results that are more accurate and useful.  It has the ability to solve and manage big equation in real-time.  It helps in the on-line data processing. 
Page 15 Programming in “ C –Language ”       On the basis of size, the computer can be of five types:    Computers can be broadly classified by their speed and computing power.   S.No. Type Specifications  1 PC (Personal Computer)  It is a single user computer system having moderately powerful microprocessor  2  Workstation It is also a single user computer system, similar to personal computer however has a more powerful microprocessor.  3  Mini Computer It is a multi-user computer system, capable of supporting hundreds of users simultaneously.  4  Main Frame It is a multi-user computer system, capable of supporting hundreds of users simultaneously. Software technology is different from minicomputer.  5  Supercomputer It is an extremely fast computer, which can execute hundreds of millions of instructions per second.   PC (Personal Computer) A PC can be defined as a small, relatively inexpensive computer designed for an individual user. PCs are based on the microprocessor technology that enables manufacturers to put an entire CPU on one chip. Businesses use personal computers for word processing, accounting, despublishing, and for running spreadsheet and database management applications. At home, the most popular use for personal computers is playing games and surfing the Internet.  Example :laptops,smartphones,tabs,desktop computers  Workstation Workstation is a computer used for engineering applications (CAD/CAM), desktop publishing, software development, and other such types of applications which require a moderate amount of computing power and relatively high quality graphics capabilities.graphics and animations ,multimedia operations can be performed through workstation computers  Minicomputer It is a midsize multi-processing system capable of supporting up to 250 users simultaneously. 
Page 16 Programming in “ C –Language ”    Mainframe Mainframe is very large in size and is an expensive computer capable of supporting hundreds or even thousands of users simultaneously. Mainframe executes many programs concurrently and supports many simultaneous execution of programs.  Supercomputer Supercomputers are one of the fastest computers currently available. Supercomputers are very expensive and are employed for specialized applications that require immense amount of mathematical calculations (number crunching).  6. Computer Generations Let us now discuss the development in Computer Technology over the different generations.  First Generation  The period 1940 to 1956, roughly considered as the First Generation of Computer.  The first generation computers were developed by using vacuum tube or thermionic valve machine.  The input of this system was based on punched cards and paper tape; however, the output was displayed on printouts.  The first generation computers worked on binary-coded concept (i.e., language of 0-1). Examples: ENIAC, EDVAC, etc.  Second Generation   The period 1956 to 1963 is roughly considered as the period of Second Generation of Computers.  The second generation computers were developed by using transistor technology.  In comparison to the first generation, the size of second generation was smaller.  In comparison to computers of the first generation, the computing time taken by the computers of the second generation was lesser.  Third Generation  The period 1963 to 1971 is roughly considered as the period of Third Generation of computers.  The third generation computers were developed by using the Integrated Circuit (IC) technology.In comparison to the computers of the second generation, the size of the computers of the third generation was smaller.   In comparison to the computers of the second generation, the computing time taken by the computers of the third generation was lesser.  The third generation computer consumed less power and also generated less heat.  The maintenance cost of the computers in the third generation was also low.  The computer system of the computers of the third generation was easier for commercial use.  Fourth Generation 
Page 17 Programming in “ C –Language ”     The period 1972 to 2010 is roughly considered as the fourth generation of computers.  The fourth generation computers were developed by using microprocessor technology.  By coming to fourth generation, computer became very small in size, it became portable.   The machine of fourth generation started generating very low amount of heat.  It is much faster and accuracy became more reliable.  The production cost reduced to very low in comparison to the previous generation.  It became available for the common people as well.  Fifth Generation   The period 2010 to till date and beyond, roughly considered as the period of fifth generation of computers.  By the time, the computer generation was being categorized on the basis of hardware only, but the fifth generation technology also included software.  The computers of the fifth generation had high capability and large memory capacity.  Working with computers of this generation was fast and multiple tasks could be performed simultaneously.  Some of the popular advanced technologies of the fifth generation include Artificial intelligence, Quantum computation, Nanotechnology, Parallel processing, etc.  Introduction To Alagorithams And Programming Lanaguages   7. Key features of algorithms: An alagoritham has a finite number of steps and some steps may involve decision-making and repetition. Boardly speaking, an alagoritham exhibits three key features, namely, sequence, decision, and repetition Sequence: sequence menas that each step of the alagoritham is in the specified order.  Q: an alagoritham to add two numbers Step:1 input the firsty number as A Step:2 input the firsty number as B Step:3 set C= A + B  Step:4 print C  Step:5 end  Decision: Decision statements are used when the outcome of the process depends on some condition. Q: an alagoritham to test the equality of two numbers 
Page 18 Programming in “ C –Language ”    Step:1 input the firsty number as A Step:2 input the firsty number as B Step:3 if A = B Then print “ equal” else Print Not Equal “ Step:4 end  Repetition : repetition, which involves executing one or more steps for a number of times, can be implemented using constructs such as the while, do-while, for loop. These loops execute one or more steps until some condition is true. Q: an alagoritham to print the first 10 natural numbers.  Step:1 [ initilization ] set I=0, N= 10.  Step:2 repeat step while I Check if operand on the left is greater than operand on the right < Check operand on the left is smaller than right operand >= check left operand is greater than or equal to right operand   right shift  The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the right operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the same precedence.  Logical operators 
GNANAJYOTHI DEGREE COLLEGE Page 50 Programming in “ C –Language ”   Assignment Operators b= 2 a = 0001000 Conditional operator  Example :    Assignment operators supported by C language are as follows.  Operator Description Example = assigns values from right side operands to left side operand a=b += adds right operand to the left operand and assign the result to left a+=b is same as a=a+b -= subtracts right operand from the left operand and assign the result to left operand a-=b is same as a=a-b *= mutiply left operand with the right operand and assign the result to left operand a*=b is same as a=a*b /= divides left operand with the right operand and assign the result to left operand a/=b is same as a=a/b %= calculate modulus using two operands and assign the result to left operand a%=b is same as a=a%b    It is also known as ternary operator and used to evaluate conditional expression. 
GNANAJYOTHI DEGREE COLLEGE Page 51 Programming in “ C –Language ”   Special operator Increment / Decrement operator    If epr1 Condition is true ? Then value expr2 : Otherwise value expr3    Operator Description Example sizeof Returns the size of an variable sizeof(x) return size of the variable x & Returns the address of an variable &x ; return address of the variable x * Pointer to a variable *x ; will be pointer to a variable x    Operator Description Example ++ Increment the value by 1 a ++ - - Decrement the value by 1 a - -  epr1 ? expr2 : expr3 
GNANAJYOTHI DEGREE COLLEGE Page 52 Programming in “ C –Language ”    13. Sample C-Programs  Q : Write a c-program to print your address ? #include #include void main() { printf(“\n name ............................... ”); printf(“\n fname .............................. ”); printf(“\n street ................................ ”); printf(“\n village .............................. ”); printf(“\n state ................................. ”); }  Q : Write a c-program to initialize the values into a variables? #include #include void main() { int a,b; clrscr(); a=4; b=6; printf(“\n A= %d”,a); printf(“\n B= %d”,b); getch(); } 
GNANAJYOTHI DEGREE COLLEGE Page 53 Programming in “ C –Language ”    Q : Write a c-program to initialize the values into a variables using input instruction? #include #include void main() { int a,b; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); printf(“\n enter b value ”); scanf(“%d”,&b); printf(“\n a= %d”,a); printf(“\n b= %d”,b); getch(); }  Q : Write a c-program to print sum of two numbers? #include #include void main() { int a,b,c; clrscr(); a=5; b=7; c=a+b; printf(“\n the sum is %d “,c); getch(); }  Q : Write a c-program to print sum of two numbers using input instruction? #include #include void main() { int a,b,c; clrscr(); printf(“\n enter a value „); scanf(“%d”,&a); printf(“\n enter b value „); scanf(“%d”,&b); c=a+b; printf(“\n the sum is %d”,c); getch(); } 
GNANAJYOTHI DEGREE COLLEGE Page 54 Programming in “ C –Language ”    Q : Write a C-program to print subtraction of two numbers ? #include #include void main() { int a,b,c; clrscr(); printf(“\n enter a value „); scanf(“%d”,&a); printf(“\n enter b value „); scanf(“%d”,&b); c=a-b; printf(“\n the subtraction is %d”,c); getch(); } Q : Write a c-program to print Division of two numbers ? #include #include void main() { float a,b,c; clrscr(); printf(“\n enter a value „); scanf(“%f”,&a); printf(“\n enter b value „); scanf(“%f”,&b); c=a/b; printf(“\n the division is %f”,c); getch(); } Q : Write a c-program to print Reminder of two numbers ? #include #include void main() { int a,b,c; clrscr(); printf(“\n enter a value „); scanf(“%d”,&a); printf(“\n enter b value „); scanf(“%d”,&b); c=a%b; printf(“\n the reminder is %d”,c); getch(); } 
GNANAJYOTHI DEGREE COLLEGE Page 55 Programming in “ C –Language ”    g=g+32; printf(“\n the character is %c”,g); getch(); }  Q : Write a c-program of swapping of two numbers? #include #include void main() { int a,b,c; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); printf(“\n enter b value ”); scanf(“%d”,&a); printf(“\n before swaping a= %d b=%d ”,a,b); c=a; a=b; b=c; printf(“\n after swaping a= %d b=%d ”,a,b); getch(); } 
GNANAJYOTHI DEGREE COLLEGE Page 56 Programming in “ C –Language ”    13. CONTROL INSTRUCTIONS  Control instruction is an instruction which instruct the complier. In C control Instructions are two types those are  1. decision making and branching 2. decision making and looping (ittrative statements )  a) Decision Making And Branching : in this control will takes some decisions according to that decision it take some branch. It is available in C in the following categories.   Simple IF  IF-Else  Nesting  IF-Else-IF  Switch Case  Simple If : If the condition is satisfied then the statement part will get executed otherwise it Not.  Syntax: if(condition)  { statement part; }  Program: #include #include void main() { int a; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); if(a>0) { printf(“\n positive ”); } getch(); }  If - Else: If the condition is satisfied then the statement part-1 will get executed otherwise statement part -2 will get executed.  Syntax: if(condition)  { 
GNANAJYOTHI DEGREE COLLEGE Page 57 Programming in “ C –Language ”    statement part-1; } else 
GNANAJYOTHI DEGREE COLLEGE Page 58 Programming in “ C –Language ”    {  }  Program: #include #include void main() { int a; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); if(a>0) { printf(“\n positive ”); } else { printf(“\n negative ”); } getch(); }  statement part-2;                     Nesting  The technique of placing one block into another block is known as Nesting.  Nested IF : Placing the one if block into another if block is called as Nested IF. --------- If the condition-1 and condition-2 is satisfied then the statement part will get Executed.  Syntax: if(condition-1)  { printf(“\n enter a value ”); scanf(“%d”,&a); if(a>0)   }  Program: #include #include void main() { int a; clrscr(); 
GNANAJYOTHI DEGREE COLLEGE Page 59 Programming in “ C –Language ”    if(Condition-2) { Statement part-2; } 
GNANAJYOTHI DEGREE COLLEGE Page 60 Programming in “ C –Language ”    { if(a%2= =0) { printf(“\n positive even”); } } getch(); } Nested IF-Else: Placing the one if-else block into another if-else block is called as Nested IF- else. Syntax: if(condition-1)  { if(condition-2) {      } else {  } else {  } Statement part 1;   Statement part 2; if(condition-3) {      }   Program: #include #include void main() { int a; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); if(a>0) {  } else {  } statement part-1;   statement part-2; if(a%2= =0) { printf(“\n positive even”); 
GNANAJYOTHI DEGREE COLLEGE Page 61 Programming in “ C –Language ”        } else {        } }  else { printf(“\n positive odd”); }   if(a%2= =0) { printf(“\n negative even”); } else { printf(“\n negative odd”); } getch(); } IF –Else- If : Syntax :    if(condition-1) { statement part; } else if(condition-2) { statement part; } else  { statement part; }  Program : #include #include void main() { int a; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); if(a>0) { printf(“\n positive ”); } 
GNANAJYOTHI DEGREE COLLEGE Page 62 Programming in “ C –Language ”    else if(a 2 ) { printf( 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } }double quotes, it produces the following result. The end thank you GNANAJYOTHI DEGREE COLLEGE Page 142 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 143 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 144 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 145 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 146 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” Page 147 GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 157 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 158 Programming in “ C –Language ” "/>

Expert Answer

c programming question and need support to help me learn. Computer science programming in c Requirements: Page 1 Programming in “ C –Language ” Unit-1 General Fundamentals of computers : Introduction to computers,Block diagram of computers,Characteristics and limitations of computers,Applications of computers ,Types of computers ,Computer genarations.Introduction to Algorithems And Programming Language:Algorithm – Key features of Algorithms, Flow Charts, Programming Languages – Generations of Programming Languages – Structured Programming Language- Design and Implementation of Correct, Efficient and Maintainable Programs 1. Introduction To Computers: A computer is an electronic device . it takes data from the keyboard as input and Process the data and gives result through the monitor as output. The literal meaning of computer is a device that can calculate. However, modern computers can do a lot more than calculate. Computer is an electronic device that receives input, stores or processes the input as per user instructions and provides output in desired format. Input-Process-Output Model Computer input is called data and the output obtained after processing it, based on user’s instructions is called information. Raw facts and figures which can be processed using arithmetic and logical operations to obtain information are called data. The processes that can be applied to data are of two types – Arithmetic operations − Examples include calculations like addition, subtraction, differentials, square root, etc.  Logical operations − Examples include comparison operations like greater than, less than, equal to, opposite, etc. Page 2 Programming in “ C –Language ” The basic parts of a computer are as follows −  Input Unit − Devices like keyboard and mouse that are used to input data and instructions to the computer are called input unit.  Output Unit − Devices like printer and visual display unit that are used to provide information to the user in desired format are called output unit.  Control Unit − As the name suggests, this unit controls all the functions of the computer. All devices or parts of computer interact through the control unit.  Arithmetic Logic Unit − This is the brain of the computer where all arithmetic operations and logical operations take place.  Memory − All input data, instructions and data interim to the processes are stored in the memory. Memory is of two types – primary memory and secondary memory. Primary memory resides within the CPU whereas secondary memory is external to it. Control unit, arithmetic logic unit and memory are together called the central processing unit or CPU. Computer devices like keyboard, mouse, printer, etc. that we can see and touch are the hardware components of a computer. The set of instructions or programs that make the computer function using these hardware parts are called software. We cannot see or touch software. Both hardware and software are necessary for working of a computer. Characteristics of Computer To understand why computers are such an important part of our lives, let us look at some of its characteristics −  Speed − Typically, a computer can carry out 3-4 million instructions per second.  Accuracy − Computers exhibit a very high degree of accuracy. Errors that may occur are usually due to inaccurate data, wrong instructions or bug in chips – all human errors.  Reliability − Computers can carry out same type of work repeatedly without throwing up errors due to tiredness or boredom, which are very common among humans.  Versatility – multitasking ,computer can perform more than two works at a time is called versatility  Storage Capacity − Computers can store a very large amount of data at a fraction of cost of traditional storage of files. Also, data is safe from normal wear and tear associated with paper. Advantages of Using Computer Page 3 Programming in “ C –Language ” Now that we know the characteristics of computers, we can see the advantages that computers offer−  Computers can do the same task repetitively with same accuracy.  Computers do not get tired or bored.  Computers can take up routine tasks while releasing human resource for more intelligent functions. Disadvantages of Using Computer Despite so many advantages, computers have some disadvantages of their own −  Computers have no intelligence; they follow the instructions blindly without considering the outcome.  Regular electric supply is necessary to make computers work, which could prove difficult everywhere especially in developing nations. Booting Starting a computer or a computer-embedded device is called booting. Booting takes place in two steps −The first program or set of instructions that run when the computer is switched on is called BIOS or Basic Input Output System. BIOS is a firmware, i.e. a piece of software permanently programmed into the hardware. If a system is already running but needs to be restarted, it is called rebooting. Rebooting may be required if a software or hardware has been installed or system is unusually slow. There are two types of booting −  Cold Booting − When the system is started by switching on the power supply it is called cold booting. The next step in cold booting is loading of BIOS.  Warm Booting − When the system is already running and needs to be restarted or rebooted, it is called warm booting. Warm booting is faster than cold booting because BIOS is not reloaded. 2. Block Diagram Of Computers Block diagram of a computer gives you the pictorial representation of a computer that how it works inside. Or you can say that, in computer's block diagram, we will see how computer works from feeding the data to getting the result. Page 4 Programming in “ C –Language ” Here is the block diagram of a computer system: In the above diagram, both control (control unit or CU) and arithmetic & logic unit (ALU) combinely called as Central Processing Unit (CPU). Let's describe about all the parts as included in the above diagram one by one. The Processor Unit (CPU) It is the brain of a computer system. All major calculation and comparisons are made inside the CPU and it is also responsible for activation and controlling the operation of other unit. This unit consists of two major components, that are arithmetic logic unit (ALU) and control unit (CU). Arithmetic Logic Unit (ALU) Here arithmetic logic unit performs all arithmetic operations such as addition, subtraction, multiplication and division. It also uses logic operation for comparison. Control Unit (CU) And the control unit of a CPU controls the entire operation of a computer. It also controls all devices such as memory, input/output devices connected to the CPU. CU fetches instructions from memory, decodes the instruction, interprets the instruction to know what the task are to be performed and sends suitable control signals to the other components to perform for the necessary steps to executes the instruction. Input/Output Unit Page 5 Programming in “ C –Language ” The input/output unit consists of devices used to transmit information between the external world and computer memory. The information fed through the input unit is stored in computer's memory for processing and the final result stored in memory can be recorded or display on the output medium. Memory Unit Memory unit is an essential component of a digital computer. It is where all data intermediate and final results are stored. The data read from the main storage or an input unit are transferred to the computer's memory where they are available for processing. Memory units are used to measure and represent data. Some of the commonly used memory units are: 1) Bit: The computer memory units start from bit. A bit is the smallest memory unit to measure data stored in main memory and storage devices. A bit can have only one binary value out of 0 and 1. 2) Byte: It is the fundamental unit to measure data. It contains 8 bits or is equal to 8 bits. Thus a byte can represent 2*8 or 256 values. 3) Kilobyte: A kilobyte contains 1024 bytes. 4) Megabyte: A megabyte contains 1024 kilobytes. 5) Gigabyte: A gigabyte contains 1024 megabyte. A) Types of Computer Memory: Primary and Secondary Although many types of memory in a computer exist, the most basic distinction is between primary memory, often called system memory, and secondary memory, which is more commonly called storage. The key difference between primary and secondary memory is speed of access. Page 6 Programming in “ C –Language ”  Primary memory includes ROM and RAM, and is located close to the CPU on the computer motherboard, enabling the CPU to read data from primary memory very quickly indeed. It is used to store data that the CPU needs imminently so that it does not have to wait for it to be delivered.  Secondary memory by contrast, is usually physically located within a separate storage device, such as a hard disk drive or solid state drive (SSD), which is connected to the computer system either directly or over a network. The cost per gigabyte of secondary memory is much lower, but the read and write speeds are significantly slower. Primary Memory Types: RAM and ROM There are two key types of primary memory: 1. RAM, or random access memory 2. ROM, or read-only memory Let's look in-depth at both types of memory. 1) RAM Computer Memory The most important things to understand about RAM are that RAM memory is very fast, it can be written to as well as read, it is volatile (so all data stored in RAM memory is lost when it loses power) and, finally, it is very expensive compared to all types of secondary memory in terms of cost per gigabyte. It is because of the relative high cost of RAM compared to secondary memory types that most computer systems use both primary and secondary memory. Types of RAM  DRAM: DRAM stands for Dynamic RAM, and it is the most common type of RAM used in computers. The oldest type is known as single data rate (SDR) DRAM, but newer computers use faster dual data rate (DDR) DRAM. DDR comes in several versions including DDR2 , DDR3, and DDR4, which offer better performance and Page 7 Programming in “ C –Language ” are more energy efficient than DDR. However different versions are incompatible, so it is not possible to mix DDR2 with DDR3 DRAM in a computer system. DRAM consists of a transistor and a capacitor in each cell.  SRAM: SRAM stands for Static RAM, and it is a particular type of RAM which is faster than DRAM, but more expensive and bulker, having six transistors in each cell. For those reasons SRAM is generally only used as a data cache within a CPU itself or as RAM in very high-end server systems. A small SRAM cache of the most imminently-needed data can result in significant speed improvements in a system 2) ROM Computer Memory ROM stands for read-only memory, and the name stems from the fact that while data can be read from this type of computer memory, data cannot normally be written to it. It is a very fast type of computer memory which is usually installed close to the CPU on the motherboard. Types of ROMs ROM is available in several different types, including PROM, EPROM, and EEPROM.  PROM PROM stands for Programmable Read-Only Memory, and it is different from true ROM in that while a ROM is programmed (i.e. has data written to it) during the manufacturing process, a PROM is manufactured in an empty state and then programmed later using a PROM programmer or burner.  EPROM EPROM stands for Erasable Programmable Read-Only Memory, and as the name suggests, data stored in an EPROM can be erased and the EPROM reprogrammed. Erasing an EPROM involves removing it from the computer and exposing it to ultraviolet light before re-burning it.  EEPROM EEPROM stands for Electrically Erasable Programmable Read-Only Memory, and the distinction between EPROM and EEPROM is that the latter can be erased and written to by the computer system it is installed in. In that sense EEPROM is not strictly read-only. However in many cases the write process is slow, so it is normally only done to update program code such as firmware or BIOS code on an occasional basis .Secondary Memory Types Secondary memory comprises many different storage media which can be directly attached to a computer system. These include:  hard disk drives  solid state drives (SSDs)  Optical (CD or DVD) drives  Tape drives Secondary memory also includes:  Storage arrays including 3D NAND flash arrays connected over a storage area network (SAN) Page 8 Programming in “ C –Language ”  Storage devices which may be connected over a conventional network (known as network attached storage, or NAS) Arguably cloud storage can also be called secondary memory. Differences between RAM and ROM ROM:  Non-volatile  Fast to read  Usually used in small quantities  Cannot be written to quickly  Used to store boot instructions or firmware  Relatively expensive per megabyte stored compared to RAM RAM:  Volatile  Fast to read and write  Used as system memory to store data (including program code) that the CPU needs to process imminently  Relatively cheap per megabyte stored compared to ROM, but relatively expensive compared to secondary memory 3. What is a computer ? Characteristcis And Limitations of Computers: The word “computer” comes from the word “compute” which means to calculate. So a computer is normally considered to be a calculating device that performs arithmetic operations at enormous speed. More accurately, a computer may be defined as a device that that operates upon information or data . Now a day’s more than 80 % of the work done by computers today is a non mathematical or non- numerical nature. Modern Definition of computers : A computer is an electronic device which is used to perform operation on raw data as per instruction given by user. All the Plugged with computer system( e.g. keyboard, mouse, printer,CPU etc) is called hardware, the language , instruction, data are the called software Page 9 Programming in “ C –Language ” . Characteristics or features of computers: 1. Speed: A computer is a very fast device. The computer takes a fraction of seconds to perform any operation. The speed of computer is measured in micro seconds (10-3), Milliseconds (10-6), nanoseconds (10-9) and even Picoseconds (10-12).A powerful computer is capable of performing about 3-4 million simple operations per second. 2. Accuracy: The accuracy of computer is very high and the degree of a particular computer depends upon its design. But for a particular computer, each and every calculation is performed with the same accuracy. Errors can occur in a computer but these are mainly due to human rather than technological weakness. 3. Storage Capacity : Computers can store data and instruction with a lot of volume and very high efficiency. 4. Diligence: unlike human being a computer is free from monotony, tiredness, luck of concentration etc. and hence can work for hours together without creating any error. A computer can perform the last calculation with exactly the same accuracy and seed as the first one. 5. Automation: Once a Program is in the computer’s memory, CPU follows the instructions until it meets the last instruction. Though the program concept many takes can be performed simultaneously, some on foreground and some on background. Thus automation bring the program execution fast 6. Reliability: Because, computer is an electronic device thus it perform all operations with 100 % accuracy and reliability. Reliability can affect only error prone by human mind. 7. Versatility: versatility is one of the most wonderful things about the computer. One moment it can do any one operation and next moment if can perform any other operation. A computer is capable of performing almost any task according to given instructions. Page 10 Programming in “ C –Language ” Limitation or Drawback of Computer 1. No I.Q. : Computer is not a magical device. It performs only those works which man can does but the main difference is that computer can work those operations with very high speed and reliable accuracy. It has no any intelligence quality or thinking power 2. No Feeling: Because computer is only a machine, it has no feeling like human being. It has no brain for thinking as man can does. Man had successes to make computer memory be different inventions of technology but he couldn’t make heart. 3. Data Machine Readable : Computer data is read by machine, meaning data obtained from the computer can be read by the computer itself. 4. It required power to operate. 5. Problem may occur due to system breakdown. 4. Computer – Applications In this chapter, we will discuss the application of computers in various fields. Business accuracy, A computer has high speed of calculation, diligence, reliability, or versatility which has made it an integrated part in all business organizations. Computer is used in business organizations for −  Payroll calculations Page 11 Programming in “ C –Language ”  Budgeting  Sales analysis  Financial forecasting  Managing employee database  Maintenance of stocks, etc. Banking Today, banking is almost totally dependent on computers. Banks provide the following facilities −  Online accounting facility, which includes checking current balance, making deposits and overdrafts, checking interest charges, shares, and trustee records.  ATM machines which are completely automated are making it even easier for customers to deal with banks. Insurance Insurance companies are keeping all records up-to-date with the help of computers. Insurance companies, finance houses, and stock broking firms are widely using computers for their concerns. Insurance companies are maintaining a database of all clients with information showing – Procedure to continue with policies  Starting date of the policies  Next due installment of a policy  Maturity date  Interests due  Survival benefits  Bonus Education The computer helps in providing a lot of facilities in the education system.  The computer provides a tool in the education system known as CBE (Computer Based Education).  CBE involves control, delivery, and evaluation of learning.  Computer education is rapidly increasing the graph of number of computer students.  There are a number of methods in which educational institutions can use a computer to educate the students.  It is used to prepare a database about performance of a student and analysis is carried out on this basis. Marketing Page 12 Programming in “ C –Language ” In marketing, uses of the computer are following − Advertising − With computers, advertising professionals create art and graphics, write and revise copy, and print and disseminate ads with the goal of selling more products.  Home Shopping − Home shopping has been made possible through the use of computerized catalogues that provide access to product information and permit direct entry of orders to be filled by the customers. Healthcare Computers have become an important part in hospitals, labs, and dispensaries. They are being used in hospitals to keep the record of patients and medicines. It is also used in scanning and diagnosing different diseases. ECG, EEG, ultrasounds and CT scans, etc. are also done by computerized machines. Following are some major fields of health care in which computers are used. Diagnostic System − Computers are used to collect data and identify the cause of illness.  Lab-diagnostic System − All tests can be done and the reports are prepared by computer.  Patient Monitoring System − These are used to check the patient's signs for abnormality such as in Cardiac Arrest, ECG, etc.  Pharma Information System − Computer is used to check drug labels, expiry dates, harmful side effects, etc.  Surgery − Nowadays, computers are also used in performing surgery. Engineering Design Computers are widely used for Engineering purpose. One of the major areas is CAD (Computer Aided Design) that provides creation and modification of images. Some of the fields are − Structural Engineering − Requires stress and strain analysis for design of ships, buildings, budgets, airplanes, etc.Industrial Engineering − Computers deal with design, implementation, and improvement of integrated systems of people, materials, and equipment. Architectural Engineering − Computers help in planning towns, designing buildings, determining a range of buildings on a site using both 2D and 3D drawings. Military Computers are largely used in defence. Modern tanks, missiles, weapons, etc. Military also employs computerized control systems. Some military areas where a computer has been used are −  Missile Control Page 13 Programming in “ C –Language ”  Military Communication  Military Operation and Planning  Smart Weapons Communication Communication is a way to convey a message, an idea, a picture, or speech that is received and understood clearly and correctly by the person for whom it is meant. Some main areas in this category are –.E-mail  Chatting  Usenet  FTP  Telnet  Video-conferencing  Government Computers play an important role in government services. Some major fields in this category are − .Budgets  Sales tax department  Income tax department  Computation of male/female ratio  Computerization of voters lists  Computerization of PAN card  Weather forecasting 5. Computer - Types We can categorize computer in two ways: on the basis of data handling capabilities and size. On the basis of data handling capabilities, the computer is of three types:  Analogue Computer  Digital Computer  Hybrid Computer 1) Analogue Computer Analogue computers are designed to process analogue data. Analogue data is continuous data that changes continuously and cannot have discrete values. We can say that analogue computers are used where we don't need exact values always such as speed, temperature, pressure and current. Advantages of using analogue computers: Page 14 Programming in “ C –Language ”  It allows real-time operations and computation at the same time and continuous representation of all data within the rage of the analogue machine.  In some applications, it allows performing calculations without taking the help of transducers for converting the inputs or outputs to digital electronic form and vice versa. Types of analogue computers:  Slide Rules: It is one of the simplest types of mechanical analogue computers. It was developed to perform basic mathematical calculations. It is made of two rods. To perform the calculation, the hashed rod is slid to line up with the markings on another rod.  Castle Clock: It was invented by Al-Jarazi. It was able to save programming instructions. Its height was around 11 feet and it was provided with the display of time, the zodiac, and the solar and lunar orbits. This device also could allow users to set the length of the day as per the current season.  Electronic Analogue Computer: In this type of analogue computer, electrical signals flow through capacitors and resistors to simulate physical phenomena. Here, the mechanical interaction of components does not take place. The voltage of the electrical signal generates the appropriate displays. 2) Digital Computer Digital computer is designed to perform calculations and logical operations at high speed. It accepts the raw data as input in the form of digits or binary numbers (0 and 1) and processes it with programs stored in its memory to produce the output. All modern computers like laptops, desktops including smartphones that we use at home or office are digital computers. Advantages of digital computers:  It allows you to store a large amount of information and to retrieve it easily whenever you need it.  You can easily add new features to digital systems more easily.  Different applications can be used in digital systems just by changing the program without making any changes in hardware  The cost of hardware is less due to the advancement in the IC technology.  It offers high speed as the data is processed digitally. 3) Hybrid Computer Hybrid computer has features of both analogue and digital computer. It is fast like an analogue computer and has memory and accuracy like digital computers. It can process both continuous and discrete data. It accepts analogue signals and convert them into digital form before processing. So, it is widely used in specialized applications where both analogue and digital data is processed. For example, a processor is used in petrol pumps that converts the measurements of fuel flow into quantity and price. Similarly, they are used in airplanes, hospitals, and scientific applications. Advantages of using hybrid computers:  Its computing speed is very high due to the all-parallel configuration of the analogue subsystem.  It produces precise and quick results that are more accurate and useful.  It has the ability to solve and manage big equation in real-time.  It helps in the on-line data processing. Page 15 Programming in “ C –Language ” On the basis of size, the computer can be of five types: Computers can be broadly classified by their speed and computing power. S.No. Type Specifications 1 PC (Personal Computer) It is a single user computer system having moderately powerful microprocessor 2 Workstation It is also a single user computer system, similar to personal computer however has a more powerful microprocessor. 3 Mini Computer It is a multi-user computer system, capable of supporting hundreds of users simultaneously. 4 Main Frame It is a multi-user computer system, capable of supporting hundreds of users simultaneously. Software technology is different from minicomputer. 5 Supercomputer It is an extremely fast computer, which can execute hundreds of millions of instructions per second. PC (Personal Computer) A PC can be defined as a small, relatively inexpensive computer designed for an individual user. PCs are based on the microprocessor technology that enables manufacturers to put an entire CPU on one chip. Businesses use personal computers for word processing, accounting, despublishing, and for running spreadsheet and database management applications. At home, the most popular use for personal computers is playing games and surfing the Internet. Example :laptops,smartphones,tabs,desktop computers Workstation Workstation is a computer used for engineering applications (CAD/CAM), desktop publishing, software development, and other such types of applications which require a moderate amount of computing power and relatively high quality graphics capabilities.graphics and animations ,multimedia operations can be performed through workstation computers Minicomputer It is a midsize multi-processing system capable of supporting up to 250 users simultaneously. Page 16 Programming in “ C –Language ” Mainframe Mainframe is very large in size and is an expensive computer capable of supporting hundreds or even thousands of users simultaneously. Mainframe executes many programs concurrently and supports many simultaneous execution of programs. Supercomputer Supercomputers are one of the fastest computers currently available. Supercomputers are very expensive and are employed for specialized applications that require immense amount of mathematical calculations (number crunching). 6. Computer Generations Let us now discuss the development in Computer Technology over the different generations. First Generation  The period 1940 to 1956, roughly considered as the First Generation of Computer.  The first generation computers were developed by using vacuum tube or thermionic valve machine.  The input of this system was based on punched cards and paper tape; however, the output was displayed on printouts.  The first generation computers worked on binary-coded concept (i.e., language of 0-1). Examples: ENIAC, EDVAC, etc. Second Generation  The period 1956 to 1963 is roughly considered as the period of Second Generation of Computers.  The second generation computers were developed by using transistor technology.  In comparison to the first generation, the size of second generation was smaller.  In comparison to computers of the first generation, the computing time taken by the computers of the second generation was lesser. Third Generation  The period 1963 to 1971 is roughly considered as the period of Third Generation of computers.  The third generation computers were developed by using the Integrated Circuit (IC) technology.In comparison to the computers of the second generation, the size of the computers of the third generation was smaller.  In comparison to the computers of the second generation, the computing time taken by the computers of the third generation was lesser.  The third generation computer consumed less power and also generated less heat.  The maintenance cost of the computers in the third generation was also low.  The computer system of the computers of the third generation was easier for commercial use. Fourth Generation Page 17 Programming in “ C –Language ”  The period 1972 to 2010 is roughly considered as the fourth generation of computers.  The fourth generation computers were developed by using microprocessor technology.  By coming to fourth generation, computer became very small in size, it became portable.  The machine of fourth generation started generating very low amount of heat.  It is much faster and accuracy became more reliable.  The production cost reduced to very low in comparison to the previous generation.  It became available for the common people as well. Fifth Generation  The period 2010 to till date and beyond, roughly considered as the period of fifth generation of computers.  By the time, the computer generation was being categorized on the basis of hardware only, but the fifth generation technology also included software.  The computers of the fifth generation had high capability and large memory capacity.  Working with computers of this generation was fast and multiple tasks could be performed simultaneously.  Some of the popular advanced technologies of the fifth generation include Artificial intelligence, Quantum computation, Nanotechnology, Parallel processing, etc. Introduction To Alagorithams And Programming Lanaguages 7. Key features of algorithms: An alagoritham has a finite number of steps and some steps may involve decision-making and repetition. Boardly speaking, an alagoritham exhibits three key features, namely, sequence, decision, and repetition Sequence: sequence menas that each step of the alagoritham is in the specified order. Q: an alagoritham to add two numbers Step:1 input the firsty number as A Step:2 input the firsty number as B Step:3 set C= A + B Step:4 print C Step:5 end Decision: Decision statements are used when the outcome of the process depends on some condition. Q: an alagoritham to test the equality of two numbers Page 18 Programming in “ C –Language ” Step:1 input the firsty number as A Step:2 input the firsty number as B Step:3 if A = B Then print “ equal” else Print Not Equal “ Step:4 end Repetition : repetition, which involves executing one or more steps for a number of times, can be implemented using constructs such as the while, do-while, for loop. These loops execute one or more steps until some condition is true. Q: an alagoritham to print the first 10 natural numbers. Step:1 [ initilization ] set I=0, N= 10. Step:2 repeat step while I<=N Step:3 print “ I” Step:4 end Page 19 Programming in “ C –Language ” 8. Flow Charts Flow Chart: a flow chart is a graphical symbolic representation of a process. It is basically used to design and document virtually complex processors to help the viewers to visualize the logic of the process. So that they can gain a better understanding of the process when designing a flow chart , each step in the process is depicted by a diffrenet symbol and is associated with a short decription Start and end symbols: start and end symbols are also known as the terminal symbols and are represented as a circules, ovals, or rounded rectangles .terminal symbols are always the first and the last symbols in a flow chart. Arrows: arrows depict the flow of control of the program. They illustrate the exact sequence in which the instructions are executed. Generic processing step: Generic processing step is also called as an activity is represented using a rectangle . Input and output symbols: Input and output symbols are represented using a parallelogram and are used to get inputs from the users or display the results to them. A conditional or decision symbol: A conditional or decision symbol is represendted using a diamond. It is basically used to depict a Yes/No question. Advantages:  They are very good communication tools to explain the logic of a system to all concerned.they are help to analyze the problem in a more effective manner.  They are also used for program documentation .they are even more helpful in the case of complex programs.  They can be used to debug programs that have error(s). they help the programmers to easily detect ,locate ,and remove mistakes in the program in a systematic manner. Page 20 Programming in “ C –Language ” Limitations:  Drawing flowcharts is a laborious and a time-consuming activity. Just imagine the effort required to draw a flw chart of a program having 50,000 statemetns in it!  Many times , the flow chart of a complex program becomes complex asn clumsy.  At a times, a little bit of alteration in the solution may require complete re-drawing of the flow chart. Page 21 Programming in “ C –Language ” 9. Type of Programming languages (Or) Generation of programming languages We now know that programming languages are the primary tools for creating software. To day, hundreds of programming languages are exists in the market, some more used than others, and each claiming to be the best. However, back in the 1940s, when computers were being developed, there was just one language – the machine language. The concept of generations of programming languages (also known as levels) is closely connected to the advances in technology that brought about the different generations of computers. The four generations of programming languages are 1. machine language, 2. assembly language, 3. high level language ( also known as third generation or 3GL) 4. very high level language ( also known as fourth generation or 4GL) First generation: machine language Programming of the first stored-program computer systems was performed in machine language. This is the lowest level of programming language and also the only language that computers understand. All the commands and data values are expressed using „1‟s and „0‟s . Second generation: assembly language The second-generation programming language include the assembley language. They are symbolic programming languages. They are symbolic programming languages that use syambolic notation to represent machine language instructions . these languages are closely connected to the machine language and the internal architecture of the computer system on which they are used. Page 22 Programming in “ C –Language ” Programmers written in assembly language require a translator, often known as an assemblers to convert them into a machine language. This is the because the computer understood only the language of 1‟s and 0‟s. Third Generation: High Level Language the third generations was introduced to make programming language more friendly. Programmers are written in an English-like manner,making them more convenient to use and giving the programmers more time to address a client problems. while some high level languages were specifically designed to serve a specific purpose. Other languages were very flexible and were considered to be general purpose languages. Most of the programmers preferred to use general purpose high level languages such as BASIC,FORTRAN,PASCAL,COBOL,C++ or java. Again translator is needed to translate the instructions written in high level languages into computer executable machine language. Such translators are commonly known as interpreters and complers. Each high level language has many compilers, and there is one for each type of computer Fourth Generation: Very High Level Language With each generation , programming languages have become easier to use and more like natural languages. A typical example of a 4GL is the query language that allows a user to request information from a database with precisely worded English like sentence. A query language is used a databse from the user. For example, when working with structured query language , the programmers jest need to remember a few rules of syntax and logic, but it is much easier to learn than COBOL or C Language processor Language processor is special software it is used to convert the source code(high level) into computer executable object code(machine language). Which is also known as interpreters and compiler Interpreters : interpreter is a special software which is used to convert soure code into object code step by step process. Compiler: compiler is special software which is used to covert source code into object code at a time process. In this procees data will be saved to further use Page 23 Programming in “ C –Language ” 10. Structured Programming C is called a structured programming language because to solve a large problem, C programming language divides the problem into smaller modules called functions or procedures each of which handles a particular responsibility. The program which solves the entire problem is a collection of such functions. Here is an example of Matrix addition program, which is divided into these sub procedures - input matrix, display matrix, add matrix, save result matrix to file. Here is a pictorial structural view of the program. Another good example is calculate student's grade. Program is divided into these sub modules - input student marks, get student record, update student record, display student record, calculate grade. Here is a structural view of the program. One major drawback of C language is that similar functions cannot be grouped inside a module or class. Also functions cannot be associated to a type or structure. Thus data and functions cannot be bound together. C++ language overcomes these problems by introducing object oriented functionality in its programming capabilities. Advantages  C structured programming is simple and easy to understand and implement.  It is well sited for small size implementation. However this is not restricted. A good design can extend it to large size implementation.  Programmers do not require to know complex design concepts to start a new program. Disadvantages  Data and methods and not be bind together in a module.  Polymorphism and inheritance are not available.  Complex design and full object oriented design cannot be implemented.  Programmers generally prefer object oriented programming language over structured programming language when implementing a complex gaming applications or front end business applications. Page 24 Programming in “ C –Language ” 11. Design and Implementation of Correct Efficient and Maintainable Programs? The entire program or software (collection of programs) development process is divided in to a number of phases, where each phase performs a well- defined task . Phases in Software development Requirements analysis: Life cycle. in this phase , the user’s expectations are gathered to understand why the program or software has to be developed. Then , all the gathered requirements are analysed and the scope or objective of the over all software product is penned down. The last activity in this phase involves documenting every identified requirement of the user in order to avoid any doubts or uncertainty regarding the functionality of the program. The functionality, capability, performance, and availability of hardware and software components are all analysed in this phase. Design: The requirement documented in the previous phase act as the input to the design phase. In this phase, a plan of actions is made before the actual development process starts. This plan will be followed throughout the development process. Moreover, in the design phase, the core structure of the software or program is broken down in to modules. The solution of the program is then specified for each module in the form of Page 25 Programming in “ C –Language ” algorithms or flow charts . The design phase, therefore specifies how the program or software will be developed. Implementation: In this phase, the designed algorithms are converted in to program code using any of the high level languages. The particular choice of language will depend on the type of program such as whether it is a system or an application program. C is preferred for writing system programs, whereas Visual basic might be preferred for an application program. The program codes are tested by the programmer to ensure their correctness. Testing: In this phase , all the modules are tested together to ensure that the overall system works well as a whole product. In this phase, the software is tested using a large number of varied inputs, also known as test data, to ensure that the software is working as expected by the user’s requirements identified in the requirements analysis phase. Software deployment, training, and support: After the code is tested and the software or the program is approved by the user’s it is then installed or deployed in the production environment. Software training and support is a crucial phase. Program designers and developers spend a lot of time creating the software, but if nobody in the organization knows how to use it or to fix certain problems , then no one will want to use it. Maintenance: Maintenance and enhancements are ongoing activities that are done to cope with newly discovered problems or new requirements. Such activities may take a long time to complete. unit-2 Introduction to c:Introduction,-strcure of c,-writing the first c program,-files used in c,-compile and excuting c program,-using comments,-keywords-identifiers-basic data types-variables-constants-i/o statements in c-operators in c-programming examples.Decision control and looping statements:introductions to decision control statements-conditional branching statements-iterative statements-nested loops-break and contine statement –goto statements ---------------------------------------------------------------------------------------------------------------- Page 26 Programming in “ C –Language ” 1. Introduction to C the programming languge C was deceloped by in the early 1970s by Dennis Ritchie at & t Bell Laboratories to be used by the UNIX operating system. It was named „C‟ because many of its features were derived from an earlier language called „B‟ C is one of the most programming languages. It is being used on several different software platforms. It is good idea to learn C because it has been around for a long time which means there is a lot of information available on it. Quiet a few other programming languages such as C++ and java are also based on C which means that one will be able to learn them more easily in the future. Like many other modern languages, C is derived from ALGOL (the first language to use a block structure). Although ALGOL was not accepted widely in the united states but it was widely used in Europe. ALGOL‟s introduction in the 1960‟s led the way for the development of structured programming concepts. Before C, several other programming languages were developed. For example , in 1967 Martin Richards developed a language BCPL( basic combined progarrmming language ) BCPL was basically a type-less(no data type concepts) language which facilitated the user with direct access of memory. This is made it usefull for system programming. Then in 1970, ken thomposn developed a language called B, B was used to develop the first version of UNIX. C was developed by Dennis Ritche in 1972 that took concepts from ALGOL,BCPL, and B in addition to the concepts of these languages, C also supports the concept of data types. Since UNIX operating system the concept of data types. Since UNIX operating system was also developed at Bell Laboratories along with the C language, C and UNIX are strongly associated with each other. Page 27 Programming in “ C –Language ” 2. Structure of a C program: a „C‟ program is composed of preprocessor commands, a global declarations section, and one or more functions the preprocessor directives contain special instructions that include how to prepare the program for compilation one of the most important and commonly used preprocessor command is include which tells the compiler that to execute the program, some more information is needed from the specified header file a C program contains one or more functions, where a function is defined as group of C statements that are executed together. The statements in a C program are written in a logical sequence to perform a specific task. The void main() function is most important function and is a part of every C program. The execution of a C program begins at this function. All functions are divided into two parts- the declaration section and the statement section. The declaration section precedes the statements and is used to describe the data that will be used in the function. Note that data declared within a function are known as local declaration as that data will be visible only within that function. Stated in other terms, the life time of the data will be only till the function ends. The statement section in a function contain the code that manipulates the data to perform a specified task. Page 28 Programming in “ C –Language ” 3. Writting First C Program Before starting the abcd of C language, you need to learn how to write, compile and run the first c program. To write the first c program, open the C console and write the following code: 1. #include 2. int main(){ 3. printf("Hello C Language"); 4. return 0; 5. } #include includes the standard input output library functions. The printf() function is defined in stdio.h . int main() The main() function is the entry point of every program in c language. printf() The printf() function is used to print data on the console. return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for successful execution and 1 for unsuccessful execution. How to compile and run the c program There are 2 ways to compile and run the c program, by menu and by shortcut. Page 29 Programming in “ C –Language ” ByMenu Now click on the compile menu then compile sub menu to compile the c program. Then click on the run menu then run sub menu to run the c program. By shortcut Or, press ctrl+f9 keys compile and run the program directly. You will see the following output on user screen. You can view the user screen any time by pressing the alt+f5 keys. 4. File used in c program Every C pogram has four kinds of files associated with it Page 30 Programming in “ C –Language ” Source code file: The source code file contain the source code of the program. The extension of any C source code file is „.C‟ this file contains C source code that defines the main function and may be other functions. The void main() is the starting point of execution when you successfully compile and run the program. A C program in general may include even other source code files Header files: when working with large projects, it is often desirable to separate out certain sub routines from the void main() of the program. There also may be a case that the same subroutine has to be used in different programs. In the latter case Standared header files in all our programs that we had been writing till now, we were using many functions that were not written by us. For example, strcmp() function which compares two strings. We do not know the details of how these functions work. Such functions that are provided by all C compilers are included in standard header files Object files: object files are generated by the compiler as a result of processing the source code file. They contain compact binary code of the function definitions. Linker uses this object file to produce an executable file (.exe file) by combining the object files together. Object files have a „.obj‟ extension name Executable file: The binary executable file is generated by the linker. The linker links the various object files to produce a binary file that can be directly executed. On windows operating system the excutable files have „.exe‟ extension. Page 31 Programming in “ C –Language ” 5. COMPILING AND EXECUTING „C- PROGRAMS C is compiled language. So once the C program is written you must run it through a C compiler that can create an executable file to be run by the computer. While the C program is human- readable, the executable file on the other hand, is a machine-readable file available in an executable form every programming language has its own compiler the compiler translate the source code into an object code. The object code contains the manchine instructions for the CPU and calls to the operating system applications programming interface(API). Page 32 Programming in “ C –Language ” Hello C 6. Comment lines: many a time the meaning or the purpose of the program code is not clear to the reader. Therefore. It is a good programming practice to place some comments in the code to help the reader understand the code clearly “ Comments are physically presented logically absented ” C supports two types of Comments  // is used to comment single statement. This is known as line comment.a line comment can be placed anywhere on the line and it does now require to specifically ended as the end of the line.  /* is used to comment multiple statements. It is state with /* end with */ and all statements that lie within these characters are commented. This type of comment is known as block statement. Single Line Comments Single line comments are represented by double slash \\. Let's see an example of a single line comment in C. #include main() { //printing information printf("Hello C"); return 0; } Output: Mult Line Comments Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code, but it can't be nested. Syntax: /* code to be commented */ Let's see an example of a multi-Line comment in C. #include int main(){ /*printing information Multi-Line Comment*/ printf("Hello C"); return 0; Page 33 Programming in “ C –Language ” } Output: Hello C Page 34 Programming in “ C –Language ” C character set: Each and every Programming language have it‟s own character set it is used to define tokens. 7. Key words: like every computer language, C has a set of resevered words often known as keywords that can‟t be used as an identifier. All key words are basically a seqauence of characters that have a fixed meaning. By convention, keywords must be written in lower case (small) letters. In C language has a 32 keywords. GNANAJYOTHI DEGREE COLLEGE Page 35 Programming in “ C –Language ” int main() { int n; // n is a local variable to main() function ... .. ... } 8. Identifiers: identifiers, as the name suggests helps us to identify data and other objects in the program. Identifiers are basically the names given to the program elements such as variables,arrays, and functions. They may consist of an alphabet,digit,or an underscore “ _ ” Rules for forming indentifier names  First letter must be an alaphabet White spaces are not allowed Uppercase letters are not allowed Key words not allowed Variables: variables is nothing but identifiers. A variable is defined as a meaningful name given to the data storage location in computer memory. When using a variable we actually refer to an address of the memory where the data is stored. C language supports two kinds of variables.  Local variables  Global variables Local variable: local variables are variables which are declared in its body. These life time and scope is valid in it‟s block only. Global variable: global variables are variables which are declared in out side body. These life time and scope is valid in through out programm. Example of Local Variable GNANAJYOTHI DEGREE COLLEGE Page 36 Programming in “ C –Language ” #include void display(); int n = 5; // global variable int main() { ++n; // variable n is not declared in the main() function display(); return 0; } In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed when main() exits. Global Variable Variables that are declared outside of all functions are known as external or global variables. They are accessible from any function inside the program. Example Global Variable Output void func() { int n1; // n1 is local to func() function } n = 7 GNANAJYOTHI DEGREE COLLEGE Page 37 Programming in “ C –Language ” Primary data types 9. Basic Data Types In C: Data types specify how we enter data into our programs and what type of data we enter. C language has some predefined set of data types to handle various kinds of data that we use in our program. These datatypes have different storage capacities. C language supports 2 different type of data types, These are fundamental data types in C namely integer(int), floating(float), charater(char) and void. Derived data types are like arrays, functions, stuctures and pointers. These are dicussed in detail later. Integer type Integers are used to store whole numbers. Derived data types GNANAJYOTHI DEGREE COLLEGE Page 38 Programming in “ C –Language ” Floating type Character type Size and range of Integer type on 16-bit machine Type Size(bytes) Range int or signed int 2 -32,768 to 32767 unsigned int 2 0 to 65535 short int or signed short int 1 -128 to 127 long int or signed long int 4 -2,147,483,648 to 2,147,483,647 unsigned long int 4 0 to 4,294,967,295 Floating types are used to store real numbers. Size and range of Integer type on 16-bit machine Type Size(bytes) Range Float 4 3.4E-38 to 3.4E+38 double 8 1.7E-308 to 1.7E+308 long double 10 3.4E-4932 to 1.1E+4932 Character types are used to store characters value. GNANAJYOTHI DEGREE COLLEGE Page 39 Programming in “ C –Language ” Size and range of Integer type on 16-bit machine GNANAJYOTHI DEGREE COLLEGE Page 40 Programming in “ C –Language ” void type Type Size(bytes) Range char or signed char 1 -128 to 127 unsigned char 1 0 to 255 void type means no value. This is usually used to specify the type of functions. GNANAJYOTHI DEGREE COLLEGE Page 41 Programming in “ C –Language ” 10. Constants: constants are identifiers whose value does not change. Variables can change their value at any time but constants can never change their value. Constants are used to define fixed values. A constant is an explicit data value specified by the programmer. The compiler knows the value of the constant at the compile time. 11. I/O statements in C Programming: In C Language input and output function are available as C compiler function or C library provided with each C compiler implementation. These all functions are collectively known as Standard I/O Library function. Here I/O stands for Input and Output used for different inputting and outputting statements. These I/O functions are categorized into three prcessing functions. Console input/output function (deals with keyborad and monitor), disk input/output function (deals with floppy or hard disk) and port input/output function (deals with serial or parallet port). As all the input/output statements deals with the console, so these are also Console Input/Output functions. Console Input/Output function access the three major files before the execution of a C Program. These are as: GNANAJYOTHI DEGREE COLLEGE Page 42 Programming in “ C –Language ” stdin: This file is used to receive the input (usually is keyborad file, but can also take input from the disk file). stdout: This file is used to send or direct the output (usually is a monitor file, but can also send the output to a disk file or any other device). stderr: This file is used to display or store error messages. Contents  Input Ouput Statement  Sample C Programs Input Ouput Statement Input and Output statement are used to read and write the data in C programming. These are embedded in stdio.h (standard Input/Output header file). There are mainly two of Input/Output functions are used for this purpose. These are discussed as: Unformatted I/O functions GNANAJYOTHI DEGREE COLLEGE Page 43 Programming in “ C –Language ” There are mainly six unformatted I/O functions discussed as follows: a) getchar() b) putchar() c) gets() d) puts() e) getch() f) getche() a) getchar() This function is an Input function. It is used for reading a single character from the keyborad. It is buffered function. Buffered functions get the input from the keyboard and store it in the memory buffer temporally until you press the Enter key. The general syntax is as: v = getchar(); where v is the variable of character type. For example: char n; n = getchar(); A simple C-program to read a single character from the keyboard is as: b) putchar() This function is an output function. It is used to display a single character on the screen. The general syntax is as: putchar(v); where v is the variable of character type. For example: char n; putchar(n); A simple program is written as below, which will read a single character using getchar() function and display inputted data using putchar() function: GNANAJYOTHI DEGREE COLLEGE Page 44 Programming in “ C –Language ” c) gets() This function is an input function. It is used to read a string from the keyboar. It is also buffered function. It will read a string, when you type the string from the keyboard and press the Enter key from the keyboard. It will mark nulll character ('\0') in the memory at the end of the string, when you press the enter key. The general syntax is as: gets(v); where v is the variable of character type. For example: char n[20]; gets(n); A simple C program to illustrate the use of gets() function: d) puts() This is an output function. It is used to display a string inputted by gets() function. It is also used to display an text (message) on the screen for program simplicity. This function appends a newline ("\n") character to the output. The general syntax is as: puts(v); or puts("text line"); where v is the variable of character type. A simple C program to illustrate the use of puts() function: e) getch() This is also an input function. This is used to read a single character from the keyboard like getchar() function. But getchar() function is a buffered is function, getchar() function is a non-buffered function. The character data read by this function is directly assign to a variable rather it goes to the memory buffer, the character data directly assign to a variable without the need to press the Enter key. GNANAJYOTHI DEGREE COLLEGE Page 45 Programming in “ C –Language ” Another use of this function is to maintain the output on the screen till you have not press the Enter Key. The general syntax is as: v = getch(); f) getche() All are same as getch(0 function execpt it is an echoed function. It means when you type the character data from the keyboard it will visible on the screen. The general syntax is as: v = getche(); where v is the variable of character type. A simple C program to illustrate the use of getch() function: Formatted I/O functions Formatted I/O functions which refers to an Input or Ouput data that has been arranged in a particular format. There are mainly two formatted I/O functions discussed as follows: a) scanf() b) printf() a) scanf() The scanf() function is an input function. It used to read the mixed type of data from keyboard. You can read integer, float and character data by using its control codes or format codes. The general syntax is as: scanf("control strings",arg1,arg2,. ............argn); or scanf("control strings",&v1,&v2,&v3,. .............. &vn); Where arg1,arg2,..........argn are the arguments for reading and v1,v2,v3, ....... vn all are the variables. The scanf() format code (spedifier) is as shown in the below table: Format Code Meaning %c To read a single character %d To read a signed decimal integer (short) %ld To read a signed long decimal integer GNANAJYOTHI DEGREE COLLEGE Page 46 Programming in “ C –Language ” %e To read a float value exponential %f To read a float (short0 or a single precision value %lf To read a double precision float value %g To read double float value %h To read short integer %i To read an integer (decimal, octal, hexadecimal) %o To read an octal integer only %x To read a hexadecimal integer only %u To read unsigned decimal integer (used in pointer) %s To read a string %[..] To read a string of words from the defined range %[^] To read string of words which are not from the defined range b) printf() This ia an output function. It is used to display a text message and to display the mixed type (int, float, char) of data on screen. The general syntax is as: printf("control strings",&v1,&v2,&v3,. .............. &vn); or printf("Message line or text line"); Where v1,v2,v3, ....... vn all are the variables. The control strings use some printf() format codes or format specifiers or conversion characters. These all are discussed in the below table as: Format Code Meaning %c To read a single character %s To read a string GNANAJYOTHI DEGREE COLLEGE Page 47 Programming in “ C –Language ” %d To read a signed decimal integer (short) %ld To read a signed long decimal integer %f To read a float (short0 or a single precision value %lf To read a double precision float value %e To read a float value exponential %g To read double float value %o To read an octal integer only %x To read a hexadecimal integer only %u To read unsigned decimal integer (used in pointer) 12. Operators in C operator is defined as a symbol that specefiers the mathematical, logical, or relational operation to be performed. C language supports many operations to be used in expressions. These operators can be categorized into the following major groups 1. Arithmetic operators 2. Relation operators 3. Logical operators 4. Bitwise operators 5. Assignment operators 6. Conditional operators 7. Special operators 8. Increment / decrement operators GNANAJYOTHI DEGREE COLLEGE Page 48 Programming in “ C –Language ” Arithmetic operators Operator: operator is a special symbol which can perform an opearation on it‟s oprands Operand: operand is identifiers which is part of the operation. C supports all the basic arithmetic operators. The following table shows all the basic arithmetic operators. Operator Description + adds two operands - subtract second operands from first * multiply two operand / divide numerator by denumerator % remainder of division ++ Increment operator increases integer value by one -- Decrement operator decreases integer value by one Relation operators The following table shows all relation operators supported by C. Operator Description == Check if two operand are equal != Check if two operand are not equal. > Check if operand on the left is greater than operand on the right < Check operand on the left is smaller than right operand >= check left operand is greater than or equal to right operand <= Check if operand on left is smaller than or equal to right operand GNANAJYOTHI DEGREE COLLEGE Page 49 Programming in “ C –Language ” Bitwise operators C language supports following 3 logical operators. Suppose a=1 and b=0, Operator Description Example && Logical AND (a && b) is false || Logical OR (a || b) is true ! Logical NOT (!a) is false Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of bitsfrom right to left. Bitwise operators are not applied to float or double. Operator Description & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR << left shift >> right shift The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the right operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the same precedence. Logical operators GNANAJYOTHI DEGREE COLLEGE Page 50 Programming in “ C –Language ” Assignment Operators b= 2 a = 0001000 Conditional operator Example : Assignment operators supported by C language are as follows. Operator Description Example = assigns values from right side operands to left side operand a=b += adds right operand to the left operand and assign the result to left a+=b is same as a=a+b -= subtracts right operand from the left operand and assign the result to left operand a-=b is same as a=a-b *= mutiply left operand with the right operand and assign the result to left operand a*=b is same as a=a*b /= divides left operand with the right operand and assign the result to left operand a/=b is same as a=a/b %= calculate modulus using two operands and assign the result to left operand a%=b is same as a=a%b It is also known as ternary operator and used to evaluate conditional expression. GNANAJYOTHI DEGREE COLLEGE Page 51 Programming in “ C –Language ” Special operator Increment / Decrement operator If epr1 Condition is true ? Then value expr2 : Otherwise value expr3 Operator Description Example sizeof Returns the size of an variable sizeof(x) return size of the variable x & Returns the address of an variable &x ; return address of the variable x * Pointer to a variable *x ; will be pointer to a variable x Operator Description Example ++ Increment the value by 1 a ++ - - Decrement the value by 1 a - - epr1 ? expr2 : expr3 GNANAJYOTHI DEGREE COLLEGE Page 52 Programming in “ C –Language ” 13. Sample C-Programs Q : Write a c-program to print your address ? #include #include void main() { printf(“\n name ............................... ”); printf(“\n fname .............................. ”); printf(“\n street ................................ ”); printf(“\n village .............................. ”); printf(“\n state ................................. ”); } Q : Write a c-program to initialize the values into a variables? #include #include void main() { int a,b; clrscr(); a=4; b=6; printf(“\n A= %d”,a); printf(“\n B= %d”,b); getch(); } GNANAJYOTHI DEGREE COLLEGE Page 53 Programming in “ C –Language ” Q : Write a c-program to initialize the values into a variables using input instruction? #include #include void main() { int a,b; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); printf(“\n enter b value ”); scanf(“%d”,&b); printf(“\n a= %d”,a); printf(“\n b= %d”,b); getch(); } Q : Write a c-program to print sum of two numbers? #include #include void main() { int a,b,c; clrscr(); a=5; b=7; c=a+b; printf(“\n the sum is %d “,c); getch(); } Q : Write a c-program to print sum of two numbers using input instruction? #include #include void main() { int a,b,c; clrscr(); printf(“\n enter a value „); scanf(“%d”,&a); printf(“\n enter b value „); scanf(“%d”,&b); c=a+b; printf(“\n the sum is %d”,c); getch(); } GNANAJYOTHI DEGREE COLLEGE Page 54 Programming in “ C –Language ” Q : Write a C-program to print subtraction of two numbers ? #include #include void main() { int a,b,c; clrscr(); printf(“\n enter a value „); scanf(“%d”,&a); printf(“\n enter b value „); scanf(“%d”,&b); c=a-b; printf(“\n the subtraction is %d”,c); getch(); } Q : Write a c-program to print Division of two numbers ? #include #include void main() { float a,b,c; clrscr(); printf(“\n enter a value „); scanf(“%f”,&a); printf(“\n enter b value „); scanf(“%f”,&b); c=a/b; printf(“\n the division is %f”,c); getch(); } Q : Write a c-program to print Reminder of two numbers ? #include #include void main() { int a,b,c; clrscr(); printf(“\n enter a value „); scanf(“%d”,&a); printf(“\n enter b value „); scanf(“%d”,&b); c=a%b; printf(“\n the reminder is %d”,c); getch(); } GNANAJYOTHI DEGREE COLLEGE Page 55 Programming in “ C –Language ” g=g+32; printf(“\n the character is %c”,g); getch(); } Q : Write a c-program of swapping of two numbers? #include #include void main() { int a,b,c; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); printf(“\n enter b value ”); scanf(“%d”,&a); printf(“\n before swaping a= %d b=%d ”,a,b); c=a; a=b; b=c; printf(“\n after swaping a= %d b=%d ”,a,b); getch(); } GNANAJYOTHI DEGREE COLLEGE Page 56 Programming in “ C –Language ” 13. CONTROL INSTRUCTIONS Control instruction is an instruction which instruct the complier. In C control Instructions are two types those are 1. decision making and branching 2. decision making and looping (ittrative statements ) a) Decision Making And Branching : in this control will takes some decisions according to that decision it take some branch. It is available in C in the following categories.  Simple IF  IF-Else  Nesting  IF-Else-IF  Switch Case Simple If : If the condition is satisfied then the statement part will get executed otherwise it Not. Syntax: if(condition) { statement part; } Program: #include #include void main() { int a; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); if(a>0) { printf(“\n positive ”); } getch(); } If - Else: If the condition is satisfied then the statement part-1 will get executed otherwise statement part -2 will get executed. Syntax: if(condition) { GNANAJYOTHI DEGREE COLLEGE Page 57 Programming in “ C –Language ” statement part-1; } else GNANAJYOTHI DEGREE COLLEGE Page 58 Programming in “ C –Language ” { } Program: #include #include void main() { int a; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); if(a>0) { printf(“\n positive ”); } else { printf(“\n negative ”); } getch(); } statement part-2; Nesting The technique of placing one block into another block is known as Nesting. Nested IF : Placing the one if block into another if block is called as Nested IF. --------- If the condition-1 and condition-2 is satisfied then the statement part will get Executed. Syntax: if(condition-1) { printf(“\n enter a value ”); scanf(“%d”,&a); if(a>0) } Program: #include #include void main() { int a; clrscr(); GNANAJYOTHI DEGREE COLLEGE Page 59 Programming in “ C –Language ” if(Condition-2) { Statement part-2; } GNANAJYOTHI DEGREE COLLEGE Page 60 Programming in “ C –Language ” { if(a%2= =0) { printf(“\n positive even”); } } getch(); } Nested IF-Else: Placing the one if-else block into another if-else block is called as Nested IF- else. Syntax: if(condition-1) { if(condition-2) { } else { } else { } Statement part 1; Statement part 2; if(condition-3) { } Program: #include #include void main() { int a; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); if(a>0) { } else { } statement part-1; statement part-2; if(a%2= =0) { printf(“\n positive even”); GNANAJYOTHI DEGREE COLLEGE Page 61 Programming in “ C –Language ” } else { } } else { printf(“\n positive odd”); } if(a%2= =0) { printf(“\n negative even”); } else { printf(“\n negative odd”); } getch(); } IF –Else- If : Syntax : if(condition-1) { statement part; } else if(condition-2) { statement part; } else { statement part; } Program : #include #include void main() { int a; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); if(a>0) { printf(“\n positive ”); } GNANAJYOTHI DEGREE COLLEGE Page 62 Programming in “ C –Language ” else if(a<0) GNANAJYOTHI DEGREE COLLEGE Page 63 Programming in “ C –Language ” { printf(“\n negitive ”); } getch(); } Switch Case : Syntax: Program : switch(variable name) { case 1 :statement part 1; break; case 2 :statement part 2; break; case 3 :statement part 3; break; case 4 :statement part 4; break; default: statement part n; } #include #include void main() { int a; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); switch(a) { case 1 :printf(“\n hai ”); break; case 2 :printf(“\n hello ”); break; case 3 :printf(“\n bye ”); break; default: printf(“\n welcome ”); } getch(); } Program : #include #include void main() { GNANAJYOTHI DEGREE COLLEGE getch(); Page 64 Programming in “ C –Language ” char a; clrscr(); printf(“\n enter a character ”); scanf(“%s”,&a); switch(a) { case „a‟: printf(“\n hai ”); break; case „s‟: printf(“\n hello ”); break; case „d‟: printf(“\n bye ”); break; default: printf(“\n welcome ”); } getch(); } Program : #include #include void main() { int a,b,c; char ch; clrscr(); printf(“\n ener a value „); scanf(“%d”,&a); printf(“\n ener b value „); scanf(“%d”,&b); printf(“\n ener your choice „); scanf(“%s”,&ch); switch(ch) { case „+‟:c=a+b; break; case „-‟: c=a-b; break; case „*‟:c=a*b; break; case „/‟:c=a/b; break; case „%‟:c=a%b; break; default: printf(“\n invlaid choice ”); } printf(“\n the result is %d ”,c); GNANAJYOTHI DEGREE COLLEGE } getch(); Page 65 Programming in “ C –Language ” LOOPING b) Decision Making And Looping : As Long as the condition is satisfied the statement part will get executed this technique is known as “Looping” in C there are three statements to support the looping those are 1. while 2. do-while 3. for While Loop: while loop is a loop it is an entry control loop why because it checks the condition at checks the condition is first and allows the control into the block next. Syntax: initialization; while(condition) { Eg: } i=1; statement part ; increment/decrement ; while(i<=10) { Program : printf(“\n GMR ”); i=i+1; } Q : Write a c program to print N below natural numbers #include #include void main() { int n,i; clrscr(); printf(“\n enter n value”); scanf(“%d”,&n); i=1; while(i<=n) { printf(“\n %d ”,i); i++; } GNANAJYOTHI DEGREE COLLEGE } Page 66 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 67 Programming in “ C –Language ” Q : Write a c program to print N below Even numbers #include #include void main() { int n,i; clrscr(); printf(“\n enter n value”); scanf(“%d”,&n); i=2; while(i<=n) { printf(“\n %d ”,i); i=i+2; } getch(); } Q : Write a c program to print N below Odd numbers #include #include void main() { int n,i; clrscr(); printf(“\n enter n value”); scanf(“%d”,&n); i=1; while(i<=n) { printf(“\n %d ”,i); i=i+2; } getch(); } Do-While Loop: Do-while loop is a loop it is an exit control loop. If the condition is satisfied or not once statement part will be executed after that it checks the condition. Syntax: initialization; do { Statement part ; Increment/decrement ; } while(condition); GNANAJYOTHI DEGREE COLLEGE Page 68 Programming in “ C –Language ” Eg: i=1; do { printf(“\n GMR ”); i=i+1; } while(i<=10); Program : Q : Write a c program to print N below natural numbers #include #include void main() { int n,i; clrscr(); printf(“\n enter n value”); scanf(“%d”,&n); i=1; do { printf(“\n %d “,i); i++; } while(i<=n); getch(); } Q : Write a c program to print N below Even numbers #include #include void main() { int n,i; clrscr(); printf(“\n enter n value”); scanf(“%d”,&n); i=2; do { printf(“\n %d “,i); i=i+2; } while(i<=n); getch(); } Q : Write a c program to print N below Odd numbers #include #include void main() GNANAJYOTHI DEGREE COLLEGE Page 69 Programming in “ C –Language ” { GNANAJYOTHI DEGREE COLLEGE Page 70 Programming in “ C –Language ” int n,i; clrscr(); printf(“\n enter n value”); scanf(“%d”,&n); i=1; do { printf(“\n %d “,i); i=i+2; }while(i<=n); getch(); } For Loop : It is an also entry control loop. As long as the condition is satisfied the statement part will get executed. Syntax: for (initialization; condition; increment/decrement) { Eg: Statement part ; } for(i=0;i<=10;i++) { Program : Printf(“\n GMR ”); } Q : Write a c program to print N below natural numbers #include #include void main() { int n,i; clrscr(); printf(“\n enter n value”); scanf(“%d”,&n); for(i=0;i<=n;i++) { printf(“\n %d “,i); } getch(); } Q : Write a c program to print N below Even numbers #include #include void main() { int n,i; GNANAJYOTHI DEGREE COLLEGE Page 71 Programming in “ C –Language ” clrscr(); GNANAJYOTHI DEGREE COLLEGE Page 72 Programming in “ C –Language ” printf(“\n enter n value”); scanf(“%d”,&n); for(i=2;i<=n;i=i+2) { printf(“\n %d “,i); } getch(); } Q : Write a c program to print N below Odd numbers #include #include void main() { int n,i; clrscr(); printf(“\n enter n value”); scanf(“%d”,&n); for(i=1;i<=n;i=i+2) { printf(“\n %d “,i); } getch(); } GOTO Statement jump statement is a statement which is used to jump the control from one place to another place of a program with out observing any condition C supports a special jump statement named “goto” goto can be used into 2 ways those are 1. forward goto 2. backward goto forward goto : Syntax: statement part -1; statement part -2; statement part -3; goto label; statement part -4; statement part -5; statement part -6; label; statement part -7; statement part -8; statement part -9; Program : #include #include void main() GNANAJYOTHI DEGREE COLLEGE Page 73 Programming in “ C –Language ” { Clrscr(); printf(“\n HAI ”); printf(“\n HELLO ”); printf(“\n BYE ”); printf(“\n NARASANNAPETA ”); printf(“\n SRIKAKULAM ”); printf(“\n VIZAG ”); goto ramu; printf(“\n JAMMU ”); printf(“\n POLAKI ”); printf(“\n NPETA ”); printf(“\n SARAVAKOTA ”); ramu: printf(“\n CHENNAI ”); printf(“\n BANGLOORE ”); printf(“\n MUMBAI ”); printf(“\n DELHI ”); printf(“\n RAJASTAN ”); getch(); } Backward goto : Syntax: statement part -1; statement part -2; statement part -3; label: statement part -4; statement part -5; statement part -6; goto label; statement part -7; statement part -8; statement part -9; Program : #include #include void main() { clrscr(); printf(“\n HAI ”); printf(“\n HELLO ”); printf(“\n BYE ”); printf(“\n NARASANNAPETA ”); printf(“\n SRIKAKULAM ”); printf(“\n VIZAG ”); GNANAJYOTHI DEGREE COLLEGE Page 74 Programming in “ C –Language ” ramu; printf(“\n JAMMU ”); printf(“\n POLAKI ”); printf(“\n NPETA ”); printf(“\n SARAVAKOTA ”); goto ramu: printf(“\n CHENNAI ”); printf(“\n BANGLOORE ”); printf(“\n MUMBAI ”); printf(“\n DELHI ”); printf(“\n RAJASTAN ”); getch(); } C break statement The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. The break statement in C can be used in the following two scenarios: Syntax: //loop or switch case break; Example #include #include void main () { int i; for(i = 0; i<10; i++) { printf("%d ",i); if(i = = 5) break; } printf("came outside of loop i = %d",i); } GNANAJYOTHI DEGREE COLLEGE Page 75 Programming in “ C –Language ” Output 0 1 2 3 4 5 came outside of loop i = 5 GNANAJYOTHI DEGREE COLLEGE Page 76 Programming in “ C –Language ” C continue statement The continue statement in C language is used to bring the program control to the beginning of the loop. The continue statement skips some lines of code inside the loop and continues with the next iteration. It is mainly used for a condition so that we can skip some code for a particular condition. Syntax: //loop statements continue; //some lines of the code which is to be skipped Continue statement example #include void main () { int i = 0; while(i!=10) { printf("%d", i); continue; i++; } } Output infinite loop GNANAJYOTHI DEGREE COLLEGE Page 77 Programming in “ C –Language ” Q : Write a c program to find factorial of given number . #include #include void main() { int f =1,n,i; clrscr(); printf(“\n enter n value ”); scanf(%d”,&n); for(i=1;i<=n;i++) { f=f*i; } printf(“\n the factorial is %d ”,f); getch(); } Q : Write a c program to print the sum of N natural numbers #include #include void main() { int n,i,s=0; clrscr(); printf(“\n enter n value”); scanf(“%d”,&n); for(i=1;i<=n;i=i+1) { s=s+i; printf(“\n the sum of %d below natural numbers is %d”,n,s); } getch(); } Q : Write a c program to find MN value #include #include void main() { int m,n,a=1,i; clrscr(); printf(“\n enter the m value ”); scanf(“%d”,&m); printf(“\n enter the n value ”); scanf(“%d”,&n); for(i=1;i<=n;i++) { GNANAJYOTHI DEGREE COLLEGE Page 46 Programming in “ C –Language ” a=a*m; } printf(“\n the %d power %d is %d ”,m,n,a); getch(); } Q : Write a c program to find given number is prime or composite #include #include void main() { int n,=0,i; clrscr(); printf(“\n enter n value ”); scanf(“%d”,&n); if(n>1) { for(i=1;i<=n;i++) { if(n%i= =0) c=c+1; } if(c= = 2) { } else { } else { } printf(“\n given number is prime ”); printf(“\n given number is comosit ”); printf(“\n given number is not a prime and composit ”); getch(); } Q : Write a c program to find reverse number of given number. #include #include void main() { int n,r,s=0; clrscr(); printf(“\n enter n value ”); scanf(“%d”,&n); while(n!=0) GNANAJYOTHI DEGREE COLLEGE Page 47 Programming in “ C –Language ” { GNANAJYOTHI DEGREE COLLEGE Page 48 Programming in “ C –Language ” r=n%10; s=(s*10)+r; n=n/10; } printf(“\n the reverse number of given number is %d ”,s); getch(); } Q : Write a c program to find given number is palindrome or not. #include #include void main() { int n,r,s=0,k; clrscr(); printf(“\n enter n value ”); scanf(“%d”,&n); k=n; while(n!=0) { r=n%10; s=(s*10)+r; n=n/10; } if(k= =s) { printf(“\n given number is palindrome ”); } else { printf(“\n given number is not palindrome ”); } getch(); } Q : Write a c program to find given number is Armstrong or not. #include #include void main() { int n,r,s=0,k; clrscr(); printf(“\n enter n value ”); scanf(“%d”,&n); k= while(n!=0) { r=n%10; s=s+(r*r*r); GNANAJYOTHI DEGREE COLLEGE Page 49 Programming in “ C –Language ” n=n/10; } if(k= =s) { printf(“\n given number is armstrong ”); } else { printf(“\n given number is not armstrong ”); } getch(); } Q : Write a c program to a number and then calculate the sum of its digits. #include #include void main() { int n,t,s=0; clrscr(); printf(“\n Enter a Number: ”); scanf(“%d”,&n); while(n!=0) { t=n%10; s=s+t; n=n/10; } printf(“\n the sum of the digit = %d ”,s); getch(); } Q : Write a c program to find multification table of given number. #include #include void main() { int n,i,r; clrscr(); printf(“\n enter n value :”); scanf(“%d”,&n); for(i=1;i<=10;i++) { r=n*i; printf(“\n %d * %d =%d ”,n,i,r); getch(); } GNANAJYOTHI DEGREE COLLEGE Page 50 Programming in “ C –Language ” Nested For Loop One for loop placing into another for loop this concept is known as nested for loop. Q : Write a c program to print a Square diagram using Star‟s #include #include void main() { int n,i,j; clrscr(); printf(„\n enter n value”); scanf(“%d”,&n); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { printf(“ * ”); } printf(“\n”); } getch(); } Output: enter n value : 5 * * * * * * * * * * * * * * * * * * * * * * * * * Q : Write a c program to print a Square diagram using I value #include #include void main() { int n,i,j; clrscr(); printf(„\n enter n value”); scanf(“%d”,&n); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { printf(“%d ”,i); } printf(“\n”); GNANAJYOTHI DEGREE COLLEGE } Page 51 Programming in “ C –Language ” getch(); GNANAJYOTHI DEGREE COLLEGE } Page 52 Programming in “ C –Language ” Output: enter n value : 5 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 Q : Write a c program to print a Square diagram using J value #include #include void main() { int n,i,j; clrscr(); printf(„\n enter n value”); scanf(“%d”,&n); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { printf(“%d ”,j); } printf(“\n”); } getch(); } Output: enter n value : 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 Q : Write a c program to print a pyramid diagram using star‟s #include #include void main() { int n,i,j; clrscr(); printf(„\n enter n value”); GNANAJYOTHI DEGREE COLLEGE Page 53 Programming in “ C –Language ” scanf(“%d”,&n); for(i=1;i<=n;i++) GNANAJYOTHI DEGREE COLLEGE Page 54 Programming in “ C –Language ” { for(j=1;j<=i;j++) { printf(“ * ”); } printf(“\n”); } getch(); } Output: enter n value : 5 * * * * * * * * * * * * * * * Q : Write a c program to print a pyramid diagram using I value #include #include void main() { int n,i,j; clrscr(); printf(„\n enter n value”); scanf(“%d”,&n); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) { printf(“%d ”,i); } printf(“\n”); } getch(); } Output: enter n value : 5 1 2 2 GNANAJYOTHI DEGREE COLLEGE 3 3 3 Page 55 Programming in “ C –Language ” 4 4 4 4 GNANAJYOTHI DEGREE COLLEGE Page 56 Programming in “ C –Language ” 5 5 5 5 5 Q : Write a c program to print a pyramid diagram using J value #include #include void main() { int n,i,j; clrscr(); printf(„\n enter n value”); scanf(“%d”,&n); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) { printf(“%d ”,j); } printf(“\n”); } getch(); } Output: enter n value : 5 1 1 2 1 2 3 1234 12345 Unit-3 Arrays:introduction-declaration of array-accessing elements of array-storing values in array-operations on array- one dimensional,two dimensional and multi dimensional array,character handling and strings 1. Introductions to array:An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. GNANAJYOTHI DEGREE COLLEGE Page 57 Programming in “ C –Language ” Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations. By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array. Properties of Array The array contains the following properties.  Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.  Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.  Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element. Advantage of C Array 1) Code Optimization: Less code to the access the data. 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily. 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only. 4) Random Access: We can access any element randomly using the array. Disadvantage of C Array 1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.  brightness_4 #include int main() { int arr[5]; arr[0] = 5; arr[2] = -10; arr[3 / 2] = 2; // this is same as arr[1] = 2 arr[3] = arr[0]; printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]); return 0; } GNANAJYOTHI DEGREE COLLEGE Page 58 Programming in “ C –Language ” 2. Declaration of C Array We can declare an array in the c language in the following way. 1. data_type array_name[array_size]; Now, let us see the example to declare the array. 1. int marks[5]; Here, int is the data_type, marks are the array_name, and 5 is the array_size. : The simplest way to initialize an array is by using the index of each element. We can initialize each element of the array by using the index. Consider the following example. 1. marks[0]=80;//initialization of array 2. marks[1]=60; 3. marks[2]=70; 4. marks[3]=85; 5. marks[4]=75; C array example 1. #include 2. int main(){ 3. int i=0; 4. int marks[5];//declaration of array 5. marks[0]=80;//initialization of array 6. marks[1]=60; 7. marks[2]=70; 8. marks[3]=85; 9. marks[4]=75; 10. //traversal of array 11. for(i=0;i<5;i++){ GNANAJYOTHI DEGREE COLLEGE Page 59 Programming in “ C –Language ” 12. printf("%d \n",marks[i]); 13. }//end of for loop 14. return 0; 15. } Output 80 60 70 85 75 C Array: Declaration with Initialization We can initialize the c array at the time of declaration. Let's see the code. 1. int marks[5]={20,30,40,50,60}; In such case, there is no requirement to define the size. So it may also be written as the following code. 1. int marks[]={20,30,40,50,60}; Let's see the C program to declare and initialize the array in C. 1. #include 2. int main(){ 3. int i=0; 4. int marks[5]={20,30,40,50,60};//declaration and initialization of array 5. //traversal of array 6. for(i=0;i<5;i++){ 7. printf("%d \n",marks[i]); 8. } 9. return 0; 10. } Output 20 30 3. Acceing elements of an array. Explanation In this program, we need to create an array and print the elements present in the array. Arrays are the special variable that stores multiple values under the same name. A contiguous memory will be allocated to store elements. Elements of the array can be accessed through their indexes. GNANAJYOTHI DEGREE COLLEGE Page 60 Programming in “ C –Language ” Here, 1, 2, 3, 4 and 5 represent the elements of the array. These elements can be accessed through their corresponding indexes, i.e., 0, 1, 2, 3 and 4. Algorithm 1. Declare and initialize an array. 2. Loop through the array by incrementing the value of i. 3. Finally, print out each element of the array. Solution Python 1. #Initialize array 2. arr = [1, 2, 3, 4, 5]; 3. 4. print("Elements of given array: "); 5. #Loop through the array by incrementing the value of i 6. 7. for i in range(0, len(arr)): 8. print(arr[i]), Output: Elements of given array: 1 2 3 4 5 1. #include 2. 3. int main() 4. { 5. //Initialize array 6. int arr[] = {1, 2, 3, 4, 5}; 7. //Calculate length of array 8. int length = sizeof(arr)/sizeof(arr[0]); 9. 10. printf("Elements of given array: \n"); 11. //Loop through the array by incrementing value of i 12. for (int i = 0; i < length; i++) { 13. printf("%d ", arr[i]); 14. } GNANAJYOTHI DEGREE COLLEGE Page 61 Programming in “ C –Language ” 15. 16. return 0; 17. } Output: Elements of given array: 1 2 3 4 5 50 60 4. Sorting an array In the following program, we are using bubble sort method to sort the array in ascending order. 1. #include 2. void main () 3. { 4. int i, j,temp; 5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23}; 6. for(i = 0; i<10; i++) 7. { 8. for(j = i+1; j<10; j++) 9. { 10. if(a[j] > a[i]) 11. { 12. temp = a[i]; 13. a[i] = a[j]; 14. a[j] = temp; 15. } 16. } 17. } 18. printf("Printing Sorted Element List ...\n"); 19. for(i = 0; i<10; i++) 20. { 21. printf("%d\n",a[i]); 22. } 23. } Program to print the largest and second largest element of the array. 1. #include 2. void main () 3. { 4. int arr[100],i,n,largest,sec_largest; 5. printf("Enter the size of the array?"); GNANAJYOTHI DEGREE COLLEGE Page 62 Programming in “ C –Language ” 6. scanf("%d",&n); 7. printf("Enter the elements of the array?"); 8. for(i = 0; ilargest) 17. { 18. sec_largest = largest; 19. largest = arr[i]; 20. } 21. else if (arr[i]>sec_largest && arr[i]!=largest) 22. { 23. sec_largest=arr[i]; 24. } 25. } 26. printf("largest = %d, second largest = %d",largest,sec_largest); 27. 28. } 5. Operations that can be performed on arrays? Following operations can be performed on arrays: 1. Traversing 2. Searching 3. Insertion 4. Deletion 5. Sorting 6. Merging 1. Traversing: It is used to access each data item exactly once so that it can be processed. E.g. We have linear array A as below: 1 2 3 4 5 10 20 30 40 50 Here we will start from beginning and will go till last element and during this process we will access value of each element exactly once as below: A [1] = 10 A [2] = 20 GNANAJYOTHI DEGREE COLLEGE Page 63 Programming in “ C –Language ” A [3] = 30 A [4] = 40 A [5] = 50 2. Searching: It is used to find out the location of the data item if it exists in the given collection of data items. E.g. We have linear array A as below: 1 2 3 4 5 15 50 35 20 25 Suppose item to be searched is 20. We will start from beginning and will compare 20 with each element. This process will continue until element is found or array is finished. Here: 1) Compare 20 with 15 20 # 15, go to next element. 2) Compare 20 with 50 20 # 50, go to next element. 3) Compare 20 with 35 20 #35, go to next element. 4) Compare 20 with 20 GNANAJYOTHI DEGREE COLLEGE Page 64 Programming in “ C –Language ” 20 = 20, so 20 is found and its location is 4. 3. Insertion: It is used to add a new data item in the given collection of data items. E.g. We have linear array A as below: 1 2 3 4 5 10 20 50 30 15 New element to be inserted is 100 and location for insertion is 3. So shift the elements from 5th location to 3rd location downwards by 1 place. And then insert 100 at 3rd location. It is shown below: 4. Deletion: It is used to delete an existing data item from the given collection of data items. E.g. We have linear array A as below: 1 2 3 4 5 10 20 50 40 25 60 The element to be deleted is 50 which is at 3rd location. So shift the elements from 4th to 6th location upwards by 1 place. It is shown below: GNANAJYOTHI DEGREE COLLEGE Page 65 Programming in “ C –Language ” After deletion the array will be: 1 2 3 4 5 6 10 20 40 25 60 5. Sorting: It is used to arrange the data items in some order i.e. in ascending or descending order in case of numerical data and in dictionary order in case of alphanumeric data. E.g. We have linear array A as below: 1 2 3 4 5 10 50 40 20 30 After arranging the elements in increasing order by using a sorting technique, the array will be: 1 2 3 4 5 10 20 30 40 50 6. Merging: It is used to combine the data items of two sorted files into single file in the sorted form We have sorted linear array A as below: 1 2 3 4 5 6 10 40 50 80 95 100 And sorted linear array B as below: 1 2 3 4 20 35 45 90 After merging merged array C is as below: 1 2 3 4 5 6 7 8 9 10 10 20 35 40 45 50 80 90 95 100 #include #include int main() { int ch; GNANAJYOTHI DEGREE COLLEGE Page 66 Programming in “ C –Language ” printf("Enter 1 for insertion into program\n"); printf("Enter 2 for deletion into program\n"); printf("Enter 3 for traversing\n"); printf("Enter your choice :\n"); scanf("%d",&ch); switch(ch) { case 1 { int i,pos,n,k,a[50]; printf("Enter how many data elements you want to enter :\n" ); scanf("%d",&n); printf("Enter your desired elements :\n" ); for(i=0;i<=n-1;i++) { scanf("%d",&a[i]); } printf("You entered : "); for(i=0;i<=n-1;i++) { printf("%d ",a[i]); } printf("\nEnter the postion where you want to insert the new element :\n"); scanf("%d",&pos); printf("Enter the data element you want to insert :\n"); scanf("%d",&k); for(i=n-1;i>=pos-1;i--) { a[i+1]=a[i]; } a[pos-1]=k; printf("Your new sequensce of elements is :\n"); for(i=0;i<=n;i++) { printf("%d ",a[i]); } } case 2 { getch(); break; int i,pos,j,n,a[50]; printf("Enter how many data elements you want to enter :\n" ); scanf("%d",&n); printf("Enter your desired elements :\n" ); for(i=0;i<=n-1;i++) GNANAJYOTHI DEGREE COLLEGE Page 67 Programming in “ C –Language ” { scanf("%d",&a[i]); } printf("You entered : "); for(i=0;i<=n-1;i++) { printf("%d ",a[i]); } printf("\nEnter the postion of element you want to delete :\n"); scanf("%d",&pos); for(i=pos-1;i<=n-1;i++) { a[i]=a[i+1]; } printf("Your new sequence of elements is :\n"); for(i=0;i<=n-2;i++) { printf("%d ",a[i]); } getch(); break; } case 3: { int i,n,a[50]; printf("Enter the no. elements you want to enter :\n"); scanf("%d",&n); printf("Enter your data elements :\n"); for(i=0;i<=n-1;i++) { scanf("%d",&a[i]); } printf("You entered : "); for(i=0;i<=n-1;i++) { printf("%d ",a[i]); } getch(); break; } } } GNANAJYOTHI DEGREE COLLEGE Page 68 Programming in “ C –Language ” 6. ARRAYS Array is collection of related data type items to share a common name. simply an array is also a variable. In array the memory is allocated to the data items in a sequential manner i.e linear fashion. The main objective of this concept is to reduce the accessing time In array all the data items have the same name uniquely identify them we use subscript. In C arrays may broadly categorized into three categories these are 1. one dimensional array 2. two dimensional array 3. three dimensional array One Dimensional Array An array in which elements are identified with the help of single subscript is called one dimensional array or single subscripted variable. datatype variable name[size]; int a[5]; float b[5]; char c[5]; :datatype variablename[ ]={value}; int a[5]={1,2,3,4,5}; float b[3]={2.3,5.6,8.5}; Program-1: #include #include void main() { int a[4]={1,8,9,4}; clrscr(); printf(“\n a[0]=%d”,a[0]); printf(“\n a[1]=%d”,a[0]); printf(“\n a[2]=%d”,a[1]); GNANAJYOTHI DEGREE COLLEGE Page 69 Programming in “ C –Language ” printf(“\n a[3]=%d”,a[1]); getch(); } Program-2: #Include #include void main() { int a[ ]={1,8,9,4}; clrscr(); printf(“\n a[0]=%d”,a[0]); printf(“\n a[0]=%d”,a[0]); printf(“\n a[1]=%d”,a[1]); printf(“\n a[1]=%d”,a[1]); getch(); } Program-3: #include #include void main() { int a[4]; clrscr(); a[0]=45; a[1]=86; a[2]=26; a[3]=63; printf(“\n a[0]=%d”,a[0]); printf(“\n a[1]=%d”,a[1]); printf(“\n a[2]=%d”,a[2]); printf(“\n a[3]=%d”,a[3]); getch(); } Example of 1d array #include int main() { int s[5] = {89, 76, 98, 91, 84}, i; printf("\n---Students marks details--- "); for(i = 0; i < 5; i++) { printf("\ns%d = %d ", i + 1, s[i]); } return 0; } Out put: 89,76,98,91,84 GNANAJYOTHI DEGREE COLLEGE Page 70 Programming in “ C –Language ” Two dimensional Array Two dimensional array is an array in which elements are identified with the help of double subscript so it is also called as double subscripted variable or two dimensional array Syntax. Ex: datatype variable name[row size][coloumn size]; Initialization: Syntax: int a[5][3]; float b[5][5]; char c[5][4]; program-1: #include #include void main() { int a[2][2]={{11,88},{99,44}}; clrscr(); printf(“\n a[0][0]=%d”,a[0][0]); printf(“\n a[0][1]=%d”,a[0][1]); printf(“\n a[1][0]=%d”,a[1][0]); printf(“\n a[1][1]=%d”,a[1][1]); getch(); } Program-2: #Include #include void main() { int a[ ]={11,88,99,44}; clrscr(); printf(“\n a[0][0]=%d”,a[0][0]); printf(“\n a[0][1]=%d”,a[0][1]); printf(“\n a[1][0]=%d”,a[1][0]); printf(“\n a[1][1]=%d”,a[1][1]); getch(); } Program-3: #include #include void main() GNANAJYOTHI DEGREE COLLEGE Page 71 Programming in “ C –Language ” { int a[2][2]; clrscr(); a[0][0]=45; a[0][1]=86; a[1][0]=26; a[1][1]=63; printf(“\n a[0][0]=%d”,a[0][0]); printf(“\n a[0][1]=%d”,a[0][1]); printf(“\n a[1][0]=%d”,a[1][0]); printf(“\n a[1][1]=%d”,a[1][1]); getch(); } Example of 2d array: #include #include void main() { int a[2][2],i,j; clrscr(); for(i=0;i<2;i++) { for(j=0;j<2j++) { printf(“\n enter a[%d][%d] ”,i,j); scanf(“%d”,&a[i][j]); } } printf(“\n the values are ”); for(i=0;i<2;i++) { for(j=0;j<2j++) { printf(“\n enter a[%d][%d] = %d ”,i,j,a[i]j]); } } getch(); } Out put:13 ,66,77,88 Multidimensional Arrays: In this tutorial, you will learn to work with multidimensional arrays (two-dimensional and three-dimensional arrays) with the help of examples. GNANAJYOTHI DEGREE COLLEGE Page 72 Programming in “ C –Language ” In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4]; Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 rows and each row has 4 columns. Similarly, you can declare a three-dimensional (3d) array. For example, float y[2][4][3]; Here, the array y can hold 24 elements. Initializing a multidimensional array Here is how you can initialize two-dimensional and three-dimensional arrays: Initialization of a 2d array // Different ways to initialize two-dimensional array int c[2][3] = {{1, 3, 0}, {-1, 5, 9}}; int c[][3] = {{1, 3, 0}, {-1, 5, 9}}; int c[2][3] = {1, 3, 0, -1, 5, 9}; Initialization of a 3d array You can initialize a three-dimensional array in a similar way like a two-dimensional array. Here's an example, GNANAJYOTHI DEGREE COLLEGE Page 73 Programming in “ C –Language ” int test[2][3][4] = { {{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}}, {{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}}; Example 1: Two-dimensional array // C program to store temperature of two cities of a week and display it. #include const int CITY = 2; const int WEEK = 7; int main() { int temperature[CITY][WEEK]; // Using nested loop to store values in a 2d array for (int i = 0; i < CITY; ++i) { for (int j = 0; j < WEEK; ++j) { printf("City %d, Day %d: ", i + 1, j + 1); scanf("%d", &temperature[i][j]); } } printf("\nDisplaying values: \n\n"); // Using nested loop to display vlues of a 2d array for (int i = 0; i < CITY; ++i) { for (int j = 0; j < WEEK; ++j) { printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]); } } return 0; } Output City 1, Day 1: 33 City 1, Day 2: 34 City 1, Day 3: 35 City 1, Day 4: 33 City 1, Day 5: 32 City 1, Day 6: 31 City 1, Day 7: 30 City 2, Day 1: 23 City 2, Day 2: 22 City 2, Day 3: 21 City 2, Day 4: 24 City 2, Day 5: 22 City 2, Day 6: 25 City 2, Day 7: 26 Displaying values: City 1, Day 1 = 33 City 1, Day 2 = 34 GNANAJYOTHI DEGREE COLLEGE Page 74 Programming in “ C –Language ” City 1, Day 3 = 35 City 1, Day 4 = 33 City 1, Day 5 = 32 City 1, Day 6 = 31 City 1, Day 7 = 30 City 2, Day 1 = 23 City 2, Day 2 = 22 City 2, Day 3 = 21 City 2, Day 4 = 24 City 2, Day 5 = 22 City 2, Day 6 = 25 City 2, Day 7 = 26 Example 3: Three-dimensional array // C Program to store and print 12 values entered by the user #include int main() { int test[2][3][2]; printf("Enter 12 values: \n"); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { for (int k = 0; k < 2; ++k) { scanf("%d", &test[i][j][k]); } } } // Printing values with proper index. printf("\nDisplaying values:\n"); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { for (int k = 0; k < 2; ++k) { printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]); } } } return 0; } Output Enter 12 values: 1 2 3 4 GNANAJYOTHI DEGREE COLLEGE Page 75 Programming in “ C –Language ” 5 6 7 8 9 10 11 12 Displaying Values: test[0][0][0] = 1 test[0][0][1] = 2 test[0][1][0] = 3 test[0][1][1] = 4 test[0][2][0] = 5 test[0][2][1] = 6 test[1][0][0] = 7 test[1][0][1] = 8 test[1][1][0] = 9 test[1][1][1] = 10 test[1][2][0] = 11 test[1][2][1] = 12 c 7. character handling or Basics of the CTYPEs The C language features a verity of functions designed to test or manipulate individual characters. The functions are all defined in the ctype.h header file. Most programmers therefore refer to the functions as the CTYPE functions, where CTYPE is pronounced “see-type,” and not “stoor-ye,” which how a native Russian would read it. To use the CTYPE functions, the ctype.h header file must be included in your source code: #include CTYPE functions fit into two categories: testing and manipulation. Function Returns TRUE When ch is isalnum(ch) A letter of the alphabet (upper- or lowercase) or a number isalpha(ch) An upper- or lowercase letter of the alphabet isascii(ch) An ASCII value in the range of 0 through 127 isblank(ch) A tab or space or another blank character iscntrl(ch) A control code character, values 0 through 31 and 127 isdigit(ch) A character 0 through 9 isgraph(ch) Any printable character except for the space ishexnumber(ch) Any hexadecimal digit, 0 through 9 or A through F (upper- or lowercase) islower(ch) A lowercase letter of the alphabet, a to z isnumber(ch) See isdigit() isprint(ch) Any character that can be displayed, including the space ispunct(ch) A punctuation symbol GNANAJYOTHI DEGREE COLLEGE Page 76 Programming in “ C –Language ” isspace(ch) A white-space character, space, tab, form feed, or an Enter, for example isupper(ch) An uppercase letter of the alphabet, A to Z isxdigit(ch) See ishexnumber() toascii(ch) The ASCII code value of ch, in the range of 0 through 127 tolower(ch) The lowercase of character ch toupper(ch) The uppercase of character ch TEXT STATISTICS #include #include int main() { char phrase[] = "When in the Course of human events, it becomes necessary "; int index,alpha,blank,punct; alpha = blank = punct = 0; index = 0; while(phrase[index]) { if(isalpha(phrase[index])) alpha++; if(isblank(phrase[index])) blank++; if(ispunct(phrase[index])) punct++; index++; printf("%s"n"); } } 8. STRINGS A string is nothing but a character array it is also called as string variable. In C every string ends with „\0‟ character (null terminator). Simply every string is null terminated. In C the strings are checked. A sequence of characters enclosed in double quotes is called string constant. E.g. “rama” ,“1024” ,“r4#a” Declaration of strings. GNANAJYOTHI DEGREE COLLEGE Page 77 Programming in “ C –Language ” Syntax. char variablename[size]; Eg. char char a[10]; f[10]; Initialization of strings . Syntax. char variablename[size]={characters}; E.g. 1. char a[5]={„r‟,„a‟,„m‟,„a‟,„\0‟}; 2. char s[ ]={„m‟,„a‟,„l‟,„l‟,„e‟,„s‟,„h‟,„\0‟}; 3. char e[5]=“gmr”; Program-1 #include #include void main() { { char a[6]={„s‟,„u‟,„r‟,„y‟,„a‟,„\0‟}; char b[ ]={„r‟,„a‟,„m‟,„u‟,„\0‟}; char c[6]=“gmr”; char d[4]; d[0]= „s‟; d[1]= „a‟; d[2]= „i‟; d[3]= „\0‟; printf(“\n A= %s ”,a); printf(“\n B= %s ”,b); printf(“\n C= %s ”,c); printf(“\n D= %s ”,d); getch(); } Program-2 #include #include void main() { char a[10]; clrscr(); printf(“\n enter a string ” ); scanf(“%s”,&a); GNANAJYOTHI DEGREE COLLEGE Page 78 Programming in “ C –Language ” printf(“\n the string is %s ”,a); getch(); } GNANAJYOTHI DEGREE COLLEGE Page 79 Programming in “ C –Language ” STRING MANIPULATION (OR) STRING SIMULATION The process of manipulating string is called string simulations. The users have a right to manipulate the strings with the help of some predefined functions in standard library. Those are  Finding the length of string  Copying one string into another string  Concatenating the two strings  Finding the reverse of string  Comparing the two strings Finding the length of string: we can find the length of a string using a predefined function called “strlen()” this function takes one argument nothing but sting argument and it returns an integer value which is length of a given string. Syntax. l=strlen(“string”); Eg. x=strlen(“sai”); #include #include void main() { char a[10]; int x; clrscr(); printf(“\n enter a string ” ); scanf(“%s”,&a); x=strlen(a); printf(“\n the length of string is %d ”,x); getch(); } Copying one string into another string: copying one string into another string we can using with the help of predefined function “strcpy()” which is in string.h header file. Syntax. strcpy(“string1”, “string2”); Eg. strcpy(b,a); The above function takes two arguments both are string arguments. The first one is must be a string variable it copies the second string into the first string. GNANAJYOTHI DEGREE COLLEGE Page 80 Programming in “ C –Language ” #include #include void main() { char a[10],b[10]; clrscr(); printf(“\n enter a string ” ); scanf(“%s”,&a); strcpy(b,a); printf(“\n the copying string is %s ”,b); getch(); } Concatenating the two strings: we can concatenate two strings with the help of a predefined function “strcat()” which is in string.h header file. Syntax. strcat(“string1”, “string2”); Eg. strcpy(a,b); The above function takes two arguments both are strings in that first argument must be a variable it concatenates the given two strings and place the result in first string . #include #include void main() { char a[10],b[10]; clrscr(); printf(“\n enter a string ” ); scanf(“%s”,&a); printf(“\n enter b string ” ); scanf(“%s”,&b); strcat(a,b); printf(“\n the concatenated string is %s ”,a); getch(); } Finding the reverse of string : we can reverse a string using a predefined function “strrev()” which is in header file string.h Syntax. strrev(“string”); GNANAJYOTHI DEGREE COLLEGE Page 81 Programming in “ C –Language ” Eg. strrev(a); The above two strings takes one argument nothing but string variable. It reverse the given sting and replace into it. #include #include void main() { char a[10]; clrscr(); printf(“\n enter a string ” ); scanf(“%s”,&a); strrev(a); printf(“\n the reverse string is %s ”,a); getch(); } Comparing two strings: We can comparing two strings with the help of a predefined function “strcmp()” which is in string.h header file Syntax. strcmp(“string1”,“strcmp”); Eg. x=strcmp(a,b); The above function takes two arguments both are strings and returns integer value.  If it is return zero then the given string are equal.  If it is return a positive value then first string is > second string  If it is return a negative value then first string is < second string #include #include void main() { char a[10],b[10]; int x; clrscr(); printf(“\n enter a string ” ); scanf(“%s”,&a); printf(“\n enter b string ” ); scanf(“%s”,&b); x=strcmp(a,b); if(x>0) { printf(“\n %s is greater than %s ”,a,b); } else if(x<0) GNANAJYOTHI DEGREE COLLEGE Page 82 Programming in “ C –Language ” { printf(“\n %s is greater than %s ”,a,b); } else if(x<0) { printf(“\n %s is less than %s ”,a,b); } else { printf(“\n %s and %s are equal ”,a,b); } getch(); } Unit-4 Functions:: Introduction – using functions – Function declaration/ prototype – Function definition – function call – return statement – Passing parameters – Scope of variables – Storage Classes – Recursive functions. Structure, Union, and Enumerated Data Types: Introduction – Nested Structures – Arrays of Structures – Structures and Functions– Union – Arrays of Unions Variables – Unions inside Structures – Enumerated Data Types. GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” return type function name(arguments) { local variables ; Statements; Statements; Statements; 1. FUNCTIONS Function is a self contained block of a code which is used to perform a manageable task. Every C program is a collection of functions each and every C program at least contains one function it is nothing but main( ) With the help of functions we can reduce the execution time of a program and also we can increase the efficiency “Functions ate building blocks of program” General syntax for a function :- Components of a function:  Function declaration  Function body  Function definition  Function calling  Arguments(formal and actual)  Return statement Function calling statement: A statement which is used to call or invoke another function is called function calling statement. Eg. clrscr(); Caller function: A function which is calls another function is called “ caller function ” Page 83 GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” Calee function: A function which is called by another function is called “ calle function ” Types of Function: In C functions are divided into two types those are 1. predefined functions 2. user defined functions Predefined Functions: A function whose meaning is already defined is called predefined functions. Predefined functions are known by compiler. Predefined functions are available in standard library those are available in header files. Predefined functions are also called as library functions Header files | Standard files | Predefined functions Eg. getch() clrscr() isalnum() isalpha() User defined functions: A function whose meaning is defined by user is called user defined functions. Eg. raj u() anil() sum() Example Program of function components: #include #include void main() { int a,b,c; actual arguments clrscr(); printf(“\n enter a value “); scanf(“%d”,&a); printf(“\n enter b value “); scanf(“%d”,&b); caller function Page 84 c=sum(a,b); GNANAJYOTHI DEGREE COLLEGE Page 85 Programming in “ C –Language ” int sum(int x,int y) function calling statement printf(“\n The sum is %d ”,c); getch(); formal arguments function definition } calee function { int z; z=x+y; } function definition local variables function declaration Program #include #include void main() { int a,b,c; clrscr(); printf(“\n enter a value “); scanf(“%d”,&a); printf(“\n enter b value “); scanf(“%d”,&b); c=sum(a,b); printf(“\n The sum is %d ”,c); getch(); } int sum(int x,int y) { Return statement int z; z=x+y; return z; } 2. The return statement in C The return statement is used to return some value or simply pass the control to the calling function. The return statement can be used in the following two ways. 1. return; 2. return expression; The first form of the return statement is used to terminate the function and pass the control to the calling function. No value from the called function is returned when this form of the return statement is used. GNANAJYOTHI DEGREE COLLEGE Page 86 Programming in “ C –Language ” The following program demonstrates the use of the first form of the return statement. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 #include void eligible_or_not(int x); int main() { int n; printf("Enter age: "); scanf("%d", &n); eligible_or_not(n); // signal to operating system everything works fine return 0; } void eligible_or_not(int age) { if(age >= 18) { printf("You are eligible to vote"); return; } else if(age == 17 ) { printf("Try next year"); return; } else { printf("You are not yet ready"); return; } } Expected Output: 1st run: 1 2 Enter age: 16 You are not yet ready 2nd run: 1 2 Enter age: 17 Try next year 3rd run: 1 2 Enter age: 19 You are eligible to vote GNANAJYOTHI DEGREE COLLEGE Page 87 Programming in “ C –Language ” Categories of a function: In c functions are bodily divided into four categories those are .  function with return type with arguments  function no return type with arguments  function with return type no arguments  function no return type no arguments Function With Return Type With Arguments: #include #include void main() { int a,b,c; clrscr(); printf(“\n enter a value “); scanf(“%d”,&a); printf(“\n enter b value “); scanf(“%d”,&b); c=sum(a,b); printf(“\n The sum is %d ”,c); getch(); } int sum(int x,int y) { int z; z=x+y; return z; } Function No Return Type With Arguments. #include #include void main() { int a,b; clrscr(); printf(“\n enter a value “); scanf(“%d”,&a); printf(“\n enter b value “); scanf(“%d”,&b); sum(a,b); printf(“\n The sum is %d ”,c); GNANAJYOTHI DEGREE COLLEGE Page 88 Programming in “ C –Language ” getch(); } int sum(int x,int y) { int z; z=x+y; printf(“\n the sum is %d ”,z); } Function With Return Type No Arguments. #include #include void main() { int c; clrscr(); c=sum( ); printf(“\n the sum is %d ”,c); getch(); } int sum(int x,int y) { int z; printf(“\n enter x value “); scanf(“%d”,&x); printf(“\n enter y value “); scanf(“%d”,&y); z=x+y; return z; } Function No Return Type No Arguments. #include #include void main() { clrscr(); sum( ); getch(); } int sum(int x,int y) { int z; printf(“\n enter x value “); scanf(“%d”,&x); printf(“\n enter y value “); GNANAJYOTHI DEGREE COLLEGE Page 89 Programming in “ C –Language ” scanf(“%d”,&y); z=x+y; printf(“\n the sum is %d ”,z); } Q :Write a c program to find factorial of given number using user defined functions . #include #include void main() { int f ,n; clarscr(); printf(“\n Enter N value ”); scanf(%d”,&n); f=fact(n); printf(“\n the factorial is %d ”,f); getch(); } int fact (int x) { int z,i; for(i=1;i<=x;i++) { z=z*i; } return z; } 3. Parameters passing in c: a) Function call by Value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C programming uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function. Consider the function swap() definition as follows. void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ GNANAJYOTHI DEGREE COLLEGE Page 90 Programming in “ C –Language ” y = temp; /* put temp into y */ return; } Now, let us call the function swap() by passing actual values as in the following example − #include /* function declaration */ void swap(int x, int y); int main () { /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b ); /* calling a function to swap the values */ swap(a, b); printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0; } void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put temp into y */ return; } Let us put the above code in a single C file, compile and execute it, it will produce the following result − Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 100 After swap, value of b : 200 b) Function call by reference The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument. GNANAJYOTHI DEGREE COLLEGE Page 91 Programming in “ C –Language ” To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments. /* function definition to swap the values */ void swap(int *x, int *y) { int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put temp into y */ return; } Let us now call the function swap() by passing values by reference as in the following example − #include int main () { /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b ); /* calling a function to swap the values */ swap(&a, &b); printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0; } void swap(int *x, int *y) { int temp; temp = *x; /* save the value of x */ *x = *y; /* put y into x */ *y = temp; /* put temp into y */ return; } Let us put the above code in a single C file, compile and execute it, to produce the following result − Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100 4. Scope of variables: GNANAJYOTHI DEGREE COLLEGE Page 92 Programming in “ C –Language ” A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed. There are three places where variables can be declared in C programming language −  Inside a function or a block which is called local variables.  Outside of all functions which is called global variables.  In the definition of function parameters which are called formal parameters. Let us understand what are local and global variables, and formal parameters. Local Variables Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following example shows how local variables are used. Here all the variables a, b, and c are local to main() function. #include int main () { /* local variable declaration */ int a, b; int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0; } Global Variables Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. The following program show how global variables are used in a program. #include /* global variable declaration */ int g; int main () { GNANAJYOTHI DEGREE COLLEGE Page 93 Programming in “ C –Language ” /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0; } A program can have same name for local and global variables but the value of local variable inside a function will take preference. Here is an example − #include /* global variable declaration */ int g = 20; int main () { /* local variable declaration */ int g = 10; printf ("value of g = %d\n", g); return 0; } When the above code is compiled and executed, it produces the following result − value of g = 10 Formal Parameters Formal parameters, are treated as local variables with-in a function and they take precedence over global variables. Following is an example − #include /* global variable declaration */ int a = 20; int main () { /* local variable declaration in main function */ int a = 10; int b = 20; int c = 0; printf ("value of a in main() = %d\n", a); c = sum( a, b); printf ("value of c in main() = %d\n", c); GNANAJYOTHI DEGREE COLLEGE Page 94 Programming in “ C –Language ” return 0; } /* function to add two integers */ int sum(int a, int b) { printf ("value of a in sum() = %d\n", a); printf ("value of b in sum() = %d\n", b); return a + b; } When the above code is compiled and executed, it produces the following result − value of a in main() = 10 value of a in sum() = 10 value of b in sum() = 20 value of c in main() = 30 Initializing Local and Global Variables When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows − Data Type Initial Default Value int 0 char '\0' float 0 double 0 pointer NULL It is a good programming practice to initialize variables properly, otherwise your program may produce unexpected results, because uninitialized variables will take some garbage value already available at their memory locati GNANAJYOTHI DEGREE COLLEGE Page 95 Programming in “ C –Language ” 5. recursive functions The technique of calling one function into in its body is known as “ recursion ” in other words a function calls itself known as “ recursion ” In below example factorial function is called in its body so it is the best example for recursion. #include #include void main() { int f ,n; clarscr(); printf(“\n Enter N value ”); scanf(%d”,&n); f=fact(n); printf(“\n the factorial is %d ”,f); getch(); } int fact (int x) { if(x= =0) return 0; else } return x*fact(x-1); 6. STORAGE CLASSES Variables in C not only a data type but also a storage class storage class provides information about variables, location and visibility ….. the storage class decides the portion of the program with in the which the variables are recognized. A variable storage class tells us  when it stores  what is the initial value of the variable  what is the scope of the variable that means in which block value of the variable is available  what is the life time of the variable that means how long the variable is exist GNANAJYOTHI DEGREE COLLEGE Page 96 Programming in “ C –Language ” There are four types of storage classes are available in C  automatic storage class  register storage class  static storage class  external storage class Automatic storage class: the feature of a variable defined in automatic storage class as. Keyword: auto Storage: main memory Default value: An unpredictable value(garbage value) Scope: local to the block in which it is defined. Life time: Till the control remains with in the block in which the variable is defined. Program : #include #include void main() { auto int a; clrscr(); printf(“\n A=%d ”,a); getch(); } Register storage class: the feature of a variable defined is register storage class as Keyword: register Storage: CPU registers Default value: An unpredictable value (garbage value) Scope: local to the block in which it is defined. Life time: Till the control remains with in the block in which the variable is defined. A variable stores in a CPU registers can always be accessed faster than the one i.e stores main memory a variable which is used at many places in a program Program : GNANAJYOTHI DEGREE COLLEGE Page 97 Programming in “ C –Language ” #include #include void main() { register int a; clrscr(); for(a=0;a<=100;a++) printf(“\n A=%d ”,a); GNANAJYOTHI DEGREE COLLEGE Page 98 Programming in “ C –Language ” getch(); } Static storage class: feature of a variable defined is register storage class as Keyword: static Storage: main memory Default value: zero Scope: local to the block in which it is defined. Life time: value of the variable presents between different function calls Program : #include #include void main() { static int a; clrscr(); printf(“\n A=%d ”,a); getch(); } External Storage class: feature of a variable defined is register storage class as Keyword: extern Storage: main memory Default value: zero Scope: global Life time: As long as the program execution doesn‟t comes to end. Program -1: Program -2: int a; int a=30; #include #include #include #include void main() void main() { { clrscr(); extern int a; printf(“\n A=%d ”,a); clrscr(); getch(); printf(“\n A=%d ”,a); GNANAJYOTHI DEGREE COLLEGE Page 99 Programming in “ C –Language ” } getch(); } 7. STRUCTURES AND UNIONS A structure is a collection of dissimilar elements it is a constrictive data structure. It is a method of packing data of different types. A structure is a convenient for handling a group of logically related data items. It is used to declare a user defined data type. It is feature of C language to design a powerful good program Structure syntax: struct structure name { data type 1 member 1; data type 2 member 2; data type 3 member 3; . . Ex: . data type n member n; }; struct student { int sno; int sage; char sname[10]; }; Declaring a structure variable: struct structure name { Data type 1 member 1; Data type 2 member 2; Data type 3 member 3; . . . Data type n member n; GNANAJYOTHI DEGREE COLLEGE Page 100 Programming in “ C –Language ” Ex: } var-1, var-2, var-3; (Or) struct structure name var-1,var-2,var-3; struct student { }x,y,z; int sno; char sname[10]; (Or) struct student x,y,z; Initializing of structure: Method -1: Program: #include #include struct Test { int a; flaot b; char c; }x={9,45.6,„m‟}; void main() { clrscr(); printf(“\n %d ”,x.a); printf(“\n %f ”,x.b); printf(“\n %c ”,x.c); getch(); } Method -2: Program: #include #include struct Test { int a; flaot b; char c; }; GNANAJYOTHI DEGREE COLLEGE Page 101 Programming in “ C –Language ” void main() { struct Test x={9,45.6,„m‟} clrscr(); printf(“\n %d ”,x.a); printf(“\n %f ”,x.b); printf(“\n %c ”,x.c); getch(); } Method -3: Program: #include #include struct Test { int a; flaot b; char c; }x; void main() { clrscr(); x.a=10; x.b=45.6; x.c= „s‟; printf(“\n %d ”,x.a); printf(“\n %f ”,x.b); printf(“\n %c ”,x.c); getch(); } GNANAJYOTHI DEGREE COLLEGE Page 102 Programming in “ C –Language ” 8. Unions in C Language Unions are conceptually similar to structures. The syntax of union is also similar to that of structure. The only differences is in terms of storage. In structure each member has its own storage location, whereas all members of union uses a single shared memory location which is equal to the size of its largest data member. #include #include union Student { int sno; flaot sage; char sname[10]; }; void main() { union Student x; clrscr(); printf(“\n enter student number”); scanf(“%d”,&x.sno); printf(“\n enter student age”); scanf(“%f”,&x.sage); printf(“\n enter student name”); scanf(“%s”,&x.sname); GNANAJYOTHI DEGREE COLLEGE Page 103 Programming in “ C –Language ” printf(“\n the student number is %d ”,x.sno); printf(“\n the student ahe is %f ”,x.sage); printf(“\n the student name is %s ”,x.sname); getch(); } 9. Nested Structure: The technique of placing one structure variable as a member of anther structure is called “nested structure” or “structure with in structure” Program: #include #include struct Student { int sno; flaot sage; char sname[10]; struct Marks { }x; }y; int m; int p; int c; void main() { clrscr(); printf(“\n enter student number”); scanf(“%d”,&x.sno); printf(“\n enter student age”); scanf(“%f”,&x.sage); printf(“\n enter student name”); scanf(“%s”,&x.sname); printf(“\n enter Maths marks”); scanf(“%d”,&x.y.m); printf(“\n enter Physics marks”); scanf(“%d”,&x.y.p); printf(“\n enter Computers marks”); scanf(“%d”,&x.y.c); printf(“\n the student number is %d ”,x.sno); printf(“\n the student ahe is %f ”,x.sage); printf(“\n the student name is %s ”,x.sname); printf(“\n the Maths marks is %d ”,x.y.m); printf(“\n the Physics marks is %d ”,x.y.p); printf(“\n the Computers marks is %d ”,x.y.c); getch();} 10. Array of Structures :Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a collection of elements of the same type. In an array of structures, each element of an array is of the structure type. Programming in “ C –Language example: struct car { char make[20]; char model[30]; int year; }; Here is how we can declare an array of 1 struct car arr_car[10]; Here arr_car is an array of 10use arr_car to store 10structure variables of type we will use subscript notation ([](.) operator as usual. 1 arr_stu[0] : points to the 0th element of the array.2 arr_stu[1] : points to the 1st elementand so on. Similarly, 1 arr_stu[0].name : refers to the namearr_stu[0].roll_no : refers to the roll_noto the marks member 1 of the array. Recall that the precedence of [] from left to right. Therefore in the above expression first array subscript(by dot (.) operator. The array subscriptGNANAJYOTHICOLLEGELanguage ” Here is how we can declare an array of structure car. 10 elements where each element is of type struct carstructure variables of type struct car. To access individual elements[]) and to access the members of each element1 arr_stu[0] : points to the 0th element of the array. element of the array. name member of the 0th element of the array. roll_no member of the 0th element of the array. 3 arr_stu[0].marks array subscript and dot(.) operator is same and they evaluatesfrom left to right. Therefore in the above expression first array subscript([]) is applied followedsubscript ([]) and dot(.) operator is same and theyGNANAJYOTHI DEGREE COLLEGE Page 104 struct car. We can cess individual elements access the members of each element we will use dot arr_stu[0].marks : refers ) operator is same and they evaluates ) is applied followed same and they evaluates from GNANAJYOTHI DEGREE COLLEGE Page 105 Programming in “ C –Language ” left to right. Therefore in the above expression first [] array subscript is applied followed by dot (.) operator. Let‟s rewrite the program we used in the last chapter as an introduction to structures. #include #include #define MAX 2 struct student { char name[20]; int roll_no; float marks; }; int main() { struct student arr_student[MAX]; int i; for(i = 0; i < MAX; i++ ) { printf("\nEnter details of student %d\n\n", i+1); printf("Enter name: "); scanf("%s", arr_student[i].name); printf("Enter roll no: "); scanf("%d", &arr_student[i].roll_no); printf("Enter marks: "); scanf("%f", &arr_student[i].marks); } printf("\n"); printf("Name\tRoll no\tMarks\n"); for(i = 0; i < MAX; i++ ) { printf("%s\t%d\t%.2f\n", arr_student[i].name, arr_student[i].roll_no, arr_student[i].marks); } return 0; } Expected Output: Enter details of student 1 2 E3 nter name: Jim Enter roll no: 1 Enter marks: 44 Enter details of student 2 GNANAJYOTHI DEGREE COLLEGE Page 106 Programming in “ C –Language ” Enter name: Tim Enter roll no: 2 Enter marks: 76 Name Roll no Marks Jim 1 44.00 Tim 2 76.00 Initializing Array of Structures We can also initialize the array of structures using the same syntax as that for initializing arrays. Let‟s take an example: struct car { char make[20]; char model[30]; int year; }; struct car arr_car[2] = { {"Audi", "TT", 2016},{"Bentley", "Azure", 2002} }; 11. Structures and Functions :Like all other types, we can pass structures as arguments to a function. In fact, we can pass, individual members, structure variables, a pointer to structures etc to the function. Similarly, functions can return either an individual member or structures variable or pointer to the structure. Let's start with passing individual member as arguments to a function. Passing Structure Members as arguments to Function We can pass individual members to a function just like ordinary variables. The following program demonstrates how to pass structure members as arguments to the function. #include struct student { char name[20]; int roll_no; int marks; }; void print_struct(char name[], int roll_no, int marks); int main() { struct student stu = {"Tim", 1, 78}; print_struct(stu.name, stu.roll_no, stu.marks); return 0; } void print_struct(char name[], int roll_no, int GNANAJYOTHI DEGREE COLLEGE Page 107 Programming in “ C –Language ” marks) { printf("Name: %s\n", name); printf("Roll no: %d\n", roll_no); printf("Marks: %d\n", marks); printf("\n"); } Expected Output: 1 2 3 Name: Tim Roll no: 1 Marks: 78 12. Array of Union variable: Here I declared array of union variable .in this firest we declare array in side the union after we can declare variable of an arry in side union. union Function { char* name; double (*fnct)(); int args; }; union Function functions[ ] = { {.name = "acos", .fnct = acos, .args = 1}, {.name = "asin", .fnct = asin, .args = 1}, {.name = "atan", .fnct = atan, .args = 1}, }; for(int i = 0; i < sizeof(functions) / sizeof(union Function); i++) { printf("%d\n", functions[i].args); printf("%s\n", functions[i].name); } A union contains either of its members, not all of its members. So the last initializer is the final one, meaning its value is just 1. So printing the name ( a string) results in a seg fault because printf tries to dereference the address 1. GNANAJYOTHI DEGREE COLLEGE Page 108 Programming in “ C –Language ” If you want to have all of its members, use struct instead of union.For some reason you are using a union when you actually want to use a struct. You need to study what union means before you can use it. The reason your code is crashing, is because of the initialization: {.name = "acos", .fnct = acos, .args = 1}, This means that you write to all union members in turn, from left to right. But since all members are all stored at the same memory location, which is the whole point of using union, only the last one will be valid 1).A decent compiler will give you a warning for this, since an initialization list like this does not make any sense. """ A union is a variable that may hold (at different times) objects of different types and sizes, with the compiler keeping track of size and alignment requirements. """ You're indeed using the incorrect data structure here. You should be using a 'struct' instead of a union. A union is useful if you have a variable that could be one (and only one) kind of a choice of differing data types. I find the name 'union' misleading since a mathematical union implies the entire collection of all its members, whereas a C union does not contain all its members at once. Furthermore, the syntax for a union is identical to a struct: union u_tag { int ival; float fval; char *sval; } u; Infact, a union is a special case of a struct where all members have offset zero from the base and sufficient memory is allocated to hold the biggest member. One rule of thumb to quickly decide whether to use a struct or a union is that all members of a union should have similar names, as they can all be used to represent the same kind of data (albeit with a differing data type). The fact that the members of your union have very different names (name, fnct, args) representing entirely different kinds of data, is a give away that a struct is the right choice of data structure. GNANAJYOTHI DEGREE COLLEGE Page 109 Programming in “ C –Language ” 13. Union inside structure: Unions basically represent two or more different views of the same data. A good example would be a data record in a file (organized with a fixed record length). One way of looking at the record, say, would be as a sequence of 16 bytes. Another way would be to look at it as structured data. Something union { unsigned char raw_data[16]; struct { char name[12]; short age; short height; } } Code that reads or writes data from/to disk would be using the raw_data member. Code that actually interprets the data (e.g., presents it in a UI) would be using the struct representation. Unions basically represent two or more different views of the same data. A good example would be a data record in a file (organized with a fixed record length). One way of looking at the record, say, would be as a sequence of 16 bytes. Another way would be to look at it as structured data. Something union { unsigned char raw_data[15]; struct { char name[12]; short age; short height; float balance; }} GNANAJYOTHI DEGREE COLLEGE Page 110 Programming in “ C –Language ” enum flag { const1, const2, ..., constN }; Code that reads or writes data from/to disk would be using the raw_data member. Code that actually interprets the data (e.g., presents it in a UI) would be using the struct representation. It is just a design choice whether to put union inside the structure or a structure inside a union. Similar to the example given by Toth there is a union in Linux data structures also. Which is IP address. It is: union ipv4addr { unsigned addr; char octets[4]; }; Generally we want to refer to the 32-bit value directly, at that time we can use the addr part of the API or if we want to access individual bytes of the IP address then we can use octets. Thus it is the way of giving different meaning to a single API. 14. Enumerated Data Types An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, keyword enum is used. Here, name of the enumeration is flag. And, const1, const2,. .. , constN are values of type flag. By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements during declaration (if necessary). enum suit { club = 0, diamonds = 10, hearts = 20, spades = 3, }; GNANAJYOTHI DEGREE COLLEGE Page 111 Programming in “ C –Language ” enum boolean { false, true }; enum boolean check; enum boolean { false, true } check; Enumerated Type Declaration When you create an enumerated type, only blueprint for the variable is created. Here's how you can create variables of enum type. Here, a variable check of type enum boolean is created. Here is another way to declare same check variable using different syntax. Example: Enumeration Type Page 112 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE enum w eek today; today = wednesday; printf("Day %d",today+1); return 0; Out put:day 4 Page 123 Unit-5 Pointers: Understanding Computer Memory – Introduction to Pointers – declaring Pointer Variables – Pointer Expressions and Pointer Arithmetic – Null Pointers - Passing Arguments to Functions using Pointer – Pointer and Arrays – Memory Allocation in C Programs – Memory Usage – Dynamic Memory Allocation – Drawbacks of Pointers Files: Introduction to Files – Using Files in C – Reading Data from Files – Writing Data to Files – Detecting the End-of-file – Error Handling during File Operations – Accepting Command Line Arguments. 1. Pointers: Understanding Memory Addresses The previous discussion becomes a little clearer if you understand how memory addresses work in a computer's hardware. If you have not read it already, now would be a good time to read How Bits and Bytes Work to fully understand bits, bytes and words. All computers have memory, also known as RAM (random access memory). For example, your computer might have 16 or 32 or 64 megabytes of RAM installed right now. RAM holds the programs that your computer is currently running along with the data they are currently manipulating (their variables and data structures). Memory can be thought of simply as an array of bytes. In this array, every memory location has its own address -- the address of the first byte is 0, followed by 1, 2, 3, and so on. Memory addresses act just like the indexes of a normal array. The computer can access any address in memory at any time (hence the name "random access memory"). It can also group bytes together as it needs to to form larger variables, arrays, and structures. For example, a floating point variable consumes 4 contiguous bytes in memory. You might make the following global declaration in a program: float f; This statement says, "Declare a location named f that can hold one floating point value." When the program runs, the computer reserves space for the variable f somewhere in memory. That location has a fixed address in the memory space, like this: While you think of the variable f, the computer thinks of a specific address in memory (for example, 248,440). Therefore, when you create a statement like this: f = 3.14; The compiler might translate that into, "Load the value 3.14 into memory location 248,440." The computer is always thinking of memory in terms of addresses and values at those addresses. There are, by the way, several interesting side effects to the way your computer treats memory. For example, say that you include the following code in one of your programs: int i, s[4], t[4], u=0; GNANAJYOTHI DEGREE COLLEGE Page 113 Programming in “ C –Language ” for (i=0; i<=4; i++) { s[i] = i; t[i] =i; } printf("s:t\n"); for (i=0; i<=4; i++) printf("%d:%d\n", s[i], t[i]); printf("u = %d\n", u); The output that you see from the program will probably look like this: s:t 1:5 2:2 3:3 4:4 5:5 u = 5 Why are t[0] and u incorrect? If you look carefully at the code, you can see that the for loops are writing one element past the end of each array. In memory, the arrays are placed adjacent to one another, as shown here: Arrays placed adjacent to one another Therefore, when you try to write to s[4], which does not exist, the system writes into t[0] instead because t[0] is where s[4] ought to be. When you write into t[4], you are really writing into u. As far as the computer is concerned, s[4] is simply an address, and it can write into it. As you can see however, even though the computer executes the program, it is not correct or valid. The program corrupts the array t in the process of running. If you execute the following statement, more severe consequences result: s[1000000] = 5; The location s[1000000] is more than likely outside of your program's memory space. In other words, you are writing into memory that your program does not own. On a system with protected memory spaces (UNIX, Windows 98/NT), this sort of statement will cause the system to terminate execution of the program. On other systems (Windows 3.1, the Mac), however, the system is not aware of what you are doing. You end up damaging the code or variables in another application. The effect of the violation can range from nothing at all to a complete system crash. In memory, i, s, t and u are all placed next to one another at specific addresses. Therefore, if you write past the boundaries of a variable, the computer will do what you say but it will end up corrupting another memory location. Because C and C++ do not perform any sort of range checking when you access an element of an array, it is essential that you, as a programmer, pay careful attention to array ranges yourself and keep within the array's appropriate boundaries. Unintentionally reading or writing outside of array boundaries always leads to faulty program behavior. As another example, try the following: #include GNANAJYOTHI DEGREE COLLEGE Page 114 Programming in “ C –Language ” int main() { int i,j; int *p; /* a pointer to an integer */ printf("%d %d\n", p, &i); p = &i; printf("%d %d\n", p, &i); return 0; } This code tells the compiler to print out the address held in p, along with the address of i. The variable p starts off with some crazy value or with 0. The address of i is generally a large value. For example, when I ran this code, I received the following output: 0 2147478276 2147478276 2147478276 which means that the address of i is 2147478276. Once the statement p = &i; has been executed, p contains the address of i. Try this as well: #include void main() { int *p; /* a pointer to an integer */ printf("%d\n",*p); } This code tells the compiler to print the value that p points to. However, p has not been initialized yet; it contains the address 0 or some random address. In most cases, a segmentation fault (or some other run-time error) results, which means that you have used a pointer that points to an invalid area of memory. Almost always, an uninitialized pointer or a bad pointer address is the cause of segmentation faults. Having said all of this, we can now look at pointers in a whole new light. Take this program, for example: #include int main() { int i; int *p; /* a pointer to an integer */ 2. pointers: Pointer is a dynamic feature of “C” language it is a powerful tool to write a good program there is a no of reasons to using a pointers .  a pointer enables us to access a variable i.e. defined outside the function  pointer reduces the length of and compellability of the program  pointers are increases the execution speed of the program GNANAJYOTHI DEGREE COLLEGE Page 115 Programming in “ C –Language ” Variable value a 10 173 p 173 111 a ---------- > reference 10 ------- > value 173 ------- > address variable Under Standing the Pointers: Pointer is a variable which is used to store the address of a memory location i.e. a pointer is a variable which can holds the address of another variable  a pointer variable always pointes to only one variable  a variable have so many pointers  a pointer of one type is always points to variable of same type Declaring pointers: Syntax: datatype *pointername; Ex 1. int *p; In above example p is a name of the pointer variable and it is always points to any other integer variable Ex 2. float *p; In above example p is a name of the pointer variable and it is always points to any other float variable Initializing pointer variable: Syntax: pointer name =&variablename; Ex. p=&a; Accessing a variable through its pointers: #include #include void main() { int a,*p; clrscr(); p=&a; printf(“\n A is stored at %d ”,p); getch(); } GNANAJYOTHI DEGREE COLLEGE Page 116 Programming in “ C –Language ” Q. Write a c program for addition of two numbers using pointers: #include #include void main() { int a,b,c,*p,*q*,r; clrscr(); p=&a; q=&b; r=&c; printf(“\n enter a value ”); scanf(“%d”,p); printf(“\n enter b value ”); scanf(“%d”,q); *r=*p+*q; printf(“\n the result is %d ”,c); getch(); } Advantages and disadvantages of pointers in c Benefits(use) of pointers in c:  Pointers provide direct access to memory  Pointers provide a way to return more than one value to the functions  Reduces the storage space and complexity of the program  Reduces the execution time of the program  Provides an alternate way to access array elements  Pointers can be used to pass information back and forth between the calling function and called function.  Pointers allows us to perform dynamic memory allocation and deallocation.  Pointers helps us to build complex data structures like linked list, stack, queues, trees, graphs etc.  Pointers allows us to resize the dynamically allocated memory block.  Addresses of objects can be extracted using pointers Drawbacks of pointers in c:  Uninitialized pointers might cause segmentation fault.  Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory leak.  Pointers are slower than normal variables.  If pointers are updated with incorrect values, it might lead to memory corruption. Basically, pointer bugs are difficult to debug. Its programmers responsibility to use pointers effectively and correctly. Hard To debug Pointer issues are hard to debug. You'll never know what is the reason you're not getting the GNANAJYOTHI DEGREE COLLEGE Page 117 the variable associated with it. Programming in “ C –Language ” expected data. I had many issues while using pointers when I first started coding games in C++. The fact that there were 100s of files and sometimes even thousands didn't help at all. Memory Leaks Pointers are prone to memory leaks. They are common to C, C++ or objective C. Memory leaks has to be planned before hand and can be minimized using good practices only. Once they started occuring, you'll be guaranteed to miss your sleep. Pointer Arithmetic I seriously hate pointer arithmetic. They are useful in some applications, but largely it is error prone and certainly not idiot proof. I remember when my juniors got to know about these and the whole project started crashing on me. I literally had to ban any kind of pointer arithmetic in my projects. Crashes Crashes are common occurrence in pointers. It can be a null pointer error or segfault. Or you would have forgot to free a pointer or you had already freed it. The pointer data might have been corrupted while in use. There are a lot of reasons for crashes while pointers are involved. Even today when I use a C based library in an Objective C code, I am sure to get crashes in it, most of the times due to pointers. Syntax Pointer syntax is really complicated. The asterisk looks cute, but when they started swarming you by having pointer to pointer to pointer to pointer to array of functions, you started to lose 3. Declaration of C Pointer variable General syntax of pointer declaration is, datatype *pointer_name; Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. void type pointer works with all data types, but is not often used. Here are a few examples: int *ip // pointer to integer variable float *fp; // pointer to float variable double *dp; // pointer to double variable char *cp; // pointer to char variable Initialization of C Pointer variable Pointer Initialization is the process of assigning address of a variable to a pointer variable. Pointer variable can only contain address of a variable of the same data type. In C language address operator & is used to determine the address of a variable. The & (immediately preceding a variable name) returns the address of GNANAJYOTHI DEGREE COLLEGE Page 118 Programming in “ C –Language ” #include void main() { int a = 10; int *ptr; //pointer declaration ptr = &a; //pointer initialization } Pointer variable always point to variables of same datatype. Let's have an example to showcase this: #include void main() { float a; int *ptr; ptr = &a; // ERROR, type mismatch } If you are not sure about which variable's address to assign to a pointer variable while declaration, it is recommended to assign a NULL value to your pointer variable. A pointer which is assigned a NULL value is called a NULL pointer. #include int main() { int *ptr = NULL; return 0; } Using the pointer or Dereferencing of Pointer Once a pointer has been assigned the address of a variable, to access the value of the variable, pointer is dereferenced, using the indirection operator or dereferencing operator *. #include int main() { int a, *p; // declaring the variable and pointer a = 10; p = &a; // initializing the pointer printf("%d", *p); //this will print the value of 'a' printf("%d", *&a); //this will also print the value of 'a' printf("%u", &a); //this will print the address of 'a' printf("%u", p); //this will also print the address of 'a' printf("%u", &p); //this will print the address of 'p' return 0; GNANAJYOTHI DEGREE COLLEGE Page 119 Programming in “ C –Language ” } 4. Pointer expressions and pointers arithmetic: a) Pointer Expressions Like other variables pointer variables can be used in expressions. 1) If p1 and p2 are properly declared and initialized pointers, then the following statements are valid: Y=*p1**p2; Sum=sum+*p1; Z=5*-*p2/ *p1; *p2=*p2+10; *p1=*p1+*p2; *p1=*p2-*p1; NOTE: in the third statement there is a blank space between ‘/’ and * because the symbol /*is considered as beginning of the comment and therefore the statement fails. 2) if p1 and p2 are properly declared and initialized pointers then, ‘C’ allows adding integers to a pointer variable. EX: int a=5, b=10; int *p1,*p2; p1=&a; p2=&b; Now, P1=p1+1=1000+2=1002; P1=p1+2=1000+ (2*2) =1004; P1=p1+4=1000+ (2*4) =1008; P2=p2+2=3000+ (2*2) =3004; P2=p2+6=3000+ (2*6) =3012; Here addition means bytes that pointer data type hold are subtracted number of times that is subtracted to the pointer variable. 3) If p1 & p2 are properly declared and initialized, pointers then ‘C’ allows to subtract integers from pointers. From the above example, P1=p1-1=1000-2=998; P1=p1-2=1000-4=996; P1=p1-4=1000-8=992; P2=p2-2=3000-4=2996; P2=p2-6=3000-12=2988; Here the subtraction means byte that pointer data type hold are subtracted number of times that is subtracted to the pointer variable. GNANAJYOTHI DEGREE COLLEGE Page 120 Programming in “ C –Language ” 4) If p1 & p2 are properly declared and initialize pointers, and both points to the elements of same type. “Subtraction of one pointer from another pointer is also possible". NOTE: this operation is done when the both pointer variable points to the elements of the same array. EX: P2- P1 (It gives the number of elements between p1 and p2) 5) Pointer can also be used with increment and decrement operators. Ex: int a=10; int *b; b=&a; EXAMPLE PROGRAM: Write a function to calculate the roots. The function must use two pointer parameters, one to receive the coefficients a, b and c and the other to send roots to calling function. #include #include Roots (p, q) float *p,*q; { *q= (–(*(p+1) +sqrt ((*(p+1))*(*(p+1))–4*(*p)*(*(p+2))))/ (2*(*p)); *(q+1) = (–(*(p+1)-sqrt ((*(p+1))*(*(p+1))–4*(*p)*(*(p+2))))/ (2*(*p)); } void main () { float A [3], R [2]; int i; printf (‘‘Enter values for a, b, c’’); for (i=0; i< = 2; i++) scanf (‘‘%f’’, A+i); Roots (A, R); printf (‘‘root1 = %f’’, *(R+0)); printf (‘‘root2=%f’’, *(R+1)); } b) Pointer arithmetic: A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and - To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer − ptr++ After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location. This operation will move the pointer to the next memory location without impacting the actual value at the memory location. If ptr points GNANAJYOTHI DEGREE COLLEGE Page 121 Programming in “ C –Language ” to a character whose address is 1000, then the above operation will point to the location 1001 because the next character will be available at 1001. Incrementing a Pointer We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array − #include const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = var; for ( i = 0; i < MAX; i++) { printf("Address of var[%d] = %x\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr ); /* move to the next location */ ptr++; } return 0; } When the above code is compiled and executed, it produces the following result − Address of var[0] = bf882b30 Value of var[0] = 10 Address of var[1] = bf882b34 Value of var[1] = 100 Address of var[2] = bf882b38 Value of var[2] = 200 5. NULL pointer: A null pointer is a pointer which points nothing. Some uses of the null pointer are: a) To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet. b) To pass a null pointer to a function argument when we don’t want to pass any valid memory address. GNANAJYOTHI DEGREE COLLEGE Page 122 Programming in “ C –Language ” c) To check for null pointer before accessing any pointer variable. So that, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL. Algorithm Begin. Declare a pointer p of the integer datatype. Initialize *p= NULL. Print “The value of pointer is”. Print the value of the pointer p. End. Example #include int main() { int *p= NULL;//initialize the pointer as null. printf("The value of pointer is %u",p); return 0; } Output The value of pointer is 0. Program-1: #include #include int main() { int *i, *j; int *ii = NULL, *jj = NULL; if(i == j) { printf("This might get printed if both i and j are same by chance."); } if(ii == jj) { printf("This is always printed coz ii and jj are same."); } return 0; } int main() { printf("%d",NULL); return 0; } Program-2: #include GNANAJYOTHI DEGREE COLLEGE Page 123 Programming in “ C –Language ” int main() { printf("%d",sizeof(NULL)); return 0; } #include int main() { int * ptr = NULL; printf("%d",*ptr); return 0; } #include int main() { printf("%d",sizeof(void *)); return 0; } 6. Passing argunents to Functions using pointers: The communication between caller function and calee function is possible through passing values using arguments and return statements. This can be achieved in two ways those are.  Call by value  Call by address Call By Value: In this is technique the value of the actual arguments are passed to formal arguments. If any changes occur to the formal arguments doesn‟t effects the actual arguments. Why because here only the value of the actual arguments are passed from caller function to calle function. Program: #include #include void main() { int a,b; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); printf(“\n enter b value ”); scanf(“%d”,&b); printf(“\n before swapping a= %d b=%d ”,a,b); swap(a,b); printf(“\n after swapping a= %d b=%d ”,a,b); getch(); GNANAJYOTHI DEGREE COLLEGE Page 124 Programming in “ C –Language ” } swap(int x, int y) { int z; z=x; x=y; y=z; } Call By Adress: In this is technique the value of the actual arguments are passed to formal arguments. If any changes occur to the formal arguments will effects the actual arguments. Why because here the address of the actual arguments are passed from caller function to calle function. Program: #include #include void main() { int a,b; clrscr(); printf(“\n enter a value ”); scanf(“%d”,&a); printf(“\n enter b value ”); scanf(“%d”,&b); printf(“\n before swapping a= %d b=%d ”,a,b); swap(&a,&b); printf(“\n after swapping a= %d b=%d ”,a,b); getch(); } swap(int *x, int *y) { int *z; *z=*x; *x=*y; *y=*z; } 7. Pointer and Array : It is most likely that you would not understand this section until you are through with the chapter 'Pointers'. Assuming you have some understanding of pointers in C, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration − double balance[50]; GNANAJYOTHI DEGREE COLLEGE Page 125 Programming in “ C –Language ” balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p as the address of the first element of balance − double *p; double balance[10]; p = balance; It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].Once you store the address of the first element in 'p', you can access the array elements using *p, *(p+1), *(p+2) and so on. Given below is the example to show all the concepts discussed above − #include int main () { /* an array with 5 elements */ double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; double *p; int i; p = balance; /* output each array element's value */ printf( "Array values using pointer\n"); for ( i = 0; i < 5; i++ ) { printf("*(p + %d) : %f\n", i, *(p + i) ); } printf( "Array values using balance as address\n"); for ( i = 0; i < 5; i++ ) { printf("*(balance + %d) : %f\n", i, *(balance + i) ); } return 0; } When the above code is compiled and executed, it produces the following result −Array values using pointer *(p + 0) : 1000.000000 *(p + 1) : 2.000000 *(p + 2) : 3.400000 *(p + 3) : 17.000000 *(p + 4) : 50.000000 Array values using balance as address *(balance + 0) : 1000.000000 *(balance + 1) : 2.000000 *(balance + 2) : 3.400000 *(balance + 3) : 17.000000 *(balance + 4) : 50.000000 In the above example, p is a pointer to double, which means it can store the address of a variable of double type. Once we have the address in p, *p will give us the value available at the address stored in p, as we have shown in the above example. GNANAJYOTHI DEGREE COLLEGE Page 126 Programming in “ C –Language ” 8. Dynamic Memory Allocation In this article, you'll learn to dynamically allocate memory in your C program using standard library functions: malloc(), calloc(), free() and realloc() Table of Contents  Why dynamic memory allocation?  malloc()  calloc()  free()  Example: malloc() and free()  Example: calloc() and free()  realloc()  Example: realloc() An array is a collection of fixed number of values of a single type. That is, you need to declare the size of an array before you can use it. Sometimes, the size of array you declared may be insufficient. To solve this issue, you can allocate memory manually during run-time. This is known as dynamic memory allocation in C programming. There are 4 library functions defined under makes dynamic memory allocation in C programming. They are malloc(), calloc(), realloc() and free(). C malloc() The name "malloc" stands for memory allocation. The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of type void which can be casted into pointer of any form. Syntax of malloc() Example: ptr = (int*) malloc(100 * sizeof(int)); Considering the size of int is 4 bytes, this statement allocates 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. However, if the space is insufficient, allocation fails and returns a NULL pointer. C calloc() The name "calloc" stands for contiguous allocation. The malloc() function allocates a single block of memory. Whereas, calloc() allocates multiple blocks of memory and initializes them to zero. Syntax of calloc() ptr = (cast-type*)calloc(n, element-size); ptr = (cast-type*) malloc(byte-size) GNANAJYOTHI DEGREE COLLEGE Page 127 Programming in “ C –Language ” Example: This statement allocates contiguous space in memory for 25 elements each with the size offloat. C free() Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. You must explicitly use free() to release the space. Syntax of free() This statement frees the space allocated in the memory pointed by ptr. Example 1: malloc() and free() This program calculates the sum of n numbers entered by the user. To perform this task, memory is dynamically allocated using malloc(), and memory is freed using free()function. #include #include int main() { int n, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &n); ptr = (int*) malloc(n * sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; } free(ptr); ptr = (float*) calloc(25, sizeof(float)); GNANAJYOTHI DEGREE COLLEGE Page 128 Programming in “ C –Language ” Example 2: calloc() and free() This program calculates the sum of n numbers entered by the user. To perform this task,calloc() and free() is used. #include #include int main() { int n, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &n); ptr = (int*) calloc(n, sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; } C realloc() If the dynamically allocated memory is insufficient or more than required, you can change the size of previously allocated memory using realloc() function Syntax of realloc() ptr = realloc(ptr, x); Here, ptr is reallocated with new size x. Example 3: realloc() #include #include int main() { int *ptr, i , n1, n2; printf("Enter size of array: "); scanf("%d", &n1); GNANAJYOTHI DEGREE COLLEGE Page 129 Programming in “ C –Language ” ptr = (int*) malloc(n1 * sizeof(int)); printf("Addresses of previously allocated memory: "); for(i = 0; i < n1; ++i) printf("%u\n",ptr + i); printf("\nEnter new size of array: "); scanf("%d", &n2); ptr = realloc(ptr, n2 * sizeof(int)); printf("Addresses of newly allocated memory: "); for(i = 0; i < n2; ++i) printf("%u\n", ptr + i); return 0; } When you run the program, the output will be: Enter size of array: 2 Addresses of previously allocated memory:26855472 26855476 Enter new size of array: 4 Addresses of newly allocated memory:26855472 26855476 26855480 26855484 9. Advantages and disadvantages of pointers in c Benefits(use) of pointers in c:  Pointers provide direct access to memory  Pointers provide a way to return more than one value to the functions  Reduces the storage space and complexity of the program  Reduces the execution time of the program  Provides an alternate way to access array elements  Pointers can be used to pass information back and forth between the calling function and called function.  Pointers allows us to perform dynamic memory allocation and deallocation.  Pointers helps us to build complex data structures like linked list, stack, queues, trees, graphs etc.  Pointers allows us to resize the dynamically allocated memory block.  Addresses of objects can be extracted using pointers Drawbacks of pointers in c:  Uninitialized pointers might cause segmentation fault.  Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to GNANAJYOTHI DEGREE COLLEGE Page 130 Programming in “ C –Language ” memory leak.  Pointers are slower than normal variables.  If pointers are updated with incorrect values, it might lead to memory corruption. Basically, pointer bugs are difficult to debug. Its programmers responsibility to use pointers effectively and correctly. Hard To debug Pointer issues are hard to debug. You'll never know what is the reason you're not getting the expected data. I had many issues while using pointers when I first started coding games in C++. The fact that there were 100s of files and sometimes even thousands didn't help at all. Memory Leaks Pointers are prone to memory leaks. They are common to C, C++ or objective C. Memory leaks has to be planned before hand and can be minimized using good practices only. Once they started occuring, you'll be guaranteed to miss your sleep. Pointer Arithmetic I seriously hate pointer arithmetic. They are useful in some applications, but largely it is error prone and certainly not idiot proof. I remember when my juniors got to know about these and the whole project started crashing on me. I literally had to ban any kind of pointer arithmetic in my projects. Crashes Crashes are common occurrence in pointers. It can be a null pointer error or segfault. Or you would have forgot to free a pointer or you had already freed it. The pointer data might have been corrupted while in use. There are a lot of reasons for crashes while pointers are involved. Even today when I use a C based library in an Objective C code, I am sure to get crashes in it, most of the times due to pointers. Syntax Pointer syntax is really complicated. The asterisk looks cute, but when they started swarming you by having pointer to pointer to pointer to pointer to array of functions, you started to lose 10. FILE MANAGEMENT IN C: Many real life problems involving large volumes of data and in each situation the console oriented programming post the major problems 1. it becomes time consuming to handle large volumes of data 2. the entire data is lost when either the program is terminated or computer is turned off To avoid these problems the concept of file management is used File: A file is place on the disk where a group of related data items are stored File management: we can perform the following operators on file using C language GNANAJYOTHI DEGREE COLLEGE Page 131 Programming in “ C –Language ” 1. Naming a file 2. Opening a file 3. IO operations on file 4. Closing a file Naming a file: to name a file there some specific rules those are depend upon the OS the rules for naming a file in DOS A file name has two parameters Primary name Secondary name 1. Primary name should not exceed 8 characters extension name should not exceed 3 characters and they are separated by dot(.) 2. white spaces are not allowed 3.special characters are not allowed Opening a File: To open a new file or open an existing file we have fopen( ) function in stdio.h header file Syntax: FILE *file pointer name; filepointername =fopen(“file name”,“ mode”); Ex. FILE *f; f = fopen(“rama.txt”,“r”); closing a File: a file must be closed as soon as all operations on it have been completed it prevents the accidental misuse of the file to close any file we use fclose( ) function which is in stdio.h header file Syntax: FILE *file pointer name; filepointername =fclose(“file name”,“ mode”); Ex. FILE *p; p = fclose(“rama.txt”,“r”); GNANAJYOTHI DEGREE COLLEGE Page 132 Programming in “ C –Language ” C-pre processor: the c-preprocessor is a collection of special statements called directories that are executed at the beginning of the compilation process #define ,#if , #else ,#line these are all the pre- processor directive the preprocessor directives are usually appear at the beginning of a program. Program: #define ramu 10 void main() { int i,s=0; clrscr(); for(i=0;i<=ramu;i++) { s=s+i; } printf(“\n the sum is %d ”,s); getch(); } 11. Basics of File Handling in C So far the operations using C program are done on a prompt / terminal which are not stored anywhere. But in software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are: 1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”) 2. Opening an existing file (fopen) 3. Reading from file (fscanf or fgetc) 4. Writing to a file (fprintf or fputs) 5. Moving to a specific location in a file (fseek, rewind) 6. Closing a file (fclose) The text in the brackets denotes the functions used for performing those operations. 1) Opening or creating file – For opening a file, fopen function is used with the required access modes. Some of the commonly used file access modes are:  “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL.  “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn‟t exist, a new file is created. Returns NULL, if unable to open file.  “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn‟t exist, a new file is created. Returns NULL, if unable to open file.  “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.  “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn‟t GNANAJYOTHI DEGREE COLLEGE Page 133 Programming in “ C –Language ” exist a new file is created. Returns NULL, if unable to open file.  “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn‟t exist, a new file is created. Returns NULL, if unable to open file. As given above, if you want to perform operations on binary file, then you have to append „b‟ at the last. For example, instead of “w” you have to use “wb”, insead of “a+” you have to use “a+b”. For performig the operations on file, a special pointer called File pointer is used which is decalared as Creating a file: FILE *fp; So, the file can be opened as fp = fopen(“fileName.txt”, “w”) 2) Opening aexisting File(fopen): To open a new file or open an existing file we have fopen( )function in stdio.h header file Syntax: FILE*file pointer name; filepointername=fopen(“file name”,“ mode”); Ex. FILE*f; f = fopen(“rama.txt”,“r”); The C library function FILE *fopen(const char *filename, const char *mode) opens the filename pointed to, by filename using the given mode. Declaration Following is the declaration for fopen() function. FILE *fopen(const char *filename, const char *mode)  filename − This is the C string containing the name of the file to be opened.  mode − This is the C string containing a file access mode. It includes − Example The following example shows the usage of fopen() function. #include #include int main () { FILE * fp; fp = fopen ("file.txt", "w+"); fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012); GNANAJYOTHI DEGREE COLLEGE Page 134 Programming in “ C –Language ” fclose(fp); return(0); } 3. reading a file(fscanf()): Description The C library function int fscanf(FILE *stream, const char *format, ...) reads formatted input from a stream. Declaration Following is the declaration for fscanf() function. int fscanf(FILE *stream, const char *format, ...) Parameters  stream − This is the pointer to a FILE object that identifies the stream.  format − This is the C string that contains one or more of the following items − Whitespace character, Non-whitespace character and Format specifiers. A format specifier will be as [=%[*][width][modifiers]type=], which is explained below − #include #include int main () { char str1[10], str2[10], str3[10]; int year; FILE * fp; fp = fopen ("file.txt", "w+"); fputs("We are in 2012", fp); rewind(fp); fscanf(fp, "%s %s %s %d", str1, str2, str3, &year); printf("Read String1 |%s|\n", str1 ); printf("Read String2 |%s|\n", str2 ); printf("Read String3 |%s|\n", str3 ); printf("Read Integer |%d|\n", year ); fclose(fp); return(0); } Let us compile and run the above program that will produce the following result − Read String1 |We| Read String2 |are| Read String3 |in| Read Integer |2012| GNANAJYOTHI DEGREE COLLEGE Page 135 Programming in “ C –Language ” 4. Writing to a file(fprintf) –: The file write operations can be perfomed by the functions fprintf and fputs with similarities to read operations. The snippet for writing to a file is as : Description The C library function int fprintf(FILE *stream, const char *format, ...) sends formatted output to a stream. Declaration Following is the declaration for fprintf() function. int fprintf(FILE *stream, const char *format, ...) Parameters  stream − This is the pointer to a FILE object that identifies the stream.  format − This is the C string that contains the text to be written to the stream. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype is %[flags][width][.precision][length]specifier, which is explained below − is returned otherwise, a negative number is returned. Example The following example shows the usage of fprintf() function. #include #include int main () { FILE * fp; fp = fopen ("file.txt", "w+"); fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012); fclose(fp); return(0); } After every successful fie operations, you must always close a file. For closing a file, you have to use fclose function. The snippet for closing a file is given as : 5. Moving to specific location to filr(fseek(),rewind() : The C library function int fseek(FILE *stream, long int offset, int whence) sets the file position of the stream to the given offset. Declaration Following is the declaration for fseek() function. GNANAJYOTHI DEGREE COLLEGE Page 136 Programming in “ C –Language ” int fseek(FILE *stream, long int offset, int whence) Parameters  stream − This is the pointer to a FILE object that identifies the stream.  offset − This is the number of bytes to offset from whence.  whence − This is the position from where offset is added. It is specified by one of the following constants − Example The following example shows the usage of fseek() function. #include int main () { FILE *fp; fp = fopen("file.txt","w+"); fputs("This is tutorialspoint.com", fp); fseek( fp, 7, SEEK_SET ); fputs(" C Programming Language", fp); fclose(fp); return(0); } Let us compile and run the above program that will create a file file.txt with the following content. Initially program creates the file and writes This is tutorialspoint.com but later we had reset the write pointer at 7th position from the beginning and used puts() statement which over-write the file with the following content − This is C Programming Language 5.b)rewind() Description The C library function void rewind(FILE *stream) sets the file position to the beginning of the file of the given stream. Declaration Following is the declaration for rewind() function. void rewind(FILE *stream) Parameters  stream − This is the pointer to a FILE object that identifies the stream. GNANAJYOTHI DEGREE COLLEGE Page 137 Programming in “ C –Language ” Example The following example shows the usage of rewind() function. #include int main () { char str[] = "This is tutorialspoint.com"; FILE *fp; int ch; /* First let's write some content in the file */ fp = fopen( "file.txt" , "w" ); fwrite(str , 1 , sizeof(str) , fp ); fclose(fp); fp = fopen( "file.txt" , "r" ); while(1) { ch = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", ch); } rewind(fp); printf("\n"); while(1) { ch = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", ch); } fclose(fp); return(0); } Let us assume we have a text file file.txt that have the following content − This is tutorialspoint.com 6. closing a file(fclose): FILE *fp ; fp= fopen(“fileName.txt”, “w”); ---------- Some file Operations ------- fclose(fp) Description GNANAJYOTHI DEGREE COLLEGE Page 138 Programming in “ C –Language ” The C library function int fclose(FILE *stream) closes the stream. All buffers are flushed. Declaration Following is the declaration for fclose() function. int fclose(FILE *stream) Parameters  stream − This is the pointer to a FILE object that specifies the stream to be closed. Example The following example shows the usage of fclose() function. #include int main () { FILE *fp; fp = fopen("file.txt", "w"); fprintf(fp, "%s", "This is tutorialspoint.com"); fclose(fp); return(0); } Let us compile and run the above program that will create a file file.txt, and then it will write following text line and finally it will close the file using fclose() function. This is tutorialspoint.com 12.C- Error Handling As such, C programming does not provide direct support for error handling but being a system programming language, it provides you access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno. It is set as a global variable and indicates an error occurred during any function call. You can find various error codes defined in header file. So a C programmer can check the returned values and can take appropriate action depending on the return value. It is a good practice, to set errno to 0 at the time of initializing a program. A value of 0 indicates that there is no error in the program. errno, perror(). and strerror() GNANAJYOTHI DEGREE COLLEGE Page 139 Programming in “ C –Language ” #include #include #include extern int errno ; int main () { FILE * pf; int errnum; pf = fopen ("unexist.txt", "rb"); if (pf == NULL) { errnum = errno; fprintf(stderr, "Value of errno: %d\n", errno); perror("Error printed by perror"); fprintf(stderr, "Error opening file: %s\n", strerror( errnum )); } else { fclose (pf); } return 0; } The C programming language provides perror() and strerror() functions which can be used to display the text message associated with errno.  The perror() function displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.  The strerror() function, which returns a pointer to the textual representation of the current errno value. Let's try to simulate an error condition and try to open a file which does not exist. Here I'm using both the functions to show the usage, but you can use one or more ways of printing your errors. Second important point to note is that you should use stderr file stream to output all the errors GNANAJYOTHI DEGREE COLLEGE Page 140 Programming in “ C –Language ” #include #include main() { int dividend = 20; int divisor = 0; int quotient; if( divisor == 0){ fprintf(stderr, "Division by zero! Exiting...\n"); exit(-1); } When the above code is compiled and executed, it produces the following result – Division by zero! Exiting Divide by Zero Errors It is a common problem that at the time of dividing any number, programmers do not check if a divisor is zero and finally it creates a runtime error. The code below fixes this by checking if the divisor is zero before dividing − Error printed by perror: No such file or directory Error opening file: No such file or directory Value of errno: divisor is zero and finally it creates a runtime error. The code below fixes this by checking if the divisor is zero before dividing – 13.C- Command Line Arguments It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line argumentsand many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code. GNANAJYOTHI DEGREE COLLEGE Page 141 Programming in “ C –Language ” The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly – #include int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2. You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where we int main( int argc, char *argv[] ) { printf("Program name %s\n", argv[0]); if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } }double quotes, it produces the following result. The end thank you GNANAJYOTHI DEGREE COLLEGE Page 142 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 143 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 144 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 145 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 146 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” Page 147 GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 157 Programming in “ C –Language ” GNANAJYOTHI DEGREE COLLEGE Page 158 Programming in “ C –Language ”

This question has already been tackled by one of our writers and a good grade recorded. You can equally get high grades by simply making your order for this or any other school assignment that you may have.

Every Student Buys Essays from us, here is why!

Pressed for time to complete assignments or when you feel like you cannot write, you can purchase an essay on our website. Some students also want model papers to use as samples when revising or writing. There are also students who approach our essay writing service to beat deadlines. We handle every type of homework, assignment, and academic writing tasks. You can buy college essays and other assignments here. At a glance, here are some reasons students prefer our website.

100% Original Essays and Papers

You can be sure that you are getting a paper that is custom written based on your instructions. We do not sell papers that are pre-written. Instead, we write every essay from scratch. When you say “write my essay,” we respond by giving you a paper that is 100% original and free of any plagiarism. The essays you purchase from us have never been sold anywhere.

Flexible & Affordable Prices

It does not cost a fortune to get academic writing help on our website. If you have a question from class, place an order, get a discount, and get cheap essay writing services. What you see as the price is what you pay for. There are no any hidden charges. If you need urgent papers, they might cost a little more, but the price is worth the quality you get in the end. Hire a professional academic writer beginning from $13 a page.

Anonymity, Privacy, and Confidentiality

No one will ever know that you purchased an essay or assignment from our website. The essays you buy from us are written by experts. Your data is only used to coordinate the essay writing services you get. No one can access your personal information and data. Go ahead and order an essay from our website. It is safe, secure, and convenient.

Order a Unique Copy of this Assignment
275 Words

By placing an order you agree to our terms of service

Place Order »