MASTER OF COMPUTER APPLICATIONS COMPUTER PROGRAMMING MCA612/MCA617 Kiran Gurbani
CHANDIGARH UNIVERSITY Institute of Distance and Online Learning Course Development Committee Chairman Prof. (Dr.) R.S. Bawa Vice Chancellor, Chandigarh University, Punjab Advisors Prof. (Dr.) Bharat Bhushan, Director, IGNOU Prof. (Dr.) Majulika Srivastava, Director, CIQA, IGNOU Programme Coordinators & Editing Team Master of Business Administration (MBA) Bachelor of Business Administration (BBA) Co-ordinator - Prof. Pragya Sharma Co-ordinator - Dr. Rupali Arora Master of Computer Applications (MCA) Bachelor of Computer Applications (BCA) Co-ordinator - Dr. Deepti Rani Sindhu Co-ordinator - Dr. Raju Kumar Master of Commerce (M.Com.) Bachelor of Commerce (B.Com.) Co-ordinator - Dr. Shashi Singhal Co-ordinator - Dr. Minakshi Garg Master of Arts (Psychology) Bachelor of Science (Travel & Tourism Management) Co-ordinator - Dr. Samerjeet Kaur Co-ordinator - Dr. Shikha Sharma Master of Arts (English) Bachelor of Arts (General) Co-ordinator - Dr. Ashita Chadha Co-ordinator - Ms. Neeraj Gohlan Master of Arts (Mass Communication and Bachelor of Arts (Mass Communication and Journalism) Journalism) Co-ordinator - Dr. Chanchal Sachdeva Suri Co-ordinator - Dr. Kamaljit Kaur Academic and Administrative Management Prof. (Dr.) Pranveer Singh Satvat Prof. (Dr.) S.S. Sehgal Pro VC (Academic) Registrar Prof. (Dr.) H. Nagaraja Udupa Prof. (Dr.) Shiv Kumar Tripathi Director – (IDOL) Executive Director – USB © No part of this publication should be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of the author and the publisher. SLM SPECIALLY PREPARED FOR CU IDOL STUDENTS Printed and Published by: Himalaya Publishing House Pvt. Ltd., E-mail: [email protected], Website: www.himpub.com For: CHANDIGARH UNIVERSITY Institute of Distance and Online Learning
COMPUTER PROGRAMMING PRACTICAL Course Code: MCA617 Credits: 1 Course Objectives: To develop programming logic, use of programming instructions, syntax and program structure. To analyze the foundation of complex programming languages like C++ etc. To practice the techniques for the development and application of problem-solving skills. Syllabus 1 C Basics and Control structure: 1. Write a program that reads two nos. from key board and gives their addition, subtraction, multiplication, division and modulo 2. The distance between two cities (In KM) is input through key board. Write a program to convert and print this distance in meters, feet, inches and centimeters. 3. Write a C program to perform post and pre-increment, post and pre-decrement operations. 4. Write a program which implements the working of all Bit-wise operators 5. Write a program to select and print the largest of the three nos. using Nested-If-Else statement. 6. Write a program to perform arithmetic operations using switch case. 7. Write a program to find sum of all integers greater than 100 & less than 200 and are divisible by 5. 8. Write a C program to implement ex 1 x x2 x3 , 1! 2! 3!
2. Arrays, Strings, Functions and Structure: 1. Write a program to perform various matrix operations, Addition, Subtraction, Multiplication, Transpose using switch-case statement 2. Programs based on string handling 3. Write a program using function to implement Pascal Triangle 4. Write a program that used user defined function Swap ( ) and interchange the value of two variable. 5. Write a function prime that return 1 if it’s argument is prime and return 0 otherwise 6. Define a structure type, personal, that would contain person name, date of joining and salary. Using this structure, write a program to read this information for one person from the key screen. 7. Define a structure called cricket that will describe the following information: (a) Player name (b) Team name (c) Batting average 3. Pointers and DMA: 1. Write a program using pointer and function to determine the length of string. 2. Write a program using pointer to compare two strings. 3. Write a program using pointer to concatenate two strings. 4. Write a program using pointer to copy one string to another string. 5. Write a program using pointer to read an array if integer and print element in reverse order.
6. Write a program that uses a table of integers whose size will be specified interactively at run time. 7. Write a program to store a character string in block of memory space created by malloc and then modify the same to store a large string. 4. C Pre-Processor and File management: 1. Write a program which reads diameter and height of a cone and calculate its volume using macros. 2. A program to illustrate reading files contents. 3. A program to illustrate the use of fgets( ) 4. A program to illustrate the use of fputc ( ) and fputs( ) Text Books: 1. Balaguruswamy (2017 ).Programming in ANSI C. New Delhi: McGraw-Hill. 2. Kanetkar, Y. (2014), Programming in C ANSI standard. New Delhi: BPB Publications. 3. Gottfried (2005).Programming with C. New York: Tata McGraw-Hill. Reference Books: 1. Harrow K., Jones J. (1996). Problem Solving with C. London: Pearson Education. 2. Jeri R., Hanly, Koffman E.P. (2000). Problem Solving and Program Design in C. 3rd Ed. Boston: Addison Wesley.
CONTENTS Unit 1: Introduction to Computer and Programming 1 – 28 29 – 60 Unit 2 Fundamentals of C 61 – 98 99 – 133 Unit 3 Operators and Expressions 134 - 144 145 - 158 Unit 4 Decision and Loop Control structure 159 - 190 191 – 216 Unit 5 Arrays 217 – 243 244 – 259 Unit 6 Strings 260 – 271 272 – 302 Unit 7 Functions 303 – 310 311 – 324 Unit 8 Pointers 325 – 332 333 – 336 Unit 9 Structure Unit 10 Dynamic Memory Allocation Unit 11 C Preprocessor Unit 12 File Management Practical Unit 1 C Basics and Control Structure Practical Unit 2 Arrays, Strings, Functions and Structure Practical Unit 3 Pointers and DMA Practical Unit 4 C Pre-Processor and File Management
Introduction to Computer and Programming 1 UNIT 1 INTRODUCTION TO COMPUTER AND PROGRAMMING Structure: 1.0 Learning Objectives 1.1 Introduction 1.2 Basic Block Diagrams 1.3 Interconnection between Functional Components 1.4 Algorithm Flowcharts 1.5 Machines and Knowledge about Problem Solving 1.6 Stages of Program Development Process 1.7 Importance of Discipline in Programming 1.8 Summary 1.9 Key Words/Abbreviations 1.10 Learning Activity 1.11 Unit End Questions (MCQ and Descriptive) 1.12 References 1.0 Learning Objectives After studying this unit, you will be able to: Define computer Draw the block diagram of computer Explain functioning of different components of computer Describe algorithm and flowcharts CU IDOL SELF LEARNING MATERIAL (SLM)
2 Computer Programming Describe the machines related to problem solving Discuss the knowledge and concepts of problem solving Explain problem development steps Elaborate the importance of discipline in problem solving 1.1 Introduction Being a modern-day kid you must have used, seen, or read about computers. This is because they are an integral part of our everyday existence. Be it school, banks, shops, railway stations, hospital or your own home, computers are present everywhere, making our work easier and faster for us. As they are such integral parts of our lives, we must know what they are and how they function. Let us start with defining the term computer formally. Types of Computers: Computers can be generally classified by size and power as follows, though there is considerable overlap: Personal computer: A small, single-user computer based on a microprocessor. Workstation: A powerful, single-user computer. A workstation is like a personal computer, but it has a more powerful microprocessor and, in general, a higher-quality monitor. Minicomputer: A multi-user computer capable of supporting up to hundreds of users simultaneously. Mainframe: A powerful multi-user computer capable of supporting many hundreds or thousands of users simultaneously. Supercomputer: An extremely fast computer that can perform hundreds of millions of instructions per second. Supercomputer and Mainframe Supercomputer is a broad term for one of the fastest computers currently available. Supercomputers are very expensive and are employed for specialized applications that require immense amounts of mathematical calculations (number crunching). For example, weather CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 3 forecasting requires a supercomputer. Other uses of supercomputers scientific simulations (animated) graphics, fluid dynamic calculations, nuclear energy research, electronic design, and analysis of geological data (e.g., in petrochemical prospecting). Perhaps the best known supercomputer manufacturer is Cray Research. Mainframe was a term originally referring to the cabinet containing the central processor unit or “main frame” of a room-filling Stone Age batch machine. After the emergence of smaller “minicomputer” designs in the early 1970s, the traditional big iron machines were described as “mainframe computers” and eventually just as mainframes. Nowadays a Mainframe is a very large and expensive computer capable of supporting hundreds, or even thousands, of users simultaneously. The chief difference between a supercomputer and a mainframe is that a supercomputer channels all its power into executing a few programs as fast as possible, whereas a mainframe uses its power to execute many programs concurrently. In some ways, mainframes are more powerful than supercomputers because they support more simultaneous programs. But supercomputers can execute a single program faster than a mainframe. The distinction between small mainframes and minicomputers is vague, depending really on how the manufacturer wants to market its machines. Minicomputer It is a midsize computer. In the past decade, the distinction between large minicomputers and small mainframes has blurred, however, as has the distinction between small minicomputers and workstations. But in general, a minicomputer is a multiprocessing system capable of supporting from up to 200 users simultaneously. Workstation It is a type of computer used for engineering applications (CAD/CAM), desktop publishing, software development, and other types of applications that require a moderate amount of computing power and relatively high quality graphics capabilities. Workstations generally come with a large, high-resolution graphics screen, at large amount of RAM, built-in network support, and a graphical user interface. Most workstations also have a mass storage device such as a disk drive, but a special type of workstation, called a diskless workstation, comes without a disk drive. The most common operating systems for workstations are UNIX and Windows NT. Like personal computers, most workstations are single-user computers. However, workstations are typically linked together to form a local-area network, although they can also be used as stand-alone systems. CU IDOL SELF LEARNING MATERIAL (SLM)
4 Computer Programming N.B.: In networking, workstation refers to any computer connected to a local-area network. It could be a workstation or a personal computer. Personal Computer It can be defined as a small, relatively inexpensive computer designed for an individual user. In price, personal computers range anywhere from a few hundred pounds to over five thousand pounds. All 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, desktop publishing, and for running spreadsheet and database management applications. At home, the most popular use for personal computers is for playing games and recently for surfing the Internet. Personal computers first appeared in the late 1970s. One of the first and most popular personal computers was the Apple II, introduced in 1977 by Apple Computer. During the late 1970s and early 1980s, new models and competing operating systems seemed to appear daily. Then, in 1981, IBM entered the fray with its first personal computer, known as the IBM PC. The IBM PC quickly became the personal computer of choice, and most other personal computer manufacturers fell by the wayside. P.C. is short for personal computer or IBM PC. One of the few companies to survive IBM’s onslaught was Apple Computer, which remains a major player in the personal computer marketplace. Other companies adjusted to IBM’s dominance by building IBM clones, computers that were internally almost the same as the IBM PC, but that cost less. Because IBM clones used the same microprocessors as IBM PCs, they were capable of running the same software. Over the years, IBM has lost much of its influence in directing the evolution of PCs. Therefore, after the release of the first PC by IBM the term PC increasingly came to mean IBM or IBM-compatible personal computers, to the exclusion of other types of personal computers, such as Macintoshes. In recent years, the term PC has become more and more difficult to pin down. In general, though, it applies to any personal computer based on an Intel microprocessor, or on an Intel-compatible microprocessor. For nearly every other component, including the operating system, there are several options, all of which fall under the rubric of PC. Today, the world of personal computers is basically divided between Apple Macintoshes and PCs. The principal characteristics of personal computers are that they are single-user systems and are based on microprocessors. However, although personal computers are designed as single-user systems, it is common to link them together to form a network. In terms of power, there is great CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 5 variety. At the high end, the distinction between personal computers and workstations has faded. High-end models of the Macintosh and PC offer the same computing power and graphics capability as low-end workstations by Sun Microsystems, Hewlett-Packard, and DEC. Personal Computer Types Actual personal computers can be generally classified by size and chassis / case. The chassis or case is the metal frame that serves as the structural support for electronic components. Every computer system requires at least one chassis to house the circuit boards and wiring. The chassis also contains slots for expansion boards. If you want to insert more boards than there are slots, you will need an expansion chassis, which provides additional slots. There are two basic flavours of chassis designs – desktop models and tower models — but there are many variations on these two basic types. Then come the portable computers that are computers small enough to carry. Portable computers include notebook and subnotebook computers, hand-held computers, palmtops, and PDAs. Tower Model The term refers to a computer in which the power supply, motherboard, and mass storage devices are stacked on top of each other in a cabinet. This is in contrast to desktop models, in which these components are housed in a more compact box. The main advantage of tower models is that there are fewer space constraints, which makes installation of additional storage devices easier. Desktop Model A computer designed to fit comfortably on top of a desk, typically with the monitor sitting on top of the computer. Desktop model computers are broad and low, whereas tower model computers are narrow and tall. Because of their shape, desktop model computers are generally limited to three internal mass storage devices. Desktop models designed to be very small are sometimes referred to as slimline models. Notebook Computer An extremely lightweight personal computer. Notebook computers typically weigh less than 6 pounds and are small enough to fit easily in a briefcase. Aside from size, the principal difference between a notebook computer and a personal computer is the display screen. Notebook computers use a variety of techniques, known as flat-panel technologies, to produce a lightweight and non- bulky display screen. The quality of notebook display screens varies considerably. In terms of CU IDOL SELF LEARNING MATERIAL (SLM)
6 Computer Programming computing power, modern notebook computers are nearly equivalent to personal computers. They have the same CPUs, memory capacity, and disk drives. However, all this power in a small package is expensive. Notebook computers cost about twice as much as equivalent regular-sized computers. Notebook computers come with battery packs that enable you to run them without plugging them in. However, the batteries need to be recharged every few hours. Laptop Computer A small, portable computer — small enough that it can sit on your lap. Nowadays, laptop computers are more frequently called notebook computers. Subnotebook Computer A portable computer that is slightly lighter and smaller than a full-sized notebook computer. Typically, subnotebook computers have a smaller keyboard and screen, but are otherwise equivalent to notebook computers. Hand-held Computer A portable computer that is small enough to be held in one’s hand. Although extremely convenient to carry, hand-held computers have not replaced notebook computers because of their small keyboards and screens. The most popular hand-held computers are those that are specifically designed to provide PIM (personal information manager) functions, such as a calendar and address book. Some manufacturers are trying to solve the small keyboard problem by replacing the keyboard with an electronic pen. However, these pen-based devices rely on handwriting recognition technologies, which are still in their infancy. Hand-held computers are also called PDAs, palmtops and pocket computers. Palmtop A small computer that literally fits in your palm. Compared to full-size computers, palmtops are severely limited, but they are practical for certain functions such as phone books and calendars. Palmtops that use a pen rather than a keyboard for input are often called hand-held computers or PDAs. Because of their small size, most palmtop computers do not include disk drives. However, many contain PCMCIA slots in which you can insert disk drives, modems, memory, and other devices. Palmtops are also called PDAs, hand-held computers and pocket computers. CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 7 PDA Short for personal digital assistant, a handheld device that combines computing, telephone/ fax, and networking features. A typical PDA can function as a cellular phone, fax sender, and personal organizer. Unlike portable computers, most PDAs are pen-based, using a stylus rather than a keyboard for input. This means that they also incorporate handwriting recognition features. Some PDAs can also react to voice input by using voice recognition technologies. The field of PDA was pioneered by Apple Computer, which introduced the Newton MessagePad in 1993. Shortly thereafter, several other manufacturers offered similar products. To date, PDAs have had only modest success in the marketplace, due to their high price tags and limited applications. However, many experts believe that PDAs will eventually become common gadgets. PDAs are also called palmtops, hand-held computers and pocket computers. 1.2 Basic Block Diagrams Input-Process-Output Model Computer input is the data entered by the user for the storage, processing, and manipulation 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. Fig. 1.1: Input-Process-Output Model The processes that can be applied to data are of two types — Arithmetic operations — Examples include calculations like addition, subtraction, differentials, square root, etc. CU IDOL SELF LEARNING MATERIAL (SLM)
8 Computer Programming Logical operations — Examples include comparison operations like greater than, less than, equal to, opposite, etc. The corresponding figure for an actual computer looks something like this — Memory Section Fig. 1.2: Basic Parts of a Computer 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. An arithmetic logic unit (ALU) is a major component of the central processing unit of a computer system. It does all processes related to arithmetic and logic operations that need to be done on instruction words. In some microprocessor architectures, the ALU is divided into the arithmetic unit (AU) and the logic unit (LU). An ALU can be designed by engineers to calculate any operation. As the operations become more complex, the ALU also becomes more expensive, takes up more space in the CPU and dissipates more heat. That is why engineers make the ALU powerful enough to ensure that the CPU is also powerful and fast, but not so complex as to become prohibitive in terms of cost and other disadvantages. CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 9 An arithmetic logic unit is also known as an integer unit (IU). The arithmetic logic unit is that part of the CPU that handles all the calculations the CPU may need. Most of these operations are logical in nature. Depending on how the ALU is designed, it can make the CPU more powerful, but it also consumes more energy and creates more heat. Therefore, there must be a balance between how powerful and complex the ALU is and how expensive the whole unit becomes. This is why faster CPUs are more expensive, consume more power and dissipate more heat. The main functions of the ALU are to do arithmetic and logic operations, including bit shifting operations. These are essential processes that need to be done on almost any data that is being processed by the CPU. ALUs routinely perform the following operations: Logical Operations: These include AND, OR, NOT, XOR, NOR, NAND, etc. Bit-Shifting Operations: This pertains to shifting the positions of the bits by a certain number of places to the right or left, which is considered a multiplication operation. Arithmetic Operations: This refers to bit addition and subtraction. Although multiplication and division are sometimes used, these operations are more expensive to make. Addition can be used to substitute for multiplication and subtraction for division. 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. 1.3 Interconnection between Functional Components A computer consists of input unit that takes input, a CPU that processes the input and an output unit that produces output. All these devices communicate with each other through a common CU IDOL SELF LEARNING MATERIAL (SLM)
10 Computer Programming bus. A bus is a transmission path, made of a set of conducting wires over which data or information in the form of electric signals, is passed from one component to another in a computer. The bus can be of three types – Address bus, Data bus and Control Bus. Following figure shows the connection of various functional components: Fig. 1.3: Interconnection between Functional Components The address bus carries the address location of the data or instruction. The data bus carries data from one component to another and the control bus carries the control signals. The system bus is the common communication path that carries signals to/from CPU, main memory and input/ output devices. The input/output devices communicate with the system bus through the controller circuit which helps in managing various input/output devices attached to the computer. Characteristics of Computer To understand why computers are such an important part of our lives, let us look at some of its characteristics — CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 11 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 — Computers can carry out a wide range of work from data entry and ticket booking to complex mathematical calculations and continuous astronomical observations. If you can input the necessary data with correct instructions, computer will do the processing. 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 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. CU IDOL SELF LEARNING MATERIAL (SLM)
12 Computer Programming 1.4 Algorithm and Flowcharts Algorithm and flowchart are two types of tools to explain the process of a program. This page extends the differences between an algorithm and a flowchart, and how to create a flowchart to explain an algorithm in a visual way. Algorithms and flowcharts are two different tools used for creating new programs, especially in computer programming. An algorithm is a step-by-step analysis of the process, while a flowchart explains the steps of a program in a graphical way. Definition of Algorithm To write a logical step-by-step method to solve the problem is called algorithm, in other words, an algorithm is a procedure for solving problems. In order to solve a mathematical or computer problem, this is the first step of the procedure. An algorithm includes calculations, reasoning and data processing. Algorithms can be presented by natural languages, pseudo code and flowcharts, etc. Definition of Flowchart A flowchart is the graphical or pictorial representation of an algorithm with the help of different symbols, shapes and arrows in order to demonstrate a process or a program. With algorithms, we can easily understand a program. The main purpose of a flowchart is to analyze different processes. Several standard graphics are applied in a flowchart: Terminal Box – Start/End Input/Output CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 13 Process/Instruction Decision Connector / Arrow The graphics above represent different part of a flowchart. The process in a flowchart can be expressed through boxes and arrows with different sizes and colours. In a flowchart, we can easily highlight a certain element and the relationships between each part. Difference between Algorithm and Flowchart If you compare a flowchart to a movie, then an algorithm is the story of that movie. In other words, an algorithm is the core of a flowchart. Actually, in the field of computer programming, there are many differences between algorithm and flowchart regarding various aspects, such as the accuracy, the way they display, and the way people feel about them. Below is a table illustrating the differences between them in detail. Table 1.1: Difference between Algorithm and Flowchart Algorithm Flowchart It is a procedure for solving problems. It is a graphic representation of a process. The process is shown in step-by-step instruction. The process is shown in block-by-block information diagram. It is complex and difficult to understand. It is intuitive and easy to understand. It is convenient to debug errors. It is hard to debug errors. The solution is showcased in natural language. The solution is showcased in pictorial format. It is somewhat easier to solve complex problem. It is hard to solve complex problem. It costs more time to create an algorithm. It costs less time to create a flowchart. CU IDOL SELF LEARNING MATERIAL (SLM)
14 Computer Programming Characteristics of Algorithm Finiteness Fig. 1.4: Characteristics of Algorithm Not all procedures can be called an algorithm. An algorithm should have the following characteristics: Unambiguous: Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning. Input: An algorithm should have 0 or more well-defined inputs. Output: An algorithm should have 1 or more well-defined outputs, and should match the desired output. Finiteness: Algorithms must terminate after a finite number of steps. Feasibility: Should be feasible with the available resources. Independent: An algorithm should have step-by-step directions, which should be independent of any programming code. Algorithms are mainly used for mathematical and computer programs, whilst flowcharts can be used to describe all sorts of processes: business, educational, personal and of course algorithms. So flowcharts are often used as a program planning tool to visually organize the step-by-step process of a program. Here are some examples: CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 15 Example 1: Print 1 to 20: Algorithm: Step 1: Initialize X as 0, Step 2: Increment X by 1, Step 3: Print X, Step 4: If X is less than 20 then go back to step 2. Flowchart: Start Initialize x = 0 Increment x by 1 Print x YES x > 20 No End Fig. 1.5: Flowchart for Printing 1 to 20 Example 2: Convert Temperature from Fahrenheit (°F) to Celsius (!) Algorithm: Step 1: Read temperature in Fahrenheit, Step 2: Calculate temperature with formula C=5/9*(F-32), Step 3: Print C, CU IDOL SELF LEARNING MATERIAL (SLM)
16 Computer Programming Flowchart: Fig. 1.6: Flowchart for Converting Temperature from Fahrenheit (ºF) to Celsius (!) Example 3: Determine Whether A Student Passed the Exam or Not: Algorithm: Step 1: Input grades of 4 courses M1, M2, M3 and M4, Step 2: Calculate the average grade with formula “Grade=(M1+M2+M3+M4)/4” Step 3: If the average grade is less than 60, print “FAIL”, else print “PASS”. CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 17 Flowchart: Fig. 1.7: Flowchart to Determine whether a Student passed the Exam or Not 1.5 Machines and Knowledge about Problem Solving ‘Machine learning’ is one of the popular buzzwords that have been slowly moving from the tech side to the other departments. Every day, new applications for machine learning combined with big data and artificial intelligence has been doing its rounds in almost all fields. With Google, Amazon and Microsoft introducing their own machine learning platforms, it has attained newer levels of fame! Here are a few significant applications and solutions of machine learning that can be compared with the business problems you have: CU IDOL SELF LEARNING MATERIAL (SLM)
18 Computer Programming Image Recognition Remember how Facebook automatically tags your friends accurately when you upload a group picture? Facebook started using machine learning to record the faces of the millions of Facebook users and store them and identifies them with the faces in the picture you upload. This face recognition technique from Facebook is just one application of machine learning in image recognition. There are a lot of other applications in assembly lines in factories, in healthcare applications and it has also been tested out with the driverless cars. Customer Segmentation This has been widely used by the marketing departments across all businesses. Customer retention, churn prediction and lead generation have always been a major challenge for all marketers but with the advancements in machine learning, marketers can now eliminate the guesswork and get real-time, accurate results in customer segmentation from the past and current data. Marketers can now get the complete analysis of each segment’s behaviour which can be leveraged in their marketing campaigns for more specific results. Customer Service Customer service is yet another department that every company will have no matter the size and the volume of the business. With the machine learning technology, businesses can now analyse the past data from the customer support and provide better services to the customers while also reducing the manpower. Product Recommendations This is majorly used in the e-commerce service sectors where the websites use machine learning to tempt the customers in buying more things. Remember the section of ‘Also Bought’ in many popular e-commerce websites where you will be displayed related items for the things you just added to a cart? This has been widely used by almost all online shopping websites where, based on the customer historical data of the individual customer and the total gathered data, the top predicted things that the customer will most likely buy will be displayed in the home page and in some sections of the product pages too. CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 19 Machine learning can definitely make a major impact in solving the business problems if the right approach and the right set of data are used. 1.6 Stages of Program Development Process The various stages in the development of a computer program are : 1. Problem Definition 2. Program Design 3. Coding 4. Debugging 5. Testing 6. Documentation 7. Maintenance Fig. 1.8: Stages of Program Development Process CU IDOL SELF LEARNING MATERIAL (SLM)
20 Computer Programming Problem Definition: The first step in the process of program development is the thorough understanding and identification of the problem for which is the program or software is to be developed. In this step the problem has to be defined formally. All the factors like Input/output, processing requirement, memory requirements, error handling, interfacing with other programs have to be taken into consideration in this stage. Program Design: The next stage is the program design. The software developer makes use of tools like algorithms and flowcharts to develop the design of the program. Algorithm Flowchart Coding: Once the design process is complete, the actual computer program is written, i.e. the instructions are written in a computer language. Coding is generally a very small part of the entire program development process and also a less time consuming activity in reality. In this process all the syntax errors, i.e., errors related to spelling, missing commas, undefined labels etc. are eliminated. For effective coding some of the guidelines which are applied are : Use of meaningful names and labels of variables, Simple and clear expressions, Modularity with emphasis on making modules generalized, Making use of comments and indenting the code properly, Avoiding jumps in the program to transfer control. CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 21 Debugging: At this stage the errors in the programs are detected and corrected. This stage of program development is an important process. Debugging is also known as program validation. Some common errors which might occur in the programs include: Uninitialization of variables. Reversing of order of operands. Confusion of numbers and characters. Inverting of conditions, e.g., jumping on zero instead of on not zero. Testing: The program is tested on a number of suitable test cases. A test plan of the program has to be done at the stage of the program design itself. This ensures a thorough understanding of the specifications. The most trivial and the most special cases should be identified and tested. It is always useful to include the maximum and minimum values of all variables as test data. Documentation: Documentation is a very essential step in the program development. Documentation help the users and the people who maintain the software. This ensures that future modification if required can be done easily. Also it is required during redesigning and maintenance. Maintenance: Updating and correction of the program for changed conditions and field experience is accounted for in maintenance. Maintenance becomes essential in following situations: Change in specification, Change in equipment, Errors which are found during the actual execution of the program. CU IDOL SELF LEARNING MATERIAL (SLM)
22 Computer Programming 1.7 Importance of Discipline in Programming Programming Discipline and Software Development Environment A good programming discipline and software development environment goes a long way in doing productive and efficient work. Here is a list: 1. Lots of programming errors can be avoided by proper usage of tools for compilation and static code analysis. 2. For compilation, one should always use — Wall option. 3. For example: gcc -Wall myprogram.c For static code analysis, “splint” utility. 4. The software development environment must have a Makefile, even if one has a single C file. The advantage will become obvious as number of C files and header files grow over a period of time. 5. In a big project, one needs to search for files, function names, variable names and so on. One can use “cscope” and/or “ctags” utilities for this purpose. 6. All programs must follow a good C coding guideline. For Linux and C programming, one should look at guidelines used by Linux kernel developers. Here are few links for C-coding guidelines: Mentioned below is a derived version of this C coding style:- 1. Indentation The code must be indented properly. Use tabspaces for indentation. Web developers can use 4 or 8 spaces instead of tabspace for web publishing (For example publishing a post in sanfoundry.com). Indentation level 0 -> align to column 1 Indentation level 1 -> indent by 1 tab to the right of indentation level 0 Indentation level n+1 -> indent by 1 tab to the right of indentation level n Indentation levels in a switch statement is to align the “switch” and “case” labels in the same column. For example: CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 23 switch(var){ case’t’: avar=10; break; case’u’: avar=20; break; default: break; } 2. Breaking Long Lines and Strings Don’t put multiple statements on a single line. Don’t put multiple assignments on a single line either. Don’t leave whitespace at the end of lines. The maximum length of a line should be 80 columns. Statements longer than 80 columns will be broken into sensible chunks. For example: void fun(int a,int b,int c) { if(condition) printf(“Warning this is a long printf with 3 parameters” “ a: %u b: %u c: %u n”, a, b, c); else next_statement; } 3. Placing Braces and Spaces Put the opening brace last on the line, and put the closing brace first, thus: if(x is true){ wedo y } CU IDOL SELF LEARNING MATERIAL (SLM)
24 Computer Programming This applies to all non-function statement blocks (if, switch, for, while, do). E.g.: switch(var){ case’t’: avar=10; break; case’u’: avar=20; break; default: break; } However, there is one special case, namely functions: they have the opening brace at the beginning of the next line. 1.8 Summary An electronic data processing device, which requires input raw data for processing and generates the output in desired form. It stores the data in its memory which can be accessed any number of times for reference from its memory. It is made up of a lot of electronics, software and mechanical parts. A computer is divided into three basic units namely: 1. Input Unit 2. Central Processing Unit 3. Output Unit (1) Input Unit As the name suggests, this unit contains devices with the help of which the data is entered into the computer. This unit is a basic requirement for computer system. The input devices are of many types such as keyboard, mouse, joystick, microphone, camera etc. Input devices give different set of input values converted into a form understandable to the computer. CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 25 (2) Central Processing Unit (CPU) Central Processing Unit (CPU) is known as the brain of the computer. It performs all types of data processing operations as required by a programmer. It stores all the data, intermediate results, and instructions as given by the programmer in the form of codes (program). Central Processing Unit controls the operation of each part of the computer. It has following three components: 1. Arithmetic Logic Unit (ALU) 2. Memory Unit 3. Control Unit (3) Output Unit The devices with the help of which we get the information from the computer are known as the output devices. Output Unit is an interface between the computer and the user. Output devices notify the information displayed into a form which is understandable by the computer user. Characteristics of Computer 1. Speed 2. Accuracy 3. Reliability 4. Versatility 5. Storage Capacity Problem It is a systematic approach to find and implement the solution to a problem. Steps in Problem Solving 1. Problem Definition 2. Problem Analysis 3. Design 4. Coding CU IDOL SELF LEARNING MATERIAL (SLM)
26 Computer Programming 5. Testing 6. Maintenance 1.9 Key Words/Abbreviations Algorithm: An Algorithm is a step by step instruction of a problem which defines the solution of a particular problem in simple language. An algorithm is expressed in pseudo code which resembles somewhat with C language, but with some statements in English rather than any kind of programming language. In Algorithm there is no ambiguity about which instruction is to executed next. Flowchart: A flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning tool to solve a problem. It makes use of symbols which are connected among them to indicate the flow of information and processing. The process of drawing a flowchart for an algorithm is known as “flowcharting”. Program: It is a set of instructions written in computer languages. 1.10 Learning Activity 1. Write algorithm and draw the flowchart to find average of three numbers. ....................................................................................................................................... ....................................................................................................................................... 2. Write algorithm and draw the flowchart to find whether a number entered is even or odd. ....................................................................................................................................... ....................................................................................................................................... 1.11 Unit End Questions (MCQ and Descriptive) A. Descriptive Type: Short Answer Type Questions 1. Define Computer and its characteristics. 2. Draw and explain Basic Block Diagram of Computer. CU IDOL SELF LEARNING MATERIAL (SLM)
Introduction to Computer and Programming 27 3. Explain different Components of Computer. 4. What is Flowchart. Draw Symbols of flowchart. 5. What is Algorithm. Give any one example of writing Algorithm. 6. Explain different types of Algorithms. 7. Explain how Machines and Knowledge about solving can be done with computers. 8. What are different Steps involved in Program Development? 9. Explain Importance of Discipline in Programming. B. Multiple Choice/Objective Type Questions 1. In how many generations a computer can be classified? (a) 3 (b) 4 (c) 5 (d) 6 2. The brain of any computer system is (a) CPU (b) Memory (c) ALU (d) Control unit 3. Which generation of computer is still under development (a) Fourth Generation (b) Fifth Generation (c) Sixth Generation (d) Seventh Generation (a) the number of partitions (b) the CPU utilization (c) the memory size (d) all of the mentioned 4. In computer science, algorithm refers to a pictorial representation of a flowchart. (a) True (b) False 5. The process of drawing a flowchart for an algorithm is called __________ (a) Performance (b) Evaluation (c) Algorithmic Representation (d) Flowcharting Answers : 1. (c), 2. (a), 3. (b), 4. (b), 5. (d) CU IDOL SELF LEARNING MATERIAL (SLM)
28 Computer Programming 1.12 References 1. https://www.includehelp.com/basics/computer-definition-parts-functions-and-its- advantages.aspx 2. https://www.techoschool.com/MCA/Computer-Concepts-and-Programming-in-C/UNIT- 1-Basics-Of-Programming_Concept-of-Algorithm-and-Flowchart 3. http://newhorizonindia.edu/nhc_kasturinagar/wp-content/uploads/2018/07/PROBLEM- SOLVING-TECHNIQUES-USING-C.pdf 4. Introduction to Computing Explorations in Language, Logic, and Machines by David Evans 5. Introduction to computers by Rutendo Makaha CU IDOL SELF LEARNING MATERIAL (SLM)
Fundamentals of C 29 UNIT 2 FUNDAMENTALS OF C Structure: 2.0 Learning Objectives 2.1 Introduction 2.2 Features of C Language 2.3 Structure of C Program 2.4 Comments 2.5 Header Files and Body 2.6 Data Types 2.7 Constants 2.8 Format specifiers with scanf() and printf() 2.9 Variables 2.10 Summary 2.11 Key Words/Abbreviations 2.12 Learning Activity 2.13 Unit End Questions (MCQ and Descriptive) 2.14 References 2.0 Learning Objectives After studying this unit, you will be able to: List the features of C language Describe the structure of C program CU IDOL SELF LEARNING MATERIAL (SLM)
30 Computer Programming Define comments and header files Explain C data types 2.1 Introduction C is a powerful general-purpose programming language. It is fast, portable and available in all platforms. If you are new to programming, C is a good choice to start your programming journey. C was the basics language to write everything from operating systems (Windows and many others) to complex programs like the Oracle database, Git, Python interpreter and more. It is said that ‘C’ is a god’s programming language. One can say, C is a base for the programming. If you know ‘C,’ you can easily grasp the knowledge of the other programming languages that uses the concept of ‘C’. It is essential to have a background in computer memory mechanisms because it is an important aspect when dealing with the C programming language. Why Name “C” was given to Language? 1. Many of C’s principles and ideas were derived from the earlier language B. (Ken Thompson was the developer of B Language.) 2. BCPL and CPL are the earlier ancestors of B Language. 3. CPL is common Programming Language. In 1967, BCPL Language (Basic CPL) was created as a scaled down version of CPL. 4. As many of the features were derived from “B” Language that’s why it was named as “C”. 5. After 7-8 years C++ came into existence which was first example of object-oriented programming. CU IDOL SELF LEARNING MATERIAL (SLM)
Fundamentals of C 31 C Programming Language Timeline: ANSI Committee ISO Committee Fig. 2.1: C Programming Language Timeline C language has evolved from three different structured languages ALGOL, BCPL and B Language. It uses many concepts from these languages and introduced many new concepts such as data types, structure pointer. In 1988, the language was formalized by American National Standard Institute (ANSI). In 1990, a version of C language was approved by the International Standard Organization (ISO) and that version of C is also referred to as C89. 2.2 Features of C Language Features of C language: C is a structured programming language, which means that it allows you to develop programs using well defined control structures (you will learn about control structures in the articles to CU IDOL SELF LEARNING MATERIAL (SLM)
32 Computer Programming come), and provides modularity (breaking the task into multiple sub tasks that are simple enough to understand and to reuse). C is often called a middle-level language because it combines the best elements of low-level or machine language with high-level languages. Portable Structured Mid-level Simple Memory C Language Rich Library Management Extensible Pointers Faster Recursion Fig. 2.2: C Language Features (1) C is a Case Sensitive Language: Case sensitivity indicates that it differtiates the characters either upper case or lower case based on their ASCII value. (2) C is Mother of all Languages: C is mother of all languages because from C language BASIC language is invented and from BASIC language Visual Basic and VB. Net languages are invented. From C language C++, VC++, C#, J#, JAVA languages are invented. (3) Portable: C is highly portable this means that programs once written can be run on another machines with little or no modification. if we write C program in turbo C we can run same program in Borland or ANSI C without any modification on windows platform as well as we can Run on gcc complier on Linux Platform. (4) C is a Structured Programming Language: C is a structured programming language since it follows fixed structure for writing any program, which should have compulsory main() function in the structure. CU IDOL SELF LEARNING MATERIAL (SLM)
Fundamentals of C 33 (5) Modularity in structured programming refers to the breakdown of large C Language into small modules hence due to modularity complication can be reduced and debugging is fast. (6) C is a Middle Level Language: C is also used to do low level programming. It is used to develop system applications such as kernel, driver, etc. It also supports the feature of high level language. That is why it is known as mid-level language. (7) C has Inbuilt Library Functions: C has inbuilt Library functions and packages bundled into header files, Programs written in C are efficient and fast. This is due to its variety of data type and powerful operators. (8) C allows Us to Create User Defined Functions: Apart from using inbuilt functions, C allows us to create your own defined functions depends on requirement. (9) C has its own Compiler: The C compiler combines the capabilities of an assembly language with features of a high-level language. (10) C is Used for Creating Powerful System Programs, since with the help of C programming system, programs and kernel coding for Linux operating system can be written. (11) C is a Flexible and Powerful Language. (12) C has 32 Keywords or Reserved Words which are identifiers reserved only for C language and cannot used for variable declaration and function declaration. (13) C supports Graphics. (14) Robust Language: It is a robust language with rich set of built-in functions and operators that can be used to write any complex program. (15) Memory Management: It supports the feature of dynamic memory allocation. In C language, we can free the allocated memory at any time by calling the free() function. (16) Pointer: C provides the feature of pointers. We can directly interact with the memory by using the pointers. We can use pointers for memory, structures, functions, array, etc. C supports different functions, structures, arrays with powerful data structures like Stack, Linked list, Queue, Trees. CU IDOL SELF LEARNING MATERIAL (SLM)
34 Computer Programming (17) Efficient and Fast: Programs written in C are efficient and fast. This is due to its variety of data type and powerful operators. (18) Extensible: In C language, new features can be added by the programmer, hence it is extensible. (19) Recursion: In C, we can call the function within the function. It provides code reusability for every function. The C programming language is used for developing system applications that forms a major portion of operating systems such as Windows, UNIX and Linux. Below are some examples of C being used. Database systems Graphics packages Word processors Spreadsheets Operating system development Compilers and assemblers Network drivers Interpreters 2.3 Structure of C Program Structure of the Program Every C program follows the structure of Program Documentation Section/Comment section Definition section Link Section/Include Section Global Declaration void main( ) function section { CU IDOL SELF LEARNING MATERIAL (SLM)
Fundamentals of C 35 Local declaration part funaction call statemenr; Executable part } returntype functionname( parameters list with data type) { Local declaration of variables; function statements; return statement; } 1. The documentation section consists of only comments. This section is also called the comment section, It is not compiled by the compiler, It is a user section. Use of comments The Single line comment can be written by // (double slash) and Multi line comment comment can be written by /* ——— —————— */ Comments (remarks) may appear anywhere within a program, as long as they are placed within the delimiters /* and */ (e.g., /* this is a comment */). Such comments are helpful in identifying the program’s principal features or in explaining the underlying logic of various program features. 2. Definition Section: All the symbolic constants are written in definition section. Macros are known as symbolic constants. 3. The Link section provides instruction to the compiler to take function from system library. E.g., To use the input and output functions we use #include<stdio.h>, this is a link file, Please note that the character (#) should be in the first column and there is no semicolon at the end of this line. CU IDOL SELF LEARNING MATERIAL (SLM)
36 Computer Programming 4. In the Global Declaration section the variable used in more than one function can be declared in Global section. Functions can be declared in this section. 5. Every C program consist of one or more function, one of which must be called the main( ) function. The program will always begin by executing the main( ) function, which may access other functions. Any other function definitions must be defined separately, either ahead of or after main( ) function. Each function must contain: 1. A function heading, which consists of the function name, followed by an optional list of arguments, enclosed in parentheses. A function header must contain returntype function_name and its arguments. For example: void sum(int a, int b) is the function header 2. A list of argument declarations, if arguments are included in the heading. 3. A function body, which comprises the remainder of the function. The arguments are symbols that represent information being passed between the function and other parts of the program. (Arguments are also referred to as parameters.) Each function body is enclosed within a pair of braces, i.e., { }. The braces may contain one or more elementary statements (called expression statements) and other function body. Each expression statement must end with a semicolon (;). The C program may contain one or more sections Both the parts must be placed between opening and closing braces. The program execution begins with the opening braces of main( ) function. Thus the closing brace of main( ) function is the logical end of the program. Rules for Writing the Program 1. Every function in a program has a unique name and is designed to perform a specific task. The task is defined by a group of instruction. 2. main() function is always the first function which is called when a program execution begins. CU IDOL SELF LEARNING MATERIAL (SLM)
Fundamentals of C 37 3. Each instruction in a function is written as a separate statement. 4. The statements within a function, i.e., function body should be enclosed within a pair of braces { }. The closing brace of the main( ) function signals the end of the program. 5. All C statements are terminated by semicolon ( ; ) 6. No blank spaces are allowed within a word. However, two words may be separated by blank spaces to improve the readability of the statement. A Simple Program for printing message #include<stdio.h> void main() { printf(“Programming is fun.”) ; } Output: Programming is fun. Working Methology of ‘C’: Object Code Linked Code .Obj .Exe Source Code .C 2.4 Comments Comments are user defined help can be written anywhere in the program. Comments can be written in documentation section. Comment section is not Executable by the compiler. It is comment section, comments can be Single line comment or Multiline comment The Single line comment can be written by // (double slash) Example of Single Line Comment // program to print hello Example of Multiline comment comment can be written by CU IDOL SELF LEARNING MATERIAL (SLM)
38 Computer Programming /* ——— —————— */ 2.5 Header Files and Body 1. Link Section/Include Section File Inclusion: #include The second preprocessor directive causes one file to be included in another. The preprocessor command for file inclusion looks like this: #include <file_name> The source code of the file “file_name” is included in the main( ) function C program where “#include <file_name>” is mentioned. Of course this assuming that the file being included is existing. This directive is normally used for very large programs which can be divided into several different files each containing related functions. These files are #include at the beginning of main() function program file. Secondly, the commonly needed functions and macro definitions can be stored in a file, and that file can be included in every program later. The prototypes of all the library functions are grouped into different categories and then stored in different header files. For example prototypes of all mathematics related functions are stored in the header file ‘math.h’ which can be included as shown below: #include<math.h> The #include directive can be used in two ways as discussed below: #include “filename” #include <filename> #include “sum.c” #include “c:\\employee.c” It is Link section also called as include section, this section is prefixed by # sign # include<stdio.h> # include<conio.h> CU IDOL SELF LEARNING MATERIAL (SLM)
Fundamentals of C 39 # include<math.h> #include<stdlib.h> # is preprocessor directive which gives direction to the compiler that include specified header file from Library to main( ) function program. Header File Description #include<stdio.h> It is standard input output header files, consist of standard input function #include<conio.h> scanf() and standard output function printf() #include<math.h> #include<stdlib.h It is console input output header file, consist of clrscr() function to clear #include<string.h> screen and getch() function to get character to see the output on screen. #include<Ctype.h> It is Math Medical Header File consist of all mathematical functions, sin( ), cos( ), tan( ), sqrt( ). It is Standard Library File consist of Exit( ) function It is String Header File consist of string functions, strcmp( ), strlen( ), strcpy( ), strrev( ), strcat( ). All character handling functions are defined in this header file.functionsIt consist of islower( ), isupper( ), isdigit( ) 2.6 Data Types C supports several different types of data, each of which may be represented differently within the computer’s memory. C data types are defined as the data storage format that a variable can store a data to perform a specific operation. Data types are used to define a variable before to use in a program. Size of variable, constant and array are determined by data types. CU IDOL SELF LEARNING MATERIAL (SLM)
40 Computer Programming The basic data types are listed below. Inbuilt Data Types Data Types Primitive User Defined Data Types Non Primitive Numeric Structure integer floating point Arrays double float Union byte short int long non-numeric character boolean Fig. 2.3: The Basic Data Types Built-in-type 1. Integer type: The data types in this type are int and char. The modifiers signed, unsigned, long and short may be applied to character and integer basic data type. The size of int is 2 bytes and the size of char is 1 byte. Example: int a=10; 2. Floating Type: The data type in this can be float or double. The size of the float is 4 bytes and size of double is 8 bytes. It is used to store the numbers with decimal. The modifier long can be applied to double and the size of long double is 10 bytes. Example: float per=95.3; float data type supports single precision numbers. double data type supports double precision numbers and having size greater than float. long double can store double precision numbers and having size greater than double. CU IDOL SELF LEARNING MATERIAL (SLM)
Fundamentals of C 41 3. char – characters stored like type char, It stores single character, Sixe is 1 byte. 4. void: void is used for: To specify the return type of a function when it is not returning any value. To indicate an empty argument list to a function Table 2.1: List of All Datatype in C programming language Data Type Format Specifier Size Data Range char %c 1 Byte -128 to +127 unsigned char %c 8 Byte 0 to 255 int %d 2 Byte -32768 to +32767 long int %ld 4 Byte -231 to +2 31 unsigned int %u 2 Byte 0 to 65535 float %f 4 Byte -3.4e38 to +3.4e38 double %lf 8 Byte -1.7e38 to +1.7e38 long double %Lf 12-16 Byte -3.4e38 to +3.4e38 2.7 Constants Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well. Constants are treated just like regular variables except that their values cannot be modified after their definition. You use a named constant when you want to assign a useful name for a value that will never be changed during a program’s execution. There are two simple ways in C to define constants: Using #define preprocessor Using const keyword CU IDOL SELF LEARNING MATERIAL (SLM)
42 Computer Programming The #define Preprocessor Given below is the form to use #define preprocessor to define a constant: #define identifier value #define WIDTH 10 The Constant Keyword You can use const prefix to declare constants with a specific type as follows: const type variable = value; constint WIDTH = 10; Constants Numeric Character Constants Constants Integer Real Single String Constants Constants Character Constants Constants e.g. 123,-123,0 e.g. e.g. ‘5’,’x’,’a’ e.g. “Hello”, 0.0083,0.95 “1+2+3+4+5...” Fig. 2.4: The Constant Keyword Integer Constants An integer constant is an integer quantity which contains a sequence of digits. It should not have a decimal point. Blanks and commas are not allowed within an integer constant. An integer constant can be either +ve or -ve. The constant must lie within the range of the declared data type (including qualifiers long, short, etc.). Example of valid integer constants: 976 8987 5 -25 etc. Example of invalid integer constants: 78.43 7-8 89,76 etc. CU IDOL SELF LEARNING MATERIAL (SLM)
Fundamentals of C 43 An integer constant can be either Decimal, Hexa Decimal or Octal. See the table below to understand how these three different constants are defined in C. Floating Point Constants They are also known as real constants. A real constant contains a decimal point or an exponent. It can be either +ve or -ve. Commas and blank space are not allowed within a real constant. Examples: 254.175, -16.47 -0.5e-7 +4.1e8 Character Constant A character constant is a character which is enclosed in single quotes. A character constant is of size 1 byte and can contain only 1 character. A character can be an alphabet like a,b,A,C etc or a special character like &,^, $, #,@ etc or a single digit from 0 through 9. It can also be an escape sequence character like space ‘ ‘ or a null character ‘\\o’ or a new line ‘\\n’ etc. Example: ‘A’ ‘a’ ‘b’ ‘8’ ‘#’ etc. Each character has a corresponding ASCII value. ASCII value is the numeric code of a particular character and is stored inside the machine’s character set. Example: A sample program of printing ASCII value of a character can be included. #include<stdio.h> int main() { char ch; printf(“Enter any character:”); scanf(“%c”, &ch); printf(“ASCII value is %d”, ch); return 0; } String Constants (a) A string constant is a collection of characters enclosed in double quotations “ “ (b) It may contain alphabets, digits, special characters and blank space. CU IDOL SELF LEARNING MATERIAL (SLM)
Search
Read the Text Version
- 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
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344