🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

PART- A Unit–1: Introduction to Programming Syllabus Introduction to components of a computer system: Memory, processor, I/O devices, storage, operating system, concept of assembler, compiler, interpreter, loader and linker. Concept of algorithm: Representation of...

PART- A Unit–1: Introduction to Programming Syllabus Introduction to components of a computer system: Memory, processor, I/O devices, storage, operating system, concept of assembler, compiler, interpreter, loader and linker. Concept of algorithm: Representation of an algorithm, flowchart, Pseudocode with examples, converting algorithms to programs. 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, data types, variables and constants, memory storage, storage classes. Introduction to components of a computer system A computer is a combination of hardware and software resources which integrate together and provides various functionalities to the user. Components of computer system  Input unit  Output unit  CPU Fig: Components of computer system Components of a computer system Input Unit- are input devices that take input and convert it into binary language. Some of the common input devices are keyboard, mouse, joystick, scanner etc Output Unit : consists of output devices that converts the binary data coming from CPU to human understandable form. The common output devices are monitor, printer, plotter etc. Central Processing Unit (CPU) Brain of the computer Control center of the computer Fetches instructions from memory and then interprets them Three main components which are responsible for different functions –  Arithmetic Logic Unit (ALU),  Control Unit (CU)  Memory registers Central Processing Unit (CPU) Arithmetic and Logic Unit (ALU) : performs mathematical calculations and takes logical decisions. Arithmetic calculations include addition, subtraction, multiplication and division. Logical decisions involve comparison of two data items to see which one is larger or smaller or equal. Control Unit : The Control unit coordinates and controls the data flow in and out of CPU and also controls all the operations of ALU, memory registers and also input/output units. It is also responsible for carrying out all the instructions stored in the program. It decodes the fetched instruction, interprets it and sends control signals to input/output devices until the required operation is done properly by ALU and memory. Memory Registers : A register is a temporary unit of memory in the CPU. These are used to store the data which is directly used by the processor. Registers can be of different sizes(16 bit, 32 bit, 64 bit and so on) and each register inside the CPU has a specific function like storing data, storing an instruction, storing address of a location in memory etc. The user registers can be used by an assembly language programmer for storing operands, intermediate results etc. Accumulator (ACC) is the main register in the ALU and contains one of the operands of an operation to be performed in the ALU. Memory Unit Memory unit is the amount of data that can be stored in the storage unit. This storage capacity is expressed in terms of Bytes Main memory storage units are as follows-  Bit (Binary Digit)-A binary digit is logical 0 and 1 representing a passive or an active state of a component in an electric circuit.  Nibble-A group of 4 bits is called nibble.  Byte-A group of 8 bits is called byte. A byte is the smallest unit, which can represent a data item or a character.  Word-A computer word, like a byte, is a group of fixed number of bits processed as a unit, which varies from computer to computer but is fixed for each computer. The length of a computer word is called word- size or word length. It may be as small as 8 bits or may be as long as 96 bits. A computer stores the information in the form of computer words. Storage Storage is a mechanism that enables a computer to retain data, either temporarily or permanently. Storage is among the key components of a computer system and can be classified into several forms, although there are two major types: Volatile Storage (Memory): Requires a continuous supply of electricity to store/retain data. It acts as a computer's primary storage for temporarily storing data and handling application workloads. Examples are-storage include cache memory and random access memory (RAM). Non-Volatile Storage: A type of storage mechanism that retains digital data even if it’s powered off or isn’t supplied with electrical power. This is often referred to as a secondary storage mechanism, and is used for permanent data storage requiring I/O operations. Examples are-storage include a hard disk, USB storage and optical media. Storage Common storage devices that are in use or have been used in the past include: Hard disks. Flash drives. Floppy diskettes. Tape drives. CD-ROM disks. Blu-ray disks. Memory cards. Cloud drives. Question? Storage v/s memory Answer Storage is often confused for memory, although in computing the two terms have different meanings. Memory refers to short-term location of temporary data, while storage devices, in fact, store data on a long-term basis for later uses and access. While memory is cleared every time a computer is turned off, stored data is saved and stays intact until it’s manually deleted. Primary or volatile storage tends to me much faster than secondary storage due to its proximity to the processor, but it’s also comparably smaller. Secondary storage can hold and handle significantly larger sizes of data, and keeps it inactive until it’s needed again. Operating system OS is an interface between the user and the machine. It is a software which performs all the basic tasks like file management, memory management, process management, handling input and output, and controlling peripheral devices such as disk drives and printers. Some popular Operating Systems include Linux Operating System, Windows Operating System, VMS, OS/400, AIX, z/OS, etc. Important functions of an Operating System. Memory Management Processor Management Device Management File Management Security Control over system performance Job accounting Error detecting aids Coordination between other software and users Fig: Function of Operating system Concept of Assembler It is a type of computer program that interprets software programs written in assembly language into machine language, code and instructions that can be executed by a computer. Assembler is a program for converting instructions written in low-level assembly code into relocatable machine code and generating along information for the loader. https://www.toppr.com/guides/computer-science/computer- fundamentals/system-software/assembler/ Assembler The source program is an input of an assembler that contains assembly language instructions. The output generated by the assembler is the object code or machine code understandable by the computer. Assembler is basically the 1st interface that is able to communicate humans with the machine. We need an Assembler to fill the gap between human and machine so that they can communicate with each other. Assembler Fig: working of assembler Compiler The language processor that reads the complete source program written in high-level language as a whole in one go and translates it into an equivalent program in machine language is called a Compiler. Example: C, C++, C#, Java. The compiler specifies the errors at the end of the compilation with line numbers when there are any errors in the source code. Compiler Fig: working of compiler Interpreter Interpreter : The translation of a single statement of the source program into machine code is done by a language processor and executes immediately before moving on to the next line is called an interpreter. If there is an error in the statement, the interpreter terminates its translating process at that statement and displays an error message. The interpreter moves on to the next line for execution only after the removal of the error. An Interpreter directly executes instructions written in a programming or scripting language without previously converting them to an object code or machine code. Example: Perl, Python and Matlab. Interpreter Fig: working of interpreter Loader and Linker In execution of the program, major role is played by two utility programs known as Linker and Loader. 1. Linker : A linker is special program that combines the object files, generated by compiler/assembler, and other pieces of codes to originate an executable file have. exe extension. In the object file, linker searches and append all libraries needed for execution of file. It regulates the memory space that will hold the code from each module. It also merges two or more separate object programs and establishes link among them. Generally, linkers are of two types : 1. Linkage Editor 2. Dynamic Linker Fig: Flowchart Fig: Flow Diagram Loader Loader : The loader is special program that takes input of object code from linker, loads it to main memory, and prepares this code for execution by computer. Loader allocates memory space to program. Even it settles down symbolic reference between objects. It is in charge of loading programs and libraries in operating system. The embedded computer systems don’t have loaders. In them, code is executed through ROM. There are following various loading schemes: 1. Absolute Loaders 2. Relocating Loaders 3. Direct Linking Loaders 4. Bootstrap Loaders https://www.youtube.com/watch?v=cJDRShqtTbk Subtopic –Unit-1 Concept of algorithm: Representation of an algorithm, flowchart, Pseudocode with examples, converting algorithms to programs. Concept of Algorithm Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. Fig: Definition of Algorithm Algorithm It can be understood by taking an example of cooking a new recipe. To cook a new recipe, one reads the instructions and steps and execute them one by one, in the given sequence. The result thus obtained is the new dish cooked perfectly. Similarly, algorithms help to do a task in programming to get the expected output. The Algorithm designed are language- independent, i.e. they are just plain instructions that can be implemented in any language, and yet the output will be the same, as expected. Characteristics of an Algorithm Characteristics of 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. How to Design an Algorithm? In order to write an algorithm, following things are needed as a pre-requisite: The problem that is to be solved by this algorithm. The constraints of the problem that must be considered while solving the problem. The input to be taken to solve the problem. The output to be expected when the problem the is solved. The solution to this problem, in the given constraints. Categories of Algorithms From the data structure point of view, following are some important categories of algorithms − Search − Algorithm to search an item in a data structure. Sort − Algorithm to sort items in a certain order. Insert − Algorithm to insert item in a data structure. Update − Algorithm to update an exis ng item in a data structure. Delete − Algorithm to delete an exis ng item from a data structure. Problem − Design an algorithm to add two numbers and display the result. Can you design another Algorithm for same problem? Alternatively, the algorithm can be written as Insight We design an algorithm to get a solution of a given problem. A problem can be solved in more than one ways. Hence, many solution algorithms can be derived for a given problem. Algorithm Analysis Efficiency of an algorithm can be analyzed at two different stages, before implementation and after implementation. They are the following − A Priori Analysis − This is a theoretical analysis of an algorithm. Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation. A Posterior Analysis − This is an empirical analysis of an algorithm. The selected algorithm is implemented using programming language. This is then executed on target computer machine. In this analysis, actual statistics like running time and space required, are collected. We shall learn about a priori algorithm analysis. Algorithm analysis deals with the execution or running time of various operations involved. The running time of an operation can be defined as the number of computer instructions executed per operation. Algorithm Complexity Suppose X is an algorithm and n is the size of input data, the time and space used by the algorithm X are the two main factors, which decide the efficiency of X. Time Factor − Time is measured by counting the number of key operations such as comparisons in the sorting algorithm. Space Factor − Space is measured by counting the maximum memory space required by the algorithm. The complexity of an algorithm f(n) gives the running time and/or the storage space required by the algorithm in terms of n as the size of input data. Representation of an algorithm We can express an algorithm in the following ways- Natural language  Flow charts  Pseudocode  Actual programming languages. 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”. Example: Draw a flowchart to input two numbers from the user and display the largest of two numbers Fig: Example of Flow chart Pseudocode with examples Pseudo-codes is a false code that can be understood by a layman with a basic knowledge of programming. It is one of the methods which can be used to represent an algorithm for a program. It does not have a specific syntax like any of the programming languages and thus cannot be executed on a computer. There are several formats which are used to write pseudo-codes and most of them take down the structures from languages such as C, Lisp, FORTRAN, etc. Many time algorithms are presented using pseudocode since they can be read and understood by programmers who are familiar with different programming languages. Pseudocode allows you to include several control structures such as While, If-then-else, Repeat-until, for and case, which is present in many high-level languages. Note: Pseudocode is not an actual programming language. 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. 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. 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. Use appropriate sentence casings, such as CamelCase for methods, upper case for constants and lower case for variables. 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. Pseudocode for Addition of 2 numbers BEGIN NUMBER s1, s2, sum OUTPUT("Input number1:") INPUT s1 OUTPUT("Input number2:") INPUT s2 sum=s1+s2 OUTPUT sum END Linear Search Start from the leftmost element of arr[] and one by one compare x with each element of arr[] If x matches with an element, return the index. If x doesn’t match with any of elements, return -1. Pseudocode for Linear Search : Converting algorithms to programs Problem Definition: Write an algorithm for Subtracting two Numbers. Step 1: Start. Step 2: Read two numbers A and B. Step 3: Answer = A - B. Step 4: Display Answer. Step 5: Stop Program #include int main() { int A, B, Answer; printf("Enter number A:"); scanf("%d",&A); printf("Enter number B:"); scanf("%d",&B); Answer = A - B; printf("%d", Answer); return 0; } Subtopic- Unit-1 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, data types, variables and constants, memory storage, storage classes. C language C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. The C Language was developed for creating system applications that directly interact with the hardware devices such as drivers, kernels, etc. A structured programming language is a subset of the procedural language. Structure means to break a program into parts or blocks so that it may be easy to understand. A procedure is known as a function, method, routine, subroutine, etc. A procedural language specifies a series of steps for the program to solve the problem. C language is considered as the mother language of all the modern programming languages because most of the compilers, JVMs, Kernels, etc. are written in C language C language A Low-level language is specific to one machine, i.e., machine dependent. It is machine dependent, fast to run. But it is not easy to understand. A High-Level language is not specific to one machine, i.e., machine independent. It is easy to understand. Application of C Operating systems: C is widely used for developing operating systems such as Unix, Linux, and Windows. Embedded systems: C is a popular language for developing embedded systems such as microcontrollers, microprocessors, and other electronic devices. System software: C is used for developing system software such as device drivers, compilers, and assemblers. Networking: C is widely used for developing networking applications such as web servers, network protocols, and network drivers. Database systems: C is used for developing database systems such as Oracle, MySQL, and PostgreSQL. Gaming: C is often used for developing computer games due to its ability to handle low-level hardware interactions. Artificial Intelligence: C is used for developing artificial intelligence and machine learning applications such as neural networks and deep learning algorithms. Scientific applications: C is used for developing scientific applications such as simulation software and numerical analysis tools. Financial applications: C is used for developing financial applications such as stock market analysis and trading systems. Form of a C Program Form of a C program indicates how it has to be written/typed. There are certain rules about the form of a C program that are applicable to all C programs. These are as under: (a) Each instruction in a C program is written as a separate statement. (b) The statements in a program must appear in the same order in which we wish them to be executed. (c) Blank spaces may be inserted between two words to improve the readability of the statement. (d) All statements should be in lower case letters. (e) C has no specific rules for the position at which a statement is to be written in a given line. That’s why it is often called a free-form language. (f) Every C statement must end with a semicolon ( ; ). Thus ; acts as a statement terminator Structure of C program The basic structure of a C program is divided into 6 parts which makes it easy to read, modify, document, and understand in a particular format. Debugging is easier in a well-structured C program Structure of C program Sections of the C Program There are 6 basic sections responsible for the proper execution of a program. Sections are mentioned below: Documentation Preprocessor Section Definition Global Declaration Main() Function Sub Programs 1. Documentation This section consists of the description of the program, the name of the program, and the creation date and time of the program. It is specified at the start of the program in the form of comments. Documentation can be represented as: Anything written as comments will be treated as documentation of the program and this will not interfere with the given code. Basically, it gives an overview to the reader of the program. 2. Pre-processor Section All the header files of the program will be declared in the pre- processor section of the program. Header files help us to access other’s improved code into our code. A copy of these multiple files is inserted into our program before the process of compilation. Pre-processor Preprocessors are programs that process the source code before compilation. You can see the intermediate steps in the diagram on next slide. The source code written by programmers is first stored in a file, let the name be “program.c“. This file is then processed by preprocessors and an expanded source code file is generated named “program.i”. This expanded file is compiled by the compiler and an object code file is generated named “program.obj”. Finally, the linker links this object code file to the object code of the library functions to generate the executable file “program.exe” Pre-processor Pre-processor All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will go to the preprocessor program to get executed. We can place these preprocessor directives anywhere in our program. Examples of some preprocessor directives are: #include, #define, #ifndef, etc. Note: Remember that the # symbol only provides a path to the preprocessor, and a command such as include is processed by the preprocessor program. For example, #include will include the code or content of the specified file in your program. The following table lists all the preprocessor directives in C/C++: Types of C/C++ Preprocessors There are 4 Main Types of Preprocessor Directives: Macros File Inclusion Conditional Compilation Other directives Macros In C/C++, Macros are pieces of code in a program that is given some name. Whenever this name is encountered by the compiler, the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to define a macro. Example Output In this program, when the compiler executes the word LIMIT, it replaces it with 5. The word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion Note: There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need a semi-colon to end. There are also some Predefined Macros in C which are useful in providing various functionalities to our program. File Inclusion This type of preprocessor directive tells the compiler to include a file in the source code program. The #include preprocessor directive is used to include the header files in the C/C++ program. There are two types of files that can be included by the user in the program: 1. Standard Header Files 2. User-defined Header Files Standard Header Files The standard header files contain definitions of pre-defined functions like printf(), scanf(), etc. These files must be included to work with these functions. Different functions are declared in different header files. where file_name is the name of the header file to be included. The ‘’ brackets tell the compiler to look for the file in the standard directory. User-defined Header Files When a program becomes very large, it is a good practice to divide it into smaller files and include them whenever needed. These types of files are user-defined header files. These files can be included as: The double quotes ( ” ” ) tell the compiler to search for the header file in the source file’s directory. Conditional Compilation Conditional Compilation in C/C++ directives is a type of directive that helps to compile a specific portion of the program or to skip the compilation of some specific part of the program based on some conditions. There are the following preprocessor directives that are used to insert conditional code: #if Directive #ifdef Directive #ifndef Directive #else Directive #elif Directive #endif Directive #endif directive is used to close off the #if, #ifdef, and #ifndef opening directives which means the preprocessing of these directives is completed. Syntax If the macro with the name ‘macro_name‘ is defined, then the block of statements will execute normally, but if it is not defined, the compiler will simply skip this block of statements. Other Directives Apart from the above directives, there are two more directives that are not commonly used. These are: #undef Directive #pragma Directive 1. #undef Directive The #undef directive is used to undefine an existing macro. This directive works as: #undef LIMIT Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef LIMIT” statement will evaluate as false. 2. #pragma Directive This directive is a special purpose directive and is used to turn on or off some features. These types of directives are compiler-specific, i.e., they vary from compiler to compiler. Some of the #pragma directives are discussed below: #pragma startup: These directives help us to specify the functions that are needed to run before program startup (before the control passes to main()). #pragma exit: These directives help us to specify the functions that are needed to run just before the program exit (just before the control returns from main()). 3. Definition Preprocessors are the programs that process our source code before the process of compilation. There are multiple steps which are involved in the writing and execution of the program. Preprocessor directives start with the ‘#’ symbol. The #define preprocessor is used to create a constant throughout the program. Whenever this name is encountered by the compiler, it is replaced by the actual piece of defined code. 4. Global Declaration The global declaration section contains global variables, function declaration, and static variables. Variables and functions which are declared in this scope can be used anywhere in the program. 5. Main() Function Every C program must have a main function. The main() function of the program is written in this section. Operations like declaration and execution are performed inside the curly braces of the main program. The return type of the main() function can be int as well as void too. void() main tells the compiler that the program will not return any value. The int main() tells the compiler that the program will return an integer value. What is main( )? main( ) is a function. A function is nothing but a container for a set of statements. In a C program there can be multiple functions. To begin with, we would concentrate only on those programs which have only one function. The name of this function has to be main( ), it cannot be anything else. All statements that belong to main( ) are enclosed within a pair of braces { } as shown below. Main() The way functions in a calculator return a value, similarly, functions in C also return a value. main( ) function always returns an integer value, hence there is an int before main( ). The integer value that we are returning is 0. 0 indicates success. If for any reason the statements in main( ) fail to do their intended work we can return a non-zero number from main( ). This would indicate failure. Some compilers like Turbo C/C++ even permit us to return nothing from main( ). In such a case we should precede it with the keyword void. But this is non-standard way of writing the main( ) function. Main Function 6. Sub Programs User-defined functions are called in this section of the program. The control of the program is shifted to the called function whenever they are called from the main or outside the main() function. These are specified as per the requirements of the programmer. printf( ) and its Purpose C C does not contain any instruction to display output on the screen. All output to screen is achieved using readymade library functions. One such function is printf( ). Once the value of a variable is calculated it needs to be displayed on the screen. We have used printf( ) to do so. (b) For us to be able to use the printf( ) function, it is necessary to use #include at the beginning of the program. #include is a preprocessor directive How to get input scanf( ). This function is a counter-part of the printf( ) function. printf( ) outputs the values to the screen whereas scanf( ) receives them from the keyboard. Example Example Doubt -1-Example of flowcharts https://www.tutorialspoint.com/what-is-an- algorithm-and-flowchart-in-c-language https://www.javatpoint.com/flowchart-in-c- programming-language Doubt-2 Return 0 https://www.geeksforgeeks.org/return-0-vs- return-1-in-c/ The main function is generally supposed to return a value and after it returns something it finishes execution. The return 0 means success and returning a non-zero number means failure. Thus we "return 0" at the end of main function Example Fig: Structure of c programe Example Various parts of the program are− The first line of the program #include is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation. The next line int main() is the main function where the program execution begins. The next line will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program. The next line printf(...) is another function available in C which causes the message "Hello, World!" to be displayed on the screen. The next line return 0; terminates the main() function and returns the value 0. Compile and Execute C Program How to save the source code in a file, and how to compile and run it. Following are the simple steps − Open a text editor and add the above-mentioned code. Save the file as hello.c Open a command prompt and go to the directory where you have saved the file. Type gcc hello.c and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line and would generate a.out executable file. Now, type a.out to execute your program. You will see the output "Hello World" printed on the screen. Importance of structure Structure helps us analyze the format to write a program for the least errors. It gives better clarity and the concept of a program. https://www.javatpoint.com/structure-of-a-c- program Question “C has been already superseded by languages like C++, C# and Java, so why bother to learn C today”. I seriously beg to differ with this opinion. There are several reasons for this. Explain?? Syntax and logical errors in compilation What is an 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. Most common errors can be broadly classified as follows. 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: – Missing Parenthesis (}) – Printing the value of variable without declaring it – Missing semicolon like this: 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. 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(). 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. Semantic errors This error occurs when the statements written in the program are not meaningful to the compiler. Use this link or more examples https://www.geeksforgeeks.org/errors-in-cc/ Object and executable code object code is a program or a file that is created after compiling the source code while executable code is a file or a program that indicates tasks according to encoded instructions the CPU can directly execute Object v/s executable code Diagram Diagram Components of C language Components of C language, standard I/O in C, data types, variables and constants, memory storage, storage classes. Standard I/O in C I/O operations are useful for a program to interact with users. stdlib is the standard C library for input-output operations. While dealing with input-output operations in C, two important streams play their role. These are: Standard Input (stdin) Standard Output (stdout) Standard input or stdin is used for taking input from devices such as the keyboard as a data stream. Standard output or stdout is used for giving output to a device such as a monitor. For using I/O functionality, programmers must include stdio header- file within the program. Standard I/O in C In the case of C, Input/Output is provided to us by the C Standard Library via a set of functions defined in the stdio.h header file. You can import this library using: #include This library provides us, among many other functions: printf() scanf() sscanf() fgets() fprintf() https://flaviocopes.com/c-input-output/ 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 − 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. Given below are two different statements − Comments Comments are like helping text in your C program and they are ignored by the compiler. They start with as shown below − You cannot have comments within comments and they do not occur within a string or character literals. Identifiers A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C. Here are some examples of acceptable iden fiers − Keywords The following list shows the reserved words in C. These reserved words may not be used as constants or variables or any other identifier names. Keywords Data types In every language we have to perform some operations means some task on some values of variables. Example: Like 'Ramesh' Here Ramesh is a set of alphabets all characters. like '290' here 290 is a Numerical value. So here Ramesh and 290 are different types and they are allotted to some variables. So in order to recognise each variables and its type we have to specify their types and their types are called 'data types' of that variable. Doubt-Int main() vs void main() The void main() indicates that the main() function will not return any value, but the int main() indicates that the main() can return integer type data. When our program is simple, and it is not going to terminate before reaching the last line of the code, or the code is error free, then we can use the void main(). But if we want to terminate the program using exit() method, then we have to return some integer values (zero or non-zero). In that situation, the void main() will not work. So it is good practice to use int main() over the void main(). Is void main correct in C? No. It's non-standard. The standard prototype of main is int main() with the optional command line arguments argc and argv. The int returned by main() is a way for a program to return a value to the system that invokes it. Command line arguments in C/C++ argc (ARGument Count) is int and stores number of command-line arguments passed by the user including the name of the program.... The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments. Character Set In Real world to communicate with people we use language like Hindi English Urdu extra which is constructed and Defined by some characters, words extra. Similarly in C programming language we have various characters to communicate with the computer in order to produce a meaningful program and can produce an output 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 dis nguish 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. Example Int a=6; Int= datatype a=variable = is assignment operator 6 is value Constants in C 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. Defining Constants There are two simple ways in C to define constants − Using #define preprocessor. Using const keyword. The #define Preprocessor Given below is the form to use #define preprocessor to define a constant − #define identifier value Example The const Keyword You can use const prefix to declare constants with a specific type as follows − const type variable = value; The following example explains it in detail − Example Memory storage The memory layout for C programs is like below. There are few levels. These are − Stack Segment Heap Segment Text Segment Data segment Fig: Memory layout Memory storage Stack The process Stack contains the temporary data such as method/function parameters, return address and local variables. It is an area of memory allotted for automatic variables and function parameters. It also stores a return address while executing function calls. Stack uses LIFO (Last- In- First-Out) mechanism for storing local or automatic variables, function parameters and storing next address or return address. The return address refers to the address to return after completion of function execution. This segment size is variable as per local variables, function parameters, and function calls. This segment grows from a higher address to a lower address. Heap This is dynamically allocated memory to a process during its run time. This is area of memory allotted for dynamic memory storage such as for malloc() and calloc() calls. This segment size is also variable as per user allocation. This segment grows from a lower address to a higher address. Let us now check how the segments (data and bss segments) size vary with a few sample programs. Segment size is known by executing the command “size”. Text This includes the current activity represented by the value of Program Counter and the contents of the processor's registers. It is represented by.text section. This defines an area in memory that stores the instruction codes. This is also a fixed area. Data This section contains the global and static variables. It is represented by.data section and the.bss. The.data section is used to declare the memory region, where data elements are stored for the program. This section cannot be expanded after the data elements are declared, and it remains static throughout the program. The.bss section is also a static memory section that contains buffers for data to be declared later in the program. This buffer memory is zero-filled. Storage classes Storage Classes are used to describe the features of a variable/function. These features basically include the scope, visibility and life- time which help us to trace the existence of a particular variable during the runtime of a program. https://www.geeksforgeeks.org/storage-classes-in-c/ END OF UNIT-1

Use Quizgecko on...
Browser
Browser