unit 1.pdf
Document Details
Uploaded by PowerfulTin
Galgotias College of Engineering and Technology
Tags
Related
- Program Development Process PDF
- High-Level Programming I - Program Development Process PDF
- Prime Number Calculations Exercise (PDF)
- TOPIC 1. Overview of Computer Programming and Problem Solving.pdf
- 1- Steps in Program Development.pdf
- Lecture 1: Subject Introduction and Overview on Structured Programming Approach PDF
Full Transcript
Lecture Notes-Unit Wise Programming for Problem Solving (BCS-101/BCS-201) Course Outcome ( CO) Bloom’s...
Lecture Notes-Unit Wise Programming for Problem Solving (BCS-101/BCS-201) Course Outcome ( CO) Bloom’s Level At the End of Course , the Student will be Able to Understand CO 1 To Develop Simple Algorithms for Arithmetic and K2, K3 Logical Problems. CO 2 To Translate the Algorithms to Programs & K3 Execution (in C Language). CO 3 To Implement Conditional Branching, Iteration K3 and Recursion. CO 4 To Decompose a Problem into Functions and K4 Synthesize a Complete Program Using Divide and Conquer Approach. CO 5 To Use Arrays, Pointers and Structures to K2, K3 Develop Algorithms and Programs. K1‐ Remember, K2‐ Understand, K3‐ Apply, K4‐ Analyze , K5‐ Evaluate , K6‐ Create Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 1 Lecture Notes Index L. Number Content of Syllabus Page Number Unit Number CO-1: To develop simple algorithms for arithmetic and logical problems. 1. Introduction of subject, Syllabus, COs, Teaching-learning strategy. 3 2. Components of a computer system: Memory, processor ,I/O Devices, storage 9 3. Operating System and its functions 16 Unit – 1 4. Idea of Algorithm: Representation of Algorithm, Pseudo code, Flowchart 20 L1-One Lecture:Examples of flowchart and algorithms CO-2: To translate the algorithms to programs & execution (in C language). 5. Programming Basics: Concept of assembler, compiler, interpreter, loader and linker 29 Structure of C program, First C program 6. Compilation and Execution steps, Errors 33 7. Components of C language , Fundamental Data Types, Variables and Memorylocations, 40 Type Conversion Unit – 1 8. Standard I/O in C 48 9. Storage classes 52 10. Types of Operators 58 Unit – 2 11. Operator Precedence and Associativity & Solving Expressions 63 L2,L3 Two Lectures:Basic C programs CO-3: To implement conditional branching, iteration and recursion. 12. Branching: Applying if ,if-else and nested if statements with examples 67 13. Branching-Applying switch statement, Use of Break & Default 71 Unit – 2 14. Iteration- Loops (While, do while,for,multiple loop variable) 73 Unit – 3 L4,L5,L6,L7,L8 Five Lectures; Programs Based on Branching, Iteration CO-4: To decompose a problem into functions and synthesize a program using D &C approach. 15. Functions Basics: Introduction ,Types of functions 82 16. Passing Parameters -Call by Value 86 17. Passing Parameters - Call by Reference 89 Unit – 3 18. Recursive Functions 91 L9,L10 Two Lectures:Programs Based on user defined functions CO-5: To use arrays, pointers and structures to develop algorithms and programs. 19. Single Dimensional Arrays : Notation, Manipulation 95 20. Multi-Dimensional Array :Notation ,Manipulation 98 21. Array and Functions 103 22. Strings 106 23. Structure, Array of structures, Self-referential structures 112 24. Union, Enumerated data types 116 25. Basic Algorithms: Searching 119 Unit – 4 26. Basic Sorting Algorithms: Bubble 123 27. Basic Sorting Algorithms:Insertion 126 28. Basic Sorting Algorithms: Selection 128 29. Finding roots of equations, Notion of order of complexity 130 L11,L12 Two Lectures :Programs based on Arrays CO-5: To use arrays, pointers and structures to develop algorithms and programs. 30. Pointers: Introduction, Declaration, Applications 133 31. Introduction to dynamic memory allocation (malloc, calloc, realloc, free) 138 32. Notion of linked list (no implementation) 143 33. File Handling 145 Unit – 5 34. Standard C preprocessors, Defining and calling macros, command-line arguments 149 L13,L14,l15 Three Lectures :Programs based on applications of pointers L16,L17,L18 Three Lectures : Revision Total Lectures:34+18L=52 Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 2 Lecture Notes || Unit -1 || Lecture Number-1 Topic Introduction of subject, Syllabus, COs, Teaching-learning strategy. Lecture Objective To know about subject, Syllabus, COs and Teaching Learning Strategy. Lecture structure What do you mean by the term “Programming for Problem solving”? Syllabus What is NBA? Course Outcome Vs Programme Outcome Teaching Learning Strategy Related State COs of PPS. Questions What is NBA? Differentiate PO and CO. What do you mean by the term “Programming for Problem Solving”? Solving problems is the core of computer science. Programmers must first understand how a human solves a problem, then understand how to translate this "algorithm" into something a computer can do, and finally how to "write" the specific syntax (required by a computer) to get the job done. It is sometimes the case that a machine will solve a problem in a completely different way than a human. Especially when it comes to programming, problem-solving is the must. If you do not develop sound problem-solving skills, you will end up messing around with a given problem, and you would not be able to obtain a solution for ages. Computer Programmers are problem solvers. In order to solve a problem on a computer you must: Know how to represent the information (data) describing the problem &Determine the steps to transform the information from one representation into another. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 3 Syllabus Unit Wise Unit – 1 : (Introduction to Programming) Introduction to components of a computer system: Memory, processor, I/O Devices, storage, operating system, Concept of assembler, compiler, interpreter, loader and linker. Idea of Algorithm: Representation of Algorithm, Flowchart, Pseudo code with examples, From algorithms to programs, source code. Programming Basics: Structure of C program, writing and executing the first C program,Syntax and logical errors in compilation, object and executable code. Components of C language. Standard I/O in C, Fundamental data types, Variables and memory locations, Storage classes. Unit – 2 : (Arithmetic expressions & Conditional Branching) Arithmetic expressions and precedence: Operators and expression using numeric and relational operators, mixed operands, type conversion, logical operators, bit operations, assignment operator, operator precedence and associativity. Conditional Branching: Applying if and switch statements, nesting if and else, use of break and default with switch. Unit– 3 : (Loops ) Iteration and loops: use of while, do while and for loops, multiple loop variables, use ofbreak and continue statements. Arrays: Array notation and representation, manipulating array elements, using multi- dimensional arrays. Character arrays and strings, Structure, union, enumerated data types, Array of structures, passing arrays to functions. Unit – 4 : (Arrays & Basic Algorithms) Functions Functions: Introduction, types of functions, functions with array, passing parameters tofunctions, call by value, call by reference, recursive functions. Basic Algorithms: Searching &Basic Sorting Algorithms (Bubble, Insertion and Selection), Finding roots of equations, Notion of order of complexity. Unit– 5 :( Pointer& File Handling) Pointers: Introduction, declaration, applications, Introduction to dynamic memory allocation (malloc, calloc, realloc, free), Use of pointers in self-referential structures, notion of linked list (no implementation) File handling: File I/O functions, Standard C preprocessors, defining and calling macros, command-line arguments. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 4 Syllabus CO Wise CO-1: To develop simple algorithms for arithmetic and logical problems. Introduction of subject, Syllabus, CO, PO, teaching-learning strategy. Introduction to components of a computer system: Memory, processor I/O Devices, storage operating system Concept of assembler, compiler, interpreter, loader and linker. Idea of Algorithm: Representation of Algorithm Flowchart, Pseudo code with examples, From algorithms to programs, source code. CO-2:To translate the algorithms to programs & execution (in C language). Programming Basics: Structure of C Program Writing and executing the first C program, Syntax and logical errors in compilation, object and executable code. Components of C language. Standard I/O in C, Fundamental data types, Variables and memory locations, Storage classes Operators and expression using numeric and relational operators, mixed operands, Type conversion Logical operators, bit operations, assignment operator, Operator precedence and associativity. CO-3: To implement conditional branching, iteration and recursion. Applying if statement Applying switch statement Nesting if and else Use of break and default with switch. Use of while, do while Use of for loops Multiple loop variables, use of break and continue statements. CO-4: To decompose a problem into functions and synthesize a complete program using divide and conquer approach. Functions Functions: Introduction, types of functions, functions with array, passing parameters to functions, call by value, call by reference, recursive functions. Basic Algorithms: Searching &Basic Sorting Algorithms (Bubble, Insertion and Selection), Finding roots of equations, Notion of order of complexity. CO-5: To use arrays, pointers and structures to develop algorithms and programs. Unit– 5 :( Pointer& File Handling) Pointers: Introduction, declaration, applications, Introduction to dynamic memory allocation (malloc, calloc, realloc, free), Use of pointers in self-referential structures, notion of linked list (no implementation) File handling: File I/O functions, Standard C preprocessors, defining and calling macros, command-line arguments. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 5 What is NBA? The National Board of Accreditation (NBA) is one of the two major bodies responsible for accreditation of higher education institutions in India, along with the National Assessment and Accreditation Council (NAAC). NBA accredits technical programmes, such engineering and management programmes, while NAAC accredits general colleges and universities. NBA was established by the All India Council for Technical Education (AICTE) in 1994 and operated as an autonomous body since 2010. In 2014 it was granted a full membership status in the Washington Accord. The NBA accredits programmes and not institutes. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 6 Course Outcome Vs Programme Outcome CO Course Outcome(Statement) CO1 To develop simple algorithms for arithmetic and logical problems. CO2 To translate the algorithms to programs & execution (in C language). CO3 To implement conditional branching, iteration and recursion. CO4 To decompose a problem into functions and synthesize a complete program using divide and conquer approach. CO5 To use arrays, pointers and structures to develop algorithms and programs.) PO Statement Engineering knowledge: Apply the knowledge of mathematics, science, engineering PO1 fundamentals, and an engineering specialization to the solution of complex computer engineering problems. Problem analysis: Identify, formulate, review research literature, and analyze complex PO2 computer engineering problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences. Design/development of solutions: Design solutions for complex computer engineering problems and design system components or processes that meet the specific needs with appropriate PO3 considerations for the public health and safety, and the cultural, societal, and environmental considerations. Conduct investigations of complex problems: Use research-based knowledge and research PO4 methods including design of experiments, analysis and interpretation of data, and synthesis of the information to provide conclusions Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern PO5 engineering and IT tools including prediction and modeling to complex engineering activities with an understanding of the limitations The engineer and society: Apply reasoning informed by the contextual knowledge to assess PO6 societal, health, safety, legal and cultural issues and the consequent relevant to the professional engineering practices Environment and sustainability: Understand the impact of the professional engineering PO7 solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development Ethics: Applyethical principles and commit to professional ethics and responsibilities and norm PO8 of the engineering practices Individual and team work: Function effectively as an individual, and as a member or leader in PO9 diverse teams, and in multidisciplinary settings Communications: Communicate effectively on complex engineering activities with the engineering community and with society at large, such as, being able to comprehend and write PO10 effective reports and design documentation, make effective presentations, and give and receive clear instructions Project management and finance: Demonstrate knowledge and understanding of the PO11 engineering and management principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in multidisciplinary environments. Life-long learning: Recognize the need for, and have the preparation and ability to engage in PO12 independent and life learning in the broadest context of technological change. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 7 Teaching Learning Strategy Teaching- Syllabus coverage (including revisions and practice programs) through 52 online/offline lectures Lecture Notes/PPT/Video Lectures will be provided just after the completion of lecture. Revision /Q & A sessions after each CO syllabus coverage. For fast learner’s initiation of project based learning. (As applicable) Assessment- 2 test (CAE-1 & CAE-2) 5 Online /Offline quiz (CO wise) Teacher Assessment -10 Marks based on 5 CO wise assignment Attendance-10 Marks (Criteria- you`ll get 10 marks if attendance is more than 90%) Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 8 Lecture Notes || Unit -1 || CO1 || Lecture Number-2 Topic Introduction to components of a computer system: Memory, Processor, I/O Devices CO Covered To develop simple algorithms for arithmetic and logical problems. Lecture Objective To know about working and components of digital computer. Lecture structure Pre-requisite Keywords-Data, Information, Program, Software, Hardware Introduction to computer Explanation of working of digital computer using Block diagram Input Unit Storing Processing Output Unit Controlling Memory Organization Related Questions (i) Explain working and components of digital computer with proper block diagram in detail. (ii) What do you mean by Memory Hierarchy? Extra topics for fast Digital Vs analog,Motherboard,Memory organization,ASCII,History of learners/Topics beyond computers,EBCDIC,ISO,UNICODE syllabus Pre-requisite keywords Program- A program can be defined as a collection of instructions written to perform any user`s defined task in computer. Data- Any raw facts Information- Collection of data that has some meaning (Meaningful Data) Hardware- Computer hardware is a collective term used to describe any of the physical components of an analog or digital computer. Software- Software commands the hardware what to do & how to do it. Together, the hardware & software form the computer system. This software is further classified as system software & application software. System Software- System software are a set of programs, responsible for running the computer, controlling various operations of computer systems and management of computer resources. They act as an interface between the hardware of the computer & the application software. E.g.: Operating System. Application software Application Software is a set of programs designed to solve a particular problem for users. It allows the end user to do something besides simply running the hardware. E.g.: Web Browser, Gaming Software, etc. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 9 Introduction to computers Right from its inception, to the present day, all computer system (irrespective of their shape & size) perform the following 5 basic operations. It converts the raw input data into information, which is useful to the users. Input: It is the process of entering data & instructions to the computer system. Storing: The data & instructions are stored for either initial or additional processing, as & when required. Processing: It requires performing arithmetic or logical operation on the saved data to convert it into useful information. Output: It is the process of producing the output data to the end user. Controlling: The above operations have to be directed in a particular sequence to be completed. Explanation of working of digital computer using Block diagram Input Unit We need to first enter the data & instruction in the computer system, before any computation begins. This task is accomplished by the input devices. (The data accepted is in a human readable form. The input device converts it into a computer readable form). Input device: The input device is the means through which data and instructions enter in a computer. 1. Camera - The camera transmits a picture from one computer to another, or can be used to record a short video. 2. Compact Disc (CD) - CDs store information. The CD can then be put into another computer, and the information can be opened and added or used on the second computer. Note: A CD-R or CD-RW can also be used as an OUTPUT device. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 10 3. Keyboard - The keyboard is a way to input letters or numbers into different applications or programs. A keyboard also has special keys that help operate the computer. 4. Mouse - The mouse is used to open and close files, navigate web sites, and click on a lot of commands (to tell the computer what to do) when using different applications. 5. Microphone - A microphone is used to record sound. The sound is then saved as a sound file on the computer. 6. Scanner - A scanner is used to copy pictures or other things and save them as files on the computer. 7. Joystick - A joystick is used to move the cursor from place to place, and to click on various items in programs. A joystick is used mostly for computer games. 8. Bar Code Scanner - A bar code scanner scans a little label that has a bar code on it. The information is then saved on the computer. Bar code scanners are used in libraries a lot. Storing/Storage Unit The data & instruction that are entered have to be stored in the computer. Similarly, the end results & the intermediate results also have to be stored somewhere before being passed to the output unit. The storage unit provides solution to all these issues. The storage unit is designed to save the initial data, the intermediate result & the final result. They are of two types: Primary storage & Secondary storage. Primary Storage: The primary storage, also called as the main memory, holds the data when the computer is currently on. As soon as the system is switched off or restarted, the information held in primary storage disappears (i.e. it is volatile in nature). Moreover, the primary storage normally has a limited storage capacity, because it is very expensive as it is made up of semiconductor devices.RAM is a primary storage. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 11 Secondary Storage: The secondary storage, also called as the auxiliary storage, handles the storage limitation & the volatile nature of the primary memory. It can retain information even when the system is off. It is basically used for holding the program instructions & data on which the computer is not working on currently, but needs to process them later.for example- a. Magnetic Disk The Magnetic Disk is Flat, circular platter with metallic coating that is rotated beneath read/write heads. It is a Random access device; read/write head can be moved to any location on the platter. b. floppy Disk These are small removable disks that are plastic coated with magnetic recording material. Floppy disks are typically 3.5″ in size (diameter) and can hold 1.44 MB of data. This portable storage device is a rewritable media and can be reused a number of times. Floppy disks are commonly used to move files between different computers. The main disadvantage of floppy disks is that they can be damaged easily and, therefore, are not very reliable. c. Hard disk A hard disk consists of one or more rigid metal plates coated with a metal oxide material that allows data to be magnetically recorded on the surface of the platters. The hard disk platters spin at a high rate of speed, typically 5400 to 7200 revolutions per minute (RPM). Storage capacities of hard disks for personal computers range from 10 GB to 120 GB (one billion bytes are called a gigabyte). d. CD: Compact Disk (CD) is portable disk having data storage capacity between 650-700 MB. It can hold large amount of information such as music, full-motion videos, and text etc. It contains digital information that can be read, but cannot be rewritten. Separate drives exist for reading and writing CDs. Since it is a very Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 12 reliable storage media, it is very often used as a medium for distributing large amount of information to large number of users. e. DVD Digital Versatile Disk (DVD) is similar to a CD but has larger storage capacity and enormous clarity. Depending upon the disk type it can store several Gigabytes of data (as opposed to around 650MB of a CD). DVDs are primarily used to store music or movies and can be played back on your television or the computer too. They are not rewritable media. It’s also termed DVD (Digital Video Disk) Processing Central Processing Unit: Together the Control Unit & the Arithmetic Logic Unit are called as the Central Processing Unit (CPU). The CPU is the brain of the computer. Like in humans, the major decisions are taken by the brain itself & other body parts function as directed by the brain. Similarly, in a computer system, all the major calculations & comparisons are made inside the CPU. The CPU is responsible for activating & controlling the operation of other units of the computer system. Arithmetic Logic Unit: The actual execution of the instructions (arithmetic or logical operations) takes place over here. The data & instructions stored in the primary storage are transferred as & when required. No processing is done in the primary storage. Intermediate results that are generated in ALU are temporarily transferred back to the primary storage, until needed later. Hence, data may move from the primary storage to ALU & back again to storage, many times, before the processing is done. OutputUnit The job of an output unit is just the opposite of an input unit. It accepts the results produced by the computer in coded form. It converts these coded results to human readable form. Finally, it displays the converted results to the outside world with the help of output devices (E.g.: monitors, printers, projectors etc.). Output device: Device that lets you see what the computer has accomplished. 1. Monitor -A monitor is the screen on which words, numbers, and graphics can be seem. The monitor is the most common output device. 2. Compact Disk - Some compact disks can be used to put information on. This is called burning information to a CD. NOTE: A CD can also be an input device. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 13 3. Printer - A printer prints whatever is on the monitor onto paper. Printers can print words, numbers, or pictures. 4. Speaker- A speaker gives you sound output from your computer. Some speakers are built into the computer and some are separate. 5. Headphones - Headphones give sound output from the computer. They are similar to speakers, except they are worn on the ears so only one person can hear the output at a time. Control Unit: This unit controls the operations of all parts of the computer but does not carry out any actual data processing. It is responsible for the transfer of data and instructions among other units of the computer. It manages and coordinates all the units of the system. It also communicates with Input/Output devices for transfer of data or results from the storage units. Memory Organization in Computer A memory unit is the collection of storage units or devices together. The memory unit stores the binary information in the form of bits. Generally, memory/storage is classified into 2 categories: Volatile Memory: This loses its data, when power is switched off. Non-Volatile Memory: This is a permanent storage and does not lose any data when power is switched off. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 14 The total memory capacity of a computer can be visualized by hierarchy of components. The memory hierarchy system consists of all storage devices contained in a computer system from the slow Auxiliary Memory to fast Main Memory and to smaller Cache memory. Auxiliary memory access time is generally 1000 times that of the main memory, hence it is at the bottom of the hierarchy. The main memory occupies the central position because it is equipped to communicate directly with the CPU and with auxiliary memory devices through Input/output processor (I/O). When the program not residing in main memory is needed by the CPU, they are brought in from auxiliary memory. Programs not currently needed in main memory are transferred into auxiliary memory to provide space in main memory for other programs that are currently in use. The cache memory is used to store program data which is currently being executed in the CPU. Approximate access time ratio between cache memory and main memory is about 1 to 7~10 Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 15 Lecture Notes || Unit -1 || CO1 || Lecture Number-3 Topic Operating System CO Covered To develop simple algorithms for arithmetic and logical problems. Lecture Objective To learn definition of OS and it`s functionality Lecture structure Pre-requisite Keywords Definition & Importance of OS. Functions of OS Related Questions i.Define Opreating System.Explain functions of OS in detail. ii.“An OS acts as resource allocator” justify the statement. Extra topics for fast Kernel, Android, OS, Linux, Virus, DOS, NOS, Device Drivers, DLL, learners/Topics beyond Multiprogramming,Multitasking,Multiprocessor,Multithreading syllabus Pre-requisite keywords Program- A program is a set of instruction written to implement any task. Process- A program in execution is known as process. File- A file can be understood as a container in a computer system for storing information/data. Data/information Network- Computer network can be defined as the group of computers connected for the purpose of communicating data from one computer to other. Resources- In computer, resources can be CPU, RAM, Input/Output devices, Processor. Multiprogramming- A computer running more than one program at a time (like running Excel and Firefox simultaneously). Bug- Bug is a logical error which generate wrong output. Debugging- Identification of bug is debugging. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 16 Definition & Importance of OS An operating system (OS) is a collection of software that manages computer hardware resources and provides common services for computer programs. Functions of OS Following are some of important functions of an operating System. Memory Management Processor Management Device Management File Management Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 17 Security Control over system performance Job accounting Error detecting aids Coordination between other software and users Memory Management Memory management refers to management of Primary Memory or Main Memory. Main memory is a large array of words or bytes where each word or byte has its own address. Main memory provides a fast storage that can be accessed directly by the CPU. For a program to be executed, it must in the main memory. An Operating System does the following activities for memory management − a. Keeps tracks of primary memory, i.e., what part of it are in use by whom, what part are not in use. b. In multiprogramming, the OS decides which process will get memory when and how much. c. Allocates the memory when a process requests it to do so. d. De-allocates the memory when a process no longer needs it or has been terminated. Processor Management In multiprogramming environment, the OS decides which process gets the processor when and for how much time. This function is called process scheduling. An Operating System does the following activities for processor management − Keeps tracks of processor and status of process. The program responsible for this task is known as traffic controller. Allocates the processor (CPU) to a process. De-allocates processor when a process is no longer required. Device Management An Operating System manages device communication via their respective drivers. It does the following activities for device management − Keeps tracks of all devices. Program responsible for this task is known as the I/O controller. Decides which process gets the device when and for how much time. Allocates the device in the efficient way. De-allocates devices. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 18 File Management A file system is normally organized into directories for easy navigation and usage. These directories may contain files and other directions. An Operating System does the following activities for file management − Keeps track of information, location, uses, status etc. The collective facilities are often known as file system. Decides who gets the resources. Allocates the resources. De-allocates the resources. Other Important Activities Following are some of the important activities that an Operating System performs − i. Security − By means of password and similar other techniques, it prevents unauthorized access to programs and data. ii. Control over system performance − Recording delays between request for a service and response from the system. iii. Job accounting − Keeping track of time and resources used by various jobs and users. iv. Error detecting aids − Production of error messages, and other debugging and error detecting aids. v. Coordination between other softwares and users − Coordination and assignment of compilers, interpreters, assemblers and other software to the various users of the computer systems. Common services provided by an operating system − Program execution I/O operations File System manipulation Communication Error Detection Resource Allocation Protection Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 19 Lecture Notes || Unit -1 || CO1 || Lecture Number-4 Topic Idea of Algorithm: Representation of Algorithm, Pseudo code, Flowchart CO Covered To develop simple algorithms for arithmetic and logical problems. Lecture Objective To explore and learn the algorithm and pseudocode with examples Lecture structure Pre-requisite Keywords Algorithm with Example Characteristics of algorithm What is pseudocode? Examples of pseudocode Flowchart and its representation Related Questions 1. Define algorithm. Also explain its characteristics. 2. Compare algorithm and pseudocode. 3. Write algorithm and draw flowchart for the following problems- a. To calculate roots of quadratic equation b. To find greatest number among three numbers. c. To calculate the grades of any student d. To calculate factorial of any given number Extra topics for fast Design algorithms and draw flowchart for -a)To print Fibonacci Series up to nth term b) To learners/Topics beyond print first 100 prime numbers c)To reverse digits of any given number syllabus Pre-requisite Keywords Problem statement- A problem statement is usually one or two sentences to explain the problem you are going to address by programming. Algorithm with Example Algorithm: It’s an organized logical sequence of the actions or the approach towards a particular problem. A programmer implements an algorithm to solve a problem. Algorithms are expressed using natural verbal but somewhat technical annotations. Example: Algorithm to calculate factorial 1. Start 2. Input number N (for which we want to calculate factorial.) 3. Let M=1 and F=1. 4. F=F*M. 5. Is M=N? 6. If NO then M=M+1 and go to step 3. 7. If YES then output F 8. End Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 20 Characteristics of algorithm Input specified-The input is the data to be transformed during the computation to produce the output. Input precision requires that you know what kind of data, how much and what form the data should be required for algorithm. Output specified-The output is the data resulting from the computation (your intended result). Output precision also requires that you know what kind of data, how much and what form the output should be (or even if there will be any output at all!) Definiteness-Each statement of algorithm should be clear, well defined and precise in nature. Effectiveness-For an algorithm to be effective, it means that all those steps that are required to get to output MUST BE DOABLE! Finiteness-The algorithm should have sequence of finite instructions. What is pseudocode? Pseudo code: a. It’s simply an implementation of an algorithm in the form of annotations and informative text written in plain English. It has no syntax like any of the programming language and thus can’t be compiled or interpreted by the computer. b. Pseudocode is an artificial and informal language that helps programmers develop algorithms. Pseudocode is a "text-based" detail (algorithmic) design tool. c. The rules of Pseudocode are reasonably straightforward. All statements showing "dependency" are to be indented. These include while, do, for, if, switch. Examples below will illustrate this notion. d. It is a methodology that allows the programmer to represent the implementation of an algorithm. Simply, we can say that it’s the cooked up representation of an algorithm. e. Often at times, algorithms are represented with the help of pseudo codes as they can be interpreted by programmers no matter what their programming background or knowledge is. f. Pseudo code, as the name suggests, is a false code or a representation of code which can be understood by even a layman with some school level programming knowledge. Advantages of Pseudocode Improves the readability of any approach. It’s one of the best approaches to start implementation of an algorithm. Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough documentation, so the program of one developer can be understood easily when a pseudo code is written out. In industries, the approach of documentation is essential. And that’s where a pseudo- code proves vital. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 21 The main goal of a pseudo code is to explain what exactly each line of a program should do, hence making the code construction phase easier for the programmer. How to write a Pseudo-code? Arrange the sequence of tasks and write the pseudocode accordingly. Start with the statement of a pseudo code which establishes the main goal or the aim. Example: This program will allow the user to check The number whether it's even or odd. The way the if-else, for, while loops are indented in a program, indent the statements likewise, as it helps to comprehend the decision control and execution mechanism. They also improve the readability to a great extent. Example: if "1" print response "I am case 1" if "2" print response "I am case 2" Use appropriate naming conventions. The human tendency follows the approach to follow what we see. If a programmer goes through a pseudo code, his approach will be the same as per it, so the naming must be simple and distinct. Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code abstract. Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in programming. Check whether all the sections of a pseudo code is complete, finite and clear to understand and comprehend. Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to understand even for a layman or client, hence don’t incorporate too many technical terms. Examples of pseudocode *For students: Can you guess for what purpose the following pseudocode has been written? 1. If student's grade is greater than or equal to 60 Print "passed" Else Print "failed" Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 22 2. Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Set the class average to the total divided by ten Print the class average. 3. Initialize total to zero Initialize counter to zero Input the first grade while the user has not as yet entered the sentinel add this grade into the running total add one to the grade counter input the next grade (possibly the sentinel) if the counter is not equal to zero set the average to the total divided by the counter print the average else print 'no grades were entered' 4. initialize passes to zero initialize failures to zero initialize student to one while student counter is less than or equal to ten input the next exam result if the student passed add one to passes else add one to failures add one to student counter print the number of passes print the number of failures if eight or more students passed print "raise tuition" Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 23 Flowchart and its representation A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. This diagrammatic representation can give a step-by-step solution to a given problem. Example: For factorial. Advantages of Using Flowchart: - Communication: - Flowcharts are better way of communicating the logic of a system to all concerned. Effective analysis: - With the help of flowchart, problem can be analyzed in more effective way. Proper documentation: - Program flowcharts serve as a good program documentation, which is needed for various purposes. Efficient Program Maintenance: - The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part Disadvantages of Using Flowchart: - Complex logic: - Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and clumsy. Alterations and Modifications: - If alterations are required the flowchart may require re-drawing completely. Reproduction: - As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem. The essentials of what is done can easily be lost in the technical details of how it is done. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 24 Some examples of flow chart and algorithm 1. Example: Calculate the Interest of a Bank Deposit Algorithm: (i) Step 1: Read amount, (ii) Step 2: Read years, (iii) Step 3: Read rate, (iv) Step 4: Calculate the interest with formula "Interest=Amount*Years*Rate/100 (v) Step 5: Print interest, Flowchart: 2. Example: Determine and Output Whether Number N is Even or Odd Algorithm: (i) Step 1: Read number N, (ii) Step 2: Set remainder as N modulo 2, (iii) Step 3: If remainder is equal to 0 then number N is even, else number N is odd, (iv) Step 4: Print output. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 25 Flowchart: 3. Example: Determine Whether a Student Passed the Exam or Not: Algorithm: (i) Step 1: Input grades of 4 courses M1, M2, M3 and M4, (ii) Step 2: Calculate the average grade with formula "Grade=(M1+M2+M3+M4)/4" (iii) Step 3: If the average grade is less than 60, print "FAIL", else print "PASS". Flowchart: Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 26 4. Draw flowchart to find the largest among three different numbers entered by user. 5. Draw a flowchart to find all the roots of a quadratic equation ax2+bx+c=0 Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 27 6. Draw a flowchart to find the Fibonacci series till term≤1000. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 28 Lecture Notes || Unit -1 || CO2 || Lecture Number-5 Topic Programming Basics: Concept of assembler, compiler, interpreter, loader and linker Structure of C program, First C program CO Covered To translate the algorithms to programs & execution in C language Lecture Objective To get the idea of programing language translators and structure of C program Lecture structure Pre-requisite Keywords Programming Language Translators Structure of C Program First C program Related Questions 1. Explain structure of a C program with example. 2. Explain following terms-a)Assembler b)Interpreter c)Loader d)Linker e)Compiler Extra topics for fast History of computer languages, Compiler design issues, Types of compiler learners/Topics beyond syllabus Pre-requisite Keywords Computer Language- A language that is acceptable to a computer system is called a computer language or programming language and the process of creating a sequence of instructions in such a language is called programming or coding. A program is a set of instructions, written to perform a specific task by the computer. A set of large program is called software. To develop software, one must have knowledge of a programming language. Before moving on to any programming language, it is important to know about the various types of languages used by the computer. Just as every language like English, Hindi has its own grammatical rules; every computer languageis also bounded by rules known as syntax of that language. The user is bound by that syntax while communicating with the computer system. Computer languages are broadly classified as: a. Low Level Language: The term low level highlights the fact that it is closer to a language which the machine understands. The low level languages are classified as: Machine Language: This is the language (in the form of 0’s and 1’s, called binary numbers) understood directly by the computer. It is machine dependent. It is difficult to learn and even more difficult to write programs. Assembly Language: This is the language where the machine codes comprising of 0’sand 1’s are substituted by symbolic codes (called mnemonics) to improve their understanding. It is the first step to improve programming structure. Assembly language programming is simpler and less time Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 29 consuming than machine level programming, it is easier to locate and correct errors in assembly language than in machine language programs. It is also machine dependent. Programmers must have knowledge of the machine on which the program will run. b. High Level Language: a) Low level language requires extensive knowledge of the hardware since it is machine dependent. To overcome this limitation, high level language has been evolved which uses normal English, which is easy to understand to solve any problem. High level languages are computer independent and programming becomes quite easy and simple. Various high level languages are given below: b) BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easy to learn general purpose language. Mainly used in microcomputers in earlier days. c) COBOL (Common Business Oriented language): A standardized language used for commercial applications. d) FORTRAN (Formula Translation): Developed for solving mathematical and scientific problems. One of the most popular languages among scientific community. e) C: Structured Programming Language used for all purpose such as scientific application, commercial application, developing games etc. f) C++: Popular object oriented programming language, used for general purpose. Programming Language Translators As you know that high level language is machine independent and assembly language though it is machine dependent yet mnemonics that are being used to represent instructions are not directly understandable by the machine. Hence to make the machine understand the instructions provided by both the languages, programming language instructors are used. They transform the instruction prepared by programmers into a form which can be interpreted & executed by the computer. Flowing are the various tools to achieve this purpose: Compiler: The software that reads a program written in high level language and translates it into an equivalent program in machine language is called as compiler. The program written by the programmer in high level language is called source program and the program generated by the compiler after translation is called as object program. Interpreter: it also executes instructions written in a high level language. Both complier & interpreter have the same goal i.e. to convert high level language into binary instructions, but their method of execution is different. The complier converts the entire source code into machine level program, while the interpreter takes 1 statement, translates it, executes it & then again takes the next statement. Assembler: The software that reads a program written in assembly language and translates it into an equivalent program in machine language is called as assembler. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 30 Linker: A linker or link editor is a computer program that takes one or more object files generated by a compiler and combines them into a single executable file, library file, or another object file. Structure of C Program The structure of a C program is a protocol (rules) to the programmer, which he has to follow while writing a C program. The general basic structure of C program is shown in the figure below. First C program Based on the structure, we can sketch a C program. Example: #include void main(void) { int number; printf( "Please enter a number: " ); scanf( "%d", &number ); printf( "You entered %d", number ); return 0; } #include The part of the compiler which actually gets your program from the source file is called the preprocessor. #include #include is a pre-processor directive. It is not really part of our program, but instead it is an instruction to the compiler to make it do something. It tells the C compiler to include the contents of a file (in this case the system file called stdio.h). The compiler knows it is a system file, and therefore must be looked for in a special place, by the fact that the filename is enclosed in characters Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 31 stdio.h is the name of the standard library definition file for all Standard Input and Output functions. Your program will almost certainly want to send information to the screen and read things from the keyboard, and stdio.h is the name of the file in which the functions that we want to use are defined. The function we want to use is called printf. The actual code of printf will be tied in later by the linker. The ".h" portion of the filename is the language extension, which denotes an include file. void This literally means that this means nothing. In this case, it is referring to the function whose name follows.Void tells to C compiler that a given entity has no meaning, and produces no error. Main In this particular example, the only function in the program is called main. A C program is typically made up of large number of functions. Each of these is given a name by the programmer and they refer to each other as the program runs.C regards the name main as a special case and will run this function first i.e. the program execution starts from main. A parameter to a function gives the function something to work on. { (Brace) This is a brace (or curly bracket). As the name implies, braces come in packs of two - for every open brace there must be a matching close one. Braces allow us to group pieces of program together, often called a block. A block can contain the declaration of variable used within it, followed by a sequence of program statements. In this case the braces enclose the working parts of the function main. ;( semicolon) The semicolon marks the end of the list of variable names, and also the end of that declaration statement. All statements in C programs are separated by ";" (semicolon) characters. The ";" character is actually very important. It tells the compiler where a given statement ends. If the compiler does not find one of these characters where it expects to see one, then it will produce an error. scanf In other programming languages, the printing and reading functions are a part of the language. In C this is not the case; instead they are defined as standard functions which are part of the language specification, but are not a part of the language itself. The standard input/output library contains a number of functions for formatted data transfer; the two we are going to use are scanf (scan formatted) and printf (print formatted). printf The printf function is the opposite of scanf. It takes text and values from within the program and sends it out onto the screen. Just like scanf, it is common to all versions of C and just like scanf, it is described in the system file stdio.h.The first parameter to a printf is the format string, which contains text, value descriptions and formatting instructions. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 32 Lecture Notes || Unit -1 || CO-2 || Lecture Number-6 Topic Compilation and Execution steps, Errors CO Covered To translate the algorithms to programs & execution in C language Lecture Objective To get the idea of steps behind C program execution and types of errors Lecture structure Pre-requisite Keywords IDE Introduction Compilation and Execution steps Errors Related Questions i. Explain Execution steps of any C program. ii. Explain the types of errors occurred in an program Extra topics for fast Explore Floating exception error,Parse error ,Implicit declaration error,Parsing learners/Topics beyond syllabus Pre-requisite Keywords Source File- This file contains the source code of the program. The file extension of any c file is.c. The file contains C source code that defines the main function & maybe other functions. Header File- A header file is a file with extension.h which contains the C function declarations and macro definitions and to be shared between several source files. Object File- An object file is a file containing object code, with an extension.obj, meaning relocatable format machine code that is usually not directly executable. Object files are produced by an assembler, compiler, or other language translator, and used as input to the linker, which in turn typically generates an executable or library by combining parts of object files. 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. IDE Introduction Integrated Development Environment or IDE for short is an application or software which programmers use for programming. It helps a programmer to program easily by providing all comprehensive facilities required for the development of software. IDE can improve the productivity of a programmer or developer because of its fast setup and various tools. Without this, a programmer takes a lot of time deciding various tools to use for their tasks. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 33 Mainly, an IDE includes 3 parts i.e. source code editor, build automation tool (compiler) and a debugger. The source code editor is something where programmers can write the code, whereas, build automation tool is used by the programmers for compiling the codes and the debugger is used to test or debug the program in order to resolve any errors in the code. Furthermore, these IDEs also comes with additional features like object and data modeling, unit testing, source code library, and a lot more. As a teacher I am going to use following IDE (Because this is the lab setup@GCET and you can relate your learning easily) But, you can use any one of the following integrated development environment (IDE) for C programming- Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 34 Compilation and Execution steps Source code is the C program that you write in your editor and save with a ‘.C ‘ extension. Which is un-compiled (when written for the first time or whenever a change is made in it and saved). Object code is the output of a compiler after it processes the source code. The object code is usually a machine code, also called a machine language, which can be understood directly by a specific type of CPU (central processing unit), such as x86 (i.e., Intel-compatible) or PowerPC. However, some compilers are designed to convert source code into an assembly language or some other another programming language. An assembly language is a human-readable notation using the mnemonics (mnemonics a symbolic name for a single executable machine language instruction called an opcode) in the ISA (Instruction Set Architecture) of that particular CPU. Executable (also called the Binary) is the output of a linker after it processes the object code. A machine code file can be immediately executable (i.e., runnable as a program), or it might require linking with other object code files (e.g. libraries) to produce a complete executable program. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 35 Types of Error Error is an illegal operation performed by the user which results in abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. The most common errors can be broadly classified as follows. Type of errors Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax are known as syntax errors. This compiler error indicates something that must be fixed before the code can be compiled. All these errors are detected by compiler and thus are known as compile-time errors. Most frequent syntax errors are: 1. Missing Parenthesis (}) 2. Printing the value of variable without declaring it 3. Missing semicolon like this: // C program to illustrate // syntax error #include void main() { int x = 10; int y = 15; printf("%d", (x, y)) // semicolon missed } Error: error: expected ';' before '}' Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 36 Syntax of a basic construct is written wrong. For example : while loop // C program to illustrate // syntax error #include int main(void) { // while() cannot contain "." as an argument. while(.) { printf("hello"); } return 0; } Error: error: expected expression before '.' while(.) In the given example, the syntax of while loop is incorrect. This causes a syntax error. Run-time Errors: Errors which occur during program execution (run-time) after successful compilation are called run-time errors. One of the most common run-time error is division by zero also known as Division error. These types of error are hard to find as the compiler doesn’t point to the line at which the error occurs. For more understanding run the example given below. // C program to illustrate // run-time error #include void main() { int n = 9, div = 0; // wrong logic // number is divided by 0, // so this program abnormally terminates div = n/0; printf("resut = %d", div); } Error: warning: division by zero div = n/0; In the given example, there is Division by zero error. This is an example of run-time error i.e errors occurring while running the program. Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 37 Linker Errors: These error occurs when after compilation we link the different object files with main’s object using Ctrl+F9 key (RUN). These are errors generated when the executable of the program cannot be generated. This may be due to wrong function prototyping, incorrect header files. One of the most common linker error is writing Main() instead of main(). // C program to illustrate // linker error #include void Main() // Here Main() should be main() { int a = 10; printf("%d", a); } Error: (.text+0x20): undefined reference to `main' Logical Errors: On compilation and execution of a program, desired output is not obtained when certain input values are given. These types of errors which provide incorrect output but appears to be error free are called logical errors. These are one of the most common errors done by beginners of programming. These errors solely depend on the logical thinking of the programmer and are easy to detect if we follow the line of execution and determine why the program takes that path of execution. // C program to illustrate // logical error int main() { int i = 0; // logical error : a semicolon after loop for(i = 0; i < 3; i++); { printf("loop "); continue; } getchar(); return 0; } No output Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 38 Semantic errors : This error occurs when the statements written in the program are not meaningful to the compiler. // C program to illustrate // semantic error void main() { int a, b, c; a + b = c; //semantic error } Error error: lvalue required as left operand of assignment a + b = c; //semantic error Lecture Notes ||Programming for Problem Solving (BCS-101/BCS-201) || CSEGCET 39 Lecture Notes || Unit -1 || CO-2 || Lecture Number-7 Topic Components of C language , Fundamental Data Types, Variables and Memory locations, Type Conversion CO Covered To translate the algorithms to programs & execution in C language Lecture Objective To get the idea of different components of C language Lecture structure Components of C Language Fundamental Data Types Type Casting Related Questions i. Explain different components of C Language in detail. ii. Explain rules to construct constants. iii. Explain different data types in terms of their size,range,and way of declaration. Extra topics for fast Comparative analysis of components of C,C++,JAVA,Python learners/Topics beyond syllabus Components of C language Every language has some basic elements & grammatical rules. Before starting with programming, we should be acquainted with the basic elements that build the language. Character Set Communicating with a computer involves speaking the language the computer understands. In C, various characters have been given to communicate. Character set in C consists of; Types Character Set Lower case a-z Upper case A-Z Digits 0-9 Special Character !@#$%^&* White space Tab or new lines or space Keywords Keywords are the words whose meaning has already been explained to the C compiler. The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. There are only 32 keywords available in C. Below figure gives a list of these keywords for your ready reference. Lecture Notes || Programming for Problem Solving (KCS-101/KCS-201) || Mahesh -GCET 40 Identifier In the programming language C, an identifier is a combination of alphanumeric characters, the first being a letter of the alphabet or an underline, and the remaining being any letter of the alphabet, any numeric digit, or the underline. Two rules must be kept in mind when naming identifiers. 1. The case of alphabetic characters is significant. Using "INDEX" for a variable is not the same as using "index" and neither of them is the same as using "InDeX" for a variable. All three refer to different variables. 2. As C is defined, up to 32 significant characters can be used and will be considered significant by most compilers. If more than 32 are used, they will be ignored by the compiler. Data Type In the C programming language, data types refer to a domain of allowed values & the operations that can be performed on those values. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. There are 4 fundamental data types in C, which are- char, int, float &, double. Char is used to store any single character; int is used to store any integer value, float is used to store any single precision floating point number & double is used to store any double precision floating point number. We can use 2 qualifiers with these basic types to get more types. Sign qualifier- signed & unsigned Size qualifier- short & long The data types in C can be classified as follows: Type Storage size Value range Char 1 byte -128 to 127 unsigned char 1 byte 0 to 255 Integrity 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 unsigned integrity 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 Short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 Long 4 bytes -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295 Type Storage size Value range Precision Float 4 bytes 1.2E-38 to 3.4E+38 6 decimal places double 8 bytes 2.3E-308 to 1.7E+308 15 decimal places long double 10 bytes 3.4E-4932 to 1.1E+4932 19 decimal places Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 41 Constants A constant is an entity that doesn’t change whereas a variable is an entity that may change constants can be divided into two major categories: Primary Constants, Secondary Constants Rules for Constructing Integer Constants: An integer constant must have at least one digit. It must not have a decimal point. It can be either positive or negative. If no sign precedes an integer constant it is assumed to be positive. No commas or blanks are allowed within an integer constant The allowable range for integer constants is -32768to 32767. Ex.: 426, +782,-8000, -7605 Rules for Constructing Real Constants: Real constants are often called Floating Point constants. The real constants could be written in two forms—Fractional form and Exponential form. A real constant must have at least one digit. It must have a decimal point. It could be either positive or negative. Default sign is positive. No commas or blanks are allowed within a real constant. Ex. +325.34, 426.0, -32.76, -48.5792 Rules for constructing real constants expressed in exponential form: The mantissa part and the exponential part should be separated by a letter e. The mantissa part may have a positive or negative sign. Default sign of mantissa part is positive. The exponent must have at least one digit, which must be a positive or negative integer. Default sign is positive. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38. Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 42 Ex. +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5 Rules for Constructing Character Constants: A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas.The maximum length of a character constant can be 1 character.Ex.: ‘M’, ‘6’, ‘+’ Variables- Variables are names that are used to store values. It can take different values but one at a time. A data type is associated with each variable & it decides what values the variable can take. Variable declaration requires that you inform C of the variable's name and data type. Syntax – data type variable name; Eg:int page_no; char grade; float salary; long y; Declaring Variables: There are two places where you can declare a variable: After the opening brace of a block of code (usually at the top of a function) Before a function name (such as before main() in the program) Consider various examples: Initialization of Variables When a variable is declared, it contains undefined value commonly known as garbage value. If we want we can assign some initial value to the variables during the declaration itself. This is called initialization of the variable. Eg-int pageno=10; Expressions An expression consists of a combination of operators, operands, variables & function calls. An expression can be arithmetic, logical or relational. Here are some expressions: a+b – arithmetic operation a>b- relational operation a == b - logical operation func (a,b) – function call Statements Statements are the primary building blocks of a program. A program is a series of statements with some necessary punctuation. A statement is a complete instruction to the computer. In C, statements are indicated by a semicolon at the end. a semicolon is needed to identify instructions that truly are statements. Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 43 Tokens in C A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following C statement consists of five tokens − printf("Hello, World! \n"); The individual tokens are − printf ( "Hello, World! \n" ) ; Semicolons In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity. Whitespace in C A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement − int age; There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement − fruit = apples + oranges; // get the total fruit No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish to increase readability. Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 44 Type casting Type casting /type conversion is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can typecast long to int. You can convert values from one type to another explicitly using the cast operator. There are two types of type casting in c languages that are implicit conversions and Explicit Conversions. New data type should be mentioned before the variable name or value in brackets which to be typecast. Example- In the below C program, 7/5 alone will produce integer value as 1.So, type cast is done before division to retain float value (1.4). #include int main () { float x; x = (float) 7/5; printf(“%f”,x); } Output: 1.400000 Types of typecasting in C Implicit Conversion Explicit Conversion Implicit Conversion Implicit conversions do not require any operator for converted. They are automatically performed when a value is copied to a compatible type in the program. #include #include void main() { int i=20; double p; clrscr(); p=i; // implicit conversion Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 45 printf(“implicit value is %d”,p); getch();} Output:- implicit value is 20. Explicit Conversion In C language, Many conversions, especially those that imply a different interpretation of the value, require an explicit conversion. Example :- #include #include void main() { int i=20; short p; clrscr(); p = (short) i; // Explicit conversion printf(“Explicit value is %d”,p); getch(); } Output:- Explicit value is 20. Usual Arithmetic Conversion The usual arithmetic conversions are implicitly performed to cast their values in a common type, C uses the rule that in all expressions except assignments, any implicit type conversions made from a lower size type to a higher size type as shown below: Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 46 Inbuilt Typecast Functions in C: There are many inbuilt type casting functions available in C language which performs data type conversion from one type to another. S.No Typecast Function Description 1 atof() Convert string to Float 2 atoi() Convert string to int 3 atol() Convert string to long 4 itoa() Convert int to string 5 ltoa() Convert long to string Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 47 Lecture Notes || Unit -1 || CO-2 || Lecture Number-8 Topic Standard I/O in C CO Covered To translate the algorithms to programs & execution in C language Lecture Objective To get the idea of different Standard Input and output methods in C Lecture structure What is library functions? Working of scanf () and printf function Working of getchar () and putchar () function Working of gets () and puts () function Use of format specifier and escape sequences in formatting the input and output Related Questions i. What do you mean by formatted input output in C Language? ii. Explain the working of different standard input output method/functions with proper examples. Extra topics for fast Explore getc(),putc(),fprintf(),fscanf(),fgets(),fputs() learners/Topics beyond syllabus Standard I/O in C When we say Input, it means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement. When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files. The Standard Files C programming treats all the devices as files. So devices such as the display are addressed in the same way as files and the following three files are automatically opened when a program executes to provide access to the keyboard and screen. File Standard File Device Pointer Standard input stdin Keyboard Standard output stdout Screen Standard error stderr Your screen The getchar() and putchar() Functions The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. You can use this method in the loop in case you want to read more than one character from the screen. Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 48 The int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only single character at a time. You can use this method in the loop in case you want to display more than one character on the screen. Check the following example − #include int main( ) { int c; printf( "Enter a value :"); c = getchar( ); printf( "\nYou entered: "); putchar( c ); return 0; } When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads only a single character and displays it as follows − Enter a value: this is test You entered: t The gets() and puts() Functions The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File). The int puts(const char *s) function writes the string ‘s’ and ‘a’ trailing newline to stdout. #include int main( ) { char str; printf( "Enter a value :"); gets( str ); printf( "\nYou entered: "); puts( str ); return 0; } When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads the complete line till end, and displays it as follows − Enter a value : this is test Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 49 You entered: this is test The scanf() and printf() Functions The int scanf(const char *format, …) function reads the input from the standard input stream stdin and scans that input according to the format provided. The int printf(const char *format, …) function writes the output to the standard output stream stdout and produces the output according to the format provided. The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or float respectively. There are many other formatting options available which can be used based on requirements. Let us now proceed with a simple example to understand the concepts better - #include int main( ) { char str; int i; printf( "Enter a value :"); scanf("%s %d", str, &i); printf( "\nYou entered: %s %d ", str, i); return 0; } When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then program proceeds and reads the input and displays it as follows − Enter a value : seven 7 You entered: seven 7 Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which means you have to provide valid inputs like “string integer”. If you provide “string string” or “integer integer”, then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as soon as it encounters a space, so “this is test” are three strings for scanf(). Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 50 Formatted Input and Output- Data can be entered & displayed in a particular format. Through format specifications, better presentation of results can be obtained. #include int main() {printf("Case 1:%6d\n",9876); printf("Case 2:%3d\n",9876); printf("Case 3:%.2f\n",987.6543); printf("Case 4:%.f\n",987.6543); printf("Case 5:%e\n",987.6543); return 0; } Output Case 1: 9876 Case 2:9876 Case 3:987.65 Case 4:988 Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 51 Lecture Notes || Unit -1 || CO-2 || Lecture Number-9 Topic Storage Classes CO Covered To translate the algorithms to programs & execution in C language Lecture Objective To explore and understand the storage classes Lecture structure Memory Vs CPU Registers Initial value of variable, Scope Importance of storage class Automatic storage class Static storage class Register storage class Extern storage class Related Questions i. Explain the terms-scope, initial value of any variable, visibility, life of variable. ii. What is storage class? Explain importance of storage class in programming. iii. Explain different types of storage classes with programming examples. Extra topics for fast CPU registers,Microprocessors,Types of CPU registers,Cost of CPU registers learners/Topics beyond syllabus Storage classes Generally, there are two kinds of locations in a computer where such a value can be present, these are Memory and CPU registers. The storage class of a particular variable determines in which of the above two locations the variable’s value is stored. There are four properties by which storage class of a variable can be recognized. These are scope, default initial value, scope and life. A variable’s storage class reveals the following things about a variable (i) Where the variable is stored. (ii) What is the initial value of the variable if the value of the variable is not specified? (iii) What is the scope of the variable (To which function or block the variable is available)? (iv) What is the life of particular variable (Up to what extent the variable exists in a program)? In c there are four types of storage class. They are: 1. Auto 2. Register 3. Static 4. Extern Visibility of a variable in c: Visibility means accessibility. Up to witch part or area of a program, we can access a variable, that area or part is known as visibility of that variable. For example: In the following figure yellow color represents visibility of variable a. Scope of a variable in c: Meaning of scope is to check either variable is alive or dead. Alive means data of a variable has not destroyed from memory. Up to which part or area of the program a variable is alive, that area or part is known as scope of a variable. There are four type of scope in c: 1. Block scope. Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 52 2. Function scope. 3. File scope. 3. Program scope. Automatic Storage Class Syntax to declare automatic variable is: auto datatype variablename; Example: auto int i; Features of Automatic Storage Class are as follows Storage: Memory Default Initial Value: Garbage Value Scope: Local to the block in which the variable is defined Life: Till the control remains within the block in which the variable is defined by default every variable is automatic variable The following program illustrates the work of automatic variables. void test(); void main() { test(); test(); test(); } void test() { auto int k=10; printf(“%d\n”,k); k++; } Output: 10 10 10 Lecture Notes || Programming for Problem Solving (BCS-101/BCS-201) || Mahesh Singh CSE-GCET 53 In the above program when the function test() is called for the first time ,variable k is created and initialized to 10. When the control returns to main(), k is destroyed. When function test() is called for the second time again k is created , initialized and destroyed after execution of the function. Hence automatic variables came into existence each time the function is executed and