Computer Programming PDF
Document Details
Tags
Related
Summary
This document provides a basic introduction to computer programming. It covers fundamental concepts like the CPU, main memory, secondary storage, input/output devices, and software. The text is suitable for introductory computer science courses or self-study.
Full Transcript
Computer Programming CPU (Central Processing Unit) A central processing unit ( CPU ), also called a central processor, main processor, or just processor, is the most important processor in a given computer. The CPU is the part of a computer that actually runs programs. The CPU is the most...
Computer Programming CPU (Central Processing Unit) A central processing unit ( CPU ), also called a central processor, main processor, or just processor, is the most important processor in a given computer. The CPU is the part of a computer that actually runs programs. The CPU is the most important component in a computer because without it, the computer could not run software. ENIAC - Electronic Numerical Integrator And Computer In the earliest computers, CPUs were huge devices made of electrical and mechanical components such as vacuum tubes and switches. The ENIAC, which is considered by many to be the world’s first programmable electronic computer, was built in 1945 to calculate artillery ballistic tables for the U.S. Army. This machine, which was primarily one big CPU, was 8 feet tall, 100 feet long, and weighed 30 tons. ENIAC Microprocessor Today, CPUs are small chips known as microprocessors. A microprocessor is the predominant type of modern computer processor. It combines the components and function of a central processing unit (CPU) into a single integrated circuit (IC) or a few connected ICs. Like CPUs, microprocessors are commonly thought of as the “brain” of the computer. Microprocessor Main Memory Computer memory stores information, such as data and programs, for immediate use in the computer. The term memory is often synonymous with the terms RAM, main memory, or primary storage. Archaic synonyms for main memory include core and store. You can think of main memory as the computer’s work area. This is where the computer stores a program while the program is running, as well as the data that the program is working with. Main memory is commonly known as random - access memory, or RAM. It is called this because the CPU is able to quickly access data stored at any random location in RAM. RAM is usually a volatile type of memory that is used only for temporary storage while a program is running. When the computer is turned off, the contents of RAM are erased. Inside your computer, RAM is stored in chips, Secondary Storage Devices Secondary storage is a type of memory that can hold data for long periods of time, even when there is no power to the computer. Programs are normally stored in secondary memory and loaded into main memory as needed. Important data, such as word processing documents, payroll data, and inventory records, is saved to secondary storage as well. Secondary Storage Devices A disk drive stores data by magnetically encoding it onto a circular disk. External disk drives , which connect to one of the computer’s communication ports, are also available. External disk drives can be used to create backup copies of important data or to move data to another computer. A floppy disk drive records data onto a small floppy disk, which can be removed from the drive. USB drives are small devices that plug into the computer’s USB (universal serial bus) port, and appear to the system as a disk drive. Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are also popular for data storage. Secondary Storage Devices Input Devices Input is any data the computer collects from people and from other devices. The component that collects the data and sends it to the computer is called an input device. Common input devices are the keyboard, mouse, scanner, microphone, and digital camera. Disk drives and optical drives can also be considered input devices because programs and data are retrieved from them and loaded into the computer’s memory. Input Devices Output Devices Output is any data the computer produces for people or for other devices. It might be a sales report, a list of names, or a graphic image. The data is sent to an output device, which formats and presents it. Common output devices are video displays and printers. Disk drives and CD recorders can also be considered output devices because the system sends data to them in order to be saved. Output Devices Software If a computer is to function, software is not optional. Everything that a computer does, from the time you turn the power switch on until you shut the system down, is under the control of software. There are two general categories of software: system software and application software. System Software The programs that control and manage the basic operations of a computer are generally referred to as system software. System software typically includes the following types of programs: Operating Systems. An operating system is the most fundamental set of programs on a computer. The operating system controls the internal operations of the computer’s hardware, manages all of the devices connected to the computer, allows data to be saved to and retrieved from storage devices, and allows other programs to run on the computer. Three popular operating systems: Windows Vista, Mac OS X, and Linux. System Software Utility Programs. A utility program performs a specialized task that enhances the computer’s operation or safeguards data. Examples of utility programs are virus scanners, file compression programs, and data backup programs. Software Development Tools. Software development tools are the programs that programmers use to create, modify, and test software. Assemblers, compilers, and interpreters are examples of programs that fall into this category. Application Software Programs that make a computer useful for everyday tasks are known as application software. These are the programs that people normally spend most of their time running on their computers. Two commonly used applications: Microsoft Word, a word processing program, and Adobe Photoshop, an image editing program. Some other examples of application software are spreadsheet programs, email programs, web browsers, and game programs. https://www.pearsonhighered.com/assets/samplechapter/0/3/2/1/0321537 114.pdf I N T R O D U C T I O N T O C O M P U T E R P R O G R A M M I N G I N S T I T U T E O F T E C H N O L O G Y COMPUTER PROGRAMMING 1 Flowchart and Algorithm FLOWCHARTING AND ALGORITHMS A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the steps as boxes of various kinds, and their order by connecting them with arrows. This diagrammatic representation illustrates a solution model to a given problem. Flowchart Continuation... A flowchart is a diagram representing the logical sequence in which combination of steps or operations is to be performed. It is a blue print of the program. Algorithm - a process or set of rules to be followed in calculations of other problem - solving operations, specially by a computer. Example of Algorithm Algorithm: Step 1: Enter www.facebook.com in your browser (I/O) Step 2: Facebook Home page loads (PROCESS) Step 3: Enter you Email ID and Password (I/O) Step 4: Is Email ID and Password Valid (DECISION) If NO then Log in error (PROCESS) Go to Step 3 Else Display Facebook Account (I/O) Stop Flowchart Basic Symbols Used in Flowcharting Flowcharts use special shapes to represent different types of actions or steps in a process. Lines and arrows show the sequence of the steps, and the relationships among them. These are known as flowchart symbols. The type of diagram dictates the flowchart symbols that are used Basic Control Structures Any problem that is suitable for a computer program can be broken down into smaller tasks that are connected by a framework made up of the three fundamental control structures. 1. Sequence – a process is executed from one to another in a straight forward manner. 2. Selection (if - then - else) – a choice is provided between two alternatives. 3. Repetition (Looping) - A loop structure is used to execute a certain set of actions for a predefined number of times or until a particular condition is satisfied. Operators Commonly Used in Flowcharting Arithmetic Operators Operators Meaning + Addition - Subtraction Multiplication / Division Relational Operators = Equal Greater than < Less tha n < > Not equal > Greater than < Less than Logical Operators && AND || OR ! NOT Basic Control Structures Sequence (Examples) Construct a flowchart that will add 10 and 20 1. To solve this problem we will take a variable sum and set it to zero. Then we will take the two numbers 10 and 20 as input. Next we will add both the numbers and save the result in the variable sum i.e., sum = 10 + 20. Finally we will print the value stored in the variable sum. Algorithm: Step 1: Initialize sum = 0 (PROCESS) Step 2: Enter the numbers (I/O) Step 3: Add them and store the result in sum (PROCESS) Step 4: Print the sum (I/O) Flowchart 2. Draw a flowchart that will accept and display a number. Write its equivalent algorithms. Algorithm: Step 1: Read in the value of X Step 2: Print the value of X 3. Design a flowchart that will compute and display the sum and difference of two numbers. Write its equivalent algorithm. Algorithm: Step 1: Initialize Sum and Difference into 0 Step 2: Read in the values of num1 and num2 Step 3: Compute Sum by adding num1 and num2 then Difference by subtracting num1by num2. Step 4: Display the value of Sum and Difference Construct a flowchart that will convert an input number in Inches to its equivalent measure in Feet. Formula: Feet = Inches/12; Algorithm: Step 1: Initialize Feet into 0 Step 2: Read in the value of Inches Step 3: Compute the value of Feet Step 4: Print the computed value of Feet Selection (Examples) 1. Draw a flowchart that will input integer value for X and Y. Compare the two values inputted then print which of the values is higher including the word “Higher”. Algorithm: Step 1: Read in the value of X and Y Step 2: Test if X is greater than Y Step 3: If X is greater than Y, X is higher. However, if X is less than Y, then Y is higher. Step 4: Print the number and the word “Higher” 2. Draw a flowchart that will input the name and grade of student and determine whether the grade is passed or failed. Print the name, grade and the remark of the student. Algorithm: Step 1: Initialize Name and Remark into blank Step 2: Read the values of Name and Grade Step 3: Test if Grade is greater than or equal to 75. Step 4: If Grade is greater than or equal to 75, the Remark is “PASSED”. If Grade is below 75, the Remark is “FAILED”. Step 5: Print the Name, Grade and Remark 3. HIJK Company plans to give a mid - year bonus to its employee. Draw a flowchart the will input the name, salary and compute the bonus of each employee. Consider the following conditions: If the employee’s monthly salary is less than or equal to 15000.00, the bonus is 50% of the salary; for employees with salary greater than 15000.00 the bonus is 10000.00 pesos. Print the name and bonus of each employee. Algorithm: Step 1: Initialize Name into blank and Bonus to 0 Step 2: Read in employee’s name and Salary Step 3: Test if Salary is less than or equal to 15000.00 Step 4: If Salary is less than or equal to 15000.00 then Bonus = Salary *.50 Else Bonus = 10000.00 Step 5: Print the name and bonus of an employee Draw a flowchart that will accept the name and evaluation score of a teacher and determine is equivalent remarks. Print the name of the teacher and the remark obtained. Remark are based on the following criteria: 4.50 - 5.00 OUTSTANDING 4.00 - 4.49 VERYS SATISFACTORY 3.50 - 3.99 SATISFACTORY 3.00 - 3.49 NEEDS IMPROVEMENT 2.99 - below POOR Algorithm: Step 1: Initialize Name and Remark to blank Step 2: Read in the value of Name and Score Step 3: Test if the Score is greater than or equal to 4.50, If the score is greater than or equal to 4.50 , Remark is “OUTSTANDING” Step 4: Test if the Score is greater than or equal to 4.00, If the score is greater than or equal to 4.00, Remark is “VERY SATISFACTORY” Step 5: : Test if the Score is greater than or equal to 3.50, If the score is greater than or equal to 3.50, Remark is “SATISFACTORY” Step 6: : Test if the Score is greater than or equal to 3.00, If the score is greater than or equal to 3.00, Remark is “NEEDS IMPROVEMENT” Step 7: : if the score is less the 3.00,the Remark is “POOR” Step 8: Print the name and Remark Repetition (Examples) 1. Construct a flowchart that will count from 1 to 50 and print each number counted using repetition structure. Algorithm: Step 1: Initialize the value of Count to 0 Step 2: Test if C is less than 50 Step 3: If C is less than 50, add 1 to the value of Count, print the value then go back to Step 2. However, if Count is greater than 50, then stop. 2. Create a flowchart that will input 5 numbers then compute the sum of these 5 numbers. Display the sum. Algorithm: Step 1: Initialize Sum and Count to 0. Step 2: Read the value of Num. Step 3: Compute Sum + Num and assign it to Sum and then increment Count by 1. Step 4: If Count is less than 5 then go back to Step 2, otherwise print the Sum Solve the following: 1. Construct a flowchart that will compute and print the sum and average of 3 numbers. 2. Draw a flowchart that will compute and display the Area of a rectangle using the formula: Area = Length * Width 3. Design a flowchart and algorithm that calculates the total of a retail sale. The program should ask the user for the following: the retail price of the item being purchased and the sales tax rate. Once the information has been entered the program should calculate and display the following: the sales tax for the purchase and the total sale. 4. Obtain from the user the hourly pay rate and the number of hours worked for the week. Calculate their pay for the week ( no overtime and no taxes). Output the result. 5. Obtain a name and age from the user. If the user is 20 or older, output a message indicating they are old enough to drive. For people under 20, output the message indicating how many years they must wait before they can drive legally. C Programming Language Data Types Keywords Variable Variable Name All variable must be declared before they may be used. The general form of declaration is shown here: datatype variable list; example: int i, j, k; Note: Before declaring variable, specify first the data type of the variable/s Variables must be separated by comma All declarations must be terminated by a semi-colon( ; ) Variable Declaration A. Local Variable variables that are declared inside a function are called local variable. It can only be referenced by statements that are inside the block in which the variables are declared. Example: #include main( ) { int a, b, c; →local variable statement1; : : } Two Kinds of Variable B. Global Variables Global variables are known throughout the entire program and may be used by any piece of code. Global variables are created by declaring them outside of any function. Example: #include int a, b, c; →global variable main( ) { ___________ ___________ ___________ } Two kinds of variable Constant Constants in C means the content whose value does not change at the time of execution of the program. Example: cons int count =100; where integer count has a fixed value of 100. Constant Arithmetic Operators C sample program Sample output Arithmetic Operators Relational Operators Logical Operators Structure of a simple C programs main( ) { variable declaration section statements; : } A. #include directive – contains information needed by the program to ensure the correct operation of Turbo C’s standard library function Example: #include B. #define directive – used to shorten the keywords in the program Example: #define p printf C. Variable declaration section – it is the place where you declare your variables D. Body of the program – start by typing main( ) and the { and }(open and close braces). All statements should be written inside the { and } braces. Note: turbo c is a case sensitive program, therefore use lowercase letters only. C program structure Commonly used include files in C language 1. alloc.h – declares memory management functions 2. conio.h – declares various functions used in calling IBM- PC, ROM, BIOS 3. ctype.h – contains information used by the classification and character conversion macros. 4. math.h – declares prototype for the math functions. 5. stdio.h – defines types and macros needed for standard I/O 6. string.h – declares several string manipulation and memory manipulation routines. include files Input and Output statements Format Strings and Escape Sequences All format specifiers start with a percent sign (%) and are followed by a single letter including the type of data and how data are to be formatted. List of commonly used format specifiers %c used for single char in C scanf(“%c”, &ch); printf(“%c”, ch); %d decimal number ( whole number) scanf(“%d”, &num); printf(“%d”, num); %f number with floating point or decimal point scanf(“%f”, &amount); printf(“%f”, amount); %s string of characters scanf(“%s”, &name); printf(“%s”, name); String format List of commonly used escape sequences \\ prints backslash \’ prints single quotes \” prints double quotes \? Prints question mark \n new line \t tab Escape sequences COMPUTER PROGRAMMING 1 Conditional Statement Conditional Statement are statements that check an expression then may or may not execute a statement or group of statements depending on the result of the condition. The if statement The general form of the if statement is: if (expression) statement; if statement... where: if is a reserve word in Turbo C Expression is a relational or boolean expression that evaluates to a TRUE(1) or FALSE(2) value. Statement may either be a single Turbo C or a block of Turbo C statements if statement The general form of if block statements is: If i if (expression) { Statement_sequence; } if block statement In an if statement, if the expression evaluates to TRUE(1), the statement or the block of statements that forms the target of the if statement will be executed. Otherwise, the program will ignore the statement or the block of statements. The if-else statement The general form of the if-else statement is: If (expression) statement_1; else statement_2; Where: if and else are reserve w.ords in Turbo C if-else statement Expression is relational or boolean expression that evaluates to a TRUE(1) or FALSE(2) value Statement_1 and statement_2 may either be a single Turbo C statement or a block of Turbo C statements. The general form is: If (expression) { Statement_sequence; } Else Statement_sequence; } A switch statement This statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. COMPUTER PROGRAMMING 1 LOOP LOOP This refers to a set of statements in a program executed repeatedly, either a fixed number of times or until some condition is true or false. It is also a control structures in which a block of instruction is repeated until a condition is fulfilled. ITERATIVE STATEMENT This is a statement in a program that allows the program to repeat one or more statements. ITERATION – refers to the act of executing one or more statements or instructions repeatedly. Program Control Statements for loop statement do...while statement while statement for loop statement This allows a set of instructions to be repeated until a certain condition is reached. Syntax: for(initialization; condition; increment/decrement); { statements; } LOOP statements Initialization – This is an assignment statement that is used to set loop-control variable. Condition – This is a relational expression that determines when the loop will exit by testing the loop-control variable against some value. Increment/Decrement – It defines how the loop-control variable will change each time the loop is repeated. while loop statement The “while loop” continues to loop while some condition is true. When the condition become false, looping is discontinued. It therefore does just what it says it does. Syntax: Initialization; while(condition) { statements; increment/decrement; } do...while loop This is a loop control structure that continues to carry out its function until a condition is satisfied. The do while control structure establishes a condition that, if true, allows the program to wait the test is false, then move on to the next instruction. Syntax; initialization; do { statements; increment/decrement; } while (condition);