93% found this document useful (14 votes)
10K views

Jntuk r23 Introduction To Programming

Introduction to Programming and Problem Solving History of Computers, Basic organization of a computer: ALU, input-output units, memory, program counter, Introduction to Programming Languages, Basics of a Computer Program- Algorithms, flowcharts (Using Dia Tool), pseudo code. Introduction to Compilation and Execution, Primitive Data Types, Variables, and Constants, Basic Input and Output, Operations, Type Conversion, and Casting. Problem solving techniques: Algorithmic approach, characteristic

Uploaded by

uday TMC
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
93% found this document useful (14 votes)
10K views

Jntuk r23 Introduction To Programming

Introduction to Programming and Problem Solving History of Computers, Basic organization of a computer: ALU, input-output units, memory, program counter, Introduction to Programming Languages, Basics of a Computer Program- Algorithms, flowcharts (Using Dia Tool), pseudo code. Introduction to Compilation and Execution, Primitive Data Types, Variables, and Constants, Basic Input and Output, Operations, Type Conversion, and Casting. Problem solving techniques: Algorithmic approach, characteristic

Uploaded by

uday TMC
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 42
INTRODUCTION TO PROGRAMMING Introduction to Programming and Problem Solving History of Computers, Basic organization of a computer: ALU, input-output units, memory, program counter, Introduction to Programming Languages, Basics of a Computer Program- Algorithms, flowcharts (Using Dia Tool), pseudo code. Introduction to Compilation and Execution, Primitive Data ‘Types, Variables, and Constants, Basic Input and Output, Operations, ‘Type Conversion, and Casting. Problem solving techniques: Algorithmic approach, characteristics of algorithm, Problem solving strategies: Top-down approach, Bottom-up approach, Time and space complexities of algorithms UNIT 2 Control Structures Simple sequential programs Conditional Statements (if, if-else, switch), Loops (for, while, do while) Break and Continue UNIT 3 Arrays and Strings Arrays indexing, memory model, programs with array of integers, two dimensional arrays, Introduction to Strings. UNIT 4 Pointers & User Defined Data types Pointers, dereferencing and address operators, pointer and address arithmetic, array manipulation using pointers, User-defined data types- Structures and Unions. UNIT 5 Functions & File Handling Introduction to Functions, Function Declaration and Definition, Function call Return Types and Arguments, modifying parameters inside functions using pointers, arrays as parameters. Scope and Lifetime of Variables, Basics of File Handling SEaM/ Mc Uday Introduction to Programming and Problem Solving 1.1. History of Computers, fs) 1.2, Basic organization of a computer: ALU, input-output units, memory, program counter, 1.3. Introduction to Programming Languages, 1.4, Basics of Computer Program- Algorithms, Flowcharts (Using Dia. Tool), pseudo code. 1.5. Introduction to Compilation and Execution, 1.6. Primitive Data Types, 1.7. Variables, and Constants, 1.8. Basic Input and Output, Operations, 1.9. Type Conversion, and Casting. 1.10, Problem solving techniques: Algorithmic approach, Characteristics of algorithm, 1.11, Problem solving strategies: Top-down approach, Bottom-up approach, 1,12. Time and space complexities of algorithms SEaM/ Mc Uday What is a Computer? A computer is an electronic machine that collects information, stores it, processes it ~ according to user instructions, and then — returns the result. A computer is a programmable electronic device that performs arithmetic and logical operations automatically using a set of instructions provided by the user. 1.1.1, Early computing devices/ Evolution of a Computer: People used sticks, stones, and bones as counting tools before computers were invented. Let us look at a few of the early-age computing devices used by mankind. © In order to simplify the process of counting, people in Asia Minor built a counting device called abacus. This device allowed users to do calculations using a system of sliding beads arranged on a rack. © With the passage of time, many computing devices such as Napier bones and slide rule were invented. © In 1642, a French mathematician, Blaise Pascal invented the first functional automatic calculator. This brass rectangular box, also called a Pascaline, used eight movable dios to adds sums eight figures long. © In 1694, german mathematician Gottfried wilhem von Leibniz extended pascal’s design to perform multiplication, division and to find square root. This machine is known as Stepped Reckoner. © The real beginnings of computers as we know them today, however, lay with an English Charles Babbage mathematics professor, Charles Babbage. Seen In 1822, he proposed a machine to perform differential equations, called a Difference Engine. (M/ tM Uday © In 1946, John Eclcert and John Mauchy of developed ENIAC (electronic numerical integrator and calculator) © Thus computer used electronic vacuum tubes to make internal parts of the computer o Eckert and mauchy also proposed the development of EDVAC (electronic discrete variable automatic computer. *) ©. It was the first electronic computer to use the stored program Ys concept introduced by John von Neumann. o In 1949, at the Cambridge university, Maurice wilkes developed EDSAC (electronic delay storage automatic calculator) © This machine used mercury delay lines for memory and vacuum tubes for logic. © The Eckert ~ mauchy corporation manufactured UNIVAC ( universal automatic computer) in 1951 and its implementation marked the real beginning of the computer era 1.1.2. Computer Generations : 1st Generation: Vacuum Tube (1940 - 1956) o. First generation computer were vacuum tubes/thermionic value based machines these computers used vacuum tubes for circuitry and magnetic drums for memory. o Input was based on punched cards and paper tape and output was in the form of printouts. o Example: ENIAC, EDVAC AND UNIVAC. © Characteristics of 1st Generation of a computer: * These computers were based on vacuum tube technology. + These were the fastest computing devices of their time. * These computers were very large, and required a lot of space for installation. * These were non-portable and very slow equipments. 24 Generation: Transistors (1959 - 1965) © A transistor is made up of semiconductor material like germanium and silicon. It usually had three leads and performed electrical functions such as voltage, current or power amplification with low power requirement. © Computers became smaller, faster, cheaper, energy- efficient and more reliable than their predecssors. (M/ tM Uday 34 Generation: Integrated Circuits (1965 - 1971) ° © Magnetic cores- were used as primary memory and magnetic disks as secondary storage devices. © Example: PDP -8 , IBM 1401 and IBM 7090 © Characteristics of 2° Generation of a computer: * These machines were based on transistor technology +. These were smaller as compared to the first generation computers, * These were more portable and generated less amount of heat. ‘Second Generation A= eo ~ Third Generation Fourth Generation Fifth Genera ‘The development of the integrated circuit was the trait of the third generation computer. Also called an ic, an integrated circuit consists of a single chip with many components such as transistors and resistors fabricated on i Integrated circuit replaced several individually wired transistors. This development made Computers smaller in size, reliable and efficient. Instead of punched cards and printouts, users interacted with third generation computers through keyboards and monitors and interfaced with operating system. example : NCR 395 and B6500 Characteristics of 3" generation computer: + These computers were based on integrated circuit (ic) technology. + They were able to reduce computational time from micro seconds to nano seconds. + Extensive use of high — level language became possible (M/ tM Uday 4* Generation: Microprocessors (1971 - 1980) ° ‘The technology of this generation was still based on the integrated circuit, these have been made readily available to use because of the development of the microprocessor. ‘The fourth generation computers led to an era of large scale integration (LSI) and very large scale integration (visi) technology. LSI technology allowed thousands of transistors to be constructed on one small slice of silicon material whereas visi squeezed hundreds of thousands of components ULTRA - large scale integration (ULSI) increased that number into millions the fourth generation computer became more powerful compact, reliable and affordable. example: apple ii, attair 8800 and CRAY-1 Characteristics of 4th generation computer: * Fourth generation computers are microprocessor based systems + These computers are very small * Interconnection of computers leads to better communication and resource sharing. 5t Generation: AI and ULSI (1980 - till date) ° ‘These computers have been utilized since 1980 and continue to be used now. This is the present and the future of the computer world ‘The defining aspect of this generation is artificial intelligence. The use of parallel processing and superconductors are making this a reality and provide a lot of scope for the future Fifth-generation computers use ULSI (Ultra Large Scale Integration) technology. These are the most recent and sophisticated computers. C, C++, Java,.Net, and more programming languages are used Example: IBM, Pentium, Desktop, Laptop, Notebook, Ultra book, and so on. Characteristics of 5% Generation : + They used ULSI and Al Technology + Ituses advanced computing technologies (M/ tM Uday According to Von Neumann, The basic organization of computer diagram has the following units Control Unit, Arithmetic and Logic Unit (ALU), Memory Unit, Registers and Inputs/Outputs. Von Neumann architecture is based fs) on the stored-program computer Cet cei concept, where instruction data and erent program data are stored in the same ————— memory. This design is ot Attest — still used in most computers Reiter C= C= J} produced today. E1tJCe)} Central Processing Unit (CPU) The Central Processing Unit (CPU) is the electronic circuit responsible for executing the instructions of a computer program. It is sometimes referred to as the microprocessor or processor. The CPU contains the ALU, CU and a variety of registers. Registers Registers are high speed storage areas in the CPU. All data must be stored in a register before it can be processed. Memory Address Holds the memory location of data that needs to MAR < Register be accessed Holds data that is being transferred to or MDR Memory Data Register io snemory Where intermediate arithmetic and logic results AC Accumulator are stored Contains the address of the next instruction to PC Program Counter ee Current Instruction Contains the current instruction during Rn i CIR Register processing (M/ tM Uday Arithmetic and Logic Unit (ALU) The ALU allows arithmetic (add, subtract etc) and logic (AND, OR, NOT etc) operations to be carried out. Control Unit (CU) () The control unit controls the operation of the computer's ALU, memory and. 7 input/output devices, telling them how to respond to the program instructions it has just read and interpreted from the memory unit. The control unit also provides the timing and control signals required by other computer components. Buses Buses are the means by which data is transmitted from one part of a computer to another, connecting all major internal components to the CPU and memory. A standard CPU system bus is comprised of a control bus, data bus and address bus. Carries the addresses of data between the processor and memory Address Bus Carries data between the processor, the memory unit and the Data Bi ata Bus | input/output devices Carries control signals/commands from the CPU (and status Control Bus __ signals from other devices) in order to control and coordinate all the activities within the computer Memory Unit ‘The memory unit consists of RAM, sometimes referred to as primary or main memory. Unlike a hard drive (secondary memory), this memory is fast and also directly accessible by the CPU. RAM is split into partitions. Each partition consists of an address and its contents (both in binary form) The address will uniquely identify every location in the memory. (M/ tM Uday Loading data from permanent memory (hard drive), into the faster and directly accessible temporary memory (RAM), allows the CPU to operate much quicker. Input/output Devices Program or data is read into main memory from the input device or - secondary storage under the control of CPU input instruction. Output >) devices are used to output information from a computer. If some results are evaluated by the computer and it is stored in the computer, then with the help of output devices, we can present them to the user. Program: The set of instructions are called a program. For Example, Programmers create programs by writing code that instructs the computer what to do and execute it on special software designed for it such as turbo C for executing ‘C’ Programs. Programming: We can say that the process of writing a program is called Programming. A programming language is a set of rules that provides a way of telling a computer what operations to perform “A programming language is a notational system for describing computation in @ machine - readable and human — readable form “ English is a natural language. It has words, symbols and grammatical rules Similarly a programming language also has words, symbols and rules of grammar. The grammatical rules are called SYNTAX. First programming language is developed in 1950s. Since then thousands of languages have been developed because different programming languages are designed for different types of programs. Why many programming languages? Different programming languages are designed for different types of applications Levels of programming languages: High level: High-level language is a computer language which can be understood by the users. The high-level language is very similar to human languages and has a set of grammar rules that are used to make instructions more easily. SEaM/ Mc Uday Computer Languages Ceres) rege) - Use 1" 5&0" sto ‘Use mnemonics to Similar to 11) create instructions create instructions human langugas _ Ex: Binary Language ‘Assembly Language COBOL, FORTRAN, BASIC 6. C++, JAVA Middle level: instructions are created using symbols such as letters, digits and special characters Assembly language is an example of middle-level language. In assembly language, we use predefined words called mnemonics. Low level: Low-Level language is the only language which can be understood by the computer. Low-level language is also known as Machine Language. The machine language contains only two symbols 1 & 0. mov sec ebx winclude int maint) ( nee Sec printf CHello World"; (1000110111101 mov rax rdx return 0;) Machine Assembly High-level language language language of a Cie java The principle paradigm: Programming paradigms are different ways or styles in which a given program or programming language can be organized. Imperative programming ( Ex: C, Forton , Basic ) Procedure oriented programming ( Ex: C, Pacal ) Object oriented programming (Ex: Java, Python) Logical programming( Ex: Prolog } SEaM/ Mc Uday Traditional Programming languages: FORTRAN: — FORmula TRANslation > Developed by IBM in mid 1950s -> Designed for scientific and mathematical applications . COBOL: S + COmmon Business Oriented Language > Developed in 1959 —> Used to develop business applications BASIC: > Beginners All Purpose Symbolic Instruction Code > Developed at Dartmouth college in mid 1960s — Written by students to interact with terminals C Programming languag Cis a general purpose, simple and procedural programming language. It was initially developed by Dennis Ritchie in the year 1972 at AT & T Bell labs. It was mainly developed as a system programming language to write an operating system. UNIX is written in C C was first designed by Dennis Ritchie for use with UNIX on DEC PDP-11 computers. The language evolved from Martin Richard's BCPL, Demis ce and one of its earlier forms was the B language; — first book on C was “The C Programming : Language “by Brian Kernighan and Dennis ‘ Ritchie, published in 1978. In 1983, the American National Standards Institute (ANSI) established a committee to standardize the definition of C. The resulting standard is known as ANSI C, and it is the recognized standard for the language, grammar, and a core set of libraries There is also an ISO (International Standards Organization) standard that is very similar to the ANSI standard. It appears that there will be yet another ANSI C standard officially dated 1999 or in the early 2000 years; it is currently known as "C9X." SEaM/ Mc Uday Features of C: Cis the widely used language. It provides many features that are given below. 1 2. 2. Simple Machine Independent or Portable structured programming language Memory Management Fast Speed Pointers Recursion Extensible Simpl Cis a simple language in the sense that it provides a structured approach (to break the problem into parts), the rich set of library functions, data types, etc. Machine Independent or Portable Unlike assembly language, c programs ean be executed on different machines with some machine specific changes . structured programming language C is a structured programming language in the sense that we ean break the program into parts using functions. So, it is easy to understand and modify. Functions also provide code reusability. |. Rich Library C provides a lot of inbuilt functions that make the development fast. . Memory Management It supports the feature ofdynamic memory allocation. In C language, we can free the allocated memory at any time by calling the free() function. Fast Speed The compilation and execution time of C language is fast 7. Pointers C provides the feature of pointers. We can directly interact with the memory by using the pointers fia) Recursion In C, we ean call the function within the function. It provides code rel ‘ability for every function 9. Extensible C language is extensible because it can easily adopt new features. A typical programming task can be divided into 2 phases ~» Problem solving phase: Produce an ordered sequence of steps that describe solution of problem. This sequence of steps is called algorithm. ~» Implementation phas Implement the program in some programming language 1.4.1. Steps in Problem solving phase (Algorithm and pseudo code) ©. First produce a general algorithm (one can use pseudo code) ©. Refine the algorithm successively to get step by step detailed algorithm that is very close to a computer language. © Pseudo code is an artificial and informal language that helps programmers develop algorithms. o Pseudo code is very similar to everyday English. Example 1: Write an algorithm to determine a student to indicate whether he is passing or failing using average of four marks. i.e., if he is failed to get average less than 50 then he is failed (M/ tM Uday Pseudo code: Input a set of 4 marks Calculate their average by summing and dividing by 4 if average is below 50 Print “FAIL” fe oe &) Print “PASS” Algorithm: step 1: Start step 2: Take 4 integer inputs for the different 4 subject like math, english, physics, chemistry. step 3 :Then calculate average = ( math + english + physics + chemistry) / 4 step 4: if the value of average is below 50 , it will print fail otherwise it shows pass step 5: END Algorithm Pseudocode It is a step-by-step Tt is an easy way of writing description of the solution. | algorithms for users to understand. It is always a real algorithm | These are fake codes, and not fake codes. They are a sequence of They are representations of solutions to a problem. algorithms. It is a systematically written | These are simpler ways of writing code. codes 1.4.2. Flow chart: Now we can also transform the algorithm to a flowchart A flowchart is a graphical representation of the algorithm (again, a sequence of instructions that reach an end). Different symbols are used to draw each type of flowchart. (M/ tM Uday ‘Symbols used in flow chart: Name Function Indicates any type of internal Process operation inside the Processor ‘or Memory ‘Used for any Input / Output (UO) operation. Indicates that ‘Symbol Z___7_ | inmtloutpet | the computer is o obeain data >) ‘or output results Used to ask a question that can Decision ‘be answered in a binary format (Yes/No, True/False) Predefined Process ‘Terminal of the program, process, or to Flow Lines Shows direction of flow. (M/ tM Uday Example 2: Find algorithm and flow chart of Sum of Two Numbers Entered Algorithm: Step 1: Start Step 2: Read the Integers n1,n2 Step 4: Perform the addition by using the formula: sum=n1+n2. Step 5: Print the Integer sum Step 6: Stop Flow chart: ‘Sum of two numbers ni, n2, sum sum = nitn2 4 Write: sum Z 1.4.3 Dia tool to draw Flow chart in computer: Step 1. Select Flow Chart in the diagram tools window Select the flow chart in diagram tools window as shown below, JS “SM Mc Uday © Fig. Select Flow Chart Menu Item from Dia ‘This will show the flow charting tools in the window. Process Input/Output Decision Connector Display Start / stop and so on.. SPP Se PS Step 2. Select and draw using tools Select the flow chart tool and start drawing. In the following example, I started with the ‘Start’ flow-chart component Fig: “Start” Flow Chart Component in the Dia Program In the following example, I quickly drew 5 flow chart components — Start, Get Input, Process, Display Output, and Stop. At this stage, these flow chart components are not aligned properly. © Fig: All Flow Chart Components in Dia Unaligned Step 3. Align and Spread out the components At this stage the flowchart may not look neat, as )) the components are neither aligned nor spread- out properly. [exvesnesarenn J Before aligning and spreading-out the components, select all the flow-chart components on the screen using the mouse as shown below. Fig: Select all Dia Flow Chart Components Using Mouse Align all the components to center Click on Object Menu -> Align -> Center to center all the selected components. (M/ tM Uday Spread Out all the components to center When you draw the flow chart, each component will have a different distance from the other component. To make all the spaces equivalent use the spread out option. Click on Object Menu -> Align -> Spread Out Vertically. ‘am View Objects Select Tools i / ‘tnpitaand pions Jo i rocesancrnsmiA.8) i / Dipay ope (son user Fig: Dia Flow Chart after Spread Out Vertically Step 4. Connect Flow Chart Components Using Arrows Select the arrow from general tools window, and then connect the components one by one. You can also change the arrow type, and the thickness in the tools window. (M/ tM Uday am Yew Qbjecs select Tos Ire 1 phy prc (am ower Fig: Dia Flow Chart with the Arrows Step 5. Export the Flow Chart as an Image Finally you can export the flow chart to an image file using the export option. Click on File Menu -> Export -> Select the file type as png, or as what ever you wanted -> Click export after specifying the file name. Get Input A and B from user ¥ [receensrnim (a 8) v [ stey om to use 7 Fig: Final Flow Chart Image Export from Dia (M/ tM Uday Generally coding is done in high level language or middle level language (assembly language). For the computer to understand these languages, they must be translated into machine level language. The translation process is carried out by a compiler/interpreter (for high level language) or an assembler (for assembly language program). In an interpreted program, each program statement is converte’ machine code before program is executed. The execution occurs immediately one statement at a time sequentially A compiler converts a given source code into object code. Once an object code is obtained, the compiled programs can be faster and more efficient than interpreted programs. Compilation process: A source code must go through several steps before it becomes an executable program. In the first step the source code is checked for anny syntax errors, After the syntax errors are [==] =] traced out a source file is passed through a compiler which first translates high level language into object code (A machine code not ready to be executed). A linker then links the object code with pre- compiled library functions, thus creating an executable program. This executable program is then loaded into the memory for execution. General compilation process is shown in Figure:> qq Steps to Execute C program in Turbo C @ compiler: —> Enter the program in C editor -» Save the program (File >Save) or F2. Also use the extension “.c “ to save the program o Ex: Sample.c —» Compile the program (compile>compile) or Alt+F9 — Run the program (Run>Run) or Ctrl+F9 to see output SEaM/ Mc Uday In C, each variable has a specific data type, where a data type tells us the size, range and the type of a value that can be stored in a variable. In G, there are about seven primitive data types. These data types are short, int, long, char, float, double primitive data types are categorized into these parts fs + integer data types, such as short, int, long. + floating-point data types, such as float, double. + ‘character data type, such as char. Tnteaer ‘Character Int Uunsignedint signed char shortint _unsignedshort int ‘nsignedchar longint —_unsignediong int Floating Point Type float | double | longdouble Primitive data type’s size, range and format Specifier are given table below: Size Format Data Type (bytes) Range Specifier short int 1 byte =128 to 127 eh unsigned short | 1 bytes Oto 255 %hu int int 2 bytes -32768 to 32767 %d unsigned int | 2 bytes 0 to 65535 wu -2147483648 to , long int 4 bytes apa sold ‘anatgest long | 4 bytes 0 to 4294967295 yu SEaM/ Mc Uday signed char 1 byte -128 to 127 %e unsigned char 1 byte Oto 255 %e float 4 bytes -3.4€38 to +3.4e38 Ee double 8 bytes -1.7e308 to 1.7e308 lt long double 10 bytes | -1.7¢4932 to +1.7¢4932 LE Note : The sizes given are compiler dependent , sizes given in the figure are for 16- bit Compiler "Primitive data types" may refer to the standard data types built into a programming language (built-in types ~ already defined data types by programming language developer). Example code Output #include int value is 10 #include float value is 88.88 main() char value is a { int a=10; float b=88.88; char c clrser(); printf(“int value is %d\n”,a); printf{“float value is %f\n",b); printf{“char value is %c”,c); getch(); return 0; } Data types which are not primitive are referred to as derived or non primitive data types. Non primitive data types in C: These are the data types derived from primitive data types only. SEaM/ Mc Uday Examples include Arrays, strings, Function, Pointers etc., fe) User defined Data types in C: Here one data type can store data of different data types under the same variable name. Examples include structure, union etc., 1.7.1. Variables: Variables are used to allocate memory and variables may take different values during program execution ‘Syntax: Datatype variable; Example: int a; double b; char c; We can also provide values to variables directly using = operator Called initialization int a=100; 88.88; float char Rules for defining a variable: © variable cannot be a keyword S@8M/ tMc Uday * Ex: int a; Vint float; X © It can have sequence of letters and digits and must begin with a alphabet only or _ symbol are allowed * Ex: intal;v int 2n;X © White spaces are not allowed. * Ex: int sum; ¥ os it s um; X os) © variables are case sensitive ., Upper case and lower case alphabets treated as different. Note : Same rules applied for naming user defined functions also ‘Types of variables in C: local: variables have scope with in a function global: variables have scope more than one function auto: default variable static: to retain values between different function calls external: have scope within entire program, register: variables stored in register memory for faster access (Note: in detailed explanation about types of variables will be discussed in functions concept) 1.7.2. Constants: As the name suggests, a constant in C is a variable that cannot be modified once it is declared in the program. We cannot make any change in the value of the constant variables after they are defined. Defining a constant in C: ‘There are 2 ways to define a constant 1. using const keyword 2. using #define preprocessor 1) Using const keyword: The const keyword is used to define constant in C programming. E 1 -onst float PI Now, the value of PI variable can't be changed, (M/ tM Uday Example code #include #include main() { const float PI=3.14; elrser(); printf{“PI=%f",PI); getch(); return 0; } 2) Using #define pre processor: The #define preprocessor is also used to define constant. This is also called macro substitution Example code Output #include #include #define PI 3.14 main() { clrser(); print£(“PI=%f",PI); getch(); return 0; } PIF3.14 List of Constants in C SEaM/ Mc Uday Constant Example Decimal Constant 10, 20, 450 ete. Real or Floating-point Constant 10.3, 20.2, 450.6 etc. 28) Octal Constant 021, 033, 046 etc. Hexadecimal Constant 0x2a, Ox7b, Oxaa etc. Character Constant ‘a’, 'b’, 'x' ete. String Constant "c’, "c program’, "tme uday’” etc. C provides a collection of library functions such as getchar, putchar, scanf, printf, gets and puts. These functions enable the transfer of data between the C program and standard input/output devices. The standard input-output devices or the associated files or text streams, are referred as — «stdin - standard input file, normally connected to the keyboard + stdout - standard output file, normally connected to the screen/ console + stderr - standard error display device file, normally connected to the screen/console In order to be able to use the above mentioned input-output functions in your C program, you must begin each C program with a pre-processor directive to include these standard library functions. «This can be done with a line entry - #include This input and output functions categorized into 2 types: — Formatted - printf() , scanf() > Un formatted — getchar(), putchar() , gets(), puts() 1.8.1, Formatted output statement: printf) printf) acts as a formatted output statement in C programming language it is used to output data on standard output device This can be done in 2 ways, On 1** way used to show message, SEaM/ Mc Uday Syntax 1: printff"message”); whatever you write in between that double quotes (*) will be printed on console Example code Output #include Hello world #include main() { cirser(); printf{‘Hello world”); getch(); return 0; 1 On 2n4 way used to access a value in a variable, Syntax 2: Printf{* ”, variable); Here it will print value in variable in place of format specifier in console We can print values of multiple variables also Example code Output #include #include main() { int 00; clrser(); printf{‘value in a is %d”,a); getch(); return 0; 1 value in a is 100 1.8.2. Formatted input statement: scanf{) SEaM/ Mc Uday scanf{) acts as formatted input statement in C programming language. It is used to read value from console and store it in the specified location ie., variable Syntax: scanf{“formatspecifier” variable); format specifier can be %d for int, %f for float etc., already discussed in data © types concept &wvariable tells address of variable. Example code ‘Output ‘include Enter a value: 100 include #include main() t char ch; clrscr(); printf{‘Enter a character:”); ch=getchar(); printf(“Given character:”); putchar(ch); getch(); return 0; } Enter a character : a Given character: a 1.8.4. Escape Sequences: Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences.” Typical use of escape sequences are listed below Escape Sequence \a \b \t \n \r \t Ww \ . . Meaning ‘Alarm or Beep Backspace Form Feed New Line Carriage Return Tab (Horizontal) Vertical Tab Backslash Single Quote Double Quote Example code Output SEaM/ Mc Uday #include Helloworld ; Hellworld #include world main() Hello Fi world : Hello'world’ clrser();, Hello”world” printf(‘Hello\a world”); 2 printf{‘Hello \ bworld”); printf{*Hello\rworld’); printf{*Hello\nworld”); printf{‘Hello\‘world\”); printf{*Hello\"world\””); getch(); return 0; } In programming languages sometimes expressions contains different data types then they must be converted to the single data type of destination data type. For example, the multiplication of an integer data value with the float data value and storing the result into a float variable. In this case, the integer value must be converted to float value In a C programming language, the data conversion is performed in two different methods as follows... a. Type Conversion b. Type Casting 1.9.1. Type Conversion: It is also called widening conversion. Here destination type is larger than source type. For example float SEaM/ Mc Uday Here int variable a takes 2 bytes where float variable b takes 4 bytes so destination type is larger than source type. 1.9.2. Type casting: It is also called a narrowing conversion, Here the destination data type must be smaller than the source data type. ‘Syntax: Destination_datatype = (target_datatype) variable; For Example, float =9.6; int d= (int) ¢; // b=9 here float variable c takes 4 bytes where as int variable d takes 2 bytes so destination type is smaller than source type Example code Output #include 20.000 #include 2 main() { int ad; float b,c} clrscr(); a=20; b=a; 6; d-(int)c; printf(“%f\n",b); printf{*%d",d); getch(); cs return 0; } SEaM/ Mc Uday As we discussed earlier in topic 1.4, writing algorithm is initial step in problem solving Let us see definition of algorithm 1st Algorithm: Algorithm is step by step process of a given problem to solve it which defines / a set of instructions to be executed in a certain order to get the desired output. An algorithm can be implemented in more than one programming language Characteristics of an Algorithm Not all procedures can be called an algorithm. An algorithm should have the following characteristics - + Unambiguous ~ Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning. + Input ~ An algorithm should have 0 or more well-defined inputs. + Output - An algorithm should have 1 or more well-defined outputs, and should match the desired output. + Finiteness ~ Algorithms must terminate after a finite number of steps. + Feasibility - Should be feasible with the available resources. + Independent ~ An algorithm should have step-by-step directions, which should be independent of any programming code. 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 existing item in a data structure. Delete - Algorithm to delete an existing item from a data structure. Example Algorithm for Addition of 2 numbers: Step 1: Start Step 2: Read the Integers n1,n2 Step 4: Perform the addition by using the formula: sum=n1+n2. Step 5: Print the Integer sum Step 6: Stop SEaM/ MC Uday In the top-down approach, a bigger module/problem is divided into smaller modules. In the bottom-up approach, the smaller problems are solved and then they are integrated to find the solution of a bigger problem. 5) 1.11.1. Top-down approach: Top-Down Approach is an approach to design algorithms in which a bigger problem is broken down into smaller parts. ‘Thus, it uses the decomposition approach. This approach is generally used by structured programming languages such as C, COBOL, FORTRAN The drawback of using the top-down approach is that it may have redundancy since every part of the code is developed separately. Also, there is less interaction and communication between the modules in this approach. The implementation of algorithm using top-down approach depends on the programming language and platform. 1.11.2. Bottom-up approach: Bottom-Up Approach is one in which the smaller problems are solved, and then these solved problems are integrated to find the solution to a bigger problem. Therefore, it uses composition approach. It is generally used with object oriented programming paradigm such as C++, Java, and Python. It requires a significant amount of communication among different modules. Data encapsulation and data hiding is also implemented in this approach. The bottom-up approach is generally used in testing modules. SEaM/ MC Uday 1.11.3. Difference between Top - down and Bottom - up approaches: The following table highlights all the major differences between top-down approach and bottom-up approach S.No. ‘Top-Down Approach Bottom-Up Approach Fe) 1. | inthis approach, the problem is broken | In this approach, the smaller problems are | down into smaller parts solved. 2. | Itis generally used by structured It is generally used with object oriented programming languages such as C, COBOL, FORTRAN, ete. programming paradigm such as C+, Java, Python, ete. 3. | Itis generally used with documentati of module and debugging code. It is generally used in testing modules. 4, | It does not require communication between modules. It requites relatively more communication between modules. It contains redundant information, It does not contain redundant information. Decomposition approach is used here. Composition approach is used here. The implementation depends on the programming language and platform Data encapsulation and data hiding is implemented in this approach The Complexity of an Algorithm The algorithm's performance can be measured in two ways: Time Complexity + The amount of time required to complete an algorithm's execution is called time complexity. + The big O notation is used to represent an algorithm's time complexity. SEaM/ Mc Uday + The time complexity is calculated primarily by counting the number of steps required to complete the execution. Let us look at an example of time complexity. iS) mul // Suppose you have to calculate the multiplication of n numbers. for i=1 ton. mul = mul *1; // when the loop ends, then mul holds the multiplication of the n numbers return mul; The time complexity of the loop statement in the preceding code is at least n, and as the value of n escalates, so does the time complexity. While the code's complexity, i.e., returns mul, will be constant because its value is not dependent on the importance of n and will provide the result in a single step. The worst-time complexity is generally considered because it is the maximum time required for any given input size. Space Complexity * The amount of space an algorithm requires to solve a problem and produce an output is called its space complexity. * Space complexity, notation. ike time complexity, is expressed in big O The space is required for an algorithm for the following reasons: 1. To store program instructions. (M/ tM Uday 2. To store track of constant values. 3. To store track of variable values. 4. To store track of function calls, jumping statements, and so on. Space Complexity = Auxiliary Space + Input Size (M/ tM Uday - Assignment 1: Q: Write an Algorithm and flow chart for calculate simple interest? ANS: Signature of the faculty SEaM/ Mc Uday - Assignment 2 Q: write algorithm and flow chart for Determining the Largest Number Among All the Entered Integers ANS: Signature of the faculty SEaM/ Mc Uday Assignment 3 Q: write algorithm and flow chart for Work Out All the Roots of a Quadratic Equation ax? +bx+c=0 ANS: Signature of the faculty SEaM/ Mc Uday - Assignment 4 Q write a C program to illustrate sizeof in data types? ANS: Signature of the faculty SEaM/ Mc Uday -

You might also like